MyMesh.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. #include "MyMesh.h"
  2. #include <algorithm>
  3. /* ------------------------------ Config -------------------------------- */
  4. #ifndef LORA_FREQ
  5. #define LORA_FREQ 915.0
  6. #endif
  7. #ifndef LORA_BW
  8. #define LORA_BW 250
  9. #endif
  10. #ifndef LORA_SF
  11. #define LORA_SF 10
  12. #endif
  13. #ifndef LORA_CR
  14. #define LORA_CR 5
  15. #endif
  16. #ifndef LORA_TX_POWER
  17. #define LORA_TX_POWER 20
  18. #endif
  19. #ifndef ADVERT_NAME
  20. #define ADVERT_NAME "repeater"
  21. #endif
  22. #ifndef ADVERT_LAT
  23. #define ADVERT_LAT 0.0
  24. #endif
  25. #ifndef ADVERT_LON
  26. #define ADVERT_LON 0.0
  27. #endif
  28. #ifndef ADMIN_PASSWORD
  29. #define ADMIN_PASSWORD "password"
  30. #endif
  31. #ifndef SERVER_RESPONSE_DELAY
  32. #define SERVER_RESPONSE_DELAY 300
  33. #endif
  34. #ifndef TXT_ACK_DELAY
  35. #define TXT_ACK_DELAY 200
  36. #endif
  37. #define FIRMWARE_VER_LEVEL 1
  38. #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
  39. #define REQ_TYPE_KEEP_ALIVE 0x02
  40. #define REQ_TYPE_GET_TELEMETRY_DATA 0x03
  41. #define REQ_TYPE_GET_ACCESS_LIST 0x05
  42. #define REQ_TYPE_GET_NEIGHBOURS 0x06
  43. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  44. #define CLI_REPLY_DELAY_MILLIS 600
  45. #define LAZY_CONTACTS_WRITE_DELAY 5000
  46. void MyMesh::putNeighbour(const mesh::Identity &id, uint32_t timestamp, float snr) {
  47. #if MAX_NEIGHBOURS // check if neighbours enabled
  48. // find existing neighbour, else use least recently updated
  49. uint32_t oldest_timestamp = 0xFFFFFFFF;
  50. NeighbourInfo *neighbour = &neighbours[0];
  51. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  52. // if neighbour already known, we should update it
  53. if (id.matches(neighbours[i].id)) {
  54. neighbour = &neighbours[i];
  55. break;
  56. }
  57. // otherwise we should update the least recently updated neighbour
  58. if (neighbours[i].heard_timestamp < oldest_timestamp) {
  59. neighbour = &neighbours[i];
  60. oldest_timestamp = neighbour->heard_timestamp;
  61. }
  62. }
  63. // update neighbour info
  64. neighbour->id = id;
  65. neighbour->advert_timestamp = timestamp;
  66. neighbour->heard_timestamp = getRTCClock()->getCurrentTime();
  67. neighbour->snr = (int8_t)(snr * 4);
  68. #endif
  69. }
  70. uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data) {
  71. ClientInfo* client = NULL;
  72. if (data[0] == 0) { // blank password, just check if sender is in ACL
  73. client = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
  74. if (client == NULL) {
  75. #if MESH_DEBUG
  76. MESH_DEBUG_PRINTLN("Login, sender not in ACL");
  77. #endif
  78. }
  79. }
  80. if (client == NULL) {
  81. uint8_t perms;
  82. if (strcmp((char *)data, _prefs.password) == 0) { // check for valid admin password
  83. perms = PERM_ACL_ADMIN;
  84. } else if (strcmp((char *)data, _prefs.guest_password) == 0) { // check guest password
  85. perms = PERM_ACL_GUEST;
  86. } else {
  87. #if MESH_DEBUG
  88. MESH_DEBUG_PRINTLN("Invalid password: %s", data);
  89. #endif
  90. return 0;
  91. }
  92. client = acl.putClient(sender, 0); // add to contacts (if not already known)
  93. if (sender_timestamp <= client->last_timestamp) {
  94. MESH_DEBUG_PRINTLN("Possible login replay attack!");
  95. return 0; // FATAL: client table is full -OR- replay attack
  96. }
  97. MESH_DEBUG_PRINTLN("Login success!");
  98. client->last_timestamp = sender_timestamp;
  99. client->last_activity = getRTCClock()->getCurrentTime();
  100. client->permissions |= perms;
  101. memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
  102. if (perms != PERM_ACL_GUEST) { // keep number of FS writes to a minimum
  103. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  104. }
  105. }
  106. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  107. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  108. reply_data[4] = RESP_SERVER_LOGIN_OK;
  109. reply_data[5] = 0; // Legacy: was recommended keep-alive interval (secs / 16)
  110. reply_data[6] = client->isAdmin() ? 1 : 0;
  111. reply_data[7] = client->permissions;
  112. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  113. reply_data[12] = FIRMWARE_VER_LEVEL; // New field
  114. return 13; // reply length
  115. }
  116. int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload, size_t payload_len) {
  117. // uint32_t now = getRTCClock()->getCurrentTimeUnique();
  118. // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  119. memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
  120. if (payload[0] == REQ_TYPE_GET_STATUS) { // guests can also access this now
  121. RepeaterStats stats;
  122. stats.batt_milli_volts = board.getBattMilliVolts();
  123. stats.curr_tx_queue_len = _mgr->getOutboundCount(0xFFFFFFFF);
  124. stats.noise_floor = (int16_t)_radio->getNoiseFloor();
  125. stats.last_rssi = (int16_t)radio_driver.getLastRSSI();
  126. stats.n_packets_recv = radio_driver.getPacketsRecv();
  127. stats.n_packets_sent = radio_driver.getPacketsSent();
  128. stats.total_air_time_secs = getTotalAirTime() / 1000;
  129. stats.total_up_time_secs = _ms->getMillis() / 1000;
  130. stats.n_sent_flood = getNumSentFlood();
  131. stats.n_sent_direct = getNumSentDirect();
  132. stats.n_recv_flood = getNumRecvFlood();
  133. stats.n_recv_direct = getNumRecvDirect();
  134. stats.err_events = _err_flags;
  135. stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
  136. stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
  137. stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
  138. stats.total_rx_air_time_secs = getReceiveAirTime() / 1000;
  139. memcpy(&reply_data[4], &stats, sizeof(stats));
  140. return 4 + sizeof(stats); // reply_len
  141. }
  142. if (payload[0] == REQ_TYPE_GET_TELEMETRY_DATA) {
  143. uint8_t perm_mask = ~(payload[1]); // NEW: first reserved byte (of 4), is now inverse mask to apply to permissions
  144. telemetry.reset();
  145. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  146. // query other sensors -- target specific
  147. sensors.querySensors((sender->isAdmin() ? 0xFF : 0x00) & perm_mask, telemetry);
  148. uint8_t tlen = telemetry.getSize();
  149. memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
  150. return 4 + tlen; // reply_len
  151. }
  152. if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) {
  153. uint8_t res1 = payload[1]; // reserved for future (extra query params)
  154. uint8_t res2 = payload[2];
  155. if (res1 == 0 && res2 == 0) {
  156. uint8_t ofs = 4;
  157. for (int i = 0; i < acl.getNumClients() && ofs + 7 <= sizeof(reply_data) - 4; i++) {
  158. auto c = acl.getClientByIdx(i);
  159. if (c->permissions == 0) continue; // skip deleted entries
  160. memcpy(&reply_data[ofs], c->id.pub_key, 6); ofs += 6; // just 6-byte pub_key prefix
  161. reply_data[ofs++] = c->permissions;
  162. }
  163. return ofs;
  164. }
  165. }
  166. if (payload[0] == REQ_TYPE_GET_NEIGHBOURS) {
  167. uint8_t request_version = payload[1];
  168. if (request_version == 0) {
  169. // reply data offset (after response sender_timestamp/tag)
  170. int reply_offset = 4;
  171. // get request params
  172. uint8_t count = payload[2]; // how many neighbours to fetch (0-255)
  173. uint16_t offset;
  174. memcpy(&offset, &payload[3], 2); // offset from start of neighbours list (0-65535)
  175. 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
  176. uint8_t pubkey_prefix_length = payload[6]; // how many bytes of neighbour pub key we want
  177. // we also send a 4 byte random blob in payload[7...10] to help packet uniqueness
  178. 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);
  179. // clamp pub key prefix length to max pub key length
  180. if(pubkey_prefix_length > PUB_KEY_SIZE){
  181. pubkey_prefix_length = PUB_KEY_SIZE;
  182. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS invalid pubkey_prefix_length=%d clamping to %d", pubkey_prefix_length, PUB_KEY_SIZE);
  183. }
  184. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  185. int16_t neighbours_count = 0;
  186. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  187. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  188. auto neighbour = &neighbours[i];
  189. if (neighbour->heard_timestamp > 0) {
  190. sorted_neighbours[neighbours_count] = neighbour;
  191. neighbours_count++;
  192. }
  193. }
  194. // sort neighbours based on order
  195. if (order_by == 0) {
  196. // sort by newest to oldest
  197. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting newest to oldest");
  198. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  199. return a->heard_timestamp > b->heard_timestamp; // desc
  200. });
  201. } else if (order_by == 1) {
  202. // sort by oldest to newest
  203. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting oldest to newest");
  204. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  205. return a->heard_timestamp < b->heard_timestamp; // asc
  206. });
  207. } else if (order_by == 2) {
  208. // sort by strongest to weakest
  209. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting strongest to weakest");
  210. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  211. return a->snr > b->snr; // desc
  212. });
  213. } else if (order_by == 3) {
  214. // sort by weakest to strongest
  215. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting weakest to strongest");
  216. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  217. return a->snr < b->snr; // asc
  218. });
  219. }
  220. // build results buffer
  221. int results_count = 0;
  222. int results_offset = 0;
  223. uint8_t results_buffer[130];
  224. for(int index = 0; index < count && index + offset < neighbours_count; index++){
  225. // stop if we can't fit another entry in results
  226. int entry_size = pubkey_prefix_length + 4 + 1;
  227. if(results_offset + entry_size > sizeof(results_buffer)){
  228. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS no more entries can fit in results buffer");
  229. break;
  230. }
  231. // add next neighbour to results
  232. auto neighbour = sorted_neighbours[index + offset];
  233. uint32_t heard_seconds_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  234. memcpy(&results_buffer[results_offset], neighbour->id.pub_key, pubkey_prefix_length); results_offset += pubkey_prefix_length;
  235. memcpy(&results_buffer[results_offset], &heard_seconds_ago, 4); results_offset += 4;
  236. memcpy(&results_buffer[results_offset], &neighbour->snr, 1); results_offset += 1;
  237. results_count++;
  238. }
  239. // build reply
  240. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS neighbours_count=%d results_count=%d", neighbours_count, results_count);
  241. memcpy(&reply_data[reply_offset], &neighbours_count, 2); reply_offset += 2;
  242. memcpy(&reply_data[reply_offset], &results_count, 2); reply_offset += 2;
  243. memcpy(&reply_data[reply_offset], &results_buffer, results_offset); reply_offset += results_offset;
  244. return reply_offset;
  245. }
  246. }
  247. return 0; // unknown command
  248. }
  249. mesh::Packet *MyMesh::createSelfAdvert() {
  250. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  251. uint8_t app_data_len;
  252. {
  253. if (_prefs.advert_loc_policy == ADVERT_LOC_NONE) {
  254. AdvertDataBuilder builder(ADV_TYPE_REPEATER, _prefs.node_name);
  255. app_data_len = builder.encodeTo(app_data);
  256. } else if (_prefs.advert_loc_policy == ADVERT_LOC_SHARE) {
  257. AdvertDataBuilder builder(ADV_TYPE_REPEATER, _prefs.node_name, sensors.node_lat, sensors.node_lon);
  258. app_data_len = builder.encodeTo(app_data);
  259. } else {
  260. AdvertDataBuilder builder(ADV_TYPE_REPEATER, _prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  261. app_data_len = builder.encodeTo(app_data);
  262. }
  263. }
  264. return createAdvert(self_id, app_data, app_data_len);
  265. }
  266. File MyMesh::openAppend(const char *fname) {
  267. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  268. return _fs->open(fname, FILE_O_WRITE);
  269. #elif defined(RP2040_PLATFORM)
  270. return _fs->open(fname, "a");
  271. #else
  272. return _fs->open(fname, "a", true);
  273. #endif
  274. }
  275. bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
  276. if (_prefs.disable_fwd) return false;
  277. if (packet->isRouteFlood() && packet->path_len >= _prefs.flood_max) return false;
  278. return true;
  279. }
  280. const char *MyMesh::getLogDateTime() {
  281. static char tmp[32];
  282. uint32_t now = getRTCClock()->getCurrentTime();
  283. DateTime dt = DateTime(now);
  284. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
  285. dt.year());
  286. return tmp;
  287. }
  288. void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
  289. #if MESH_PACKET_LOGGING
  290. Serial.print(getLogDateTime());
  291. Serial.print(" RAW: ");
  292. mesh::Utils::printHex(Serial, raw, len);
  293. Serial.println();
  294. #endif
  295. }
  296. void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
  297. #ifdef WITH_BRIDGE
  298. if (_prefs.bridge_pkt_src == 1) {
  299. bridge.sendPacket(pkt);
  300. }
  301. #endif
  302. if (_logging) {
  303. File f = openAppend(PACKET_LOG_FILE);
  304. if (f) {
  305. f.print(getLogDateTime());
  306. f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d", len,
  307. pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
  308. (int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score * 1000));
  309. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  310. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  311. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  312. } else {
  313. f.printf("\n");
  314. }
  315. f.close();
  316. }
  317. }
  318. }
  319. void MyMesh::logTx(mesh::Packet *pkt, int len) {
  320. #ifdef WITH_BRIDGE
  321. if (_prefs.bridge_pkt_src == 0) {
  322. bridge.sendPacket(pkt);
  323. }
  324. #endif
  325. if (_logging) {
  326. File f = openAppend(PACKET_LOG_FILE);
  327. if (f) {
  328. f.print(getLogDateTime());
  329. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, pkt->getPayloadType(),
  330. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  331. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  332. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  333. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  334. } else {
  335. f.printf("\n");
  336. }
  337. f.close();
  338. }
  339. }
  340. }
  341. void MyMesh::logTxFail(mesh::Packet *pkt, int len) {
  342. if (_logging) {
  343. File f = openAppend(PACKET_LOG_FILE);
  344. if (f) {
  345. f.print(getLogDateTime());
  346. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n", len, pkt->getPayloadType(),
  347. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  348. f.close();
  349. }
  350. }
  351. }
  352. int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
  353. if (_prefs.rx_delay_base <= 0.0f) return 0;
  354. return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  355. }
  356. uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) {
  357. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
  358. return getRNG()->nextInt(0, 6) * t;
  359. }
  360. uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
  361. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  362. return getRNG()->nextInt(0, 6) * t;
  363. }
  364. void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
  365. uint8_t *data, size_t len) {
  366. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
  367. // client (unknown at this stage)
  368. uint32_t timestamp;
  369. memcpy(&timestamp, data, 4);
  370. data[len] = 0; // ensure null terminator
  371. uint8_t reply_len = handleLoginReq(sender, secret, timestamp, &data[4]);
  372. if (reply_len == 0) return; // invalid request
  373. if (packet->isRouteFlood()) {
  374. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  375. mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len,
  376. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  377. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  378. } else {
  379. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
  380. if (reply) sendFlood(reply, SERVER_RESPONSE_DELAY);
  381. }
  382. }
  383. }
  384. int MyMesh::searchPeersByHash(const uint8_t *hash) {
  385. int n = 0;
  386. for (int i = 0; i < acl.getNumClients(); i++) {
  387. if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
  388. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  389. }
  390. }
  391. return n;
  392. }
  393. void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
  394. int i = matching_peer_indexes[peer_idx];
  395. if (i >= 0 && i < acl.getNumClients()) {
  396. // lookup pre-calculated shared_secret
  397. memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
  398. } else {
  399. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  400. }
  401. }
  402. void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32_t timestamp,
  403. const uint8_t *app_data, size_t app_data_len) {
  404. mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
  405. // if this a zero hop advert, add it to neighbours
  406. if (packet->path_len == 0) {
  407. AdvertDataParser parser(app_data, app_data_len);
  408. if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
  409. putNeighbour(id, timestamp, packet->getSNR());
  410. }
  411. }
  412. }
  413. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  414. uint8_t *data, size_t len) {
  415. int i = matching_peer_indexes[sender_idx];
  416. if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  417. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  418. return;
  419. }
  420. ClientInfo* client = acl.getClientByIdx(i);
  421. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  422. uint32_t timestamp;
  423. memcpy(&timestamp, data, 4);
  424. if (timestamp > client->last_timestamp) { // prevent replay attacks
  425. int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
  426. if (reply_len == 0) return; // invalid command
  427. client->last_timestamp = timestamp;
  428. client->last_activity = getRTCClock()->getCurrentTime();
  429. if (packet->isRouteFlood()) {
  430. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  431. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  432. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  433. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  434. } else {
  435. mesh::Packet *reply =
  436. createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  437. if (reply) {
  438. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  439. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  440. } else {
  441. sendFlood(reply, SERVER_RESPONSE_DELAY);
  442. }
  443. }
  444. }
  445. } else {
  446. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  447. }
  448. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->isAdmin()) { // a CLI command
  449. uint32_t sender_timestamp;
  450. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  451. uint flags = (data[4] >> 2); // message attempt number, and other flags
  452. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  453. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  454. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
  455. bool is_retry = (sender_timestamp == client->last_timestamp);
  456. client->last_timestamp = sender_timestamp;
  457. client->last_activity = getRTCClock()->getCurrentTime();
  458. // len can be > original length, but 'text' will be padded with zeroes
  459. data[len] = 0; // need to make a C string again, with null terminator
  460. if (flags == TXT_TYPE_PLAIN) { // for legacy CLI, send Acks
  461. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove
  462. // to sender that we got it
  463. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  464. PUB_KEY_SIZE);
  465. mesh::Packet *ack = createAck(ack_hash);
  466. if (ack) {
  467. if (client->out_path_len < 0) {
  468. sendFlood(ack, TXT_ACK_DELAY);
  469. } else {
  470. sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY);
  471. }
  472. }
  473. }
  474. uint8_t temp[166];
  475. char *command = (char *)&data[5];
  476. char *reply = (char *)&temp[5];
  477. if (is_retry) {
  478. *reply = 0;
  479. } else {
  480. handleCommand(sender_timestamp, command, reply);
  481. }
  482. int text_len = strlen(reply);
  483. if (text_len > 0) {
  484. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  485. if (timestamp == sender_timestamp) {
  486. // WORKAROUND: the two timestamps need to be different, in the CLI view
  487. timestamp++;
  488. }
  489. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  490. temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
  491. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  492. if (reply) {
  493. if (client->out_path_len < 0) {
  494. sendFlood(reply, CLI_REPLY_DELAY_MILLIS);
  495. } else {
  496. sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS);
  497. }
  498. }
  499. }
  500. } else {
  501. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  502. }
  503. }
  504. }
  505. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  506. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  507. // TODO: prevent replay attacks
  508. int i = matching_peer_indexes[sender_idx];
  509. if (i >= 0 && i < acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  510. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  511. auto client = acl.getClientByIdx(i);
  512. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  513. client->last_activity = getRTCClock()->getCurrentTime();
  514. } else {
  515. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  516. }
  517. // NOTE: no reciprocal path send!!
  518. return false;
  519. }
  520. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  521. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  522. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  523. _cli(board, rtc, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4)
  524. #if defined(WITH_RS232_BRIDGE)
  525. , bridge(&_prefs, WITH_RS232_BRIDGE, _mgr, &rtc)
  526. #endif
  527. #if defined(WITH_ESPNOW_BRIDGE)
  528. , bridge(&_prefs, _mgr, &rtc)
  529. #endif
  530. {
  531. next_local_advert = next_flood_advert = 0;
  532. dirty_contacts_expiry = 0;
  533. set_radio_at = revert_radio_at = 0;
  534. _logging = false;
  535. #if MAX_NEIGHBOURS
  536. memset(neighbours, 0, sizeof(neighbours));
  537. #endif
  538. // defaults
  539. memset(&_prefs, 0, sizeof(_prefs));
  540. _prefs.airtime_factor = 1.0; // one half
  541. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  542. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  543. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  544. _prefs.node_lat = ADVERT_LAT;
  545. _prefs.node_lon = ADVERT_LON;
  546. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  547. _prefs.freq = LORA_FREQ;
  548. _prefs.sf = LORA_SF;
  549. _prefs.bw = LORA_BW;
  550. _prefs.cr = LORA_CR;
  551. _prefs.tx_power_dbm = LORA_TX_POWER;
  552. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  553. _prefs.flood_advert_interval = 12; // 12 hours
  554. _prefs.flood_max = 64;
  555. _prefs.interference_threshold = 0; // disabled
  556. // bridge defaults
  557. _prefs.bridge_enabled = 1; // enabled
  558. _prefs.bridge_delay = 500; // milliseconds
  559. _prefs.bridge_pkt_src = 0; // logTx
  560. _prefs.bridge_baud = 115200; // baud rate
  561. _prefs.bridge_channel = 1; // channel 1
  562. StrHelper::strncpy(_prefs.bridge_secret, "LVSITANOS", sizeof(_prefs.bridge_secret));
  563. // GPS defaults
  564. _prefs.gps_enabled = 0;
  565. _prefs.gps_interval = 0;
  566. }
  567. void MyMesh::begin(FILESYSTEM *fs) {
  568. mesh::Mesh::begin();
  569. _fs = fs;
  570. // load persisted prefs
  571. _cli.loadPrefs(_fs);
  572. acl.load(_fs);
  573. #if defined(WITH_BRIDGE)
  574. if (_prefs.bridge_enabled) {
  575. bridge.begin();
  576. }
  577. #endif
  578. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  579. radio_set_tx_power(_prefs.tx_power_dbm);
  580. updateAdvertTimer();
  581. updateFloodAdvertTimer();
  582. #if ENV_INCLUDE_GPS == 1
  583. applyGpsPrefs();
  584. #endif
  585. }
  586. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  587. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  588. pending_freq = freq;
  589. pending_bw = bw;
  590. pending_sf = sf;
  591. pending_cr = cr;
  592. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  593. }
  594. bool MyMesh::formatFileSystem() {
  595. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  596. return InternalFS.format();
  597. #elif defined(RP2040_PLATFORM)
  598. return LittleFS.format();
  599. #elif defined(ESP32)
  600. return SPIFFS.format();
  601. #else
  602. #error "need to implement file system erase"
  603. return false;
  604. #endif
  605. }
  606. void MyMesh::sendSelfAdvertisement(int delay_millis) {
  607. mesh::Packet *pkt = createSelfAdvert();
  608. if (pkt) {
  609. sendFlood(pkt, delay_millis);
  610. } else {
  611. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  612. }
  613. }
  614. void MyMesh::updateAdvertTimer() {
  615. if (_prefs.advert_interval > 0) { // schedule local advert timer
  616. next_local_advert = futureMillis(((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  617. } else {
  618. next_local_advert = 0; // stop the timer
  619. }
  620. }
  621. void MyMesh::updateFloodAdvertTimer() {
  622. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  623. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  624. } else {
  625. next_flood_advert = 0; // stop the timer
  626. }
  627. }
  628. void MyMesh::dumpLogFile() {
  629. #if defined(RP2040_PLATFORM)
  630. File f = _fs->open(PACKET_LOG_FILE, "r");
  631. #else
  632. File f = _fs->open(PACKET_LOG_FILE);
  633. #endif
  634. if (f) {
  635. while (f.available()) {
  636. int c = f.read();
  637. if (c < 0) break;
  638. Serial.print((char)c);
  639. }
  640. f.close();
  641. }
  642. }
  643. void MyMesh::setTxPower(uint8_t power_dbm) {
  644. radio_set_tx_power(power_dbm);
  645. }
  646. void MyMesh::formatNeighborsReply(char *reply) {
  647. char *dp = reply;
  648. #if MAX_NEIGHBOURS
  649. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  650. int16_t neighbours_count = 0;
  651. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  652. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  653. auto neighbour = &neighbours[i];
  654. if (neighbour->heard_timestamp > 0) {
  655. sorted_neighbours[neighbours_count] = neighbour;
  656. neighbours_count++;
  657. }
  658. }
  659. // sort neighbours newest to oldest
  660. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  661. return a->heard_timestamp > b->heard_timestamp; // desc
  662. });
  663. for (int i = 0; i < neighbours_count && dp - reply < 134; i++) {
  664. NeighbourInfo *neighbour = sorted_neighbours[i];
  665. // add new line if not first item
  666. if (i > 0) *dp++ = '\n';
  667. char hex[10];
  668. // get 4 bytes of neighbour id as hex
  669. mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
  670. // add next neighbour
  671. uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  672. sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
  673. while (*dp)
  674. dp++; // find end of string
  675. }
  676. #endif
  677. if (dp == reply) { // no neighbours, need empty response
  678. strcpy(dp, "-none-");
  679. dp += 6;
  680. }
  681. *dp = 0; // null terminator
  682. }
  683. void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
  684. #if MAX_NEIGHBOURS
  685. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  686. NeighbourInfo *neighbour = &neighbours[i];
  687. if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
  688. neighbours[i] = NeighbourInfo(); // clear neighbour entry
  689. }
  690. }
  691. #endif
  692. }
  693. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  694. self_id = new_id;
  695. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  696. IdentityStore store(*_fs, "");
  697. #elif defined(ESP32)
  698. IdentityStore store(*_fs, "/identity");
  699. #elif defined(RP2040_PLATFORM)
  700. IdentityStore store(*_fs, "/identity");
  701. #else
  702. #error "need to define saveIdentity()"
  703. #endif
  704. store.save("_main", self_id);
  705. }
  706. void MyMesh::clearStats() {
  707. radio_driver.resetStats();
  708. resetStats();
  709. ((SimpleMeshTables *)getTables())->resetStats();
  710. }
  711. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  712. while (*command == ' ')
  713. command++; // skip leading spaces
  714. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  715. memcpy(reply, command, 3); // reflect the prefix back
  716. reply += 3;
  717. command += 3;
  718. }
  719. // handle ACL related commands
  720. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  721. char* hex = &command[8];
  722. char* sp = strchr(hex, ' '); // look for separator char
  723. if (sp == NULL) {
  724. strcpy(reply, "Err - bad params");
  725. } else {
  726. *sp++ = 0; // replace space with null terminator
  727. uint8_t pubkey[PUB_KEY_SIZE];
  728. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  729. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  730. uint8_t perms = atoi(sp);
  731. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  732. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  733. strcpy(reply, "OK");
  734. } else {
  735. strcpy(reply, "Err - invalid params");
  736. }
  737. } else {
  738. strcpy(reply, "Err - bad pubkey");
  739. }
  740. }
  741. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  742. Serial.println("ACL:");
  743. for (int i = 0; i < acl.getNumClients(); i++) {
  744. auto c = acl.getClientByIdx(i);
  745. if (c->permissions == 0) continue; // skip deleted (or guest) entries
  746. Serial.printf("%02X ", c->permissions);
  747. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  748. Serial.printf("\n");
  749. }
  750. reply[0] = 0;
  751. } else{
  752. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  753. }
  754. }
  755. void MyMesh::loop() {
  756. #ifdef WITH_BRIDGE
  757. bridge.loop();
  758. #endif
  759. mesh::Mesh::loop();
  760. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  761. mesh::Packet *pkt = createSelfAdvert();
  762. if (pkt) sendFlood(pkt);
  763. updateFloodAdvertTimer(); // schedule next flood advert
  764. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  765. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  766. mesh::Packet *pkt = createSelfAdvert();
  767. if (pkt) sendZeroHop(pkt);
  768. updateAdvertTimer(); // schedule next local advert
  769. }
  770. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  771. set_radio_at = 0; // clear timer
  772. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  773. MESH_DEBUG_PRINTLN("Temp radio params");
  774. }
  775. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  776. revert_radio_at = 0; // clear timer
  777. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  778. MESH_DEBUG_PRINTLN("Radio params restored");
  779. }
  780. // is pending dirty contacts write needed?
  781. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  782. acl.save(_fs);
  783. dirty_contacts_expiry = 0;
  784. }
  785. }