MyMesh.cpp 32 KB

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