main.cpp 32 KB

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