MyMesh.cpp 49 KB

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