MyMesh.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  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 = uptime_millis / 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, 5*t + 1);
  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, 5*t + 1);
  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. static bool isShare(const mesh::Packet *packet) {
  392. if (packet->hasTransportCodes()) {
  393. return packet->transport_codes[0] == 0 && packet->transport_codes[1] == 0; // codes { 0, 0 } means 'send to nowhere'
  394. }
  395. return false;
  396. }
  397. void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32_t timestamp,
  398. const uint8_t *app_data, size_t app_data_len) {
  399. mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
  400. // if this a zero hop advert (and not via 'Share'), add it to neighbours
  401. if (packet->path_len == 0 && !isShare(packet)) {
  402. AdvertDataParser parser(app_data, app_data_len);
  403. if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
  404. putNeighbour(id, timestamp, packet->getSNR());
  405. }
  406. }
  407. }
  408. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  409. uint8_t *data, size_t len) {
  410. int i = matching_peer_indexes[sender_idx];
  411. if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  412. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  413. return;
  414. }
  415. ClientInfo* client = acl.getClientByIdx(i);
  416. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  417. uint32_t timestamp;
  418. memcpy(&timestamp, data, 4);
  419. if (timestamp > client->last_timestamp) { // prevent replay attacks
  420. int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
  421. if (reply_len == 0) return; // invalid command
  422. client->last_timestamp = timestamp;
  423. client->last_activity = getRTCClock()->getCurrentTime();
  424. if (packet->isRouteFlood()) {
  425. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  426. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  427. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  428. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  429. } else {
  430. mesh::Packet *reply =
  431. createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  432. if (reply) {
  433. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  434. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  435. } else {
  436. sendFlood(reply, SERVER_RESPONSE_DELAY);
  437. }
  438. }
  439. }
  440. } else {
  441. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  442. }
  443. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->isAdmin()) { // a CLI command
  444. uint32_t sender_timestamp;
  445. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  446. uint flags = (data[4] >> 2); // message attempt number, and other flags
  447. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  448. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  449. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
  450. bool is_retry = (sender_timestamp == client->last_timestamp);
  451. client->last_timestamp = sender_timestamp;
  452. client->last_activity = getRTCClock()->getCurrentTime();
  453. // len can be > original length, but 'text' will be padded with zeroes
  454. data[len] = 0; // need to make a C string again, with null terminator
  455. if (flags == TXT_TYPE_PLAIN) { // for legacy CLI, send Acks
  456. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove
  457. // to sender that we got it
  458. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  459. PUB_KEY_SIZE);
  460. mesh::Packet *ack = createAck(ack_hash);
  461. if (ack) {
  462. if (client->out_path_len < 0) {
  463. sendFlood(ack, TXT_ACK_DELAY);
  464. } else {
  465. sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY);
  466. }
  467. }
  468. }
  469. uint8_t temp[166];
  470. char *command = (char *)&data[5];
  471. char *reply = (char *)&temp[5];
  472. if (is_retry) {
  473. *reply = 0;
  474. } else {
  475. handleCommand(sender_timestamp, command, reply);
  476. }
  477. int text_len = strlen(reply);
  478. if (text_len > 0) {
  479. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  480. if (timestamp == sender_timestamp) {
  481. // WORKAROUND: the two timestamps need to be different, in the CLI view
  482. timestamp++;
  483. }
  484. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  485. temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
  486. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  487. if (reply) {
  488. if (client->out_path_len < 0) {
  489. sendFlood(reply, CLI_REPLY_DELAY_MILLIS);
  490. } else {
  491. sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS);
  492. }
  493. }
  494. }
  495. } else {
  496. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  497. }
  498. }
  499. }
  500. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  501. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  502. // TODO: prevent replay attacks
  503. int i = matching_peer_indexes[sender_idx];
  504. if (i >= 0 && i < acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  505. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  506. auto client = acl.getClientByIdx(i);
  507. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  508. client->last_activity = getRTCClock()->getCurrentTime();
  509. } else {
  510. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  511. }
  512. // NOTE: no reciprocal path send!!
  513. return false;
  514. }
  515. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  516. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  517. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  518. _cli(board, rtc, sensors, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4)
  519. #if defined(WITH_RS232_BRIDGE)
  520. , bridge(&_prefs, WITH_RS232_BRIDGE, _mgr, &rtc)
  521. #endif
  522. #if defined(WITH_ESPNOW_BRIDGE)
  523. , bridge(&_prefs, _mgr, &rtc)
  524. #endif
  525. {
  526. last_millis = 0;
  527. uptime_millis = 0;
  528. next_local_advert = next_flood_advert = 0;
  529. dirty_contacts_expiry = 0;
  530. set_radio_at = revert_radio_at = 0;
  531. _logging = false;
  532. #if MAX_NEIGHBOURS
  533. memset(neighbours, 0, sizeof(neighbours));
  534. #endif
  535. // defaults
  536. memset(&_prefs, 0, sizeof(_prefs));
  537. _prefs.airtime_factor = 1.0; // one half
  538. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  539. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  540. _prefs.direct_tx_delay_factor = 0.2f; // was zero
  541. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  542. _prefs.node_lat = ADVERT_LAT;
  543. _prefs.node_lon = ADVERT_LON;
  544. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  545. _prefs.freq = LORA_FREQ;
  546. _prefs.sf = LORA_SF;
  547. _prefs.bw = LORA_BW;
  548. _prefs.cr = LORA_CR;
  549. _prefs.tx_power_dbm = LORA_TX_POWER;
  550. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  551. _prefs.flood_advert_interval = 12; // 12 hours
  552. _prefs.flood_max = 64;
  553. _prefs.interference_threshold = 0; // disabled
  554. // bridge defaults
  555. _prefs.bridge_enabled = 1; // enabled
  556. _prefs.bridge_delay = 500; // milliseconds
  557. _prefs.bridge_pkt_src = 0; // logTx
  558. _prefs.bridge_baud = 115200; // baud rate
  559. _prefs.bridge_channel = 1; // channel 1
  560. StrHelper::strncpy(_prefs.bridge_secret, "LVSITANOS", sizeof(_prefs.bridge_secret));
  561. // GPS defaults
  562. _prefs.gps_enabled = 0;
  563. _prefs.gps_interval = 0;
  564. _prefs.advert_loc_policy = ADVERT_LOC_PREFS;
  565. }
  566. void MyMesh::begin(FILESYSTEM *fs) {
  567. mesh::Mesh::begin();
  568. _fs = fs;
  569. // load persisted prefs
  570. _cli.loadPrefs(_fs);
  571. acl.load(_fs);
  572. #if defined(WITH_BRIDGE)
  573. if (_prefs.bridge_enabled) {
  574. bridge.begin();
  575. }
  576. #endif
  577. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  578. radio_set_tx_power(_prefs.tx_power_dbm);
  579. updateAdvertTimer();
  580. updateFloodAdvertTimer();
  581. #if ENV_INCLUDE_GPS == 1
  582. applyGpsPrefs();
  583. #endif
  584. }
  585. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  586. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  587. pending_freq = freq;
  588. pending_bw = bw;
  589. pending_sf = sf;
  590. pending_cr = cr;
  591. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  592. }
  593. bool MyMesh::formatFileSystem() {
  594. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  595. return InternalFS.format();
  596. #elif defined(RP2040_PLATFORM)
  597. return LittleFS.format();
  598. #elif defined(ESP32)
  599. return SPIFFS.format();
  600. #else
  601. #error "need to implement file system erase"
  602. return false;
  603. #endif
  604. }
  605. void MyMesh::sendSelfAdvertisement(int delay_millis) {
  606. mesh::Packet *pkt = createSelfAdvert();
  607. if (pkt) {
  608. sendFlood(pkt, delay_millis);
  609. } else {
  610. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  611. }
  612. }
  613. void MyMesh::updateAdvertTimer() {
  614. if (_prefs.advert_interval > 0) { // schedule local advert timer
  615. next_local_advert = futureMillis(((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  616. } else {
  617. next_local_advert = 0; // stop the timer
  618. }
  619. }
  620. void MyMesh::updateFloodAdvertTimer() {
  621. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  622. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  623. } else {
  624. next_flood_advert = 0; // stop the timer
  625. }
  626. }
  627. void MyMesh::dumpLogFile() {
  628. #if defined(RP2040_PLATFORM)
  629. File f = _fs->open(PACKET_LOG_FILE, "r");
  630. #else
  631. File f = _fs->open(PACKET_LOG_FILE);
  632. #endif
  633. if (f) {
  634. while (f.available()) {
  635. int c = f.read();
  636. if (c < 0) break;
  637. Serial.print((char)c);
  638. }
  639. f.close();
  640. }
  641. }
  642. void MyMesh::setTxPower(uint8_t power_dbm) {
  643. radio_set_tx_power(power_dbm);
  644. }
  645. void MyMesh::formatNeighborsReply(char *reply) {
  646. char *dp = reply;
  647. #if MAX_NEIGHBOURS
  648. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  649. int16_t neighbours_count = 0;
  650. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  651. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  652. auto neighbour = &neighbours[i];
  653. if (neighbour->heard_timestamp > 0) {
  654. sorted_neighbours[neighbours_count] = neighbour;
  655. neighbours_count++;
  656. }
  657. }
  658. // sort neighbours newest to oldest
  659. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  660. return a->heard_timestamp > b->heard_timestamp; // desc
  661. });
  662. for (int i = 0; i < neighbours_count && dp - reply < 134; i++) {
  663. NeighbourInfo *neighbour = sorted_neighbours[i];
  664. // add new line if not first item
  665. if (i > 0) *dp++ = '\n';
  666. char hex[10];
  667. // get 4 bytes of neighbour id as hex
  668. mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
  669. // add next neighbour
  670. uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  671. sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
  672. while (*dp)
  673. dp++; // find end of string
  674. }
  675. #endif
  676. if (dp == reply) { // no neighbours, need empty response
  677. strcpy(dp, "-none-");
  678. dp += 6;
  679. }
  680. *dp = 0; // null terminator
  681. }
  682. void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
  683. #if MAX_NEIGHBOURS
  684. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  685. NeighbourInfo *neighbour = &neighbours[i];
  686. if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
  687. neighbours[i] = NeighbourInfo(); // clear neighbour entry
  688. }
  689. }
  690. #endif
  691. }
  692. void MyMesh::formatStatsReply(char *reply) {
  693. StatsFormatHelper::formatCoreStats(reply, board, *_ms, _err_flags, _mgr);
  694. }
  695. void MyMesh::formatRadioStatsReply(char *reply) {
  696. StatsFormatHelper::formatRadioStats(reply, _radio, radio_driver, getTotalAirTime(), getReceiveAirTime());
  697. }
  698. void MyMesh::formatPacketStatsReply(char *reply) {
  699. StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(),
  700. getNumRecvFlood(), getNumRecvDirect());
  701. }
  702. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  703. self_id = new_id;
  704. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  705. IdentityStore store(*_fs, "");
  706. #elif defined(ESP32)
  707. IdentityStore store(*_fs, "/identity");
  708. #elif defined(RP2040_PLATFORM)
  709. IdentityStore store(*_fs, "/identity");
  710. #else
  711. #error "need to define saveIdentity()"
  712. #endif
  713. store.save("_main", self_id);
  714. }
  715. void MyMesh::clearStats() {
  716. radio_driver.resetStats();
  717. resetStats();
  718. ((SimpleMeshTables *)getTables())->resetStats();
  719. }
  720. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  721. while (*command == ' ')
  722. command++; // skip leading spaces
  723. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  724. memcpy(reply, command, 3); // reflect the prefix back
  725. reply += 3;
  726. command += 3;
  727. }
  728. // handle ACL related commands
  729. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  730. char* hex = &command[8];
  731. char* sp = strchr(hex, ' '); // look for separator char
  732. if (sp == NULL) {
  733. strcpy(reply, "Err - bad params");
  734. } else {
  735. *sp++ = 0; // replace space with null terminator
  736. uint8_t pubkey[PUB_KEY_SIZE];
  737. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  738. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  739. uint8_t perms = atoi(sp);
  740. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  741. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  742. strcpy(reply, "OK");
  743. } else {
  744. strcpy(reply, "Err - invalid params");
  745. }
  746. } else {
  747. strcpy(reply, "Err - bad pubkey");
  748. }
  749. }
  750. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  751. Serial.println("ACL:");
  752. for (int i = 0; i < acl.getNumClients(); i++) {
  753. auto c = acl.getClientByIdx(i);
  754. if (c->permissions == 0) continue; // skip deleted (or guest) entries
  755. Serial.printf("%02X ", c->permissions);
  756. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  757. Serial.printf("\n");
  758. }
  759. reply[0] = 0;
  760. } else{
  761. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  762. }
  763. }
  764. void MyMesh::loop() {
  765. #ifdef WITH_BRIDGE
  766. bridge.loop();
  767. #endif
  768. mesh::Mesh::loop();
  769. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  770. mesh::Packet *pkt = createSelfAdvert();
  771. if (pkt) sendFlood(pkt);
  772. updateFloodAdvertTimer(); // schedule next flood advert
  773. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  774. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  775. mesh::Packet *pkt = createSelfAdvert();
  776. if (pkt) sendZeroHop(pkt);
  777. updateAdvertTimer(); // schedule next local advert
  778. }
  779. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  780. set_radio_at = 0; // clear timer
  781. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  782. MESH_DEBUG_PRINTLN("Temp radio params");
  783. }
  784. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  785. revert_radio_at = 0; // clear timer
  786. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  787. MESH_DEBUG_PRINTLN("Radio params restored");
  788. }
  789. // is pending dirty contacts write needed?
  790. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  791. acl.save(_fs);
  792. dirty_contacts_expiry = 0;
  793. }
  794. // update uptime
  795. uint32_t now = millis();
  796. uptime_millis += now - last_millis;
  797. last_millis = now;
  798. }