MyMesh.cpp 27 KB

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