MyMesh.cpp 40 KB

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