MyMesh.cpp 45 KB

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