main.cpp 29 KB

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