main.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. #include <Arduino.h> // needed for PlatformIO
  2. #include <Mesh.h>
  3. #include <SPIFFS.h>
  4. #define RADIOLIB_STATIC_ONLY 1
  5. #include <RadioLib.h>
  6. #include <helpers/CustomSX1262Wrapper.h>
  7. #include <helpers/ArduinoHelpers.h>
  8. #include <helpers/StaticPoolPacketManager.h>
  9. #include <helpers/SimpleMeshTables.h>
  10. #include <helpers/IdentityStore.h>
  11. /* ------------------------------ Config -------------------------------- */
  12. #define ANNOUNCE_DATA "repeater:v1"
  13. #define ADMIN_PASSWORD "h^(kl@#)"
  14. #if defined(HELTEC_LORA_V3)
  15. #include <helpers/HeltecV3Board.h>
  16. static HeltecV3Board board;
  17. #else
  18. #error "need to provide a 'board' object"
  19. #endif
  20. /* ------------------------------ Code -------------------------------- */
  21. #define CMD_GET_STATS 0x01
  22. #define CMD_SET_CLOCK 0x02
  23. #define CMD_SEND_ANNOUNCE 0x03
  24. #define CMD_SET_CONFIG 0x04
  25. struct RepeaterStats {
  26. uint16_t batt_milli_volts;
  27. uint16_t curr_tx_queue_len;
  28. uint16_t curr_free_queue_len;
  29. int16_t last_rssi;
  30. uint32_t n_packets_recv;
  31. uint32_t n_packets_sent;
  32. uint32_t total_air_time_secs;
  33. uint32_t total_up_time_secs;
  34. };
  35. struct ClientInfo {
  36. mesh::Identity id;
  37. uint32_t last_timestamp;
  38. uint8_t secret[PUB_KEY_SIZE];
  39. int out_path_len;
  40. uint8_t out_path[MAX_PATH_SIZE];
  41. };
  42. #define MAX_CLIENTS 4
  43. class MyMesh : public mesh::Mesh {
  44. RadioLibWrapper* my_radio;
  45. mesh::MeshTables* _tables;
  46. float airtime_factor;
  47. uint8_t reply_data[MAX_PACKET_PAYLOAD];
  48. int num_clients;
  49. ClientInfo known_clients[MAX_CLIENTS];
  50. ClientInfo* putClient(const mesh::Identity& id) {
  51. for (int i = 0; i < num_clients; i++) {
  52. if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
  53. }
  54. if (num_clients < MAX_CLIENTS) {
  55. auto newClient = &known_clients[num_clients++];
  56. newClient->id = id;
  57. newClient->out_path_len = -1; // initially out_path is unknown
  58. newClient->last_timestamp = 0;
  59. self_id.calcSharedSecret(newClient->secret, id); // calc ECDH shared secret
  60. return newClient;
  61. }
  62. return NULL; // table is full
  63. }
  64. int handleRequest(ClientInfo* sender, uint8_t* payload, size_t payload_len) {
  65. uint32_t now = getRTCClock()->getCurrentTime();
  66. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  67. switch (payload[0]) {
  68. case CMD_GET_STATS: {
  69. uint32_t max_age_secs;
  70. if (payload_len >= 5) {
  71. memcpy(&max_age_secs, &payload[1], 4); // first param in request pkt
  72. } else {
  73. max_age_secs = 12*60*60; // default, 12 hours
  74. }
  75. RepeaterStats stats;
  76. stats.batt_milli_volts = board.getBattMilliVolts();
  77. stats.curr_tx_queue_len = _mgr->getOutboundCount();
  78. stats.curr_free_queue_len = _mgr->getFreeCount();
  79. stats.last_rssi = (int16_t) my_radio->getLastRSSI();
  80. stats.n_packets_recv = my_radio->getPacketsRecv();
  81. stats.n_packets_sent = my_radio->getPacketsSent();
  82. stats.total_air_time_secs = getTotalAirTime() / 1000;
  83. stats.total_up_time_secs = _ms->getMillis() / 1000;
  84. memcpy(&reply_data[4], &stats, sizeof(stats));
  85. return 4 + sizeof(stats); // reply_len
  86. }
  87. case CMD_SET_CLOCK: {
  88. if (payload_len >= 5) {
  89. uint32_t curr_epoch_secs;
  90. memcpy(&curr_epoch_secs, &payload[1], 4); // first param is current UNIX time
  91. if (curr_epoch_secs > now) { // time can only go forward!!
  92. getRTCClock()->setCurrentTime(curr_epoch_secs);
  93. memcpy(&reply_data[4], "OK", 2);
  94. } else {
  95. memcpy(&reply_data[4], "ER", 2);
  96. }
  97. return 4 + 2; // reply_len
  98. }
  99. return 0; // invalid request
  100. }
  101. case CMD_SEND_ANNOUNCE: {
  102. // broadcast another self Advertisement
  103. auto adv = createAdvert(self_id, (const uint8_t *)ANNOUNCE_DATA, strlen(ANNOUNCE_DATA));
  104. if (adv) sendFlood(adv, 1500); // send after slight delay
  105. memcpy(&reply_data[4], "OK", 2);
  106. return 4 + 2; // reply_len
  107. }
  108. case CMD_SET_CONFIG: {
  109. if (payload_len >= 4 && payload_len < 32 && memcmp(&payload[1], "AF", 2) == 0) {
  110. payload[payload_len] = 0; // make it a C string
  111. airtime_factor = atof((char *) &payload[3]);
  112. memcpy(&reply_data[4], "OK", 2);
  113. return 4 + 2; // reply_len
  114. }
  115. return 0; // unknown config var
  116. }
  117. }
  118. // unknown command
  119. return 0; // reply_len
  120. }
  121. protected:
  122. float getAirtimeBudgetFactor() const override {
  123. return airtime_factor;
  124. }
  125. bool allowPacketForward(mesh::Packet* packet) override {
  126. uint8_t hash[MAX_HASH_SIZE];
  127. packet->calculatePacketHash(hash);
  128. if (_tables->hasForwarded(hash)) return false; // has already been forwarded
  129. _tables->setHasForwarded(hash); // mark packet as forwarded
  130. return true; // Yes, allow packet to be forwarded
  131. }
  132. void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override {
  133. if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
  134. uint32_t timestamp;
  135. memcpy(&timestamp, data, 4);
  136. if (memcmp(&data[4], ADMIN_PASSWORD, 8) == 0) { // check for valid password
  137. auto client = putClient(sender); // add to known clients (if not already known)
  138. if (client == NULL || timestamp <= client->last_timestamp) {
  139. return; // FATAL: client table is full -OR- replay attack -OR- have seen this packet before
  140. }
  141. client->last_timestamp = timestamp;
  142. uint32_t now = getRTCClock()->getCurrentTime();
  143. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  144. memcpy(&reply_data[4], "OK", 2);
  145. if (packet->isRouteFlood()) {
  146. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  147. mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
  148. PAYLOAD_TYPE_RESPONSE, reply_data, 4 + 2);
  149. if (path) sendFlood(path);
  150. } else {
  151. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, reply_data, 4 + 2);
  152. if (reply) {
  153. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  154. sendDirect(reply, client->out_path, client->out_path_len);
  155. } else {
  156. sendFlood(reply);
  157. }
  158. }
  159. }
  160. }
  161. }
  162. }
  163. int matching_peer_indexes[MAX_CLIENTS];
  164. int searchPeersByHash(const uint8_t* hash) override {
  165. int n = 0;
  166. for (int i = 0; i < num_clients; i++) {
  167. if (known_clients[i].id.isHashMatch(hash)) {
  168. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  169. }
  170. }
  171. return n;
  172. }
  173. void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
  174. int i = matching_peer_indexes[peer_idx];
  175. if (i >= 0 && i < num_clients) {
  176. // lookup pre-calculated shared_secret
  177. memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
  178. } else {
  179. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  180. }
  181. }
  182. void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, uint8_t* data, size_t len) override {
  183. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  184. int i = matching_peer_indexes[sender_idx];
  185. if (i >= 0 && i < num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
  186. auto client = &known_clients[i];
  187. uint32_t timestamp;
  188. memcpy(&timestamp, data, 4);
  189. if (timestamp > client->last_timestamp) { // prevent replay attacks AND receiving via multiple paths
  190. int reply_len = handleRequest(client, &data[4], len - 4);
  191. if (reply_len == 0) return; // invalid command
  192. client->last_timestamp = timestamp;
  193. if (packet->isRouteFlood()) {
  194. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  195. mesh::Packet* path = createPathReturn(client->id, client->secret, packet->path, packet->path_len,
  196. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  197. if (path) sendFlood(path);
  198. } else {
  199. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, client->secret, reply_data, reply_len);
  200. if (reply) {
  201. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  202. sendDirect(reply, client->out_path, client->out_path_len);
  203. } else {
  204. sendFlood(reply);
  205. }
  206. }
  207. }
  208. }
  209. } else {
  210. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  211. }
  212. }
  213. }
  214. void onPeerPathRecv(mesh::Packet* packet, int sender_idx, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
  215. // TODO: prevent replay attacks
  216. int i = matching_peer_indexes[sender_idx];
  217. if (i >= 0 && i < num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
  218. Serial.printf("PATH to client, path_len=%d\n", (uint32_t) path_len);
  219. auto client = &known_clients[i];
  220. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  221. } else {
  222. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  223. }
  224. // NOTE: no reciprocal path send!!
  225. }
  226. public:
  227. MyMesh(RadioLibWrapper& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
  228. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32)), _tables(&tables)
  229. {
  230. my_radio = &radio;
  231. airtime_factor = 5.0; // 1/6th
  232. num_clients = 0;
  233. }
  234. void sendSelfAdvertisement() {
  235. mesh::Packet* pkt = createAdvert(self_id, (const uint8_t *)ANNOUNCE_DATA, strlen(ANNOUNCE_DATA));
  236. if (pkt) {
  237. sendFlood(pkt);
  238. } else {
  239. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  240. }
  241. }
  242. };
  243. #if defined(P_LORA_SCLK)
  244. SPIClass spi;
  245. CustomSX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  246. #else
  247. CustomSX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
  248. #endif
  249. StdRNG fast_rng;
  250. SimpleMeshTables tables;
  251. MyMesh the_mesh(*new CustomSX1262Wrapper(radio, board), *new ArduinoMillis(), fast_rng, *new VolatileRTCClock(), tables);
  252. void halt() {
  253. while (1) ;
  254. }
  255. void setup() {
  256. Serial.begin(115200);
  257. delay(5000);
  258. board.begin();
  259. #if defined(P_LORA_SCLK)
  260. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  261. int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
  262. #else
  263. int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
  264. #endif
  265. if (status != RADIOLIB_ERR_NONE) {
  266. Serial.print("ERROR: radio init failed: ");
  267. Serial.println(status);
  268. halt();
  269. }
  270. SPIFFS.begin(true);
  271. IdentityStore store(SPIFFS, "/identity");
  272. if (!store.load("_main", the_mesh.self_id)) {
  273. the_mesh.self_id = mesh::LocalIdentity(the_mesh.getRNG()); // create new random identity
  274. store.save("_main", the_mesh.self_id);
  275. }
  276. Serial.print("Repeater ID: ");
  277. mesh::Utils::printHex(Serial, the_mesh.self_id.pub_key, PUB_KEY_SIZE); Serial.println();
  278. the_mesh.begin();
  279. // send out initial Advertisement to the mesh
  280. the_mesh.sendSelfAdvertisement();
  281. }
  282. void loop() {
  283. the_mesh.loop();
  284. // TODO: periodically check for OLD/inactive entries in known_clients[], and evict
  285. }