MyMesh.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. #include "MyMesh.h"
  2. #define REPLY_DELAY_MILLIS 1500
  3. #define PUSH_NOTIFY_DELAY_MILLIS 2000
  4. #define SYNC_PUSH_INTERVAL 1200
  5. #define PUSH_ACK_TIMEOUT_FLOOD 12000
  6. #define PUSH_TIMEOUT_BASE 4000
  7. #define PUSH_ACK_TIMEOUT_FACTOR 2000
  8. #define POST_SYNC_DELAY_SECS 6
  9. #define FIRMWARE_VER_LEVEL 1
  10. #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
  11. #define REQ_TYPE_KEEP_ALIVE 0x02
  12. #define REQ_TYPE_GET_TELEMETRY_DATA 0x03
  13. #define REQ_TYPE_GET_ACCESS_LIST 0x05
  14. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  15. #define LAZY_CONTACTS_WRITE_DELAY 5000
  16. struct ServerStats {
  17. uint16_t batt_milli_volts;
  18. uint16_t curr_tx_queue_len;
  19. int16_t noise_floor;
  20. int16_t last_rssi;
  21. uint32_t n_packets_recv;
  22. uint32_t n_packets_sent;
  23. uint32_t total_air_time_secs;
  24. uint32_t total_up_time_secs;
  25. uint32_t n_sent_flood, n_sent_direct;
  26. uint32_t n_recv_flood, n_recv_direct;
  27. uint16_t err_events; // was 'n_full_events'
  28. int16_t last_snr; // x 4
  29. uint16_t n_direct_dups, n_flood_dups;
  30. uint16_t n_posted, n_post_push;
  31. };
  32. void MyMesh::addPost(ClientInfo *client, const char *postData) {
  33. // TODO: suggested postData format: <title>/<descrption>
  34. posts[next_post_idx].author = client->id; // add to cyclic queue
  35. StrHelper::strncpy(posts[next_post_idx].text, postData, MAX_POST_TEXT_LEN);
  36. posts[next_post_idx].post_timestamp = getRTCClock()->getCurrentTimeUnique();
  37. next_post_idx = (next_post_idx + 1) % MAX_UNSYNCED_POSTS;
  38. next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS);
  39. _num_posted++; // stats
  40. }
  41. void MyMesh::pushPostToClient(ClientInfo *client, PostInfo &post) {
  42. int len = 0;
  43. memcpy(&reply_data[len], &post.post_timestamp, 4);
  44. len += 4; // this is a PAST timestamp... but should be accepted by client
  45. uint8_t attempt;
  46. getRNG()->random(&attempt, 1); // need this for re-tries, so packet hash (and ACK) will be different
  47. reply_data[len++] = (TXT_TYPE_SIGNED_PLAIN << 2) | (attempt & 3); // 'signed' plain text
  48. // encode prefix of post.author.pub_key
  49. memcpy(&reply_data[len], post.author.pub_key, 4);
  50. len += 4; // just first 4 bytes
  51. int text_len = strlen(post.text);
  52. memcpy(&reply_data[len], post.text, text_len);
  53. len += text_len;
  54. // calc expected ACK reply
  55. mesh::Utils::sha256((uint8_t *)&client->extra.room.pending_ack, 4, reply_data, len, client->id.pub_key, PUB_KEY_SIZE);
  56. client->extra.room.push_post_timestamp = post.post_timestamp;
  57. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, client->shared_secret, reply_data, len);
  58. if (reply) {
  59. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  60. sendFlood(reply); // TODO: which path_hash_size to use?
  61. client->extra.room.ack_timeout = futureMillis(PUSH_ACK_TIMEOUT_FLOOD);
  62. } else {
  63. sendDirect(reply, client->out_path, client->out_path_len);
  64. uint8_t path_hash_count = client->out_path_len & 63;
  65. client->extra.room.ack_timeout = futureMillis(PUSH_TIMEOUT_BASE + PUSH_ACK_TIMEOUT_FACTOR * (path_hash_count + 1));
  66. }
  67. _num_post_pushes++; // stats
  68. } else {
  69. client->extra.room.pending_ack = 0;
  70. MESH_DEBUG_PRINTLN("Unable to push post to client");
  71. }
  72. }
  73. uint8_t MyMesh::getUnsyncedCount(ClientInfo *client) {
  74. uint8_t count = 0;
  75. for (int k = 0; k < MAX_UNSYNCED_POSTS; k++) {
  76. if (posts[k].post_timestamp > client->extra.room.sync_since // is new post for this Client?
  77. && !posts[k].author.matches(client->id)) { // don't push posts to the author
  78. count++;
  79. }
  80. }
  81. return count;
  82. }
  83. bool MyMesh::processAck(const uint8_t *data) {
  84. for (int i = 0; i < acl.getNumClients(); i++) {
  85. auto client = acl.getClientByIdx(i);
  86. if (client->extra.room.pending_ack && memcmp(data, &client->extra.room.pending_ack, 4) == 0) { // got an ACK from Client!
  87. client->extra.room.pending_ack = 0; // clear this, so next push can happen
  88. client->extra.room.push_failures = 0;
  89. client->extra.room.sync_since = client->extra.room.push_post_timestamp; // advance Client's SINCE timestamp, to sync next post
  90. return true;
  91. }
  92. }
  93. return false;
  94. }
  95. mesh::Packet *MyMesh::createSelfAdvert() {
  96. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  97. uint8_t app_data_len = _cli.buildAdvertData(ADV_TYPE_ROOM, app_data);
  98. return createAdvert(self_id, app_data, app_data_len);
  99. }
  100. File MyMesh::openAppend(const char *fname) {
  101. #if defined(NRF52_PLATFORM)
  102. return _fs->open(fname, FILE_O_WRITE);
  103. #elif defined(RP2040_PLATFORM)
  104. return _fs->open(fname, "a");
  105. #else
  106. return _fs->open(fname, "a", true);
  107. #endif
  108. }
  109. int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload,
  110. 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) {
  115. ServerStats 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 = uptime_millis / 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.n_posted = _num_posted;
  133. stats.n_post_push = _num_post_pushes;
  134. memcpy(&reply_data[4], &stats, sizeof(stats));
  135. return 4 + sizeof(stats);
  136. }
  137. if (payload[0] == REQ_TYPE_GET_TELEMETRY_DATA) {
  138. uint8_t perm_mask = ~(payload[1]); // NEW: first reserved byte (of 4), is now inverse mask to apply to permissions
  139. telemetry.reset();
  140. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  141. // query other sensors -- target specific
  142. if ((sender->permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_GUEST) {
  143. perm_mask = 0x00; // just base telemetry allowed
  144. }
  145. sensors.querySensors(perm_mask, telemetry);
  146. uint8_t tlen = telemetry.getSize();
  147. memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
  148. return 4 + tlen; // reply_len
  149. }
  150. if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) {
  151. uint8_t res1 = payload[1]; // reserved for future (extra query params)
  152. uint8_t res2 = payload[2];
  153. if (res1 == 0 && res2 == 0) {
  154. uint8_t ofs = 4;
  155. for (int i = 0; i < acl.getNumClients() && ofs + 7 <= sizeof(reply_data) - 4; i++) {
  156. auto c = acl.getClientByIdx(i);
  157. if (!c->isAdmin()) continue; // skip non-Admin entries
  158. memcpy(&reply_data[ofs], c->id.pub_key, 6); ofs += 6; // just 6-byte pub_key prefix
  159. reply_data[ofs++] = c->permissions;
  160. }
  161. return ofs;
  162. }
  163. }
  164. return 0; // unknown command
  165. }
  166. void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
  167. #if MESH_PACKET_LOGGING
  168. Serial.print(getLogDateTime());
  169. Serial.print(" RAW: ");
  170. mesh::Utils::printHex(Serial, raw, len);
  171. Serial.println();
  172. #endif
  173. }
  174. void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
  175. if (_logging) {
  176. File f = openAppend(PACKET_LOG_FILE);
  177. if (f) {
  178. f.print(getLogDateTime());
  179. f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d", len,
  180. pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
  181. (int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score * 1000));
  182. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  183. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  184. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  185. } else {
  186. f.printf("\n");
  187. }
  188. f.close();
  189. }
  190. }
  191. }
  192. void MyMesh::logTx(mesh::Packet *pkt, int len) {
  193. if (_logging) {
  194. File f = openAppend(PACKET_LOG_FILE);
  195. if (f) {
  196. f.print(getLogDateTime());
  197. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, pkt->getPayloadType(),
  198. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  199. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  200. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  201. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  202. } else {
  203. f.printf("\n");
  204. }
  205. f.close();
  206. }
  207. }
  208. }
  209. void MyMesh::logTxFail(mesh::Packet *pkt, int len) {
  210. if (_logging) {
  211. File f = openAppend(PACKET_LOG_FILE);
  212. if (f) {
  213. f.print(getLogDateTime());
  214. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n", len, pkt->getPayloadType(),
  215. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  216. f.close();
  217. }
  218. }
  219. }
  220. int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
  221. if (_prefs.rx_delay_base <= 0.0f) return 0;
  222. return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  223. }
  224. const char *MyMesh::getLogDateTime() {
  225. static char tmp[32];
  226. uint32_t now = getRTCClock()->getCurrentTime();
  227. DateTime dt = DateTime(now);
  228. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
  229. dt.year());
  230. return tmp;
  231. }
  232. uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) {
  233. uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.tx_delay_factor);
  234. return getRNG()->nextInt(0, 5*t + 1);
  235. }
  236. uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
  237. uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  238. return getRNG()->nextInt(0, 5*t + 1);
  239. }
  240. bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
  241. if (_prefs.disable_fwd) return false;
  242. if (packet->isRouteFlood() && packet->getPathHashCount() >= _prefs.flood_max) return false;
  243. return true;
  244. }
  245. void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
  246. uint8_t *data, size_t len) {
  247. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
  248. // client (unknown at this stage)
  249. uint32_t sender_timestamp, sender_sync_since;
  250. memcpy(&sender_timestamp, data, 4);
  251. memcpy(&sender_sync_since, &data[4], 4); // sender's "sync messags SINCE x" timestamp
  252. data[len] = 0; // ensure null terminator
  253. ClientInfo* client = NULL;
  254. if (data[8] == 0) { // blank password, just check if sender is in ACL
  255. client = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
  256. if (client == NULL) {
  257. #if MESH_DEBUG
  258. MESH_DEBUG_PRINTLN("Login, sender not in ACL");
  259. #endif
  260. }
  261. }
  262. if (client == NULL) {
  263. uint8_t perm;
  264. if (strcmp((char *)&data[8], _prefs.password) == 0) { // check for valid admin password
  265. perm = PERM_ACL_ADMIN;
  266. } else {
  267. if (strcmp((char *)&data[8], _prefs.guest_password) == 0) { // check the room/public password
  268. perm = PERM_ACL_READ_WRITE;
  269. } else if (_prefs.allow_read_only) {
  270. perm = PERM_ACL_GUEST;
  271. } else {
  272. MESH_DEBUG_PRINTLN("Incorrect room password");
  273. return; // no response. Client will timeout
  274. }
  275. }
  276. client = acl.putClient(sender, 0); // add to known clients (if not already known)
  277. if (sender_timestamp <= client->last_timestamp) {
  278. MESH_DEBUG_PRINTLN("possible replay attack!");
  279. return;
  280. }
  281. MESH_DEBUG_PRINTLN("Login success!");
  282. client->last_timestamp = sender_timestamp;
  283. client->extra.room.sync_since = sender_sync_since;
  284. client->extra.room.pending_ack = 0;
  285. client->extra.room.push_failures = 0;
  286. client->last_activity = getRTCClock()->getCurrentTime();
  287. client->permissions &= ~0x03;
  288. client->permissions |= perm;
  289. memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
  290. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  291. }
  292. if (packet->isRouteFlood()) {
  293. client->out_path_len = OUT_PATH_UNKNOWN; // need to rediscover out_path
  294. }
  295. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  296. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  297. // TODO: maybe reply with count of messages waiting to be synced for THIS client?
  298. reply_data[4] = RESP_SERVER_LOGIN_OK;
  299. reply_data[5] = 0; // Legacy: was recommended keep-alive interval (secs / 16)
  300. reply_data[6] = (client->isAdmin() ? 1 : (client->permissions == 0 ? 2 : 0));
  301. // LEGACY: reply_data[7] = getUnsyncedCount(client);
  302. reply_data[7] = client->permissions; // NEW
  303. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  304. reply_data[12] = FIRMWARE_VER_LEVEL; // New field
  305. next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS); // delay next push, give RESPONSE packet time to arrive first
  306. if (packet->isRouteFlood()) {
  307. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  308. mesh::Packet *path = createPathReturn(sender, client->shared_secret, packet->path, packet->path_len,
  309. PAYLOAD_TYPE_RESPONSE, reply_data, 13);
  310. if (path) sendFlood(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  311. } else {
  312. mesh::Packet *reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->shared_secret, reply_data, 13);
  313. if (reply) {
  314. if (client->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
  315. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  316. } else {
  317. sendFlood(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  318. }
  319. }
  320. }
  321. }
  322. }
  323. int MyMesh::searchPeersByHash(const uint8_t *hash) {
  324. int n = 0;
  325. for (int i = 0; i < acl.getNumClients(); i++) {
  326. if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
  327. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  328. }
  329. }
  330. return n;
  331. }
  332. void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
  333. int i = matching_peer_indexes[peer_idx];
  334. if (i >= 0 && i < acl.getNumClients()) {
  335. // lookup pre-calculated shared_secret
  336. memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
  337. } else {
  338. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  339. }
  340. }
  341. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  342. uint8_t *data, size_t len) {
  343. int i = matching_peer_indexes[sender_idx];
  344. if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  345. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  346. return;
  347. }
  348. auto client = acl.getClientByIdx(i);
  349. if (type == PAYLOAD_TYPE_TXT_MSG && len > 5) { // a CLI command or new Post
  350. uint32_t sender_timestamp;
  351. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  352. uint8_t flags = (data[4] >> 2); // message attempt number, and other flags
  353. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  354. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported command flags received: flags=%02x", (uint32_t)flags);
  355. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks, but send Acks for retries
  356. bool is_retry = (sender_timestamp == client->last_timestamp);
  357. client->last_timestamp = sender_timestamp;
  358. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  359. client->last_activity = now;
  360. client->extra.room.push_failures = 0; // reset so push can resume (if prev failed)
  361. // len can be > original length, but 'text' will be padded with zeroes
  362. data[len] = 0; // need to make a C string again, with null terminator
  363. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to
  364. // sender that we got it
  365. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  366. PUB_KEY_SIZE);
  367. uint8_t temp[166];
  368. bool send_ack;
  369. if (flags == TXT_TYPE_CLI_DATA) {
  370. if (client->isAdmin()) {
  371. if (is_retry) {
  372. temp[5] = 0; // no reply
  373. } else {
  374. handleCommand(sender_timestamp, (char *)&data[5], (char *)&temp[5]);
  375. temp[4] = (TXT_TYPE_CLI_DATA << 2); // attempt and flags, (NOTE: legacy was: TXT_TYPE_PLAIN)
  376. }
  377. send_ack = false;
  378. } else {
  379. temp[5] = 0; // no reply
  380. send_ack = false; // and no ACK... user shoudn't be sending these
  381. }
  382. } else { // TXT_TYPE_PLAIN
  383. if ((client->permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_GUEST) {
  384. temp[5] = 0; // no reply
  385. send_ack = false; // no ACK
  386. } else {
  387. if (!is_retry) {
  388. addPost(client, (const char *)&data[5]);
  389. }
  390. temp[5] = 0; // no reply (ACK is enough)
  391. send_ack = true;
  392. }
  393. }
  394. uint32_t delay_millis;
  395. if (send_ack) {
  396. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  397. mesh::Packet *ack = createAck(ack_hash);
  398. if (ack) sendFlood(ack, TXT_ACK_DELAY, packet->getPathHashSize());
  399. delay_millis = TXT_ACK_DELAY + REPLY_DELAY_MILLIS;
  400. } else {
  401. uint32_t d = TXT_ACK_DELAY;
  402. if (getExtraAckTransmitCount() > 0) {
  403. mesh::Packet *a1 = createMultiAck(ack_hash, 1);
  404. if (a1) sendDirect(a1, client->out_path, client->out_path_len, d);
  405. d += 300;
  406. }
  407. mesh::Packet *a2 = createAck(ack_hash);
  408. if (a2) sendDirect(a2, client->out_path, client->out_path_len, d);
  409. delay_millis = d + REPLY_DELAY_MILLIS;
  410. }
  411. } else {
  412. delay_millis = 0;
  413. }
  414. int text_len = strlen((char *)&temp[5]);
  415. if (text_len > 0) {
  416. if (now == sender_timestamp) {
  417. // WORKAROUND: the two timestamps need to be different, in the CLI view
  418. now++;
  419. }
  420. memcpy(temp, &now, 4); // mostly an extra blob to help make packet_hash unique
  421. // calc expected ACK reply
  422. // mesh::Utils::sha256((uint8_t *)&expected_ack_crc, 4, temp, 5 + text_len, self_id.pub_key,
  423. // PUB_KEY_SIZE);
  424. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  425. if (reply) {
  426. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  427. sendFlood(reply, delay_millis + SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  428. } else {
  429. sendDirect(reply, client->out_path, client->out_path_len, delay_millis + SERVER_RESPONSE_DELAY);
  430. }
  431. }
  432. }
  433. } else {
  434. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  435. }
  436. } else if (type == PAYLOAD_TYPE_REQ && len >= 5) {
  437. uint32_t sender_timestamp;
  438. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  439. if (sender_timestamp < client->last_timestamp) { // prevent replay attacks
  440. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  441. } else {
  442. client->last_timestamp = sender_timestamp;
  443. uint32_t now = getRTCClock()->getCurrentTime();
  444. client->last_activity = now; // <-- THIS will keep client connection alive
  445. client->extra.room.push_failures = 0; // reset so push can resume (if prev failed)
  446. if (data[4] == REQ_TYPE_KEEP_ALIVE && packet->isRouteDirect()) { // request type
  447. uint32_t forceSince = 0;
  448. if (len >= 9) { // optional - last post_timestamp client received
  449. memcpy(&forceSince, &data[5], 4); // NOTE: this may be 0, if part of decrypted PADDING!
  450. } else {
  451. memcpy(&data[5], &forceSince, 4); // make sure there are zeroes in payload (for ack_hash calc below)
  452. }
  453. if (forceSince > 0) {
  454. client->extra.room.sync_since = forceSince; // force-update the 'sync since'
  455. }
  456. client->extra.room.pending_ack = 0;
  457. // TODO: Throttle KEEP_ALIVE requests!
  458. // if client sends too quickly, evict()
  459. // RULE: only send keep_alive response DIRECT!
  460. if (client->out_path_len != OUT_PATH_UNKNOWN) {
  461. uint32_t ack_hash; // calc ACK to prove to sender that we got request
  462. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 9, client->id.pub_key, PUB_KEY_SIZE);
  463. auto reply = createAck(ack_hash);
  464. if (reply) {
  465. reply->payload[reply->payload_len++] = getUnsyncedCount(client); // NEW: add unsynced counter to end of ACK packet
  466. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  467. }
  468. }
  469. } else {
  470. int reply_len = handleRequest(client, sender_timestamp, &data[4], len - 4);
  471. if (reply_len > 0) { // valid command
  472. if (packet->isRouteFlood()) {
  473. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  474. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  475. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  476. if (path) sendFlood(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  477. } else {
  478. mesh::Packet *reply = createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  479. if (reply) {
  480. if (client->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
  481. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  482. } else {
  483. sendFlood(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  484. }
  485. }
  486. }
  487. }
  488. }
  489. }
  490. }
  491. }
  492. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  493. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  494. // TODO: prevent replay attacks
  495. int i = matching_peer_indexes[sender_idx];
  496. if (i >= 0 && i < acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  497. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  498. auto client = acl.getClientByIdx(i);
  499. client->out_path_len = mesh::Packet::copyPath(client->out_path, path, path_len); // store a copy of path, for sendDirect()
  500. client->last_activity = getRTCClock()->getCurrentTime();
  501. } else {
  502. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  503. }
  504. if (extra_type == PAYLOAD_TYPE_ACK && extra_len >= 4) {
  505. // also got an encoded ACK!
  506. processAck(extra);
  507. }
  508. // NOTE: no reciprocal path send!!
  509. return false;
  510. }
  511. void MyMesh::onAckRecv(mesh::Packet *packet, uint32_t ack_crc) {
  512. if (processAck((uint8_t *)&ack_crc)) {
  513. packet->markDoNotRetransmit(); // ACK was for this node, so don't retransmit
  514. }
  515. }
  516. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  517. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  518. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  519. _cli(board, rtc, sensors, acl, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4) {
  520. last_millis = 0;
  521. uptime_millis = 0;
  522. next_local_advert = next_flood_advert = 0;
  523. dirty_contacts_expiry = 0;
  524. _logging = false;
  525. set_radio_at = revert_radio_at = 0;
  526. // defaults
  527. memset(&_prefs, 0, sizeof(_prefs));
  528. _prefs.airtime_factor = 1.0; // one half
  529. _prefs.rx_delay_base = 0.0f; // off by default, was 10.0
  530. _prefs.tx_delay_factor = 0.5f; // was 0.25f;
  531. _prefs.direct_tx_delay_factor = 0.2f; // was zero
  532. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  533. _prefs.node_lat = ADVERT_LAT;
  534. _prefs.node_lon = ADVERT_LON;
  535. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  536. _prefs.freq = LORA_FREQ;
  537. _prefs.sf = LORA_SF;
  538. _prefs.bw = LORA_BW;
  539. _prefs.cr = LORA_CR;
  540. _prefs.tx_power_dbm = LORA_TX_POWER;
  541. _prefs.disable_fwd = 1;
  542. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  543. _prefs.flood_advert_interval = 12; // 12 hours
  544. _prefs.flood_max = 64;
  545. _prefs.interference_threshold = 0; // disabled
  546. #ifdef ROOM_PASSWORD
  547. StrHelper::strncpy(_prefs.guest_password, ROOM_PASSWORD, sizeof(_prefs.guest_password));
  548. #endif
  549. // GPS defaults
  550. _prefs.gps_enabled = 0;
  551. _prefs.gps_interval = 0;
  552. _prefs.advert_loc_policy = ADVERT_LOC_PREFS;
  553. next_post_idx = 0;
  554. next_client_idx = 0;
  555. next_push = 0;
  556. memset(posts, 0, sizeof(posts));
  557. _num_posted = _num_post_pushes = 0;
  558. }
  559. void MyMesh::begin(FILESYSTEM *fs) {
  560. mesh::Mesh::begin();
  561. _fs = fs;
  562. // load persisted prefs
  563. _cli.loadPrefs(_fs);
  564. acl.load(_fs, self_id);
  565. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  566. radio_set_tx_power(_prefs.tx_power_dbm);
  567. updateAdvertTimer();
  568. updateFloodAdvertTimer();
  569. board.setAdcMultiplier(_prefs.adc_multiplier);
  570. #if ENV_INCLUDE_GPS == 1
  571. applyGpsPrefs();
  572. #endif
  573. }
  574. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  575. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  576. pending_freq = freq;
  577. pending_bw = bw;
  578. pending_sf = sf;
  579. pending_cr = cr;
  580. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  581. }
  582. bool MyMesh::formatFileSystem() {
  583. #if defined(NRF52_PLATFORM)
  584. return InternalFS.format();
  585. #elif defined(RP2040_PLATFORM)
  586. return LittleFS.format();
  587. #elif defined(ESP32)
  588. return SPIFFS.format();
  589. #else
  590. #error "need to implement file system erase"
  591. return false;
  592. #endif
  593. }
  594. void MyMesh::sendSelfAdvertisement(int delay_millis, bool flood) {
  595. mesh::Packet *pkt = createSelfAdvert();
  596. if (pkt) {
  597. if (flood) {
  598. sendFlood(pkt, delay_millis); // TODO: which path_hash_size to use?
  599. } else {
  600. sendZeroHop(pkt, delay_millis);
  601. }
  602. } else {
  603. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  604. }
  605. }
  606. void MyMesh::updateAdvertTimer() {
  607. if (_prefs.advert_interval > 0) { // schedule local advert timer
  608. next_local_advert = futureMillis((uint32_t)_prefs.advert_interval * 2 * 60 * 1000);
  609. } else {
  610. next_local_advert = 0; // stop the timer
  611. }
  612. }
  613. void MyMesh::updateFloodAdvertTimer() {
  614. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  615. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  616. } else {
  617. next_flood_advert = 0; // stop the timer
  618. }
  619. }
  620. void MyMesh::dumpLogFile() {
  621. #if defined(RP2040_PLATFORM)
  622. File f = _fs->open(PACKET_LOG_FILE, "r");
  623. #else
  624. File f = _fs->open(PACKET_LOG_FILE);
  625. #endif
  626. if (f) {
  627. while (f.available()) {
  628. int c = f.read();
  629. if (c < 0) break;
  630. Serial.print((char)c);
  631. }
  632. f.close();
  633. }
  634. }
  635. void MyMesh::setTxPower(int8_t power_dbm) {
  636. radio_set_tx_power(power_dbm);
  637. }
  638. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  639. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  640. IdentityStore store(*_fs, "");
  641. #elif defined(ESP32)
  642. IdentityStore store(*_fs, "/identity");
  643. #elif defined(RP2040_PLATFORM)
  644. IdentityStore store(*_fs, "/identity");
  645. #else
  646. #error "need to define saveIdentity()"
  647. #endif
  648. store.save("_main", new_id);
  649. }
  650. void MyMesh::clearStats() {
  651. radio_driver.resetStats();
  652. resetStats();
  653. ((SimpleMeshTables *)getTables())->resetStats();
  654. }
  655. void MyMesh::formatStatsReply(char *reply) {
  656. StatsFormatHelper::formatCoreStats(reply, board, *_ms, _err_flags, _mgr);
  657. }
  658. void MyMesh::formatRadioStatsReply(char *reply) {
  659. StatsFormatHelper::formatRadioStats(reply, _radio, radio_driver, getTotalAirTime(), getReceiveAirTime());
  660. }
  661. void MyMesh::formatPacketStatsReply(char *reply) {
  662. StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(),
  663. getNumRecvFlood(), getNumRecvDirect());
  664. }
  665. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  666. while (*command == ' ')
  667. command++; // skip leading spaces
  668. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  669. memcpy(reply, command, 3); // reflect the prefix back
  670. reply += 3;
  671. command += 3;
  672. }
  673. // handle ACL related commands
  674. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  675. char* hex = &command[8];
  676. char* sp = strchr(hex, ' '); // look for separator char
  677. if (sp == NULL) {
  678. strcpy(reply, "Err - bad params");
  679. } else {
  680. *sp++ = 0; // replace space with null terminator
  681. uint8_t pubkey[PUB_KEY_SIZE];
  682. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  683. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  684. uint8_t perms = atoi(sp);
  685. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  686. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  687. strcpy(reply, "OK");
  688. } else {
  689. strcpy(reply, "Err - invalid params");
  690. }
  691. } else {
  692. strcpy(reply, "Err - bad pubkey");
  693. }
  694. }
  695. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  696. Serial.println("ACL:");
  697. for (int i = 0; i < acl.getNumClients(); i++) {
  698. auto c = acl.getClientByIdx(i);
  699. if (c->permissions == 0) continue; // skip deleted (or guest) entries
  700. Serial.printf("%02X ", c->permissions);
  701. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  702. Serial.printf("\n");
  703. }
  704. reply[0] = 0;
  705. } else{
  706. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  707. }
  708. }
  709. bool MyMesh::saveFilter(ClientInfo* client) {
  710. return client->isAdmin(); // only save Admins
  711. }
  712. void MyMesh::loop() {
  713. mesh::Mesh::loop();
  714. if (millisHasNowPassed(next_push) && acl.getNumClients() > 0) {
  715. // check for ACK timeouts
  716. for (int i = 0; i < acl.getNumClients(); i++) {
  717. auto c = acl.getClientByIdx(i);
  718. if (c->extra.room.pending_ack && millisHasNowPassed(c->extra.room.ack_timeout)) {
  719. c->extra.room.push_failures++;
  720. c->extra.room.pending_ack = 0; // reset (TODO: keep prev expected_ack's in a list, incase they arrive LATER, after we retry)
  721. MESH_DEBUG_PRINTLN("pending ACK timed out: push_failures: %d", (uint32_t)c->extra.room.push_failures);
  722. }
  723. }
  724. // check next Round-Robin client, and sync next new post
  725. auto client = acl.getClientByIdx(next_client_idx);
  726. bool did_push = false;
  727. if (client->extra.room.pending_ack == 0 && client->last_activity != 0 &&
  728. client->extra.room.push_failures < 3) { // not already waiting for ACK, AND not evicted, AND retries not max
  729. MESH_DEBUG_PRINTLN("loop - checking for client %02X", (uint32_t)client->id.pub_key[0]);
  730. uint32_t now = getRTCClock()->getCurrentTime();
  731. for (int k = 0, idx = next_post_idx; k < MAX_UNSYNCED_POSTS; k++) {
  732. auto p = &posts[idx];
  733. if (now >= p->post_timestamp + POST_SYNC_DELAY_SECS &&
  734. p->post_timestamp > client->extra.room.sync_since // is new post for this Client?
  735. && !p->author.matches(client->id)) { // don't push posts to the author
  736. // push this post to Client, then wait for ACK
  737. pushPostToClient(client, *p);
  738. did_push = true;
  739. MESH_DEBUG_PRINTLN("loop - pushed to client %02X: %s", (uint32_t)client->id.pub_key[0], p->text);
  740. break;
  741. }
  742. idx = (idx + 1) % MAX_UNSYNCED_POSTS; // wrap to start of cyclic queue
  743. }
  744. } else {
  745. MESH_DEBUG_PRINTLN("loop - skipping busy (or evicted) client %02X", (uint32_t)client->id.pub_key[0]);
  746. }
  747. next_client_idx = (next_client_idx + 1) % acl.getNumClients(); // round robin polling for each client
  748. if (did_push) {
  749. next_push = futureMillis(SYNC_PUSH_INTERVAL);
  750. } else {
  751. // were no unsynced posts for curr client, so proccess next client much quicker! (in next loop())
  752. next_push = futureMillis(SYNC_PUSH_INTERVAL / 8);
  753. }
  754. }
  755. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  756. mesh::Packet *pkt = createSelfAdvert();
  757. if (pkt) sendFlood(pkt);
  758. updateFloodAdvertTimer(); // schedule next flood advert
  759. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  760. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  761. mesh::Packet *pkt = createSelfAdvert();
  762. if (pkt) sendZeroHop(pkt);
  763. updateAdvertTimer(); // schedule next local advert
  764. }
  765. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  766. set_radio_at = 0; // clear timer
  767. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  768. MESH_DEBUG_PRINTLN("Temp radio params");
  769. }
  770. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  771. revert_radio_at = 0; // clear timer
  772. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  773. MESH_DEBUG_PRINTLN("Radio params restored");
  774. }
  775. // is pending dirty contacts write needed?
  776. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  777. acl.save(_fs, MyMesh::saveFilter);
  778. dirty_contacts_expiry = 0;
  779. }
  780. // TODO: periodically check for OLD/inactive entries in known_clients[], and evict
  781. // update uptime
  782. uint32_t now = millis();
  783. uptime_millis += now - last_millis;
  784. last_millis = now;
  785. }