MyMesh.cpp 48 KB

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