main.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. #include <Arduino.h> // needed for PlatformIO
  2. #include <Mesh.h>
  3. #if defined(NRF52_PLATFORM)
  4. #include <InternalFileSystem.h>
  5. #elif defined(ESP32)
  6. #include <SPIFFS.h>
  7. #endif
  8. #include <helpers/ArduinoHelpers.h>
  9. #include <helpers/StaticPoolPacketManager.h>
  10. #include <helpers/SimpleMeshTables.h>
  11. #include <helpers/IdentityStore.h>
  12. #include <helpers/AdvertDataHelpers.h>
  13. #include <helpers/TxtDataHelpers.h>
  14. #include <helpers/CommonCLI.h>
  15. #include <RTClib.h>
  16. #include <target.h>
  17. /* ------------------------------ Config -------------------------------- */
  18. #ifndef FIRMWARE_BUILD_DATE
  19. #define FIRMWARE_BUILD_DATE "7 Apr 2025"
  20. #endif
  21. #ifndef FIRMWARE_VERSION
  22. #define FIRMWARE_VERSION "v1.4.3"
  23. #endif
  24. #ifndef LORA_FREQ
  25. #define LORA_FREQ 915.0
  26. #endif
  27. #ifndef LORA_BW
  28. #define LORA_BW 250
  29. #endif
  30. #ifndef LORA_SF
  31. #define LORA_SF 10
  32. #endif
  33. #ifndef LORA_CR
  34. #define LORA_CR 5
  35. #endif
  36. #ifndef LORA_TX_POWER
  37. #define LORA_TX_POWER 20
  38. #endif
  39. #ifndef ADVERT_NAME
  40. #define ADVERT_NAME "Test BBS"
  41. #endif
  42. #ifndef ADVERT_LAT
  43. #define ADVERT_LAT 0.0
  44. #endif
  45. #ifndef ADVERT_LON
  46. #define ADVERT_LON 0.0
  47. #endif
  48. #ifndef ADMIN_PASSWORD
  49. #define ADMIN_PASSWORD "password"
  50. #endif
  51. #ifndef MAX_CLIENTS
  52. #define MAX_CLIENTS 32
  53. #endif
  54. #ifndef MAX_UNSYNCED_POSTS
  55. #define MAX_UNSYNCED_POSTS 32
  56. #endif
  57. #ifdef DISPLAY_CLASS
  58. #include <helpers/ui/SSD1306Display.h>
  59. static DISPLAY_CLASS display;
  60. #include "UITask.h"
  61. static UITask ui_task(display);
  62. #endif
  63. #define FIRMWARE_ROLE "room_server"
  64. #define PACKET_LOG_FILE "/packet_log"
  65. /* ------------------------------ Code -------------------------------- */
  66. enum RoomPermission {
  67. ADMIN,
  68. GUEST,
  69. READ_ONLY
  70. };
  71. struct ClientInfo {
  72. mesh::Identity id;
  73. uint32_t last_timestamp; // by THEIR clock
  74. uint32_t last_activity; // by OUR clock
  75. uint32_t sync_since; // sync messages SINCE this timestamp (by OUR clock)
  76. uint32_t pending_ack;
  77. uint32_t push_post_timestamp;
  78. unsigned long ack_timeout;
  79. RoomPermission permission;
  80. uint8_t push_failures;
  81. uint8_t secret[PUB_KEY_SIZE];
  82. int out_path_len;
  83. uint8_t out_path[MAX_PATH_SIZE];
  84. };
  85. #define MAX_POST_TEXT_LEN (160-9)
  86. struct PostInfo {
  87. mesh::Identity author;
  88. uint32_t post_timestamp; // by OUR clock
  89. char text[MAX_POST_TEXT_LEN+1];
  90. };
  91. #define REPLY_DELAY_MILLIS 1500
  92. #define PUSH_NOTIFY_DELAY_MILLIS 2000
  93. #define SYNC_PUSH_INTERVAL 1200
  94. #define PUSH_ACK_TIMEOUT_FLOOD 12000
  95. #define PUSH_TIMEOUT_BASE 4000
  96. #define PUSH_ACK_TIMEOUT_FACTOR 2000
  97. #define CLIENT_KEEP_ALIVE_SECS 128
  98. #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
  99. #define REQ_TYPE_KEEP_ALIVE 0x02
  100. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  101. struct ServerStats {
  102. uint16_t batt_milli_volts;
  103. uint16_t curr_tx_queue_len;
  104. uint16_t curr_free_queue_len;
  105. int16_t last_rssi;
  106. uint32_t n_packets_recv;
  107. uint32_t n_packets_sent;
  108. uint32_t total_air_time_secs;
  109. uint32_t total_up_time_secs;
  110. uint32_t n_sent_flood, n_sent_direct;
  111. uint32_t n_recv_flood, n_recv_direct;
  112. uint16_t n_full_events;
  113. int16_t last_snr; // x 4
  114. uint16_t n_direct_dups, n_flood_dups;
  115. uint16_t n_posted, n_post_push;
  116. };
  117. class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
  118. FILESYSTEM* _fs;
  119. unsigned long next_local_advert, next_flood_advert;
  120. bool _logging;
  121. NodePrefs _prefs;
  122. CommonCLI _cli;
  123. uint8_t reply_data[MAX_PACKET_PAYLOAD];
  124. int num_clients;
  125. ClientInfo known_clients[MAX_CLIENTS];
  126. unsigned long next_push;
  127. uint16_t _num_posted, _num_post_pushes;
  128. int next_client_idx; // for round-robin polling
  129. int next_post_idx;
  130. PostInfo posts[MAX_UNSYNCED_POSTS]; // cyclic queue
  131. ClientInfo* putClient(const mesh::Identity& id) {
  132. for (int i = 0; i < num_clients; i++) {
  133. if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
  134. }
  135. ClientInfo* newClient;
  136. if (num_clients < MAX_CLIENTS) {
  137. newClient = &known_clients[num_clients++];
  138. } else { // table is currently full
  139. // evict least active client
  140. uint32_t oldest_timestamp = 0xFFFFFFFF;
  141. newClient = &known_clients[0];
  142. for (int i = 0; i < num_clients; i++) {
  143. auto c = &known_clients[i];
  144. if (c->last_activity < oldest_timestamp) {
  145. oldest_timestamp = c->last_activity;
  146. newClient = c;
  147. }
  148. }
  149. }
  150. newClient->id = id;
  151. newClient->out_path_len = -1; // initially out_path is unknown
  152. newClient->last_timestamp = 0;
  153. self_id.calcSharedSecret(newClient->secret, id); // calc ECDH shared secret
  154. return newClient;
  155. }
  156. void evict(ClientInfo* client) {
  157. client->last_activity = 0; // this slot will now be re-used (will be oldest)
  158. memset(client->id.pub_key, 0, sizeof(client->id.pub_key));
  159. memset(client->secret, 0, sizeof(client->secret));
  160. client->pending_ack = 0;
  161. }
  162. void addPost(ClientInfo* client, const char* postData) {
  163. // TODO: suggested postData format: <title>/<descrption>
  164. posts[next_post_idx].author = client->id; // add to cyclic queue
  165. StrHelper::strncpy(posts[next_post_idx].text, postData, MAX_POST_TEXT_LEN);
  166. posts[next_post_idx].post_timestamp = getRTCClock()->getCurrentTimeUnique();
  167. next_post_idx = (next_post_idx + 1) % MAX_UNSYNCED_POSTS;
  168. next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS);
  169. _num_posted++; // stats
  170. }
  171. void pushPostToClient(ClientInfo* client, PostInfo& post) {
  172. int len = 0;
  173. memcpy(&reply_data[len], &post.post_timestamp, 4); len += 4; // this is a PAST timestamp... but should be accepted by client
  174. reply_data[len++] = (TXT_TYPE_SIGNED_PLAIN << 2); // 'signed' plain text
  175. // encode prefix of post.author.pub_key
  176. memcpy(&reply_data[len], post.author.pub_key, 4); len += 4; // just first 4 bytes
  177. int text_len = strlen(post.text);
  178. memcpy(&reply_data[len], post.text, text_len); len += text_len;
  179. // calc expected ACK reply
  180. mesh::Utils::sha256((uint8_t *)&client->pending_ack, 4, reply_data, len, client->id.pub_key, PUB_KEY_SIZE);
  181. client->push_post_timestamp = post.post_timestamp;
  182. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, client->secret, reply_data, len);
  183. if (reply) {
  184. if (client->out_path_len < 0) {
  185. sendFlood(reply);
  186. client->ack_timeout = futureMillis(PUSH_ACK_TIMEOUT_FLOOD);
  187. } else {
  188. sendDirect(reply, client->out_path, client->out_path_len);
  189. client->ack_timeout = futureMillis(PUSH_TIMEOUT_BASE + PUSH_ACK_TIMEOUT_FACTOR * (client->out_path_len + 1));
  190. }
  191. _num_post_pushes++; // stats
  192. } else {
  193. client->pending_ack = 0;
  194. MESH_DEBUG_PRINTLN("Unable to push post to client");
  195. }
  196. }
  197. uint8_t getUnsyncedCount(ClientInfo* client) {
  198. uint8_t count = 0;
  199. for (int k = 0; k < MAX_UNSYNCED_POSTS; k++) {
  200. if (posts[k].post_timestamp > client->sync_since // is new post for this Client?
  201. && !posts[k].author.matches(client->id)) { // don't push posts to the author
  202. count++;
  203. }
  204. }
  205. return count;
  206. }
  207. bool processAck(const uint8_t *data) {
  208. for (int i = 0; i < num_clients; i++) {
  209. auto client = &known_clients[i];
  210. if (client->pending_ack && memcmp(data, &client->pending_ack, 4) == 0) { // got an ACK from Client!
  211. client->pending_ack = 0; // clear this, so next push can happen
  212. client->push_failures = 0;
  213. client->sync_since = client->push_post_timestamp; // advance Client's SINCE timestamp, to sync next post
  214. return true;
  215. }
  216. }
  217. return false;
  218. }
  219. mesh::Packet* createSelfAdvert() {
  220. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  221. uint8_t app_data_len;
  222. {
  223. AdvertDataBuilder builder(ADV_TYPE_ROOM, _prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  224. app_data_len = builder.encodeTo(app_data);
  225. }
  226. return createAdvert(self_id, app_data, app_data_len);
  227. }
  228. File openAppend(const char* fname) {
  229. #if defined(NRF52_PLATFORM)
  230. return _fs->open(fname, FILE_O_WRITE);
  231. #else
  232. return _fs->open(fname, "a", true);
  233. #endif
  234. }
  235. protected:
  236. float getAirtimeBudgetFactor() const override {
  237. return _prefs.airtime_factor;
  238. }
  239. void logRxRaw(float snr, float rssi, const uint8_t raw[], int len) override {
  240. #if MESH_PACKET_LOGGING
  241. Serial.print(getLogDateTime());
  242. Serial.print(" RAW: ");
  243. mesh::Utils::printHex(Serial, raw, len);
  244. Serial.println();
  245. #endif
  246. }
  247. void logRx(mesh::Packet* pkt, int len, float score) override {
  248. if (_logging) {
  249. File f = openAppend(PACKET_LOG_FILE);
  250. if (f) {
  251. f.print(getLogDateTime());
  252. f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d",
  253. len, pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
  254. (int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score*1000));
  255. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ
  256. || pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  257. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  258. } else {
  259. f.printf("\n");
  260. }
  261. f.close();
  262. }
  263. }
  264. }
  265. void logTx(mesh::Packet* pkt, int len) override {
  266. if (_logging) {
  267. File f = openAppend(PACKET_LOG_FILE);
  268. if (f) {
  269. f.print(getLogDateTime());
  270. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)",
  271. len, pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  272. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ
  273. || pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  274. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  275. } else {
  276. f.printf("\n");
  277. }
  278. f.close();
  279. }
  280. }
  281. }
  282. void logTxFail(mesh::Packet* pkt, int len) override {
  283. if (_logging) {
  284. File f = openAppend(PACKET_LOG_FILE);
  285. if (f) {
  286. f.print(getLogDateTime());
  287. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n",
  288. len, pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  289. f.close();
  290. }
  291. }
  292. }
  293. int calcRxDelay(float score, uint32_t air_time) const override {
  294. if (_prefs.rx_delay_base <= 0.0f) return 0;
  295. return (int) ((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  296. }
  297. const char* getLogDateTime() override {
  298. static char tmp[32];
  299. uint32_t now = getRTCClock()->getCurrentTime();
  300. DateTime dt = DateTime(now);
  301. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(), dt.year());
  302. return tmp;
  303. }
  304. uint32_t getRetransmitDelay(const mesh::Packet* packet) override {
  305. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
  306. return getRNG()->nextInt(0, 6)*t;
  307. }
  308. uint32_t getDirectRetransmitDelay(const mesh::Packet* packet) override {
  309. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  310. return getRNG()->nextInt(0, 6)*t;
  311. }
  312. bool allowPacketForward(const mesh::Packet* packet) override {
  313. if (_prefs.disable_fwd) return false;
  314. if (packet->isRouteFlood() && packet->path_len >= _prefs.flood_max) return false;
  315. return true;
  316. }
  317. void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override {
  318. if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
  319. uint32_t sender_timestamp, sender_sync_since;
  320. memcpy(&sender_timestamp, data, 4);
  321. memcpy(&sender_sync_since, &data[4], 4); // sender's "sync messags SINCE x" timestamp
  322. RoomPermission perm;
  323. data[len] = 0; // ensure null terminator
  324. if (strcmp((char *) &data[8], _prefs.password) == 0) { // check for valid admin password
  325. perm = RoomPermission::ADMIN;
  326. } else {
  327. if (strcmp((char *) &data[8], _prefs.guest_password) == 0) { // check the room/public password
  328. perm = RoomPermission::GUEST;
  329. } else if (_prefs.allow_read_only) {
  330. perm = RoomPermission::READ_ONLY;
  331. } else {
  332. MESH_DEBUG_PRINTLN("Incorrect room password");
  333. return; // no response. Client will timeout
  334. }
  335. }
  336. auto client = putClient(sender); // add to known clients (if not already known)
  337. if (sender_timestamp <= client->last_timestamp) {
  338. MESH_DEBUG_PRINTLN("possible replay attack!");
  339. return;
  340. }
  341. MESH_DEBUG_PRINTLN("Login success!");
  342. client->permission = perm;
  343. client->last_timestamp = sender_timestamp;
  344. client->sync_since = sender_sync_since;
  345. client->pending_ack = 0;
  346. client->push_failures = 0;
  347. uint32_t now = getRTCClock()->getCurrentTime();
  348. client->last_activity = now;
  349. now = getRTCClock()->getCurrentTimeUnique();
  350. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  351. // TODO: maybe reply with count of messages waiting to be synced for THIS client?
  352. reply_data[4] = RESP_SERVER_LOGIN_OK;
  353. reply_data[5] = (CLIENT_KEEP_ALIVE_SECS >> 4); // NEW: recommended keep-alive interval (secs / 16)
  354. reply_data[6] = (perm == RoomPermission::ADMIN ? 1 : (perm == RoomPermission::GUEST ? 0 : 2));
  355. reply_data[7] = getUnsyncedCount(client); // NEW
  356. memcpy(&reply_data[8], "OK", 2); // REVISIT: not really needed
  357. next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS); // delay next push, give RESPONSE packet time to arrive first
  358. if (packet->isRouteFlood()) {
  359. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  360. mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
  361. PAYLOAD_TYPE_RESPONSE, reply_data, 8 + 2);
  362. if (path) sendFlood(path);
  363. } else {
  364. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, reply_data, 8 + 2);
  365. if (reply) {
  366. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  367. sendDirect(reply, client->out_path, client->out_path_len);
  368. } else {
  369. sendFlood(reply);
  370. }
  371. }
  372. }
  373. }
  374. }
  375. int matching_peer_indexes[MAX_CLIENTS];
  376. int searchPeersByHash(const uint8_t* hash) override {
  377. int n = 0;
  378. for (int i = 0; i < num_clients; i++) {
  379. if (known_clients[i].id.isHashMatch(hash)) {
  380. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  381. }
  382. }
  383. return n;
  384. }
  385. void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
  386. int i = matching_peer_indexes[peer_idx];
  387. if (i >= 0 && i < num_clients) {
  388. // lookup pre-calculated shared_secret
  389. memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
  390. } else {
  391. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  392. }
  393. }
  394. void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override {
  395. int i = matching_peer_indexes[sender_idx];
  396. if (i < 0 || i >= num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
  397. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  398. return;
  399. }
  400. auto client = &known_clients[i];
  401. if (type == PAYLOAD_TYPE_TXT_MSG && len > 5) { // a CLI command or new Post
  402. uint32_t sender_timestamp;
  403. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  404. uint flags = (data[4] >> 2); // message attempt number, and other flags
  405. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  406. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported command flags received: flags=%02x", (uint32_t)flags);
  407. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks, but send Acks for retries
  408. bool is_retry = (sender_timestamp == client->last_timestamp);
  409. client->last_timestamp = sender_timestamp;
  410. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  411. client->last_activity = now;
  412. client->push_failures = 0; // reset so push can resume (if prev failed)
  413. // len can be > original length, but 'text' will be padded with zeroes
  414. data[len] = 0; // need to make a C string again, with null terminator
  415. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to sender that we got it
  416. mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key, PUB_KEY_SIZE);
  417. uint8_t temp[166];
  418. bool send_ack;
  419. if (flags == TXT_TYPE_CLI_DATA) {
  420. if (client->permission == RoomPermission::ADMIN) {
  421. if (is_retry) {
  422. temp[5] = 0; // no reply
  423. } else {
  424. _cli.handleCommand(sender_timestamp, (const char *) &data[5], (char *) &temp[5]);
  425. temp[4] = (TXT_TYPE_CLI_DATA << 2); // attempt and flags, (NOTE: legacy was: TXT_TYPE_PLAIN)
  426. }
  427. send_ack = false;
  428. } else {
  429. temp[5] = 0; // no reply
  430. send_ack = false; // and no ACK... user shoudn't be sending these
  431. }
  432. } else { // TXT_TYPE_PLAIN
  433. if (client->permission == RoomPermission::READ_ONLY) {
  434. temp[5] = 0; // no reply
  435. send_ack = false; // no ACK
  436. } else {
  437. if (!is_retry) {
  438. addPost(client, (const char *) &data[5]);
  439. }
  440. temp[5] = 0; // no reply (ACK is enough)
  441. send_ack = true;
  442. }
  443. }
  444. uint32_t delay_millis;
  445. if (send_ack) {
  446. mesh::Packet* ack = createAck(ack_hash);
  447. if (ack) {
  448. if (client->out_path_len < 0) {
  449. sendFlood(ack);
  450. } else {
  451. sendDirect(ack, client->out_path, client->out_path_len);
  452. }
  453. }
  454. delay_millis = REPLY_DELAY_MILLIS;
  455. } else {
  456. delay_millis = 0;
  457. }
  458. int text_len = strlen((char *) &temp[5]);
  459. if (text_len > 0) {
  460. if (now == sender_timestamp) {
  461. // WORKAROUND: the two timestamps need to be different, in the CLI view
  462. now++;
  463. }
  464. memcpy(temp, &now, 4); // mostly an extra blob to help make packet_hash unique
  465. // calc expected ACK reply
  466. //mesh::Utils::sha256((uint8_t *)&expected_ack_crc, 4, temp, 5 + text_len, self_id.pub_key, PUB_KEY_SIZE);
  467. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  468. if (reply) {
  469. if (client->out_path_len < 0) {
  470. sendFlood(reply, delay_millis);
  471. } else {
  472. sendDirect(reply, client->out_path, client->out_path_len, delay_millis);
  473. }
  474. }
  475. }
  476. } else {
  477. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  478. }
  479. } else if (type == PAYLOAD_TYPE_REQ && len >= 5) {
  480. uint32_t sender_timestamp;
  481. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  482. if (sender_timestamp < client->last_timestamp) { // prevent replay attacks
  483. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  484. } else {
  485. client->last_timestamp = sender_timestamp;
  486. uint32_t now = getRTCClock()->getCurrentTime();
  487. client->last_activity = now; // <-- THIS will keep client connection alive
  488. client->push_failures = 0; // reset so push can resume (if prev failed)
  489. if (data[4] == REQ_TYPE_KEEP_ALIVE && packet->isRouteDirect()) { // request type
  490. uint32_t forceSince = 0;
  491. if (len >= 9) { // optional - last post_timestamp client received
  492. memcpy(&forceSince, &data[5], 4); // NOTE: this may be 0, if part of decrypted PADDING!
  493. } else {
  494. memcpy(&data[5], &forceSince, 4); // make sure there are zeroes in payload (for ack_hash calc below)
  495. }
  496. if (forceSince > 0) {
  497. client->sync_since = forceSince; // force-update the 'sync since'
  498. }
  499. client->pending_ack = 0;
  500. // TODO: Throttle KEEP_ALIVE requests!
  501. // if client sends too quickly, evict()
  502. // RULE: only send keep_alive response DIRECT!
  503. if (client->out_path_len >= 0) {
  504. uint32_t ack_hash; // calc ACK to prove to sender that we got request
  505. mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 9, client->id.pub_key, PUB_KEY_SIZE);
  506. auto reply = createAck(ack_hash);
  507. if (reply) {
  508. sendDirect(reply, client->out_path, client->out_path_len);
  509. }
  510. }
  511. } else if (data[4] == REQ_TYPE_GET_STATUS) {
  512. ServerStats stats;
  513. stats.batt_milli_volts = board.getBattMilliVolts();
  514. stats.curr_tx_queue_len = _mgr->getOutboundCount();
  515. stats.curr_free_queue_len = _mgr->getFreeCount();
  516. stats.last_rssi = (int16_t) radio_driver.getLastRSSI();
  517. stats.n_packets_recv = radio_driver.getPacketsRecv();
  518. stats.n_packets_sent = radio_driver.getPacketsSent();
  519. stats.total_air_time_secs = getTotalAirTime() / 1000;
  520. stats.total_up_time_secs = _ms->getMillis() / 1000;
  521. stats.n_sent_flood = getNumSentFlood();
  522. stats.n_sent_direct = getNumSentDirect();
  523. stats.n_recv_flood = getNumRecvFlood();
  524. stats.n_recv_direct = getNumRecvDirect();
  525. stats.n_full_events = getNumFullEvents();
  526. stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
  527. stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
  528. stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
  529. stats.n_posted = _num_posted;
  530. stats.n_post_push = _num_post_pushes;
  531. now = getRTCClock()->getCurrentTimeUnique();
  532. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  533. memcpy(&reply_data[4], &stats, sizeof(stats));
  534. uint8_t reply_len = 4 + sizeof(stats);
  535. if (packet->isRouteFlood()) {
  536. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  537. mesh::Packet* path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  538. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  539. if (path) sendFlood(path);
  540. } else {
  541. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  542. if (reply) {
  543. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  544. sendDirect(reply, client->out_path, client->out_path_len);
  545. } else {
  546. sendFlood(reply);
  547. }
  548. }
  549. }
  550. }
  551. }
  552. }
  553. }
  554. bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
  555. // TODO: prevent replay attacks
  556. int i = matching_peer_indexes[sender_idx];
  557. if (i >= 0 && i < num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
  558. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t) path_len);
  559. auto client = &known_clients[i];
  560. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  561. } else {
  562. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  563. }
  564. if (extra_type == PAYLOAD_TYPE_ACK && extra_len >= 4) {
  565. // also got an encoded ACK!
  566. processAck(extra);
  567. }
  568. // NOTE: no reciprocal path send!!
  569. return false;
  570. }
  571. void onAckRecv(mesh::Packet* packet, uint32_t ack_crc) override {
  572. if (processAck((uint8_t *)&ack_crc)) {
  573. packet->markDoNotRetransmit(); // ACK was for this node, so don't retransmit
  574. }
  575. }
  576. public:
  577. MyMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
  578. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  579. _cli(board, this, &_prefs, this)
  580. {
  581. next_local_advert = next_flood_advert = 0;
  582. _logging = false;
  583. // defaults
  584. memset(&_prefs, 0, sizeof(_prefs));
  585. _prefs.airtime_factor = 1.0; // one half
  586. _prefs.rx_delay_base = 0.0f; // off by default, was 10.0
  587. _prefs.tx_delay_factor = 0.5f; // was 0.25f;
  588. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  589. _prefs.node_lat = ADVERT_LAT;
  590. _prefs.node_lon = ADVERT_LON;
  591. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  592. _prefs.freq = LORA_FREQ;
  593. _prefs.sf = LORA_SF;
  594. _prefs.bw = LORA_BW;
  595. _prefs.cr = LORA_CR;
  596. _prefs.tx_power_dbm = LORA_TX_POWER;
  597. _prefs.disable_fwd = 1;
  598. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  599. _prefs.flood_advert_interval = 3; // 3 hours
  600. _prefs.flood_max = 64;
  601. #ifdef ROOM_PASSWORD
  602. StrHelper::strncpy(_prefs.guest_password, ROOM_PASSWORD, sizeof(_prefs.guest_password));
  603. #endif
  604. num_clients = 0;
  605. next_post_idx = 0;
  606. next_client_idx = 0;
  607. next_push = 0;
  608. memset(posts, 0, sizeof(posts));
  609. _num_posted = _num_post_pushes = 0;
  610. }
  611. CommonCLI* getCLI() { return &_cli; }
  612. void begin(FILESYSTEM* fs) {
  613. mesh::Mesh::begin();
  614. _fs = fs;
  615. // load persisted prefs
  616. _cli.loadPrefs(_fs);
  617. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  618. radio_set_tx_power(_prefs.tx_power_dbm);
  619. updateAdvertTimer();
  620. updateFloodAdvertTimer();
  621. }
  622. const char* getFirmwareVer() override { return FIRMWARE_VERSION; }
  623. const char* getBuildDate() override { return FIRMWARE_BUILD_DATE; }
  624. const char* getRole() override { return FIRMWARE_ROLE; }
  625. const char* getNodeName() { return _prefs.node_name; }
  626. void savePrefs() override {
  627. _cli.savePrefs(_fs);
  628. }
  629. bool formatFileSystem() override {
  630. #if defined(NRF52_PLATFORM)
  631. return InternalFS.format();
  632. #elif defined(ESP32)
  633. return SPIFFS.format();
  634. #else
  635. #error "need to implement file system erase"
  636. return false;
  637. #endif
  638. }
  639. void sendSelfAdvertisement(int delay_millis) override {
  640. mesh::Packet* pkt = createSelfAdvert();
  641. if (pkt) {
  642. sendFlood(pkt, delay_millis);
  643. } else {
  644. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  645. }
  646. }
  647. void updateAdvertTimer() override {
  648. if (_prefs.advert_interval > 0) { // schedule local advert timer
  649. next_local_advert = futureMillis((uint32_t)_prefs.advert_interval * 2 * 60 * 1000);
  650. } else {
  651. next_local_advert = 0; // stop the timer
  652. }
  653. }
  654. void updateFloodAdvertTimer() override {
  655. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  656. next_flood_advert = futureMillis( ((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  657. } else {
  658. next_flood_advert = 0; // stop the timer
  659. }
  660. }
  661. void setLoggingOn(bool enable) override { _logging = enable; }
  662. void eraseLogFile() override {
  663. _fs->remove(PACKET_LOG_FILE);
  664. }
  665. void dumpLogFile() override {
  666. File f = _fs->open(PACKET_LOG_FILE);
  667. if (f) {
  668. while (f.available()) {
  669. int c = f.read();
  670. if (c < 0) break;
  671. Serial.print((char)c);
  672. }
  673. f.close();
  674. }
  675. }
  676. void setTxPower(uint8_t power_dbm) override {
  677. radio_set_tx_power(power_dbm);
  678. }
  679. void loop() {
  680. mesh::Mesh::loop();
  681. if (millisHasNowPassed(next_push) && num_clients > 0) {
  682. // check for ACK timeouts
  683. for (int i = 0; i < num_clients; i++) {
  684. auto c = &known_clients[i];
  685. if (c->pending_ack && millisHasNowPassed(c->ack_timeout)) {
  686. c->push_failures++;
  687. c->pending_ack = 0; // reset (TODO: keep prev expected_ack's in a list, incase they arrive LATER, after we retry)
  688. MESH_DEBUG_PRINTLN("pending ACK timed out: push_failures: %d", (uint32_t)c->push_failures);
  689. }
  690. }
  691. // check next Round-Robin client, and sync next new post
  692. auto client = &known_clients[next_client_idx];
  693. bool did_push = false;
  694. if (client->pending_ack == 0 && client->last_activity != 0 && client->push_failures < 3) { // not already waiting for ACK, AND not evicted, AND retries not max
  695. MESH_DEBUG_PRINTLN("loop - checking for client %02X", (uint32_t) client->id.pub_key[0]);
  696. for (int k = 0, idx = next_post_idx; k < MAX_UNSYNCED_POSTS; k++) {
  697. if (posts[idx].post_timestamp > client->sync_since // is new post for this Client?
  698. && !posts[idx].author.matches(client->id)) { // don't push posts to the author
  699. // push this post to Client, then wait for ACK
  700. pushPostToClient(client, posts[idx]);
  701. did_push = true;
  702. MESH_DEBUG_PRINTLN("loop - pushed to client %02X: %s", (uint32_t) client->id.pub_key[0], posts[idx].text);
  703. break;
  704. }
  705. idx = (idx + 1) % MAX_UNSYNCED_POSTS; // wrap to start of cyclic queue
  706. }
  707. } else {
  708. MESH_DEBUG_PRINTLN("loop - skipping busy (or evicted) client %02X", (uint32_t) client->id.pub_key[0]);
  709. }
  710. next_client_idx = (next_client_idx + 1) % num_clients; // round robin polling for each client
  711. if (did_push) {
  712. next_push = futureMillis(SYNC_PUSH_INTERVAL);
  713. } else {
  714. // were no unsynced posts for curr client, so proccess next client much quicker! (in next loop())
  715. next_push = futureMillis(SYNC_PUSH_INTERVAL / 8);
  716. }
  717. }
  718. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  719. mesh::Packet* pkt = createSelfAdvert();
  720. if (pkt) sendFlood(pkt);
  721. updateFloodAdvertTimer(); // schedule next flood advert
  722. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  723. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  724. mesh::Packet* pkt = createSelfAdvert();
  725. if (pkt) sendZeroHop(pkt);
  726. updateAdvertTimer(); // schedule next local advert
  727. }
  728. #ifdef DISPLAY_CLASS
  729. ui_task.loop();
  730. #endif
  731. // TODO: periodically check for OLD/inactive entries in known_clients[], and evict
  732. }
  733. };
  734. StdRNG fast_rng;
  735. SimpleMeshTables tables;
  736. MyMesh the_mesh(board, radio_driver, *new ArduinoMillis(), fast_rng, rtc_clock, tables);
  737. void halt() {
  738. while (1) ;
  739. }
  740. static char command[MAX_POST_TEXT_LEN+1];
  741. void setup() {
  742. Serial.begin(115200);
  743. delay(1000);
  744. board.begin();
  745. #ifdef DISPLAY_CLASS
  746. if(display.begin()){
  747. display.startFrame();
  748. display.print("Please wait...");
  749. display.endFrame();
  750. }
  751. #endif
  752. if (!radio_init()) { halt(); }
  753. fast_rng.begin(radio_get_rng_seed());
  754. FILESYSTEM* fs;
  755. #if defined(NRF52_PLATFORM)
  756. InternalFS.begin();
  757. fs = &InternalFS;
  758. IdentityStore store(InternalFS, "");
  759. #elif defined(ESP32)
  760. SPIFFS.begin(true);
  761. fs = &SPIFFS;
  762. IdentityStore store(SPIFFS, "/identity");
  763. #else
  764. #error "need to define filesystem"
  765. #endif
  766. if (!store.load("_main", the_mesh.self_id)) {
  767. the_mesh.self_id = radio_new_identity(); // create new random identity
  768. int count = 0;
  769. while (count < 10 && (the_mesh.self_id.pub_key[0] == 0x00 || the_mesh.self_id.pub_key[0] == 0xFF)) { // reserved id hashes
  770. the_mesh.self_id = radio_new_identity(); count++;
  771. }
  772. store.save("_main", the_mesh.self_id);
  773. }
  774. Serial.print("Room ID: ");
  775. mesh::Utils::printHex(Serial, the_mesh.self_id.pub_key, PUB_KEY_SIZE); Serial.println();
  776. command[0] = 0;
  777. the_mesh.begin(fs);
  778. #ifdef DISPLAY_CLASS
  779. ui_task.begin(the_mesh.getNodeName(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION);
  780. #endif
  781. // send out initial Advertisement to the mesh
  782. the_mesh.sendSelfAdvertisement(16000);
  783. }
  784. void loop() {
  785. int len = strlen(command);
  786. while (Serial.available() && len < sizeof(command)-1) {
  787. char c = Serial.read();
  788. if (c != '\n') {
  789. command[len++] = c;
  790. command[len] = 0;
  791. }
  792. Serial.print(c);
  793. }
  794. if (len == sizeof(command)-1) { // command buffer full
  795. command[sizeof(command)-1] = '\r';
  796. }
  797. if (len > 0 && command[len - 1] == '\r') { // received complete line
  798. command[len - 1] = 0; // replace newline with C string null terminator
  799. char reply[160];
  800. the_mesh.getCLI()->handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial!
  801. if (reply[0]) {
  802. Serial.print(" -> "); Serial.println(reply);
  803. }
  804. command[0] = 0; // reset command buffer
  805. }
  806. the_mesh.loop();
  807. }