MyMesh.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. if (packet->getPathHashCount() >= _prefs.flood_max) return false;
  250. if (packet->getRouteType() == ROUTE_TYPE_FLOOD && packet->getPathHashCount() >= _prefs.flood_max_unscoped) return false;
  251. if (packet->getPayloadType() == PAYLOAD_TYPE_ADVERT && packet->getPathHashCount() >= _prefs.flood_max_advert) return false;
  252. }
  253. return true;
  254. }
  255. bool MyMesh::filterRecvFloodPacket(mesh::Packet* pkt) {
  256. // just try to determine region for packet (apply later in allowPacketForward())
  257. if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
  258. recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD);
  259. } else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) {
  260. if (region_map.getWildcard().flags & REGION_DENY_FLOOD) {
  261. recv_pkt_region = NULL;
  262. } else {
  263. recv_pkt_region = &region_map.getWildcard();
  264. }
  265. } else {
  266. recv_pkt_region = NULL;
  267. }
  268. // do normal processing
  269. return false;
  270. }
  271. void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
  272. uint8_t *data, size_t len) {
  273. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
  274. // client (unknown at this stage)
  275. uint32_t sender_timestamp, sender_sync_since;
  276. memcpy(&sender_timestamp, data, 4);
  277. memcpy(&sender_sync_since, &data[4], 4); // sender's "sync messags SINCE x" timestamp
  278. data[len] = 0; // ensure null terminator
  279. ClientInfo* client = NULL;
  280. if (data[8] == 0) { // blank password, just check if sender is in ACL
  281. client = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
  282. if (client == NULL) {
  283. #if MESH_DEBUG
  284. MESH_DEBUG_PRINTLN("Login, sender not in ACL");
  285. #endif
  286. }
  287. }
  288. if (client == NULL) {
  289. uint8_t perm;
  290. if (strcmp((char *)&data[8], _prefs.password) == 0) { // check for valid admin password
  291. perm = PERM_ACL_ADMIN;
  292. } else {
  293. if (strcmp((char *)&data[8], _prefs.guest_password) == 0) { // check the room/public password
  294. perm = PERM_ACL_READ_WRITE;
  295. } else if (_prefs.allow_read_only) {
  296. perm = PERM_ACL_GUEST;
  297. } else {
  298. MESH_DEBUG_PRINTLN("Incorrect room password");
  299. return; // no response. Client will timeout
  300. }
  301. }
  302. client = acl.putClient(sender, 0); // add to known clients (if not already known)
  303. if (sender_timestamp <= client->last_timestamp) {
  304. MESH_DEBUG_PRINTLN("possible replay attack!");
  305. return;
  306. }
  307. MESH_DEBUG_PRINTLN("Login success!");
  308. client->last_timestamp = sender_timestamp;
  309. client->extra.room.sync_since = sender_sync_since;
  310. client->extra.room.pending_ack = 0;
  311. client->extra.room.push_failures = 0;
  312. client->last_activity = getRTCClock()->getCurrentTime();
  313. client->permissions &= ~0x03;
  314. client->permissions |= perm;
  315. memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
  316. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  317. }
  318. if (packet->isRouteFlood()) {
  319. client->out_path_len = OUT_PATH_UNKNOWN; // need to rediscover out_path
  320. }
  321. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  322. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  323. // TODO: maybe reply with count of messages waiting to be synced for THIS client?
  324. reply_data[4] = RESP_SERVER_LOGIN_OK;
  325. reply_data[5] = 0; // Legacy: was recommended keep-alive interval (secs / 16)
  326. reply_data[6] = (client->isAdmin() ? 1 : (client->permissions == 0 ? 2 : 0));
  327. // LEGACY: reply_data[7] = getUnsyncedCount(client);
  328. reply_data[7] = client->permissions; // NEW
  329. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  330. reply_data[12] = FIRMWARE_VER_LEVEL; // New field
  331. next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS); // delay next push, give RESPONSE packet time to arrive first
  332. if (packet->isRouteFlood()) {
  333. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  334. mesh::Packet *path = createPathReturn(sender, client->shared_secret, packet->path, packet->path_len,
  335. PAYLOAD_TYPE_RESPONSE, reply_data, 13);
  336. if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  337. } else {
  338. mesh::Packet *reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->shared_secret, reply_data, 13);
  339. if (reply) {
  340. if (client->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
  341. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  342. } else {
  343. sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  344. }
  345. }
  346. }
  347. }
  348. }
  349. int MyMesh::searchPeersByHash(const uint8_t *hash) {
  350. int n = 0;
  351. for (int i = 0; i < acl.getNumClients(); i++) {
  352. if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
  353. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  354. }
  355. }
  356. return n;
  357. }
  358. void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
  359. int i = matching_peer_indexes[peer_idx];
  360. if (i >= 0 && i < acl.getNumClients()) {
  361. // lookup pre-calculated shared_secret
  362. memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
  363. } else {
  364. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  365. }
  366. }
  367. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  368. uint8_t *data, size_t len) {
  369. int i = matching_peer_indexes[sender_idx];
  370. if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  371. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  372. return;
  373. }
  374. auto client = acl.getClientByIdx(i);
  375. if (type == PAYLOAD_TYPE_TXT_MSG && len > 5) { // a CLI command or new Post
  376. uint32_t sender_timestamp;
  377. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  378. uint8_t flags = (data[4] >> 2); // message attempt number, and other flags
  379. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  380. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported command flags received: flags=%02x", (uint32_t)flags);
  381. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks, but send Acks for retries
  382. bool is_retry = (sender_timestamp == client->last_timestamp);
  383. client->last_timestamp = sender_timestamp;
  384. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  385. client->last_activity = now;
  386. client->extra.room.push_failures = 0; // reset so push can resume (if prev failed)
  387. // len can be > original length, but 'text' will be padded with zeroes
  388. data[len] = 0; // need to make a C string again, with null terminator
  389. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to
  390. // sender that we got it
  391. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  392. PUB_KEY_SIZE);
  393. uint8_t temp[166];
  394. bool send_ack;
  395. if (flags == TXT_TYPE_CLI_DATA) {
  396. if (client->isAdmin()) {
  397. if (is_retry) {
  398. temp[5] = 0; // no reply
  399. } else {
  400. handleCommand(sender_timestamp, (char *)&data[5], (char *)&temp[5]);
  401. temp[4] = (TXT_TYPE_CLI_DATA << 2); // attempt and flags, (NOTE: legacy was: TXT_TYPE_PLAIN)
  402. }
  403. send_ack = false;
  404. } else {
  405. temp[5] = 0; // no reply
  406. send_ack = false; // and no ACK... user shoudn't be sending these
  407. }
  408. } else { // TXT_TYPE_PLAIN
  409. if ((client->permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_GUEST) {
  410. temp[5] = 0; // no reply
  411. send_ack = false; // no ACK
  412. } else {
  413. if (!is_retry) {
  414. addPost(client, (const char *)&data[5]);
  415. }
  416. temp[5] = 0; // no reply (ACK is enough)
  417. send_ack = true;
  418. }
  419. }
  420. uint32_t delay_millis;
  421. if (send_ack) {
  422. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  423. mesh::Packet *ack = createAck(ack_hash);
  424. if (ack) sendFloodReply(ack, TXT_ACK_DELAY, packet->getPathHashSize());
  425. delay_millis = TXT_ACK_DELAY + REPLY_DELAY_MILLIS;
  426. } else {
  427. uint32_t d = TXT_ACK_DELAY;
  428. if (getExtraAckTransmitCount() > 0) {
  429. mesh::Packet *a1 = createMultiAck(ack_hash, 1);
  430. if (a1) sendDirect(a1, client->out_path, client->out_path_len, d);
  431. d += 300;
  432. }
  433. mesh::Packet *a2 = createAck(ack_hash);
  434. if (a2) sendDirect(a2, client->out_path, client->out_path_len, d);
  435. delay_millis = d + REPLY_DELAY_MILLIS;
  436. }
  437. } else {
  438. delay_millis = 0;
  439. }
  440. int text_len = strlen((char *)&temp[5]);
  441. if (text_len > 0) {
  442. if (now == sender_timestamp) {
  443. // WORKAROUND: the two timestamps need to be different, in the CLI view
  444. now++;
  445. }
  446. memcpy(temp, &now, 4); // mostly an extra blob to help make packet_hash unique
  447. // calc expected ACK reply
  448. // mesh::Utils::sha256((uint8_t *)&expected_ack_crc, 4, temp, 5 + text_len, self_id.pub_key,
  449. // PUB_KEY_SIZE);
  450. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  451. if (reply) {
  452. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  453. sendFloodReply(reply, delay_millis + SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  454. } else {
  455. sendDirect(reply, client->out_path, client->out_path_len, delay_millis + SERVER_RESPONSE_DELAY);
  456. }
  457. }
  458. }
  459. } else {
  460. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  461. }
  462. } else if (type == PAYLOAD_TYPE_REQ && len >= 5) {
  463. uint32_t sender_timestamp;
  464. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  465. if (sender_timestamp < client->last_timestamp) { // prevent replay attacks
  466. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  467. } else {
  468. client->last_timestamp = sender_timestamp;
  469. uint32_t now = getRTCClock()->getCurrentTime();
  470. client->last_activity = now; // <-- THIS will keep client connection alive
  471. client->extra.room.push_failures = 0; // reset so push can resume (if prev failed)
  472. if (data[4] == REQ_TYPE_KEEP_ALIVE && packet->isRouteDirect()) { // request type
  473. uint32_t forceSince = 0;
  474. if (len >= 9) { // optional - last post_timestamp client received
  475. memcpy(&forceSince, &data[5], 4); // NOTE: this may be 0, if part of decrypted PADDING!
  476. } else {
  477. memcpy(&data[5], &forceSince, 4); // make sure there are zeroes in payload (for ack_hash calc below)
  478. }
  479. if (forceSince > 0) {
  480. client->extra.room.sync_since = forceSince; // force-update the 'sync since'
  481. }
  482. client->extra.room.pending_ack = 0;
  483. // TODO: Throttle KEEP_ALIVE requests!
  484. // if client sends too quickly, evict()
  485. // RULE: only send keep_alive response DIRECT!
  486. if (client->out_path_len != OUT_PATH_UNKNOWN) {
  487. uint32_t ack_hash; // calc ACK to prove to sender that we got request
  488. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 9, client->id.pub_key, PUB_KEY_SIZE);
  489. auto reply = createAck(ack_hash);
  490. if (reply) {
  491. reply->payload[reply->payload_len++] = getUnsyncedCount(client); // NEW: add unsynced counter to end of ACK packet
  492. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  493. }
  494. }
  495. } else {
  496. int reply_len = handleRequest(client, sender_timestamp, &data[4], len - 4);
  497. if (reply_len > 0) { // valid command
  498. if (packet->isRouteFlood()) {
  499. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  500. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  501. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  502. if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  503. } else {
  504. mesh::Packet *reply = createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  505. if (reply) {
  506. if (client->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
  507. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  508. } else {
  509. sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  510. }
  511. }
  512. }
  513. }
  514. }
  515. }
  516. }
  517. }
  518. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  519. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  520. // TODO: prevent replay attacks
  521. int i = matching_peer_indexes[sender_idx];
  522. if (i >= 0 && i < acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  523. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  524. auto client = acl.getClientByIdx(i);
  525. client->out_path_len = mesh::Packet::copyPath(client->out_path, path, path_len); // store a copy of path, for sendDirect()
  526. client->last_activity = getRTCClock()->getCurrentTime();
  527. } else {
  528. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  529. }
  530. if (extra_type == PAYLOAD_TYPE_ACK && extra_len >= 4) {
  531. // also got an encoded ACK!
  532. processAck(extra);
  533. }
  534. // NOTE: no reciprocal path send!!
  535. return false;
  536. }
  537. void MyMesh::onAckRecv(mesh::Packet *packet, uint32_t ack_crc) {
  538. if (processAck((uint8_t *)&ack_crc)) {
  539. packet->markDoNotRetransmit(); // ACK was for this node, so don't retransmit
  540. }
  541. }
  542. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  543. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  544. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  545. region_map(key_store), temp_map(key_store),
  546. _cli(board, rtc, sensors, region_map, acl, &_prefs, this),
  547. telemetry(MAX_PACKET_PAYLOAD - 4)
  548. {
  549. last_millis = 0;
  550. uptime_millis = 0;
  551. next_local_advert = next_flood_advert = 0;
  552. dirty_contacts_expiry = 0;
  553. _logging = false;
  554. region_load_active = false;
  555. set_radio_at = revert_radio_at = 0;
  556. // defaults
  557. memset(&_prefs, 0, sizeof(_prefs));
  558. _prefs.airtime_factor = 1.0;
  559. _prefs.rx_delay_base = 0.0f; // off by default, was 10.0
  560. _prefs.tx_delay_factor = 0.5f; // was 0.25f;
  561. _prefs.direct_tx_delay_factor = 0.2f; // was zero
  562. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  563. _prefs.node_lat = ADVERT_LAT;
  564. _prefs.node_lon = ADVERT_LON;
  565. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  566. _prefs.freq = LORA_FREQ;
  567. _prefs.sf = LORA_SF;
  568. _prefs.bw = LORA_BW;
  569. _prefs.cr = LORA_CR;
  570. _prefs.tx_power_dbm = LORA_TX_POWER;
  571. _prefs.disable_fwd = 1;
  572. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  573. _prefs.flood_advert_interval = 47; // 47 hours
  574. _prefs.flood_max = 64;
  575. _prefs.flood_max_unscoped = 64;
  576. _prefs.flood_max_advert = 8;
  577. _prefs.interference_threshold = 0; // disabled
  578. #ifdef ROOM_PASSWORD
  579. StrHelper::strncpy(_prefs.guest_password, ROOM_PASSWORD, sizeof(_prefs.guest_password));
  580. #endif
  581. // GPS defaults
  582. _prefs.gps_enabled = 0;
  583. _prefs.gps_interval = 0;
  584. _prefs.advert_loc_policy = ADVERT_LOC_PREFS;
  585. next_post_idx = 0;
  586. next_client_idx = 0;
  587. next_push = 0;
  588. memset(posts, 0, sizeof(posts));
  589. _num_posted = _num_post_pushes = 0;
  590. memset(default_scope.key, 0, sizeof(default_scope.key));
  591. }
  592. void MyMesh::begin(FILESYSTEM *fs) {
  593. mesh::Mesh::begin();
  594. _fs = fs;
  595. // load persisted prefs
  596. _cli.loadPrefs(_fs);
  597. acl.load(_fs, self_id);
  598. region_map.load(_fs);
  599. // establish default-scope
  600. {
  601. RegionEntry* r = region_map.getDefaultRegion();
  602. if (r) {
  603. region_map.getTransportKeysFor(*r, &default_scope, 1);
  604. } else {
  605. #ifdef DEFAULT_FLOOD_SCOPE_NAME
  606. r = region_map.findByName(DEFAULT_FLOOD_SCOPE_NAME);
  607. if (r == NULL) {
  608. r = region_map.putRegion(DEFAULT_FLOOD_SCOPE_NAME, 0); // auto-create the default scope region
  609. if (r) { r->flags = 0; } // Allow-flood
  610. }
  611. if (r) {
  612. region_map.setDefaultRegion(r);
  613. region_map.getTransportKeysFor(*r, &default_scope, 1);
  614. }
  615. #endif
  616. }
  617. }
  618. radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  619. radio_driver.setTxPower(_prefs.tx_power_dbm);
  620. updateAdvertTimer();
  621. updateFloodAdvertTimer();
  622. board.setAdcMultiplier(_prefs.adc_multiplier);
  623. #if ENV_INCLUDE_GPS == 1
  624. applyGpsPrefs();
  625. #endif
  626. }
  627. void MyMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size) {
  628. if (scope.isNull()) {
  629. sendFlood(pkt, delay_millis, path_hash_size);
  630. } else {
  631. uint16_t codes[2];
  632. codes[0] = scope.calcTransportCode(pkt);
  633. codes[1] = 0; // REVISIT: set to 'home' Region, for sender/return region?
  634. sendFlood(pkt, codes, delay_millis, path_hash_size);
  635. }
  636. }
  637. void MyMesh::sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size) {
  638. if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // if _request_ packet scope is known, send reply with same scope
  639. TransportKey scope;
  640. if (region_map.getTransportKeysFor(*recv_pkt_region, &scope, 1) > 0) {
  641. sendFloodScoped(scope, packet, delay_millis, path_hash_size);
  642. } else {
  643. sendFlood(packet, delay_millis, path_hash_size); // send un-scoped
  644. }
  645. } else {
  646. sendFlood(packet, delay_millis, path_hash_size); // send un-scoped
  647. }
  648. }
  649. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  650. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  651. pending_freq = freq;
  652. pending_bw = bw;
  653. pending_sf = sf;
  654. pending_cr = cr;
  655. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  656. }
  657. bool MyMesh::formatFileSystem() {
  658. #if defined(NRF52_PLATFORM)
  659. return InternalFS.format();
  660. #elif defined(RP2040_PLATFORM)
  661. return LittleFS.format();
  662. #elif defined(ESP32)
  663. return SPIFFS.format();
  664. #else
  665. #error "need to implement file system erase"
  666. return false;
  667. #endif
  668. }
  669. void MyMesh::sendSelfAdvertisement(int delay_millis, bool flood) {
  670. mesh::Packet *pkt = createSelfAdvert();
  671. if (pkt) {
  672. if (flood) {
  673. sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
  674. } else {
  675. sendZeroHop(pkt, delay_millis);
  676. }
  677. } else {
  678. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  679. }
  680. }
  681. void MyMesh::updateAdvertTimer() {
  682. if (_prefs.advert_interval > 0) { // schedule local advert timer
  683. next_local_advert = futureMillis((uint32_t)_prefs.advert_interval * 2 * 60 * 1000);
  684. } else {
  685. next_local_advert = 0; // stop the timer
  686. }
  687. }
  688. void MyMesh::updateFloodAdvertTimer() {
  689. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  690. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  691. } else {
  692. next_flood_advert = 0; // stop the timer
  693. }
  694. }
  695. void MyMesh::dumpLogFile() {
  696. #if defined(RP2040_PLATFORM)
  697. File f = _fs->open(PACKET_LOG_FILE, "r");
  698. #else
  699. File f = _fs->open(PACKET_LOG_FILE);
  700. #endif
  701. if (f) {
  702. while (f.available()) {
  703. int c = f.read();
  704. if (c < 0) break;
  705. Serial.print((char)c);
  706. }
  707. f.close();
  708. }
  709. }
  710. void MyMesh::setTxPower(int8_t power_dbm) {
  711. radio_driver.setTxPower(power_dbm);
  712. }
  713. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  714. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  715. IdentityStore store(*_fs, "");
  716. #elif defined(ESP32)
  717. IdentityStore store(*_fs, "/identity");
  718. #elif defined(RP2040_PLATFORM)
  719. IdentityStore store(*_fs, "/identity");
  720. #else
  721. #error "need to define saveIdentity()"
  722. #endif
  723. store.save("_main", new_id);
  724. }
  725. void MyMesh::startRegionsLoad() {
  726. temp_map.resetFrom(region_map); // rebuild regions in a temp instance
  727. memset(load_stack, 0, sizeof(load_stack));
  728. load_stack[0] = &temp_map.getWildcard();
  729. region_load_active = true;
  730. }
  731. bool MyMesh::saveRegions() {
  732. return region_map.save(_fs);
  733. }
  734. void MyMesh::onDefaultRegionChanged(const RegionEntry* r) {
  735. if (r) {
  736. region_map.getTransportKeysFor(*r, &default_scope, 1);
  737. } else {
  738. memset(default_scope.key, 0, sizeof(default_scope.key));
  739. }
  740. }
  741. void MyMesh::clearStats() {
  742. radio_driver.resetStats();
  743. resetStats();
  744. ((SimpleMeshTables *)getTables())->resetStats();
  745. }
  746. void MyMesh::formatStatsReply(char *reply) {
  747. StatsFormatHelper::formatCoreStats(reply, board, *_ms, _err_flags, _mgr);
  748. }
  749. void MyMesh::formatRadioStatsReply(char *reply) {
  750. StatsFormatHelper::formatRadioStats(reply, _radio, radio_driver, getTotalAirTime(), getReceiveAirTime());
  751. }
  752. void MyMesh::formatPacketStatsReply(char *reply) {
  753. StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(),
  754. getNumRecvFlood(), getNumRecvDirect());
  755. }
  756. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  757. if (region_load_active) {
  758. if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation
  759. region_map = temp_map; // copy over the temp instance as new current map
  760. region_load_active = false;
  761. sprintf(reply, "OK - loaded %d regions", region_map.getCount());
  762. } else {
  763. char *np = command;
  764. while (*np == ' ') np++; // skip indent
  765. int indent = np - command;
  766. char *ep = np;
  767. while (RegionMap::is_name_char(*ep)) ep++;
  768. if (*ep) { *ep++ = 0; } // set null terminator for end of name
  769. while (*ep && *ep != 'F') ep++; // look for (optional) flags
  770. if (indent > 0 && indent < 8 && strlen(np) > 0) {
  771. auto parent = load_stack[indent - 1];
  772. if (parent) {
  773. auto old = region_map.findByName(np);
  774. auto nw = temp_map.putRegion(np, parent->id, old ? old->id : 0); // carry-over the current ID (if name already exists)
  775. if (nw) {
  776. nw->flags = old ? old->flags : (*ep == 'F' ? 0 : REGION_DENY_FLOOD); // carry-over flags from curr
  777. load_stack[indent] = nw; // keep pointers to parent regions, to resolve parent_id's
  778. }
  779. }
  780. }
  781. reply[0] = 0;
  782. }
  783. return;
  784. }
  785. while (*command == ' ')
  786. command++; // skip leading spaces
  787. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  788. memcpy(reply, command, 3); // reflect the prefix back
  789. reply += 3;
  790. command += 3;
  791. }
  792. // handle ACL related commands
  793. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  794. char* hex = &command[8];
  795. char* sp = strchr(hex, ' '); // look for separator char
  796. if (sp == NULL) {
  797. strcpy(reply, "Err - bad params");
  798. } else {
  799. *sp++ = 0; // replace space with null terminator
  800. uint8_t pubkey[PUB_KEY_SIZE];
  801. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  802. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  803. uint8_t perms = atoi(sp);
  804. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  805. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  806. strcpy(reply, "OK");
  807. } else {
  808. strcpy(reply, "Err - invalid params");
  809. }
  810. } else {
  811. strcpy(reply, "Err - bad pubkey");
  812. }
  813. }
  814. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  815. Serial.println("ACL:");
  816. for (int i = 0; i < acl.getNumClients(); i++) {
  817. auto c = acl.getClientByIdx(i);
  818. if (c->permissions == 0) continue; // skip deleted (or guest) entries
  819. Serial.printf("%02X ", c->permissions);
  820. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  821. Serial.printf("\n");
  822. }
  823. reply[0] = 0;
  824. } else{
  825. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  826. }
  827. }
  828. bool MyMesh::saveFilter(ClientInfo* client) {
  829. return client->isAdmin(); // only save Admins
  830. }
  831. void MyMesh::loop() {
  832. mesh::Mesh::loop();
  833. if (millisHasNowPassed(next_push) && acl.getNumClients() > 0) {
  834. // check for ACK timeouts
  835. for (int i = 0; i < acl.getNumClients(); i++) {
  836. auto c = acl.getClientByIdx(i);
  837. if (c->extra.room.pending_ack && millisHasNowPassed(c->extra.room.ack_timeout)) {
  838. c->extra.room.push_failures++;
  839. c->extra.room.pending_ack = 0; // reset (TODO: keep prev expected_ack's in a list, incase they arrive LATER, after we retry)
  840. MESH_DEBUG_PRINTLN("pending ACK timed out: push_failures: %d", (uint32_t)c->extra.room.push_failures);
  841. }
  842. }
  843. // check next Round-Robin client, and sync next new post
  844. auto client = acl.getClientByIdx(next_client_idx);
  845. bool did_push = false;
  846. if (client->extra.room.pending_ack == 0 && client->last_activity != 0 &&
  847. client->extra.room.push_failures < 3) { // not already waiting for ACK, AND not evicted, AND retries not max
  848. MESH_DEBUG_PRINTLN("loop - checking for client %02X", (uint32_t)client->id.pub_key[0]);
  849. uint32_t now = getRTCClock()->getCurrentTime();
  850. for (int k = 0, idx = next_post_idx; k < MAX_UNSYNCED_POSTS; k++) {
  851. auto p = &posts[idx];
  852. if (now >= p->post_timestamp + POST_SYNC_DELAY_SECS &&
  853. p->post_timestamp > client->extra.room.sync_since // is new post for this Client?
  854. && !p->author.matches(client->id)) { // don't push posts to the author
  855. // push this post to Client, then wait for ACK
  856. pushPostToClient(client, *p);
  857. did_push = true;
  858. MESH_DEBUG_PRINTLN("loop - pushed to client %02X: %s", (uint32_t)client->id.pub_key[0], p->text);
  859. break;
  860. }
  861. idx = (idx + 1) % MAX_UNSYNCED_POSTS; // wrap to start of cyclic queue
  862. }
  863. } else {
  864. MESH_DEBUG_PRINTLN("loop - skipping busy (or evicted) client %02X", (uint32_t)client->id.pub_key[0]);
  865. }
  866. next_client_idx = (next_client_idx + 1) % acl.getNumClients(); // round robin polling for each client
  867. if (did_push) {
  868. next_push = futureMillis(SYNC_PUSH_INTERVAL);
  869. } else {
  870. // were no unsynced posts for curr client, so process next client much quicker! (in next loop())
  871. next_push = futureMillis(SYNC_PUSH_INTERVAL / 8);
  872. }
  873. }
  874. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  875. mesh::Packet *pkt = createSelfAdvert();
  876. uint32_t delay_millis = 0;
  877. if (pkt) sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
  878. updateFloodAdvertTimer(); // schedule next flood advert
  879. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  880. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  881. mesh::Packet *pkt = createSelfAdvert();
  882. if (pkt) sendZeroHop(pkt);
  883. updateAdvertTimer(); // schedule next local advert
  884. }
  885. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  886. set_radio_at = 0; // clear timer
  887. radio_driver.setParams(pending_freq, pending_bw, pending_sf, pending_cr);
  888. MESH_DEBUG_PRINTLN("Temp radio params");
  889. }
  890. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  891. revert_radio_at = 0; // clear timer
  892. radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  893. MESH_DEBUG_PRINTLN("Radio params restored");
  894. }
  895. // is pending dirty contacts write needed?
  896. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  897. acl.save(_fs, MyMesh::saveFilter);
  898. dirty_contacts_expiry = 0;
  899. }
  900. // TODO: periodically check for OLD/inactive entries in known_clients[], and evict
  901. // update uptime
  902. uint32_t now = millis();
  903. uptime_millis += now - last_millis;
  904. last_millis = now;
  905. }