MyMesh.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. #include "MyMesh.h"
  2. #include <algorithm>
  3. /* ------------------------------ Config -------------------------------- */
  4. #ifndef LORA_FREQ
  5. #define LORA_FREQ 915.0
  6. #endif
  7. #ifndef LORA_BW
  8. #define LORA_BW 250
  9. #endif
  10. #ifndef LORA_SF
  11. #define LORA_SF 10
  12. #endif
  13. #ifndef LORA_CR
  14. #define LORA_CR 5
  15. #endif
  16. #ifndef LORA_TX_POWER
  17. #define LORA_TX_POWER 20
  18. #endif
  19. #ifndef ADVERT_NAME
  20. #define ADVERT_NAME "repeater"
  21. #endif
  22. #ifndef ADVERT_LAT
  23. #define ADVERT_LAT 0.0
  24. #endif
  25. #ifndef ADVERT_LON
  26. #define ADVERT_LON 0.0
  27. #endif
  28. #ifndef ADMIN_PASSWORD
  29. #define ADMIN_PASSWORD "password"
  30. #endif
  31. #ifndef SERVER_RESPONSE_DELAY
  32. #define SERVER_RESPONSE_DELAY 300
  33. #endif
  34. #ifndef TXT_ACK_DELAY
  35. #define TXT_ACK_DELAY 200
  36. #endif
  37. #define FIRMWARE_VER_LEVEL 1
  38. #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
  39. #define REQ_TYPE_KEEP_ALIVE 0x02
  40. #define REQ_TYPE_GET_TELEMETRY_DATA 0x03
  41. #define REQ_TYPE_GET_ACCESS_LIST 0x05
  42. #define REQ_TYPE_GET_NEIGHBOURS 0x06
  43. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  44. #define CLI_REPLY_DELAY_MILLIS 600
  45. #define LAZY_CONTACTS_WRITE_DELAY 5000
  46. void MyMesh::putNeighbour(const mesh::Identity &id, uint32_t timestamp, float snr) {
  47. #if MAX_NEIGHBOURS // check if neighbours enabled
  48. // find existing neighbour, else use least recently updated
  49. uint32_t oldest_timestamp = 0xFFFFFFFF;
  50. NeighbourInfo *neighbour = &neighbours[0];
  51. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  52. // if neighbour already known, we should update it
  53. if (id.matches(neighbours[i].id)) {
  54. neighbour = &neighbours[i];
  55. break;
  56. }
  57. // otherwise we should update the least recently updated neighbour
  58. if (neighbours[i].heard_timestamp < oldest_timestamp) {
  59. neighbour = &neighbours[i];
  60. oldest_timestamp = neighbour->heard_timestamp;
  61. }
  62. }
  63. // update neighbour info
  64. neighbour->id = id;
  65. neighbour->advert_timestamp = timestamp;
  66. neighbour->heard_timestamp = getRTCClock()->getCurrentTime();
  67. neighbour->snr = (int8_t)(snr * 4);
  68. #endif
  69. }
  70. uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood) {
  71. ClientInfo* client = NULL;
  72. if (data[0] == 0) { // blank password, just check if sender is in ACL
  73. client = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
  74. if (client == NULL) {
  75. #if MESH_DEBUG
  76. MESH_DEBUG_PRINTLN("Login, sender not in ACL");
  77. #endif
  78. }
  79. }
  80. if (client == NULL) {
  81. uint8_t perms;
  82. if (strcmp((char *)data, _prefs.password) == 0) { // check for valid admin password
  83. perms = PERM_ACL_ADMIN;
  84. } else if (strcmp((char *)data, _prefs.guest_password) == 0) { // check guest password
  85. perms = PERM_ACL_GUEST;
  86. } else {
  87. #if MESH_DEBUG
  88. MESH_DEBUG_PRINTLN("Invalid password: %s", data);
  89. #endif
  90. return 0;
  91. }
  92. client = acl.putClient(sender, 0); // add to contacts (if not already known)
  93. if (sender_timestamp <= client->last_timestamp) {
  94. MESH_DEBUG_PRINTLN("Possible login replay attack!");
  95. return 0; // FATAL: client table is full -OR- replay attack
  96. }
  97. MESH_DEBUG_PRINTLN("Login success!");
  98. client->last_timestamp = sender_timestamp;
  99. client->last_activity = getRTCClock()->getCurrentTime();
  100. client->permissions &= ~0x03;
  101. client->permissions |= perms;
  102. memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
  103. if (perms != PERM_ACL_GUEST) { // keep number of FS writes to a minimum
  104. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  105. }
  106. }
  107. if (is_flood) {
  108. client->out_path_len = -1; // need to rediscover out_path
  109. }
  110. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  111. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  112. reply_data[4] = RESP_SERVER_LOGIN_OK;
  113. reply_data[5] = 0; // Legacy: was recommended keep-alive interval (secs / 16)
  114. reply_data[6] = client->isAdmin() ? 1 : 0;
  115. reply_data[7] = client->permissions;
  116. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  117. reply_data[12] = FIRMWARE_VER_LEVEL; // New field
  118. return 13; // reply length
  119. }
  120. int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload, size_t payload_len) {
  121. // uint32_t now = getRTCClock()->getCurrentTimeUnique();
  122. // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  123. memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
  124. if (payload[0] == REQ_TYPE_GET_STATUS) { // guests can also access this now
  125. RepeaterStats stats;
  126. stats.batt_milli_volts = board.getBattMilliVolts();
  127. stats.curr_tx_queue_len = _mgr->getOutboundCount(0xFFFFFFFF);
  128. stats.noise_floor = (int16_t)_radio->getNoiseFloor();
  129. stats.last_rssi = (int16_t)radio_driver.getLastRSSI();
  130. stats.n_packets_recv = radio_driver.getPacketsRecv();
  131. stats.n_packets_sent = radio_driver.getPacketsSent();
  132. stats.total_air_time_secs = getTotalAirTime() / 1000;
  133. stats.total_up_time_secs = uptime_millis / 1000;
  134. stats.n_sent_flood = getNumSentFlood();
  135. stats.n_sent_direct = getNumSentDirect();
  136. stats.n_recv_flood = getNumRecvFlood();
  137. stats.n_recv_direct = getNumRecvDirect();
  138. stats.err_events = _err_flags;
  139. stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
  140. stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
  141. stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
  142. stats.total_rx_air_time_secs = getReceiveAirTime() / 1000;
  143. memcpy(&reply_data[4], &stats, sizeof(stats));
  144. return 4 + sizeof(stats); // reply_len
  145. }
  146. if (payload[0] == REQ_TYPE_GET_TELEMETRY_DATA) {
  147. uint8_t perm_mask = ~(payload[1]); // NEW: first reserved byte (of 4), is now inverse mask to apply to permissions
  148. telemetry.reset();
  149. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  150. // query other sensors -- target specific
  151. if ((sender->permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_GUEST) {
  152. perm_mask = 0x00; // just base telemetry allowed
  153. }
  154. sensors.querySensors(perm_mask, telemetry);
  155. // This default temperature will be overridden by external sensors (if any)
  156. float temperature = board.getMCUTemperature();
  157. if(!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN
  158. telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature
  159. }
  160. uint8_t tlen = telemetry.getSize();
  161. memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
  162. return 4 + tlen; // reply_len
  163. }
  164. if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) {
  165. uint8_t res1 = payload[1]; // reserved for future (extra query params)
  166. uint8_t res2 = payload[2];
  167. if (res1 == 0 && res2 == 0) {
  168. uint8_t ofs = 4;
  169. for (int i = 0; i < acl.getNumClients() && ofs + 7 <= sizeof(reply_data) - 4; i++) {
  170. auto c = acl.getClientByIdx(i);
  171. if (c->permissions == 0) continue; // skip deleted entries
  172. memcpy(&reply_data[ofs], c->id.pub_key, 6); ofs += 6; // just 6-byte pub_key prefix
  173. reply_data[ofs++] = c->permissions;
  174. }
  175. return ofs;
  176. }
  177. }
  178. if (payload[0] == REQ_TYPE_GET_NEIGHBOURS) {
  179. uint8_t request_version = payload[1];
  180. if (request_version == 0) {
  181. // reply data offset (after response sender_timestamp/tag)
  182. int reply_offset = 4;
  183. // get request params
  184. uint8_t count = payload[2]; // how many neighbours to fetch (0-255)
  185. uint16_t offset;
  186. memcpy(&offset, &payload[3], 2); // offset from start of neighbours list (0-65535)
  187. uint8_t order_by = payload[5]; // how to order neighbours. 0=newest_to_oldest, 1=oldest_to_newest, 2=strongest_to_weakest, 3=weakest_to_strongest
  188. uint8_t pubkey_prefix_length = payload[6]; // how many bytes of neighbour pub key we want
  189. // we also send a 4 byte random blob in payload[7...10] to help packet uniqueness
  190. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS count=%d, offset=%d, order_by=%d, pubkey_prefix_length=%d", count, offset, order_by, pubkey_prefix_length);
  191. // clamp pub key prefix length to max pub key length
  192. if(pubkey_prefix_length > PUB_KEY_SIZE){
  193. pubkey_prefix_length = PUB_KEY_SIZE;
  194. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS invalid pubkey_prefix_length=%d clamping to %d", pubkey_prefix_length, PUB_KEY_SIZE);
  195. }
  196. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  197. int16_t neighbours_count = 0;
  198. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  199. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  200. auto neighbour = &neighbours[i];
  201. if (neighbour->heard_timestamp > 0) {
  202. sorted_neighbours[neighbours_count] = neighbour;
  203. neighbours_count++;
  204. }
  205. }
  206. // sort neighbours based on order
  207. if (order_by == 0) {
  208. // sort by newest to oldest
  209. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting newest to oldest");
  210. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  211. return a->heard_timestamp > b->heard_timestamp; // desc
  212. });
  213. } else if (order_by == 1) {
  214. // sort by oldest to newest
  215. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting oldest to newest");
  216. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  217. return a->heard_timestamp < b->heard_timestamp; // asc
  218. });
  219. } else if (order_by == 2) {
  220. // sort by strongest to weakest
  221. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting strongest to weakest");
  222. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  223. return a->snr > b->snr; // desc
  224. });
  225. } else if (order_by == 3) {
  226. // sort by weakest to strongest
  227. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting weakest to strongest");
  228. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  229. return a->snr < b->snr; // asc
  230. });
  231. }
  232. // build results buffer
  233. int results_count = 0;
  234. int results_offset = 0;
  235. uint8_t results_buffer[130];
  236. for(int index = 0; index < count && index + offset < neighbours_count; index++){
  237. // stop if we can't fit another entry in results
  238. int entry_size = pubkey_prefix_length + 4 + 1;
  239. if(results_offset + entry_size > sizeof(results_buffer)){
  240. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS no more entries can fit in results buffer");
  241. break;
  242. }
  243. // add next neighbour to results
  244. auto neighbour = sorted_neighbours[index + offset];
  245. uint32_t heard_seconds_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  246. memcpy(&results_buffer[results_offset], neighbour->id.pub_key, pubkey_prefix_length); results_offset += pubkey_prefix_length;
  247. memcpy(&results_buffer[results_offset], &heard_seconds_ago, 4); results_offset += 4;
  248. memcpy(&results_buffer[results_offset], &neighbour->snr, 1); results_offset += 1;
  249. results_count++;
  250. }
  251. // build reply
  252. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS neighbours_count=%d results_count=%d", neighbours_count, results_count);
  253. memcpy(&reply_data[reply_offset], &neighbours_count, 2); reply_offset += 2;
  254. memcpy(&reply_data[reply_offset], &results_count, 2); reply_offset += 2;
  255. memcpy(&reply_data[reply_offset], &results_buffer, results_offset); reply_offset += results_offset;
  256. return reply_offset;
  257. }
  258. }
  259. return 0; // unknown command
  260. }
  261. mesh::Packet *MyMesh::createSelfAdvert() {
  262. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  263. uint8_t app_data_len = _cli.buildAdvertData(ADV_TYPE_REPEATER, app_data);
  264. return createAdvert(self_id, app_data, app_data_len);
  265. }
  266. File MyMesh::openAppend(const char *fname) {
  267. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  268. return _fs->open(fname, FILE_O_WRITE);
  269. #elif defined(RP2040_PLATFORM)
  270. return _fs->open(fname, "a");
  271. #else
  272. return _fs->open(fname, "a", true);
  273. #endif
  274. }
  275. bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
  276. if (_prefs.disable_fwd) return false;
  277. if (packet->isRouteFlood() && packet->path_len >= _prefs.flood_max) return false;
  278. if (packet->isRouteFlood() && recv_pkt_region == NULL) {
  279. MESH_DEBUG_PRINTLN("allowPacketForward: unknown transport code, or wildcard not allowed for FLOOD packet");
  280. return false;
  281. }
  282. return true;
  283. }
  284. const char *MyMesh::getLogDateTime() {
  285. static char tmp[32];
  286. uint32_t now = getRTCClock()->getCurrentTime();
  287. DateTime dt = DateTime(now);
  288. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
  289. dt.year());
  290. return tmp;
  291. }
  292. void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
  293. #if MESH_PACKET_LOGGING
  294. Serial.print(getLogDateTime());
  295. Serial.print(" RAW: ");
  296. mesh::Utils::printHex(Serial, raw, len);
  297. Serial.println();
  298. #endif
  299. }
  300. void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
  301. #ifdef WITH_BRIDGE
  302. if (_prefs.bridge_pkt_src == 1) {
  303. bridge.sendPacket(pkt);
  304. }
  305. #endif
  306. if (_logging) {
  307. File f = openAppend(PACKET_LOG_FILE);
  308. if (f) {
  309. f.print(getLogDateTime());
  310. f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d", len,
  311. pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
  312. (int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score * 1000));
  313. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  314. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  315. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  316. } else {
  317. f.printf("\n");
  318. }
  319. f.close();
  320. }
  321. }
  322. }
  323. void MyMesh::logTx(mesh::Packet *pkt, int len) {
  324. #ifdef WITH_BRIDGE
  325. if (_prefs.bridge_pkt_src == 0) {
  326. bridge.sendPacket(pkt);
  327. }
  328. #endif
  329. if (_logging) {
  330. File f = openAppend(PACKET_LOG_FILE);
  331. if (f) {
  332. f.print(getLogDateTime());
  333. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, pkt->getPayloadType(),
  334. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  335. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  336. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  337. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  338. } else {
  339. f.printf("\n");
  340. }
  341. f.close();
  342. }
  343. }
  344. }
  345. void MyMesh::logTxFail(mesh::Packet *pkt, int len) {
  346. if (_logging) {
  347. File f = openAppend(PACKET_LOG_FILE);
  348. if (f) {
  349. f.print(getLogDateTime());
  350. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n", len, pkt->getPayloadType(),
  351. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  352. f.close();
  353. }
  354. }
  355. }
  356. int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
  357. if (_prefs.rx_delay_base <= 0.0f) return 0;
  358. return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  359. }
  360. uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) {
  361. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
  362. return getRNG()->nextInt(0, 5*t + 1);
  363. }
  364. uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
  365. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  366. return getRNG()->nextInt(0, 5*t + 1);
  367. }
  368. bool MyMesh::filterRecvFloodPacket(mesh::Packet* pkt) {
  369. // just try to determine region for packet (apply later in allowPacketForward())
  370. if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
  371. recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD);
  372. } else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) {
  373. if (region_map.getWildcard().flags & REGION_DENY_FLOOD) {
  374. recv_pkt_region = NULL;
  375. } else {
  376. recv_pkt_region = &region_map.getWildcard();
  377. }
  378. } else {
  379. recv_pkt_region = NULL;
  380. }
  381. // do normal processing
  382. return false;
  383. }
  384. void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
  385. uint8_t *data, size_t len) {
  386. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
  387. // client (unknown at this stage)
  388. uint32_t timestamp;
  389. memcpy(&timestamp, data, 4);
  390. data[len] = 0; // ensure null terminator
  391. uint8_t reply_len;
  392. if (data[4] == 0 || data[4] >= ' ') { // is password, ie. a login request
  393. reply_len = handleLoginReq(sender, secret, timestamp, &data[4], packet->isRouteFlood());
  394. //} else if (data[4] == ANON_REQ_TYPE_*) { // future type codes
  395. // TODO
  396. } else {
  397. reply_len = 0; // unknown request type
  398. }
  399. if (reply_len == 0) return; // invalid request
  400. if (packet->isRouteFlood()) {
  401. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  402. mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len,
  403. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  404. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  405. } else {
  406. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
  407. if (reply) sendFlood(reply, SERVER_RESPONSE_DELAY);
  408. }
  409. }
  410. }
  411. int MyMesh::searchPeersByHash(const uint8_t *hash) {
  412. int n = 0;
  413. for (int i = 0; i < acl.getNumClients(); i++) {
  414. if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
  415. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  416. }
  417. }
  418. return n;
  419. }
  420. void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
  421. int i = matching_peer_indexes[peer_idx];
  422. if (i >= 0 && i < acl.getNumClients()) {
  423. // lookup pre-calculated shared_secret
  424. memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
  425. } else {
  426. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  427. }
  428. }
  429. static bool isShare(const mesh::Packet *packet) {
  430. if (packet->hasTransportCodes()) {
  431. return packet->transport_codes[0] == 0 && packet->transport_codes[1] == 0; // codes { 0, 0 } means 'send to nowhere'
  432. }
  433. return false;
  434. }
  435. void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32_t timestamp,
  436. const uint8_t *app_data, size_t app_data_len) {
  437. mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
  438. // if this a zero hop advert (and not via 'Share'), add it to neighbours
  439. if (packet->path_len == 0 && !isShare(packet)) {
  440. AdvertDataParser parser(app_data, app_data_len);
  441. if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
  442. putNeighbour(id, timestamp, packet->getSNR());
  443. }
  444. }
  445. }
  446. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  447. uint8_t *data, size_t len) {
  448. int i = matching_peer_indexes[sender_idx];
  449. if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  450. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  451. return;
  452. }
  453. ClientInfo* client = acl.getClientByIdx(i);
  454. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  455. uint32_t timestamp;
  456. memcpy(&timestamp, data, 4);
  457. if (timestamp > client->last_timestamp) { // prevent replay attacks
  458. int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
  459. if (reply_len == 0) return; // invalid command
  460. client->last_timestamp = timestamp;
  461. client->last_activity = getRTCClock()->getCurrentTime();
  462. if (packet->isRouteFlood()) {
  463. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  464. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  465. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  466. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  467. } else {
  468. mesh::Packet *reply =
  469. createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  470. if (reply) {
  471. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  472. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  473. } else {
  474. sendFlood(reply, SERVER_RESPONSE_DELAY);
  475. }
  476. }
  477. }
  478. } else {
  479. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  480. }
  481. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->isAdmin()) { // a CLI command
  482. uint32_t sender_timestamp;
  483. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  484. uint8_t flags = (data[4] >> 2); // message attempt number, and other flags
  485. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  486. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  487. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
  488. bool is_retry = (sender_timestamp == client->last_timestamp);
  489. client->last_timestamp = sender_timestamp;
  490. client->last_activity = getRTCClock()->getCurrentTime();
  491. // len can be > original length, but 'text' will be padded with zeroes
  492. data[len] = 0; // need to make a C string again, with null terminator
  493. if (flags == TXT_TYPE_PLAIN) { // for legacy CLI, send Acks
  494. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove
  495. // to sender that we got it
  496. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  497. PUB_KEY_SIZE);
  498. mesh::Packet *ack = createAck(ack_hash);
  499. if (ack) {
  500. if (client->out_path_len < 0) {
  501. sendFlood(ack, TXT_ACK_DELAY);
  502. } else {
  503. sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY);
  504. }
  505. }
  506. }
  507. uint8_t temp[166];
  508. char *command = (char *)&data[5];
  509. char *reply = (char *)&temp[5];
  510. if (is_retry) {
  511. *reply = 0;
  512. } else {
  513. handleCommand(sender_timestamp, command, reply);
  514. }
  515. int text_len = strlen(reply);
  516. if (text_len > 0) {
  517. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  518. if (timestamp == sender_timestamp) {
  519. // WORKAROUND: the two timestamps need to be different, in the CLI view
  520. timestamp++;
  521. }
  522. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  523. temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
  524. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  525. if (reply) {
  526. if (client->out_path_len < 0) {
  527. sendFlood(reply, CLI_REPLY_DELAY_MILLIS);
  528. } else {
  529. sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS);
  530. }
  531. }
  532. }
  533. } else {
  534. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  535. }
  536. }
  537. }
  538. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  539. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  540. // TODO: prevent replay attacks
  541. int i = matching_peer_indexes[sender_idx];
  542. if (i >= 0 && i < acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  543. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  544. auto client = acl.getClientByIdx(i);
  545. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  546. client->last_activity = getRTCClock()->getCurrentTime();
  547. } else {
  548. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  549. }
  550. // NOTE: no reciprocal path send!!
  551. return false;
  552. }
  553. #define CTL_TYPE_NODE_DISCOVER_REQ 0x80
  554. #define CTL_TYPE_NODE_DISCOVER_RESP 0x90
  555. void MyMesh::onControlDataRecv(mesh::Packet* packet) {
  556. uint8_t type = packet->payload[0] & 0xF0; // just test upper 4 bits
  557. if (type == CTL_TYPE_NODE_DISCOVER_REQ && packet->payload_len >= 6 && discover_limiter.allow(rtc_clock.getCurrentTime())) {
  558. int i = 1;
  559. uint8_t filter = packet->payload[i++];
  560. uint32_t tag;
  561. memcpy(&tag, &packet->payload[i], 4); i += 4;
  562. uint32_t since;
  563. if (packet->payload_len >= i+4) { // optional since field
  564. memcpy(&since, &packet->payload[i], 4); i += 4;
  565. } else {
  566. since = 0;
  567. }
  568. if ((filter & (1 << ADV_TYPE_REPEATER)) != 0 && _prefs.discovery_mod_timestamp >= since) {
  569. bool prefix_only = packet->payload[0] & 1;
  570. uint8_t data[6 + PUB_KEY_SIZE];
  571. data[0] = CTL_TYPE_NODE_DISCOVER_RESP | ADV_TYPE_REPEATER; // low 4-bits for node type
  572. data[1] = packet->_snr; // let sender know the inbound SNR ( x 4)
  573. memcpy(&data[2], &tag, 4); // include tag from request, for client to match to
  574. memcpy(&data[6], self_id.pub_key, PUB_KEY_SIZE);
  575. auto resp = createControlData(data, prefix_only ? 6 + 8 : 6 + PUB_KEY_SIZE);
  576. if (resp) {
  577. sendZeroHop(resp, getRetransmitDelay(resp)*4); // apply random delay (widened x4), as multiple nodes can respond to this
  578. }
  579. }
  580. }
  581. }
  582. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  583. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  584. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  585. _cli(board, rtc, sensors, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4), region_map(key_store), temp_map(key_store),
  586. discover_limiter(4, 120) // max 4 every 2 minutes
  587. #if defined(WITH_RS232_BRIDGE)
  588. , bridge(&_prefs, WITH_RS232_BRIDGE, _mgr, &rtc)
  589. #endif
  590. #if defined(WITH_ESPNOW_BRIDGE)
  591. , bridge(&_prefs, _mgr, &rtc)
  592. #endif
  593. {
  594. last_millis = 0;
  595. uptime_millis = 0;
  596. next_local_advert = next_flood_advert = 0;
  597. dirty_contacts_expiry = 0;
  598. set_radio_at = revert_radio_at = 0;
  599. _logging = false;
  600. region_load_active = false;
  601. #if MAX_NEIGHBOURS
  602. memset(neighbours, 0, sizeof(neighbours));
  603. #endif
  604. // defaults
  605. memset(&_prefs, 0, sizeof(_prefs));
  606. _prefs.airtime_factor = 1.0; // one half
  607. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  608. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  609. _prefs.direct_tx_delay_factor = 0.2f; // was zero
  610. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  611. _prefs.node_lat = ADVERT_LAT;
  612. _prefs.node_lon = ADVERT_LON;
  613. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  614. _prefs.freq = LORA_FREQ;
  615. _prefs.sf = LORA_SF;
  616. _prefs.bw = LORA_BW;
  617. _prefs.cr = LORA_CR;
  618. _prefs.tx_power_dbm = LORA_TX_POWER;
  619. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  620. _prefs.flood_advert_interval = 12; // 12 hours
  621. _prefs.flood_max = 64;
  622. _prefs.interference_threshold = 0; // disabled
  623. // bridge defaults
  624. _prefs.bridge_enabled = 1; // enabled
  625. _prefs.bridge_delay = 500; // milliseconds
  626. _prefs.bridge_pkt_src = 0; // logTx
  627. _prefs.bridge_baud = 115200; // baud rate
  628. _prefs.bridge_channel = 1; // channel 1
  629. StrHelper::strncpy(_prefs.bridge_secret, "LVSITANOS", sizeof(_prefs.bridge_secret));
  630. // GPS defaults
  631. _prefs.gps_enabled = 0;
  632. _prefs.gps_interval = 0;
  633. _prefs.advert_loc_policy = ADVERT_LOC_PREFS;
  634. _prefs.adc_multiplier = 0.0f; // 0.0f means use default board multiplier
  635. }
  636. void MyMesh::begin(FILESYSTEM *fs) {
  637. mesh::Mesh::begin();
  638. _fs = fs;
  639. // load persisted prefs
  640. _cli.loadPrefs(_fs);
  641. acl.load(_fs);
  642. // TODO: key_store.begin();
  643. region_map.load(_fs);
  644. #if defined(WITH_BRIDGE)
  645. if (_prefs.bridge_enabled) {
  646. bridge.begin();
  647. }
  648. #endif
  649. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  650. radio_set_tx_power(_prefs.tx_power_dbm);
  651. updateAdvertTimer();
  652. updateFloodAdvertTimer();
  653. board.setAdcMultiplier(_prefs.adc_multiplier);
  654. #if ENV_INCLUDE_GPS == 1
  655. applyGpsPrefs();
  656. #endif
  657. }
  658. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  659. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  660. pending_freq = freq;
  661. pending_bw = bw;
  662. pending_sf = sf;
  663. pending_cr = cr;
  664. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  665. }
  666. bool MyMesh::formatFileSystem() {
  667. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  668. return InternalFS.format();
  669. #elif defined(RP2040_PLATFORM)
  670. return LittleFS.format();
  671. #elif defined(ESP32)
  672. return SPIFFS.format();
  673. #else
  674. #error "need to implement file system erase"
  675. return false;
  676. #endif
  677. }
  678. void MyMesh::sendSelfAdvertisement(int delay_millis) {
  679. mesh::Packet *pkt = createSelfAdvert();
  680. if (pkt) {
  681. sendFlood(pkt, delay_millis);
  682. } else {
  683. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  684. }
  685. }
  686. void MyMesh::updateAdvertTimer() {
  687. if (_prefs.advert_interval > 0) { // schedule local advert timer
  688. next_local_advert = futureMillis(((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  689. } else {
  690. next_local_advert = 0; // stop the timer
  691. }
  692. }
  693. void MyMesh::updateFloodAdvertTimer() {
  694. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  695. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  696. } else {
  697. next_flood_advert = 0; // stop the timer
  698. }
  699. }
  700. void MyMesh::dumpLogFile() {
  701. #if defined(RP2040_PLATFORM)
  702. File f = _fs->open(PACKET_LOG_FILE, "r");
  703. #else
  704. File f = _fs->open(PACKET_LOG_FILE);
  705. #endif
  706. if (f) {
  707. while (f.available()) {
  708. int c = f.read();
  709. if (c < 0) break;
  710. Serial.print((char)c);
  711. }
  712. f.close();
  713. }
  714. }
  715. void MyMesh::setTxPower(uint8_t power_dbm) {
  716. radio_set_tx_power(power_dbm);
  717. }
  718. void MyMesh::formatNeighborsReply(char *reply) {
  719. char *dp = reply;
  720. #if MAX_NEIGHBOURS
  721. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  722. int16_t neighbours_count = 0;
  723. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  724. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  725. auto neighbour = &neighbours[i];
  726. if (neighbour->heard_timestamp > 0) {
  727. sorted_neighbours[neighbours_count] = neighbour;
  728. neighbours_count++;
  729. }
  730. }
  731. // sort neighbours newest to oldest
  732. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  733. return a->heard_timestamp > b->heard_timestamp; // desc
  734. });
  735. for (int i = 0; i < neighbours_count && dp - reply < 134; i++) {
  736. NeighbourInfo *neighbour = sorted_neighbours[i];
  737. // add new line if not first item
  738. if (i > 0) *dp++ = '\n';
  739. char hex[10];
  740. // get 4 bytes of neighbour id as hex
  741. mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
  742. // add next neighbour
  743. uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  744. sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
  745. while (*dp)
  746. dp++; // find end of string
  747. }
  748. #endif
  749. if (dp == reply) { // no neighbours, need empty response
  750. strcpy(dp, "-none-");
  751. dp += 6;
  752. }
  753. *dp = 0; // null terminator
  754. }
  755. void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
  756. #if MAX_NEIGHBOURS
  757. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  758. NeighbourInfo *neighbour = &neighbours[i];
  759. if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
  760. neighbours[i] = NeighbourInfo(); // clear neighbour entry
  761. }
  762. }
  763. #endif
  764. }
  765. void MyMesh::formatStatsReply(char *reply) {
  766. StatsFormatHelper::formatCoreStats(reply, board, *_ms, _err_flags, _mgr);
  767. }
  768. void MyMesh::formatRadioStatsReply(char *reply) {
  769. StatsFormatHelper::formatRadioStats(reply, _radio, radio_driver, getTotalAirTime(), getReceiveAirTime());
  770. }
  771. void MyMesh::formatPacketStatsReply(char *reply) {
  772. StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(),
  773. getNumRecvFlood(), getNumRecvDirect());
  774. }
  775. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  776. self_id = new_id;
  777. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  778. IdentityStore store(*_fs, "");
  779. #elif defined(ESP32)
  780. IdentityStore store(*_fs, "/identity");
  781. #elif defined(RP2040_PLATFORM)
  782. IdentityStore store(*_fs, "/identity");
  783. #else
  784. #error "need to define saveIdentity()"
  785. #endif
  786. store.save("_main", self_id);
  787. }
  788. void MyMesh::clearStats() {
  789. radio_driver.resetStats();
  790. resetStats();
  791. ((SimpleMeshTables *)getTables())->resetStats();
  792. }
  793. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  794. if (region_load_active) {
  795. if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation
  796. region_map = temp_map; // copy over the temp instance as new current map
  797. region_load_active = false;
  798. sprintf(reply, "OK - loaded %d regions", region_map.getCount());
  799. } else {
  800. char *np = command;
  801. while (*np == ' ') np++; // skip indent
  802. int indent = np - command;
  803. char *ep = np;
  804. while (RegionMap::is_name_char(*ep)) ep++;
  805. if (*ep) { *ep++ = 0; } // set null terminator for end of name
  806. while (*ep && *ep != 'F') ep++; // look for (optional) flags
  807. if (indent > 0 && indent < 8 && strlen(np) > 0) {
  808. auto parent = load_stack[indent - 1];
  809. if (parent) {
  810. auto old = region_map.findByName(np);
  811. auto nw = temp_map.putRegion(np, parent->id, old ? old->id : 0); // carry-over the current ID (if name already exists)
  812. if (nw) {
  813. nw->flags = old ? old->flags : (*ep == 'F' ? 0 : REGION_DENY_FLOOD); // carry-over flags from curr
  814. load_stack[indent] = nw; // keep pointers to parent regions, to resolve parent_id's
  815. }
  816. }
  817. }
  818. reply[0] = 0;
  819. }
  820. return;
  821. }
  822. while (*command == ' ') command++; // skip leading spaces
  823. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  824. memcpy(reply, command, 3); // reflect the prefix back
  825. reply += 3;
  826. command += 3;
  827. }
  828. // handle ACL related commands
  829. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  830. char* hex = &command[8];
  831. char* sp = strchr(hex, ' '); // look for separator char
  832. if (sp == NULL) {
  833. strcpy(reply, "Err - bad params");
  834. } else {
  835. *sp++ = 0; // replace space with null terminator
  836. uint8_t pubkey[PUB_KEY_SIZE];
  837. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  838. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  839. uint8_t perms = atoi(sp);
  840. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  841. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  842. strcpy(reply, "OK");
  843. } else {
  844. strcpy(reply, "Err - invalid params");
  845. }
  846. } else {
  847. strcpy(reply, "Err - bad pubkey");
  848. }
  849. }
  850. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  851. Serial.println("ACL:");
  852. for (int i = 0; i < acl.getNumClients(); i++) {
  853. auto c = acl.getClientByIdx(i);
  854. if (c->permissions == 0) continue; // skip deleted (or guest) entries
  855. Serial.printf("%02X ", c->permissions);
  856. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  857. Serial.printf("\n");
  858. }
  859. reply[0] = 0;
  860. } else if (memcmp(command, "region", 6) == 0) {
  861. reply[0] = 0;
  862. const char* parts[4];
  863. int n = mesh::Utils::parseTextParts(command, parts, 4, ' ');
  864. if (n == 1 && sender_timestamp == 0) {
  865. region_map.exportTo(Serial);
  866. } else if (n >= 2 && strcmp(parts[1], "load") == 0) {
  867. temp_map.resetFrom(region_map); // rebuild regions in a temp instance
  868. memset(load_stack, 0, sizeof(load_stack));
  869. load_stack[0] = &temp_map.getWildcard();
  870. region_load_active = true;
  871. } else if (n >= 2 && strcmp(parts[1], "save") == 0) {
  872. _prefs.discovery_mod_timestamp = rtc_clock.getCurrentTime(); // this node is now 'modified' (for discovery info)
  873. savePrefs();
  874. bool success = region_map.save(_fs);
  875. strcpy(reply, success ? "OK" : "Err - save failed");
  876. } else if (n >= 3 && strcmp(parts[1], "allowf") == 0) {
  877. auto region = region_map.findByNamePrefix(parts[2]);
  878. if (region) {
  879. region->flags &= ~REGION_DENY_FLOOD;
  880. strcpy(reply, "OK");
  881. } else {
  882. strcpy(reply, "Err - unknown region");
  883. }
  884. } else if (n >= 3 && strcmp(parts[1], "denyf") == 0) {
  885. auto region = region_map.findByNamePrefix(parts[2]);
  886. if (region) {
  887. region->flags |= REGION_DENY_FLOOD;
  888. strcpy(reply, "OK");
  889. } else {
  890. strcpy(reply, "Err - unknown region");
  891. }
  892. } else if (n >= 3 && strcmp(parts[1], "get") == 0) {
  893. auto region = region_map.findByNamePrefix(parts[2]);
  894. if (region) {
  895. auto parent = region_map.findById(region->parent);
  896. if (parent && parent->id != 0) {
  897. sprintf(reply, " %s (%s) %s", region->name, parent->name, (region->flags & REGION_DENY_FLOOD) ? "" : "F");
  898. } else {
  899. sprintf(reply, " %s %s", region->name, (region->flags & REGION_DENY_FLOOD) ? "" : "F");
  900. }
  901. } else {
  902. strcpy(reply, "Err - unknown region");
  903. }
  904. } else if (n >= 3 && strcmp(parts[1], "home") == 0) {
  905. auto home = region_map.findByNamePrefix(parts[2]);
  906. if (home) {
  907. region_map.setHomeRegion(home);
  908. sprintf(reply, " home is now %s", home->name);
  909. } else {
  910. strcpy(reply, "Err - unknown region");
  911. }
  912. } else if (n == 2 && strcmp(parts[1], "home") == 0) {
  913. auto home = region_map.getHomeRegion();
  914. sprintf(reply, " home is %s", home ? home->name : "*");
  915. } else if (n >= 3 && strcmp(parts[1], "put") == 0) {
  916. auto parent = n >= 4 ? region_map.findByNamePrefix(parts[3]) : &region_map.getWildcard();
  917. if (parent == NULL) {
  918. strcpy(reply, "Err - unknown parent");
  919. } else {
  920. auto region = region_map.putRegion(parts[2], parent->id);
  921. if (region == NULL) {
  922. strcpy(reply, "Err - unable to put");
  923. } else {
  924. strcpy(reply, "OK");
  925. }
  926. }
  927. } else if (n >= 3 && strcmp(parts[1], "remove") == 0) {
  928. auto region = region_map.findByName(parts[2]);
  929. if (region) {
  930. if (region_map.removeRegion(*region)) {
  931. strcpy(reply, "OK");
  932. } else {
  933. strcpy(reply, "Err - not empty");
  934. }
  935. } else {
  936. strcpy(reply, "Err - not found");
  937. }
  938. } else {
  939. strcpy(reply, "Err - ??");
  940. }
  941. } else{
  942. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  943. }
  944. }
  945. void MyMesh::loop() {
  946. #ifdef WITH_BRIDGE
  947. bridge.loop();
  948. #endif
  949. mesh::Mesh::loop();
  950. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  951. mesh::Packet *pkt = createSelfAdvert();
  952. if (pkt) sendFlood(pkt);
  953. updateFloodAdvertTimer(); // schedule next flood advert
  954. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  955. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  956. mesh::Packet *pkt = createSelfAdvert();
  957. if (pkt) sendZeroHop(pkt);
  958. updateAdvertTimer(); // schedule next local advert
  959. }
  960. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  961. set_radio_at = 0; // clear timer
  962. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  963. MESH_DEBUG_PRINTLN("Temp radio params");
  964. }
  965. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  966. revert_radio_at = 0; // clear timer
  967. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  968. MESH_DEBUG_PRINTLN("Radio params restored");
  969. }
  970. // is pending dirty contacts write needed?
  971. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  972. acl.save(_fs);
  973. dirty_contacts_expiry = 0;
  974. }
  975. // update uptime
  976. uint32_t now = millis();
  977. uptime_millis += now - last_millis;
  978. last_millis = now;
  979. }
  980. // To check if there is pending work
  981. bool MyMesh::hasPendingWork() const {
  982. return _mgr->getOutboundCount(0xFFFFFFFF) > 0;
  983. }