MyMesh.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. #include "MyMesh.h"
  2. #define REPLY_DELAY_MILLIS 1500
  3. #define PUSH_NOTIFY_DELAY_MILLIS 2000
  4. #define SYNC_PUSH_INTERVAL 1200
  5. #define PUSH_ACK_TIMEOUT_FLOOD 12000
  6. #define PUSH_TIMEOUT_BASE 4000
  7. #define PUSH_ACK_TIMEOUT_FACTOR 2000
  8. #define POST_SYNC_DELAY_SECS 6
  9. #define FIRMWARE_VER_LEVEL 1
  10. #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
  11. #define REQ_TYPE_KEEP_ALIVE 0x02
  12. #define REQ_TYPE_GET_TELEMETRY_DATA 0x03
  13. #define REQ_TYPE_GET_ACCESS_LIST 0x05
  14. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  15. #define LAZY_CONTACTS_WRITE_DELAY 5000
  16. struct ServerStats {
  17. uint16_t batt_milli_volts;
  18. uint16_t curr_tx_queue_len;
  19. int16_t noise_floor;
  20. int16_t last_rssi;
  21. uint32_t n_packets_recv;
  22. uint32_t n_packets_sent;
  23. uint32_t total_air_time_secs;
  24. uint32_t total_up_time_secs;
  25. uint32_t n_sent_flood, n_sent_direct;
  26. uint32_t n_recv_flood, n_recv_direct;
  27. uint16_t err_events; // was 'n_full_events'
  28. int16_t last_snr; // x 4
  29. uint16_t n_direct_dups, n_flood_dups;
  30. uint16_t n_posted, n_post_push;
  31. };
  32. void MyMesh::addPost(ClientInfo *client, const char *postData) {
  33. // TODO: suggested postData format: <title>/<descrption>
  34. posts[next_post_idx].author = client->id; // add to cyclic queue
  35. StrHelper::strncpy(posts[next_post_idx].text, postData, MAX_POST_TEXT_LEN);
  36. posts[next_post_idx].post_timestamp = getRTCClock()->getCurrentTimeUnique();
  37. next_post_idx = (next_post_idx + 1) % MAX_UNSYNCED_POSTS;
  38. next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS);
  39. _num_posted++; // stats
  40. }
  41. void MyMesh::pushPostToClient(ClientInfo *client, PostInfo &post) {
  42. int len = 0;
  43. memcpy(&reply_data[len], &post.post_timestamp, 4);
  44. len += 4; // this is a PAST timestamp... but should be accepted by client
  45. uint8_t attempt;
  46. getRNG()->random(&attempt, 1); // need this for re-tries, so packet hash (and ACK) will be different
  47. reply_data[len++] = (TXT_TYPE_SIGNED_PLAIN << 2) | (attempt & 3); // 'signed' plain text
  48. // encode prefix of post.author.pub_key
  49. memcpy(&reply_data[len], post.author.pub_key, 4);
  50. len += 4; // just first 4 bytes
  51. int text_len = strlen(post.text);
  52. memcpy(&reply_data[len], post.text, text_len);
  53. len += text_len;
  54. // calc expected ACK reply
  55. mesh::Utils::sha256((uint8_t *)&client->extra.room.pending_ack, 4, reply_data, len, client->id.pub_key, PUB_KEY_SIZE);
  56. client->extra.room.push_post_timestamp = post.post_timestamp;
  57. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, client->shared_secret, reply_data, len);
  58. if (reply) {
  59. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  60. unsigned long delay_millis = 0;
  61. sendFloodScoped(default_scope, reply, delay_millis, _prefs.path_hash_mode + 1); // REVISIT
  62. client->extra.room.ack_timeout = futureMillis(PUSH_ACK_TIMEOUT_FLOOD);
  63. } else {
  64. sendDirect(reply, client->out_path, client->out_path_len);
  65. uint8_t path_hash_count = client->out_path_len & 63;
  66. client->extra.room.ack_timeout = futureMillis(PUSH_TIMEOUT_BASE + PUSH_ACK_TIMEOUT_FACTOR * (path_hash_count + 1));
  67. }
  68. _num_post_pushes++; // stats
  69. } else {
  70. client->extra.room.pending_ack = 0;
  71. MESH_DEBUG_PRINTLN("Unable to push post to client");
  72. }
  73. }
  74. uint8_t MyMesh::getUnsyncedCount(ClientInfo *client) {
  75. uint8_t count = 0;
  76. for (int k = 0; k < MAX_UNSYNCED_POSTS; k++) {
  77. if (posts[k].post_timestamp > client->extra.room.sync_since // is new post for this Client?
  78. && !posts[k].author.matches(client->id)) { // don't push posts to the author
  79. count++;
  80. }
  81. }
  82. return count;
  83. }
  84. bool MyMesh::processAck(const uint8_t *data) {
  85. for (int i = 0; i < acl.getNumClients(); i++) {
  86. auto client = acl.getClientByIdx(i);
  87. if (client->extra.room.pending_ack && memcmp(data, &client->extra.room.pending_ack, 4) == 0) { // got an ACK from Client!
  88. client->extra.room.pending_ack = 0; // clear this, so next push can happen
  89. client->extra.room.push_failures = 0;
  90. client->extra.room.sync_since = client->extra.room.push_post_timestamp; // advance Client's SINCE timestamp, to sync next post
  91. return true;
  92. }
  93. }
  94. return false;
  95. }
  96. mesh::Packet *MyMesh::createSelfAdvert() {
  97. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  98. uint8_t app_data_len = _cli.buildAdvertData(ADV_TYPE_ROOM, app_data);
  99. return createAdvert(self_id, app_data, app_data_len);
  100. }
  101. File MyMesh::openAppend(const char *fname) {
  102. #if defined(NRF52_PLATFORM)
  103. return _fs->open(fname, FILE_O_WRITE);
  104. #elif defined(RP2040_PLATFORM)
  105. return _fs->open(fname, "a");
  106. #else
  107. return _fs->open(fname, "a", true);
  108. #endif
  109. }
  110. int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload,
  111. size_t payload_len) {
  112. // uint32_t now = getRTCClock()->getCurrentTimeUnique();
  113. // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  114. memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
  115. if (payload[0] == REQ_TYPE_GET_STATUS) {
  116. ServerStats stats;
  117. stats.batt_milli_volts = board.getBattMilliVolts();
  118. stats.curr_tx_queue_len = _mgr->getOutboundTotal();
  119. stats.noise_floor = (int16_t)_radio->getNoiseFloor();
  120. stats.last_rssi = (int16_t)radio_driver.getLastRSSI();
  121. stats.n_packets_recv = radio_driver.getPacketsRecv();
  122. stats.n_packets_sent = radio_driver.getPacketsSent();
  123. stats.total_air_time_secs = getTotalAirTime() / 1000;
  124. stats.total_up_time_secs = uptime_millis / 1000;
  125. stats.n_sent_flood = getNumSentFlood();
  126. stats.n_sent_direct = getNumSentDirect();
  127. stats.n_recv_flood = getNumRecvFlood();
  128. stats.n_recv_direct = getNumRecvDirect();
  129. stats.err_events = _err_flags;
  130. stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
  131. stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
  132. stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
  133. stats.n_posted = _num_posted;
  134. stats.n_post_push = _num_post_pushes;
  135. memcpy(&reply_data[4], &stats, sizeof(stats));
  136. return 4 + sizeof(stats);
  137. }
  138. if (payload[0] == REQ_TYPE_GET_TELEMETRY_DATA) {
  139. uint8_t perm_mask = ~(payload[1]); // NEW: first reserved byte (of 4), is now inverse mask to apply to permissions
  140. telemetry.reset();
  141. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  142. // query other sensors -- target specific
  143. if ((sender->permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_GUEST) {
  144. perm_mask = 0x00; // just base telemetry allowed
  145. }
  146. sensors.querySensors(perm_mask, telemetry);
  147. // This default temperature will be overridden by external sensors (if any)
  148. float temperature = board.getMCUTemperature();
  149. if(!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN
  150. telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature
  151. }
  152. uint8_t tlen = telemetry.getSize();
  153. memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
  154. return 4 + tlen; // reply_len
  155. }
  156. if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) {
  157. uint8_t res1 = payload[1]; // reserved for future (extra query params)
  158. uint8_t res2 = payload[2];
  159. if (res1 == 0 && res2 == 0) {
  160. uint8_t ofs = 4;
  161. for (int i = 0; i < acl.getNumClients() && ofs + 7 <= sizeof(reply_data) - 4; i++) {
  162. auto c = acl.getClientByIdx(i);
  163. if (!c->isAdmin()) continue; // skip non-Admin entries
  164. memcpy(&reply_data[ofs], c->id.pub_key, 6); ofs += 6; // just 6-byte pub_key prefix
  165. reply_data[ofs++] = c->permissions;
  166. }
  167. return ofs;
  168. }
  169. }
  170. return 0; // unknown command
  171. }
  172. void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
  173. #if MESH_PACKET_LOGGING
  174. Serial.print(getLogDateTime());
  175. Serial.print(" RAW: ");
  176. mesh::Utils::printHex(Serial, raw, len);
  177. Serial.println();
  178. #endif
  179. }
  180. void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
  181. if (_logging) {
  182. File f = openAppend(PACKET_LOG_FILE);
  183. if (f) {
  184. f.print(getLogDateTime());
  185. f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d", len,
  186. pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
  187. (int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score * 1000));
  188. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  189. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  190. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  191. } else {
  192. f.printf("\n");
  193. }
  194. f.close();
  195. }
  196. }
  197. }
  198. void MyMesh::logTx(mesh::Packet *pkt, int len) {
  199. if (_logging) {
  200. File f = openAppend(PACKET_LOG_FILE);
  201. if (f) {
  202. f.print(getLogDateTime());
  203. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, pkt->getPayloadType(),
  204. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  205. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  206. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  207. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  208. } else {
  209. f.printf("\n");
  210. }
  211. f.close();
  212. }
  213. }
  214. }
  215. void MyMesh::logTxFail(mesh::Packet *pkt, int len) {
  216. if (_logging) {
  217. File f = openAppend(PACKET_LOG_FILE);
  218. if (f) {
  219. f.print(getLogDateTime());
  220. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n", len, pkt->getPayloadType(),
  221. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  222. f.close();
  223. }
  224. }
  225. }
  226. int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
  227. if (_prefs.rx_delay_base <= 0.0f) return 0;
  228. return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  229. }
  230. const char *MyMesh::getLogDateTime() {
  231. static char tmp[32];
  232. uint32_t now = getRTCClock()->getCurrentTime();
  233. DateTime dt = DateTime(now);
  234. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
  235. dt.year());
  236. return tmp;
  237. }
  238. uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) {
  239. uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.tx_delay_factor);
  240. return getRNG()->nextInt(0, 5*t + 1);
  241. }
  242. uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
  243. uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  244. return getRNG()->nextInt(0, 5*t + 1);
  245. }
  246. bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
  247. if (_prefs.disable_fwd) return false;
  248. if (packet->isRouteFlood()) {
  249. uint8_t limit = _prefs.flood_max;
  250. if (packet->getRouteType() == ROUTE_TYPE_FLOOD
  251. && _prefs.flood_max_unscoped != FLOOD_MAX_UNSCOPED_UNSET) {
  252. limit = _prefs.flood_max_unscoped;
  253. }
  254. if (packet->getPathHashCount() >= limit) return false;
  255. }
  256. return true;
  257. }
  258. bool MyMesh::filterRecvFloodPacket(mesh::Packet* pkt) {
  259. // just try to determine region for packet (apply later in allowPacketForward())
  260. if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
  261. recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD);
  262. } else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) {
  263. if (region_map.getWildcard().flags & REGION_DENY_FLOOD) {
  264. recv_pkt_region = NULL;
  265. } else {
  266. recv_pkt_region = &region_map.getWildcard();
  267. }
  268. } else {
  269. recv_pkt_region = NULL;
  270. }
  271. // do normal processing
  272. return false;
  273. }
  274. void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
  275. uint8_t *data, size_t len) {
  276. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
  277. // client (unknown at this stage)
  278. uint32_t sender_timestamp, sender_sync_since;
  279. memcpy(&sender_timestamp, data, 4);
  280. memcpy(&sender_sync_since, &data[4], 4); // sender's "sync messags SINCE x" timestamp
  281. data[len] = 0; // ensure null terminator
  282. ClientInfo* client = NULL;
  283. if (data[8] == 0) { // blank password, just check if sender is in ACL
  284. client = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
  285. if (client == NULL) {
  286. #if MESH_DEBUG
  287. MESH_DEBUG_PRINTLN("Login, sender not in ACL");
  288. #endif
  289. }
  290. }
  291. if (client == NULL) {
  292. uint8_t perm;
  293. if (strcmp((char *)&data[8], _prefs.password) == 0) { // check for valid admin password
  294. perm = PERM_ACL_ADMIN;
  295. } else {
  296. if (strcmp((char *)&data[8], _prefs.guest_password) == 0) { // check the room/public password
  297. perm = PERM_ACL_READ_WRITE;
  298. } else if (_prefs.allow_read_only) {
  299. perm = PERM_ACL_GUEST;
  300. } else {
  301. MESH_DEBUG_PRINTLN("Incorrect room password");
  302. return; // no response. Client will timeout
  303. }
  304. }
  305. client = acl.putClient(sender, 0); // add to known clients (if not already known)
  306. if (sender_timestamp <= client->last_timestamp) {
  307. MESH_DEBUG_PRINTLN("possible replay attack!");
  308. return;
  309. }
  310. MESH_DEBUG_PRINTLN("Login success!");
  311. client->last_timestamp = sender_timestamp;
  312. client->extra.room.sync_since = sender_sync_since;
  313. client->extra.room.pending_ack = 0;
  314. client->extra.room.push_failures = 0;
  315. client->last_activity = getRTCClock()->getCurrentTime();
  316. client->permissions &= ~0x03;
  317. client->permissions |= perm;
  318. memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
  319. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  320. }
  321. if (packet->isRouteFlood()) {
  322. client->out_path_len = OUT_PATH_UNKNOWN; // need to rediscover out_path
  323. }
  324. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  325. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  326. // TODO: maybe reply with count of messages waiting to be synced for THIS client?
  327. reply_data[4] = RESP_SERVER_LOGIN_OK;
  328. reply_data[5] = 0; // Legacy: was recommended keep-alive interval (secs / 16)
  329. reply_data[6] = (client->isAdmin() ? 1 : (client->permissions == 0 ? 2 : 0));
  330. // LEGACY: reply_data[7] = getUnsyncedCount(client);
  331. reply_data[7] = client->permissions; // NEW
  332. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  333. reply_data[12] = FIRMWARE_VER_LEVEL; // New field
  334. next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS); // delay next push, give RESPONSE packet time to arrive first
  335. if (packet->isRouteFlood()) {
  336. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  337. mesh::Packet *path = createPathReturn(sender, client->shared_secret, packet->path, packet->path_len,
  338. PAYLOAD_TYPE_RESPONSE, reply_data, 13);
  339. if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  340. } else {
  341. mesh::Packet *reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->shared_secret, reply_data, 13);
  342. if (reply) {
  343. if (client->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
  344. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  345. } else {
  346. sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  347. }
  348. }
  349. }
  350. }
  351. }
  352. int MyMesh::searchPeersByHash(const uint8_t *hash) {
  353. int n = 0;
  354. for (int i = 0; i < acl.getNumClients(); i++) {
  355. if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
  356. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  357. }
  358. }
  359. return n;
  360. }
  361. void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
  362. int i = matching_peer_indexes[peer_idx];
  363. if (i >= 0 && i < acl.getNumClients()) {
  364. // lookup pre-calculated shared_secret
  365. memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
  366. } else {
  367. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  368. }
  369. }
  370. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  371. uint8_t *data, size_t len) {
  372. int i = matching_peer_indexes[sender_idx];
  373. if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  374. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  375. return;
  376. }
  377. auto client = acl.getClientByIdx(i);
  378. if (type == PAYLOAD_TYPE_TXT_MSG && len > 5) { // a CLI command or new Post
  379. uint32_t sender_timestamp;
  380. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  381. uint8_t flags = (data[4] >> 2); // message attempt number, and other flags
  382. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  383. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported command flags received: flags=%02x", (uint32_t)flags);
  384. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks, but send Acks for retries
  385. bool is_retry = (sender_timestamp == client->last_timestamp);
  386. client->last_timestamp = sender_timestamp;
  387. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  388. client->last_activity = now;
  389. client->extra.room.push_failures = 0; // reset so push can resume (if prev failed)
  390. // len can be > original length, but 'text' will be padded with zeroes
  391. data[len] = 0; // need to make a C string again, with null terminator
  392. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to
  393. // sender that we got it
  394. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  395. PUB_KEY_SIZE);
  396. uint8_t temp[166];
  397. bool send_ack;
  398. if (flags == TXT_TYPE_CLI_DATA) {
  399. if (client->isAdmin()) {
  400. if (is_retry) {
  401. temp[5] = 0; // no reply
  402. } else {
  403. handleCommand(sender_timestamp, (char *)&data[5], (char *)&temp[5]);
  404. temp[4] = (TXT_TYPE_CLI_DATA << 2); // attempt and flags, (NOTE: legacy was: TXT_TYPE_PLAIN)
  405. }
  406. send_ack = false;
  407. } else {
  408. temp[5] = 0; // no reply
  409. send_ack = false; // and no ACK... user shoudn't be sending these
  410. }
  411. } else { // TXT_TYPE_PLAIN
  412. if ((client->permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_GUEST) {
  413. temp[5] = 0; // no reply
  414. send_ack = false; // no ACK
  415. } else {
  416. if (!is_retry) {
  417. addPost(client, (const char *)&data[5]);
  418. }
  419. temp[5] = 0; // no reply (ACK is enough)
  420. send_ack = true;
  421. }
  422. }
  423. uint32_t delay_millis;
  424. if (send_ack) {
  425. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  426. mesh::Packet *ack = createAck(ack_hash);
  427. if (ack) sendFloodReply(ack, TXT_ACK_DELAY, packet->getPathHashSize());
  428. delay_millis = TXT_ACK_DELAY + REPLY_DELAY_MILLIS;
  429. } else {
  430. uint32_t d = TXT_ACK_DELAY;
  431. if (getExtraAckTransmitCount() > 0) {
  432. mesh::Packet *a1 = createMultiAck(ack_hash, 1);
  433. if (a1) sendDirect(a1, client->out_path, client->out_path_len, d);
  434. d += 300;
  435. }
  436. mesh::Packet *a2 = createAck(ack_hash);
  437. if (a2) sendDirect(a2, client->out_path, client->out_path_len, d);
  438. delay_millis = d + REPLY_DELAY_MILLIS;
  439. }
  440. } else {
  441. delay_millis = 0;
  442. }
  443. int text_len = strlen((char *)&temp[5]);
  444. if (text_len > 0) {
  445. if (now == sender_timestamp) {
  446. // WORKAROUND: the two timestamps need to be different, in the CLI view
  447. now++;
  448. }
  449. memcpy(temp, &now, 4); // mostly an extra blob to help make packet_hash unique
  450. // calc expected ACK reply
  451. // mesh::Utils::sha256((uint8_t *)&expected_ack_crc, 4, temp, 5 + text_len, self_id.pub_key,
  452. // PUB_KEY_SIZE);
  453. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  454. if (reply) {
  455. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  456. sendFloodReply(reply, delay_millis + SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  457. } else {
  458. sendDirect(reply, client->out_path, client->out_path_len, delay_millis + SERVER_RESPONSE_DELAY);
  459. }
  460. }
  461. }
  462. } else {
  463. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  464. }
  465. } else if (type == PAYLOAD_TYPE_REQ && len >= 5) {
  466. uint32_t sender_timestamp;
  467. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  468. if (sender_timestamp < client->last_timestamp) { // prevent replay attacks
  469. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  470. } else {
  471. client->last_timestamp = sender_timestamp;
  472. uint32_t now = getRTCClock()->getCurrentTime();
  473. client->last_activity = now; // <-- THIS will keep client connection alive
  474. client->extra.room.push_failures = 0; // reset so push can resume (if prev failed)
  475. if (data[4] == REQ_TYPE_KEEP_ALIVE && packet->isRouteDirect()) { // request type
  476. uint32_t forceSince = 0;
  477. if (len >= 9) { // optional - last post_timestamp client received
  478. memcpy(&forceSince, &data[5], 4); // NOTE: this may be 0, if part of decrypted PADDING!
  479. } else {
  480. memcpy(&data[5], &forceSince, 4); // make sure there are zeroes in payload (for ack_hash calc below)
  481. }
  482. if (forceSince > 0) {
  483. client->extra.room.sync_since = forceSince; // force-update the 'sync since'
  484. }
  485. client->extra.room.pending_ack = 0;
  486. // TODO: Throttle KEEP_ALIVE requests!
  487. // if client sends too quickly, evict()
  488. // RULE: only send keep_alive response DIRECT!
  489. if (client->out_path_len != OUT_PATH_UNKNOWN) {
  490. uint32_t ack_hash; // calc ACK to prove to sender that we got request
  491. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 9, client->id.pub_key, PUB_KEY_SIZE);
  492. auto reply = createAck(ack_hash);
  493. if (reply) {
  494. reply->payload[reply->payload_len++] = getUnsyncedCount(client); // NEW: add unsynced counter to end of ACK packet
  495. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  496. }
  497. }
  498. } else {
  499. int reply_len = handleRequest(client, sender_timestamp, &data[4], len - 4);
  500. if (reply_len > 0) { // valid command
  501. if (packet->isRouteFlood()) {
  502. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  503. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  504. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  505. if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  506. } else {
  507. mesh::Packet *reply = createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  508. if (reply) {
  509. if (client->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
  510. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  511. } else {
  512. sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  513. }
  514. }
  515. }
  516. }
  517. }
  518. }
  519. }
  520. }
  521. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  522. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  523. // TODO: prevent replay attacks
  524. int i = matching_peer_indexes[sender_idx];
  525. if (i >= 0 && i < acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  526. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  527. auto client = acl.getClientByIdx(i);
  528. client->out_path_len = mesh::Packet::copyPath(client->out_path, path, path_len); // store a copy of path, for sendDirect()
  529. client->last_activity = getRTCClock()->getCurrentTime();
  530. } else {
  531. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  532. }
  533. if (extra_type == PAYLOAD_TYPE_ACK && extra_len >= 4) {
  534. // also got an encoded ACK!
  535. processAck(extra);
  536. }
  537. // NOTE: no reciprocal path send!!
  538. return false;
  539. }
  540. void MyMesh::onAckRecv(mesh::Packet *packet, uint32_t ack_crc) {
  541. if (processAck((uint8_t *)&ack_crc)) {
  542. packet->markDoNotRetransmit(); // ACK was for this node, so don't retransmit
  543. }
  544. }
  545. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  546. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  547. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  548. region_map(key_store), temp_map(key_store),
  549. _cli(board, rtc, sensors, region_map, acl, &_prefs, this),
  550. telemetry(MAX_PACKET_PAYLOAD - 4)
  551. {
  552. last_millis = 0;
  553. uptime_millis = 0;
  554. next_local_advert = next_flood_advert = 0;
  555. dirty_contacts_expiry = 0;
  556. _logging = false;
  557. region_load_active = false;
  558. set_radio_at = revert_radio_at = 0;
  559. // defaults
  560. memset(&_prefs, 0, sizeof(_prefs));
  561. _prefs.airtime_factor = 1.0;
  562. _prefs.rx_delay_base = 0.0f; // off by default, was 10.0
  563. _prefs.tx_delay_factor = 0.5f; // was 0.25f;
  564. _prefs.direct_tx_delay_factor = 0.2f; // was zero
  565. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  566. _prefs.node_lat = ADVERT_LAT;
  567. _prefs.node_lon = ADVERT_LON;
  568. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  569. _prefs.freq = LORA_FREQ;
  570. _prefs.sf = LORA_SF;
  571. _prefs.bw = LORA_BW;
  572. _prefs.cr = LORA_CR;
  573. _prefs.tx_power_dbm = LORA_TX_POWER;
  574. _prefs.disable_fwd = 1;
  575. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  576. _prefs.flood_advert_interval = 47; // 47 hours
  577. _prefs.flood_max = 64;
  578. _prefs.flood_max_unscoped = FLOOD_MAX_UNSCOPED_UNSET;
  579. _prefs.interference_threshold = 0; // disabled
  580. #ifdef ROOM_PASSWORD
  581. StrHelper::strncpy(_prefs.guest_password, ROOM_PASSWORD, sizeof(_prefs.guest_password));
  582. #endif
  583. // GPS defaults
  584. _prefs.gps_enabled = 0;
  585. _prefs.gps_interval = 0;
  586. _prefs.advert_loc_policy = ADVERT_LOC_PREFS;
  587. next_post_idx = 0;
  588. next_client_idx = 0;
  589. next_push = 0;
  590. memset(posts, 0, sizeof(posts));
  591. _num_posted = _num_post_pushes = 0;
  592. memset(default_scope.key, 0, sizeof(default_scope.key));
  593. }
  594. void MyMesh::begin(FILESYSTEM *fs) {
  595. mesh::Mesh::begin();
  596. _fs = fs;
  597. // load persisted prefs
  598. _cli.loadPrefs(_fs);
  599. acl.load(_fs, self_id);
  600. region_map.load(_fs);
  601. // establish default-scope
  602. {
  603. RegionEntry* r = region_map.getDefaultRegion();
  604. if (r) {
  605. region_map.getTransportKeysFor(*r, &default_scope, 1);
  606. } else {
  607. #ifdef DEFAULT_FLOOD_SCOPE_NAME
  608. r = region_map.findByName(DEFAULT_FLOOD_SCOPE_NAME);
  609. if (r == NULL) {
  610. r = region_map.putRegion(DEFAULT_FLOOD_SCOPE_NAME, 0); // auto-create the default scope region
  611. if (r) { r->flags = 0; } // Allow-flood
  612. }
  613. if (r) {
  614. region_map.setDefaultRegion(r);
  615. region_map.getTransportKeysFor(*r, &default_scope, 1);
  616. }
  617. #endif
  618. }
  619. }
  620. radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  621. radio_driver.setTxPower(_prefs.tx_power_dbm);
  622. updateAdvertTimer();
  623. updateFloodAdvertTimer();
  624. board.setAdcMultiplier(_prefs.adc_multiplier);
  625. #if ENV_INCLUDE_GPS == 1
  626. applyGpsPrefs();
  627. #endif
  628. }
  629. void MyMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size) {
  630. if (scope.isNull()) {
  631. sendFlood(pkt, delay_millis, path_hash_size);
  632. } else {
  633. uint16_t codes[2];
  634. codes[0] = scope.calcTransportCode(pkt);
  635. codes[1] = 0; // REVISIT: set to 'home' Region, for sender/return region?
  636. sendFlood(pkt, codes, delay_millis, path_hash_size);
  637. }
  638. }
  639. void MyMesh::sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size) {
  640. if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // if _request_ packet scope is known, send reply with same scope
  641. TransportKey scope;
  642. if (region_map.getTransportKeysFor(*recv_pkt_region, &scope, 1) > 0) {
  643. sendFloodScoped(scope, packet, delay_millis, path_hash_size);
  644. } else {
  645. sendFlood(packet, delay_millis, path_hash_size); // send un-scoped
  646. }
  647. } else {
  648. sendFlood(packet, delay_millis, path_hash_size); // send un-scoped
  649. }
  650. }
  651. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  652. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  653. pending_freq = freq;
  654. pending_bw = bw;
  655. pending_sf = sf;
  656. pending_cr = cr;
  657. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  658. }
  659. bool MyMesh::formatFileSystem() {
  660. #if defined(NRF52_PLATFORM)
  661. return InternalFS.format();
  662. #elif defined(RP2040_PLATFORM)
  663. return LittleFS.format();
  664. #elif defined(ESP32)
  665. return SPIFFS.format();
  666. #else
  667. #error "need to implement file system erase"
  668. return false;
  669. #endif
  670. }
  671. void MyMesh::sendSelfAdvertisement(int delay_millis, bool flood) {
  672. mesh::Packet *pkt = createSelfAdvert();
  673. if (pkt) {
  674. if (flood) {
  675. sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
  676. } else {
  677. sendZeroHop(pkt, delay_millis);
  678. }
  679. } else {
  680. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  681. }
  682. }
  683. void MyMesh::updateAdvertTimer() {
  684. if (_prefs.advert_interval > 0) { // schedule local advert timer
  685. next_local_advert = futureMillis((uint32_t)_prefs.advert_interval * 2 * 60 * 1000);
  686. } else {
  687. next_local_advert = 0; // stop the timer
  688. }
  689. }
  690. void MyMesh::updateFloodAdvertTimer() {
  691. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  692. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  693. } else {
  694. next_flood_advert = 0; // stop the timer
  695. }
  696. }
  697. void MyMesh::dumpLogFile() {
  698. #if defined(RP2040_PLATFORM)
  699. File f = _fs->open(PACKET_LOG_FILE, "r");
  700. #else
  701. File f = _fs->open(PACKET_LOG_FILE);
  702. #endif
  703. if (f) {
  704. while (f.available()) {
  705. int c = f.read();
  706. if (c < 0) break;
  707. Serial.print((char)c);
  708. }
  709. f.close();
  710. }
  711. }
  712. void MyMesh::setTxPower(int8_t power_dbm) {
  713. radio_driver.setTxPower(power_dbm);
  714. }
  715. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  716. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  717. IdentityStore store(*_fs, "");
  718. #elif defined(ESP32)
  719. IdentityStore store(*_fs, "/identity");
  720. #elif defined(RP2040_PLATFORM)
  721. IdentityStore store(*_fs, "/identity");
  722. #else
  723. #error "need to define saveIdentity()"
  724. #endif
  725. store.save("_main", new_id);
  726. }
  727. void MyMesh::startRegionsLoad() {
  728. temp_map.resetFrom(region_map); // rebuild regions in a temp instance
  729. memset(load_stack, 0, sizeof(load_stack));
  730. load_stack[0] = &temp_map.getWildcard();
  731. region_load_active = true;
  732. }
  733. bool MyMesh::saveRegions() {
  734. return region_map.save(_fs);
  735. }
  736. void MyMesh::onDefaultRegionChanged(const RegionEntry* r) {
  737. if (r) {
  738. region_map.getTransportKeysFor(*r, &default_scope, 1);
  739. } else {
  740. memset(default_scope.key, 0, sizeof(default_scope.key));
  741. }
  742. }
  743. void MyMesh::clearStats() {
  744. radio_driver.resetStats();
  745. resetStats();
  746. ((SimpleMeshTables *)getTables())->resetStats();
  747. }
  748. void MyMesh::formatStatsReply(char *reply) {
  749. StatsFormatHelper::formatCoreStats(reply, board, *_ms, _err_flags, _mgr);
  750. }
  751. void MyMesh::formatRadioStatsReply(char *reply) {
  752. StatsFormatHelper::formatRadioStats(reply, _radio, radio_driver, getTotalAirTime(), getReceiveAirTime());
  753. }
  754. void MyMesh::formatPacketStatsReply(char *reply) {
  755. StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(),
  756. getNumRecvFlood(), getNumRecvDirect());
  757. }
  758. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  759. if (region_load_active) {
  760. if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation
  761. region_map = temp_map; // copy over the temp instance as new current map
  762. region_load_active = false;
  763. sprintf(reply, "OK - loaded %d regions", region_map.getCount());
  764. } else {
  765. char *np = command;
  766. while (*np == ' ') np++; // skip indent
  767. int indent = np - command;
  768. char *ep = np;
  769. while (RegionMap::is_name_char(*ep)) ep++;
  770. if (*ep) { *ep++ = 0; } // set null terminator for end of name
  771. while (*ep && *ep != 'F') ep++; // look for (optional) flags
  772. if (indent > 0 && indent < 8 && strlen(np) > 0) {
  773. auto parent = load_stack[indent - 1];
  774. if (parent) {
  775. auto old = region_map.findByName(np);
  776. auto nw = temp_map.putRegion(np, parent->id, old ? old->id : 0); // carry-over the current ID (if name already exists)
  777. if (nw) {
  778. nw->flags = old ? old->flags : (*ep == 'F' ? 0 : REGION_DENY_FLOOD); // carry-over flags from curr
  779. load_stack[indent] = nw; // keep pointers to parent regions, to resolve parent_id's
  780. }
  781. }
  782. }
  783. reply[0] = 0;
  784. }
  785. return;
  786. }
  787. while (*command == ' ')
  788. command++; // skip leading spaces
  789. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  790. memcpy(reply, command, 3); // reflect the prefix back
  791. reply += 3;
  792. command += 3;
  793. }
  794. // handle ACL related commands
  795. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  796. char* hex = &command[8];
  797. char* sp = strchr(hex, ' '); // look for separator char
  798. if (sp == NULL) {
  799. strcpy(reply, "Err - bad params");
  800. } else {
  801. *sp++ = 0; // replace space with null terminator
  802. uint8_t pubkey[PUB_KEY_SIZE];
  803. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  804. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  805. uint8_t perms = atoi(sp);
  806. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  807. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  808. strcpy(reply, "OK");
  809. } else {
  810. strcpy(reply, "Err - invalid params");
  811. }
  812. } else {
  813. strcpy(reply, "Err - bad pubkey");
  814. }
  815. }
  816. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  817. Serial.println("ACL:");
  818. for (int i = 0; i < acl.getNumClients(); i++) {
  819. auto c = acl.getClientByIdx(i);
  820. if (c->permissions == 0) continue; // skip deleted (or guest) entries
  821. Serial.printf("%02X ", c->permissions);
  822. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  823. Serial.printf("\n");
  824. }
  825. reply[0] = 0;
  826. } else{
  827. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  828. }
  829. }
  830. bool MyMesh::saveFilter(ClientInfo* client) {
  831. return client->isAdmin(); // only save Admins
  832. }
  833. void MyMesh::loop() {
  834. mesh::Mesh::loop();
  835. if (millisHasNowPassed(next_push) && acl.getNumClients() > 0) {
  836. // check for ACK timeouts
  837. for (int i = 0; i < acl.getNumClients(); i++) {
  838. auto c = acl.getClientByIdx(i);
  839. if (c->extra.room.pending_ack && millisHasNowPassed(c->extra.room.ack_timeout)) {
  840. c->extra.room.push_failures++;
  841. c->extra.room.pending_ack = 0; // reset (TODO: keep prev expected_ack's in a list, incase they arrive LATER, after we retry)
  842. MESH_DEBUG_PRINTLN("pending ACK timed out: push_failures: %d", (uint32_t)c->extra.room.push_failures);
  843. }
  844. }
  845. // check next Round-Robin client, and sync next new post
  846. auto client = acl.getClientByIdx(next_client_idx);
  847. bool did_push = false;
  848. if (client->extra.room.pending_ack == 0 && client->last_activity != 0 &&
  849. client->extra.room.push_failures < 3) { // not already waiting for ACK, AND not evicted, AND retries not max
  850. MESH_DEBUG_PRINTLN("loop - checking for client %02X", (uint32_t)client->id.pub_key[0]);
  851. uint32_t now = getRTCClock()->getCurrentTime();
  852. for (int k = 0, idx = next_post_idx; k < MAX_UNSYNCED_POSTS; k++) {
  853. auto p = &posts[idx];
  854. if (now >= p->post_timestamp + POST_SYNC_DELAY_SECS &&
  855. p->post_timestamp > client->extra.room.sync_since // is new post for this Client?
  856. && !p->author.matches(client->id)) { // don't push posts to the author
  857. // push this post to Client, then wait for ACK
  858. pushPostToClient(client, *p);
  859. did_push = true;
  860. MESH_DEBUG_PRINTLN("loop - pushed to client %02X: %s", (uint32_t)client->id.pub_key[0], p->text);
  861. break;
  862. }
  863. idx = (idx + 1) % MAX_UNSYNCED_POSTS; // wrap to start of cyclic queue
  864. }
  865. } else {
  866. MESH_DEBUG_PRINTLN("loop - skipping busy (or evicted) client %02X", (uint32_t)client->id.pub_key[0]);
  867. }
  868. next_client_idx = (next_client_idx + 1) % acl.getNumClients(); // round robin polling for each client
  869. if (did_push) {
  870. next_push = futureMillis(SYNC_PUSH_INTERVAL);
  871. } else {
  872. // were no unsynced posts for curr client, so proccess next client much quicker! (in next loop())
  873. next_push = futureMillis(SYNC_PUSH_INTERVAL / 8);
  874. }
  875. }
  876. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  877. mesh::Packet *pkt = createSelfAdvert();
  878. uint32_t delay_millis = 0;
  879. if (pkt) sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
  880. updateFloodAdvertTimer(); // schedule next flood advert
  881. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  882. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  883. mesh::Packet *pkt = createSelfAdvert();
  884. if (pkt) sendZeroHop(pkt);
  885. updateAdvertTimer(); // schedule next local advert
  886. }
  887. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  888. set_radio_at = 0; // clear timer
  889. radio_driver.setParams(pending_freq, pending_bw, pending_sf, pending_cr);
  890. MESH_DEBUG_PRINTLN("Temp radio params");
  891. }
  892. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  893. revert_radio_at = 0; // clear timer
  894. radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  895. MESH_DEBUG_PRINTLN("Radio params restored");
  896. }
  897. // is pending dirty contacts write needed?
  898. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  899. acl.save(_fs, MyMesh::saveFilter);
  900. dirty_contacts_expiry = 0;
  901. }
  902. // TODO: periodically check for OLD/inactive entries in known_clients[], and evict
  903. // update uptime
  904. uint32_t now = millis();
  905. uptime_millis += now - last_millis;
  906. last_millis = now;
  907. }