MyMesh.cpp 44 KB

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