MyMesh.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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 = _cli.buildAdvertData(ADV_TYPE_REPEATER, app_data);
  252. return createAdvert(self_id, app_data, app_data_len);
  253. }
  254. File MyMesh::openAppend(const char *fname) {
  255. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  256. return _fs->open(fname, FILE_O_WRITE);
  257. #elif defined(RP2040_PLATFORM)
  258. return _fs->open(fname, "a");
  259. #else
  260. return _fs->open(fname, "a", true);
  261. #endif
  262. }
  263. bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
  264. if (_prefs.disable_fwd) return false;
  265. if (packet->isRouteFlood() && packet->path_len >= _prefs.flood_max) return false;
  266. return true;
  267. }
  268. const char *MyMesh::getLogDateTime() {
  269. static char tmp[32];
  270. uint32_t now = getRTCClock()->getCurrentTime();
  271. DateTime dt = DateTime(now);
  272. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
  273. dt.year());
  274. return tmp;
  275. }
  276. void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
  277. #if MESH_PACKET_LOGGING
  278. Serial.print(getLogDateTime());
  279. Serial.print(" RAW: ");
  280. mesh::Utils::printHex(Serial, raw, len);
  281. Serial.println();
  282. #endif
  283. }
  284. void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
  285. #ifdef WITH_BRIDGE
  286. if (_prefs.bridge_pkt_src == 1) {
  287. bridge.sendPacket(pkt);
  288. }
  289. #endif
  290. if (_logging) {
  291. File f = openAppend(PACKET_LOG_FILE);
  292. if (f) {
  293. f.print(getLogDateTime());
  294. f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d", len,
  295. pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
  296. (int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score * 1000));
  297. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  298. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  299. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  300. } else {
  301. f.printf("\n");
  302. }
  303. f.close();
  304. }
  305. }
  306. }
  307. void MyMesh::logTx(mesh::Packet *pkt, int len) {
  308. #ifdef WITH_BRIDGE
  309. if (_prefs.bridge_pkt_src == 0) {
  310. bridge.sendPacket(pkt);
  311. }
  312. #endif
  313. if (_logging) {
  314. File f = openAppend(PACKET_LOG_FILE);
  315. if (f) {
  316. f.print(getLogDateTime());
  317. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, pkt->getPayloadType(),
  318. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  319. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  320. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  321. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  322. } else {
  323. f.printf("\n");
  324. }
  325. f.close();
  326. }
  327. }
  328. }
  329. void MyMesh::logTxFail(mesh::Packet *pkt, int len) {
  330. if (_logging) {
  331. File f = openAppend(PACKET_LOG_FILE);
  332. if (f) {
  333. f.print(getLogDateTime());
  334. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n", len, pkt->getPayloadType(),
  335. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  336. f.close();
  337. }
  338. }
  339. }
  340. int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
  341. if (_prefs.rx_delay_base <= 0.0f) return 0;
  342. return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  343. }
  344. uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) {
  345. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
  346. return getRNG()->nextInt(0, 6) * t;
  347. }
  348. uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
  349. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  350. return getRNG()->nextInt(0, 6) * t;
  351. }
  352. void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
  353. uint8_t *data, size_t len) {
  354. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
  355. // client (unknown at this stage)
  356. uint32_t timestamp;
  357. memcpy(&timestamp, data, 4);
  358. data[len] = 0; // ensure null terminator
  359. uint8_t reply_len = handleLoginReq(sender, secret, timestamp, &data[4]);
  360. if (reply_len == 0) return; // invalid request
  361. if (packet->isRouteFlood()) {
  362. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  363. mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len,
  364. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  365. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  366. } else {
  367. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
  368. if (reply) sendFlood(reply, SERVER_RESPONSE_DELAY);
  369. }
  370. }
  371. }
  372. int MyMesh::searchPeersByHash(const uint8_t *hash) {
  373. int n = 0;
  374. for (int i = 0; i < acl.getNumClients(); i++) {
  375. if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
  376. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  377. }
  378. }
  379. return n;
  380. }
  381. void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
  382. int i = matching_peer_indexes[peer_idx];
  383. if (i >= 0 && i < acl.getNumClients()) {
  384. // lookup pre-calculated shared_secret
  385. memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
  386. } else {
  387. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  388. }
  389. }
  390. void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32_t timestamp,
  391. const uint8_t *app_data, size_t app_data_len) {
  392. mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
  393. // if this a zero hop advert, add it to neighbours
  394. if (packet->path_len == 0) {
  395. AdvertDataParser parser(app_data, app_data_len);
  396. if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
  397. putNeighbour(id, timestamp, packet->getSNR());
  398. }
  399. }
  400. }
  401. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  402. uint8_t *data, size_t len) {
  403. int i = matching_peer_indexes[sender_idx];
  404. if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  405. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  406. return;
  407. }
  408. ClientInfo* client = acl.getClientByIdx(i);
  409. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  410. uint32_t timestamp;
  411. memcpy(&timestamp, data, 4);
  412. if (timestamp > client->last_timestamp) { // prevent replay attacks
  413. int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
  414. if (reply_len == 0) return; // invalid command
  415. client->last_timestamp = timestamp;
  416. client->last_activity = getRTCClock()->getCurrentTime();
  417. if (packet->isRouteFlood()) {
  418. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  419. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  420. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  421. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  422. } else {
  423. mesh::Packet *reply =
  424. createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  425. if (reply) {
  426. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  427. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  428. } else {
  429. sendFlood(reply, SERVER_RESPONSE_DELAY);
  430. }
  431. }
  432. }
  433. } else {
  434. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  435. }
  436. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->isAdmin()) { // a CLI command
  437. uint32_t sender_timestamp;
  438. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  439. uint flags = (data[4] >> 2); // message attempt number, and other flags
  440. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  441. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  442. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
  443. bool is_retry = (sender_timestamp == client->last_timestamp);
  444. client->last_timestamp = sender_timestamp;
  445. client->last_activity = getRTCClock()->getCurrentTime();
  446. // len can be > original length, but 'text' will be padded with zeroes
  447. data[len] = 0; // need to make a C string again, with null terminator
  448. if (flags == TXT_TYPE_PLAIN) { // for legacy CLI, send Acks
  449. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove
  450. // to sender that we got it
  451. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  452. PUB_KEY_SIZE);
  453. mesh::Packet *ack = createAck(ack_hash);
  454. if (ack) {
  455. if (client->out_path_len < 0) {
  456. sendFlood(ack, TXT_ACK_DELAY);
  457. } else {
  458. sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY);
  459. }
  460. }
  461. }
  462. uint8_t temp[166];
  463. char *command = (char *)&data[5];
  464. char *reply = (char *)&temp[5];
  465. if (is_retry) {
  466. *reply = 0;
  467. } else {
  468. handleCommand(sender_timestamp, command, reply);
  469. }
  470. int text_len = strlen(reply);
  471. if (text_len > 0) {
  472. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  473. if (timestamp == sender_timestamp) {
  474. // WORKAROUND: the two timestamps need to be different, in the CLI view
  475. timestamp++;
  476. }
  477. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  478. temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
  479. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  480. if (reply) {
  481. if (client->out_path_len < 0) {
  482. sendFlood(reply, CLI_REPLY_DELAY_MILLIS);
  483. } else {
  484. sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS);
  485. }
  486. }
  487. }
  488. } else {
  489. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  490. }
  491. }
  492. }
  493. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  494. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  495. // TODO: prevent replay attacks
  496. int i = matching_peer_indexes[sender_idx];
  497. if (i >= 0 && i < acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  498. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  499. auto client = acl.getClientByIdx(i);
  500. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  501. client->last_activity = getRTCClock()->getCurrentTime();
  502. } else {
  503. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  504. }
  505. // NOTE: no reciprocal path send!!
  506. return false;
  507. }
  508. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  509. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  510. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  511. _cli(board, rtc, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4)
  512. #if defined(WITH_RS232_BRIDGE)
  513. , bridge(&_prefs, WITH_RS232_BRIDGE, _mgr, &rtc)
  514. #endif
  515. #if defined(WITH_ESPNOW_BRIDGE)
  516. , bridge(&_prefs, _mgr, &rtc)
  517. #endif
  518. {
  519. next_local_advert = next_flood_advert = 0;
  520. dirty_contacts_expiry = 0;
  521. set_radio_at = revert_radio_at = 0;
  522. _logging = false;
  523. #if MAX_NEIGHBOURS
  524. memset(neighbours, 0, sizeof(neighbours));
  525. #endif
  526. // defaults
  527. memset(&_prefs, 0, sizeof(_prefs));
  528. _prefs.airtime_factor = 1.0; // one half
  529. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  530. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  531. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  532. _prefs.node_lat = ADVERT_LAT;
  533. _prefs.node_lon = ADVERT_LON;
  534. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  535. _prefs.freq = LORA_FREQ;
  536. _prefs.sf = LORA_SF;
  537. _prefs.bw = LORA_BW;
  538. _prefs.cr = LORA_CR;
  539. _prefs.tx_power_dbm = LORA_TX_POWER;
  540. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  541. _prefs.flood_advert_interval = 12; // 12 hours
  542. _prefs.flood_max = 64;
  543. _prefs.interference_threshold = 0; // disabled
  544. // bridge defaults
  545. _prefs.bridge_enabled = 1; // enabled
  546. _prefs.bridge_delay = 500; // milliseconds
  547. _prefs.bridge_pkt_src = 0; // logTx
  548. _prefs.bridge_baud = 115200; // baud rate
  549. _prefs.bridge_channel = 1; // channel 1
  550. StrHelper::strncpy(_prefs.bridge_secret, "LVSITANOS", sizeof(_prefs.bridge_secret));
  551. // GPS defaults
  552. _prefs.gps_enabled = 0;
  553. _prefs.gps_interval = 0;
  554. _prefs.advert_loc_policy = ADVERT_LOC_PREFS;
  555. }
  556. void MyMesh::begin(FILESYSTEM *fs) {
  557. mesh::Mesh::begin();
  558. _fs = fs;
  559. // load persisted prefs
  560. _cli.loadPrefs(_fs);
  561. acl.load(_fs);
  562. #if defined(WITH_BRIDGE)
  563. if (_prefs.bridge_enabled) {
  564. bridge.begin();
  565. }
  566. #endif
  567. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  568. radio_set_tx_power(_prefs.tx_power_dbm);
  569. updateAdvertTimer();
  570. updateFloodAdvertTimer();
  571. #if ENV_INCLUDE_GPS == 1
  572. applyGpsPrefs();
  573. #endif
  574. }
  575. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  576. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  577. pending_freq = freq;
  578. pending_bw = bw;
  579. pending_sf = sf;
  580. pending_cr = cr;
  581. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  582. }
  583. bool MyMesh::formatFileSystem() {
  584. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  585. return InternalFS.format();
  586. #elif defined(RP2040_PLATFORM)
  587. return LittleFS.format();
  588. #elif defined(ESP32)
  589. return SPIFFS.format();
  590. #else
  591. #error "need to implement file system erase"
  592. return false;
  593. #endif
  594. }
  595. void MyMesh::sendSelfAdvertisement(int delay_millis) {
  596. mesh::Packet *pkt = createSelfAdvert();
  597. if (pkt) {
  598. sendFlood(pkt, delay_millis);
  599. } else {
  600. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  601. }
  602. }
  603. void MyMesh::updateAdvertTimer() {
  604. if (_prefs.advert_interval > 0) { // schedule local advert timer
  605. next_local_advert = futureMillis(((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  606. } else {
  607. next_local_advert = 0; // stop the timer
  608. }
  609. }
  610. void MyMesh::updateFloodAdvertTimer() {
  611. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  612. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  613. } else {
  614. next_flood_advert = 0; // stop the timer
  615. }
  616. }
  617. void MyMesh::dumpLogFile() {
  618. #if defined(RP2040_PLATFORM)
  619. File f = _fs->open(PACKET_LOG_FILE, "r");
  620. #else
  621. File f = _fs->open(PACKET_LOG_FILE);
  622. #endif
  623. if (f) {
  624. while (f.available()) {
  625. int c = f.read();
  626. if (c < 0) break;
  627. Serial.print((char)c);
  628. }
  629. f.close();
  630. }
  631. }
  632. void MyMesh::setTxPower(uint8_t power_dbm) {
  633. radio_set_tx_power(power_dbm);
  634. }
  635. void MyMesh::formatNeighborsReply(char *reply) {
  636. char *dp = reply;
  637. #if MAX_NEIGHBOURS
  638. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  639. int16_t neighbours_count = 0;
  640. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  641. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  642. auto neighbour = &neighbours[i];
  643. if (neighbour->heard_timestamp > 0) {
  644. sorted_neighbours[neighbours_count] = neighbour;
  645. neighbours_count++;
  646. }
  647. }
  648. // sort neighbours newest to oldest
  649. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  650. return a->heard_timestamp > b->heard_timestamp; // desc
  651. });
  652. for (int i = 0; i < neighbours_count && dp - reply < 134; i++) {
  653. NeighbourInfo *neighbour = sorted_neighbours[i];
  654. // add new line if not first item
  655. if (i > 0) *dp++ = '\n';
  656. char hex[10];
  657. // get 4 bytes of neighbour id as hex
  658. mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
  659. // add next neighbour
  660. uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  661. sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
  662. while (*dp)
  663. dp++; // find end of string
  664. }
  665. #endif
  666. if (dp == reply) { // no neighbours, need empty response
  667. strcpy(dp, "-none-");
  668. dp += 6;
  669. }
  670. *dp = 0; // null terminator
  671. }
  672. void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
  673. #if MAX_NEIGHBOURS
  674. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  675. NeighbourInfo *neighbour = &neighbours[i];
  676. if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
  677. neighbours[i] = NeighbourInfo(); // clear neighbour entry
  678. }
  679. }
  680. #endif
  681. }
  682. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  683. self_id = new_id;
  684. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  685. IdentityStore store(*_fs, "");
  686. #elif defined(ESP32)
  687. IdentityStore store(*_fs, "/identity");
  688. #elif defined(RP2040_PLATFORM)
  689. IdentityStore store(*_fs, "/identity");
  690. #else
  691. #error "need to define saveIdentity()"
  692. #endif
  693. store.save("_main", self_id);
  694. }
  695. void MyMesh::clearStats() {
  696. radio_driver.resetStats();
  697. resetStats();
  698. ((SimpleMeshTables *)getTables())->resetStats();
  699. }
  700. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  701. while (*command == ' ')
  702. command++; // skip leading spaces
  703. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  704. memcpy(reply, command, 3); // reflect the prefix back
  705. reply += 3;
  706. command += 3;
  707. }
  708. // handle ACL related commands
  709. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  710. char* hex = &command[8];
  711. char* sp = strchr(hex, ' '); // look for separator char
  712. if (sp == NULL) {
  713. strcpy(reply, "Err - bad params");
  714. } else {
  715. *sp++ = 0; // replace space with null terminator
  716. uint8_t pubkey[PUB_KEY_SIZE];
  717. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  718. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  719. uint8_t perms = atoi(sp);
  720. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  721. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  722. strcpy(reply, "OK");
  723. } else {
  724. strcpy(reply, "Err - invalid params");
  725. }
  726. } else {
  727. strcpy(reply, "Err - bad pubkey");
  728. }
  729. }
  730. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  731. Serial.println("ACL:");
  732. for (int i = 0; i < acl.getNumClients(); i++) {
  733. auto c = acl.getClientByIdx(i);
  734. if (c->permissions == 0) continue; // skip deleted (or guest) entries
  735. Serial.printf("%02X ", c->permissions);
  736. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  737. Serial.printf("\n");
  738. }
  739. reply[0] = 0;
  740. } else{
  741. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  742. }
  743. }
  744. void MyMesh::loop() {
  745. #ifdef WITH_BRIDGE
  746. bridge.loop();
  747. #endif
  748. mesh::Mesh::loop();
  749. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  750. mesh::Packet *pkt = createSelfAdvert();
  751. if (pkt) sendFlood(pkt);
  752. updateFloodAdvertTimer(); // schedule next flood advert
  753. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  754. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  755. mesh::Packet *pkt = createSelfAdvert();
  756. if (pkt) sendZeroHop(pkt);
  757. updateAdvertTimer(); // schedule next local advert
  758. }
  759. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  760. set_radio_at = 0; // clear timer
  761. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  762. MESH_DEBUG_PRINTLN("Temp radio params");
  763. }
  764. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  765. revert_radio_at = 0; // clear timer
  766. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  767. MESH_DEBUG_PRINTLN("Radio params restored");
  768. }
  769. // is pending dirty contacts write needed?
  770. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  771. acl.save(_fs);
  772. dirty_contacts_expiry = 0;
  773. }
  774. }