InterfaceController.c 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "crypto/AddressCalc.h"
  16. #include "crypto/Ca.h"
  17. #include "interface/Iface.h"
  18. #include "net/InterfaceController.h"
  19. #include "memory/Allocator.h"
  20. #include "net/SwitchPinger.h"
  21. #include "wire/PFChan.h"
  22. #include "net/EventEmitter.h"
  23. #include "util/Base32.h"
  24. #include "util/Bits.h"
  25. #include "util/events/Time.h"
  26. #include "util/events/Timeout.h"
  27. #include "util/Identity.h"
  28. #include "util/version/Version.h"
  29. #include "util/AddrTools.h"
  30. #include "util/Defined.h"
  31. #include "util/Checksum.h"
  32. #include "util/Hex.h"
  33. #include "util/Kbps.h"
  34. #include "wire/Error.h"
  35. #include "wire/Message.h"
  36. #include "wire/Headers.h"
  37. #include "wire/Metric.h"
  38. #include "wire/CryptoHeader.h"
  39. /** After this number of milliseconds, a node will be regarded as unresponsive. */
  40. #define UNRESPONSIVE_AFTER_MILLISECONDS (20*1024)
  41. /**
  42. * After this number of milliseconds without a valid incoming message,
  43. * a peer is "lazy" and should be pinged.
  44. */
  45. #define PING_AFTER_MILLISECONDS (3*1024)
  46. /** How often to ping "lazy" peers, "unresponsive" peers are only pinged 20% of the time. */
  47. #define PING_INTERVAL_MILLISECONDS 1024
  48. /** The number of milliseconds to wait for a ping response. */
  49. #define TIMEOUT_MILLISECONDS (2*1024)
  50. /**
  51. * The number of seconds to wait before an unresponsive peer
  52. * making an incoming connection is forgotten.
  53. */
  54. #define FORGET_AFTER_MILLISECONDS (256*1024)
  55. /** Wait 32 seconds between sending beacon messages. */
  56. #define BEACON_INTERVAL 32768
  57. /** Every 3 seconds inform the pathfinder of the current link states. */
  58. #define LINKSTATE_UPDATE_INTERVAL 3000
  59. // Recommended by boringtun documentation
  60. #define HANDSHAKE_CYCLE_INTERVAL 100
  61. // ---------------- Map ----------------
  62. #define Map_NAME EndpointsBySockaddr
  63. #define Map_ENABLE_HANDLES
  64. #define Map_KEY_TYPE struct Sockaddr*
  65. #define Map_VALUE_TYPE struct Peer*
  66. #define Map_USE_HASH
  67. #define Map_USE_COMPARATOR
  68. #include "util/Map.h"
  69. static inline uint32_t Map_EndpointsBySockaddr_hash(struct Sockaddr** key)
  70. {
  71. return Sockaddr_hash(*key);
  72. }
  73. static inline int Map_EndpointsBySockaddr_compare(struct Sockaddr** keyA, struct Sockaddr** keyB)
  74. {
  75. return Sockaddr_compare(*keyA, *keyB);
  76. }
  77. // ---------------- EndMap ----------------
  78. #define ArrayList_TYPE struct InterfaceController_Iface_pvt
  79. #define ArrayList_NAME OfIfaces
  80. #include "util/ArrayList.h"
  81. struct InterfaceController_pvt;
  82. struct InterfaceController_Iface_pvt
  83. {
  84. struct InterfaceController_Iface pub;
  85. struct Map_EndpointsBySockaddr peerMap;
  86. /** The number of the next peer to try pinging, this iterates through the list of peers. */
  87. uint32_t lastPeerPinged;
  88. struct InterfaceController_pvt* ic;
  89. struct Allocator* alloc;
  90. Identity
  91. };
  92. struct Peer
  93. {
  94. /** The interface which is registered with the switch. */
  95. struct Iface switchIf;
  96. struct Iface plaintext;
  97. struct Iface ciphertext;
  98. struct Allocator* alloc;
  99. Ca_Session_t* caSession;
  100. struct Kbps sendBw;
  101. struct Kbps recvBw;
  102. /** The interface which this peer belongs to. */
  103. struct InterfaceController_Iface_pvt* ici;
  104. /** The address within the interface of this peer. */
  105. struct Sockaddr* lladdr;
  106. struct Address addr;
  107. /** Milliseconds since the epoch when the last *valid* message was received. */
  108. uint64_t timeOfLastMessage;
  109. /** Time when the last switch ping response was received from this node. */
  110. uint64_t timeOfLastPing;
  111. /** A counter to allow for 3/4 of all pings to be skipped when a node is definitely down. */
  112. uint32_t pingCount;
  113. /** The handle which can be used to look up this endpoint in the endpoint set. */
  114. uint32_t handle;
  115. /** True if we should forget about the peer if they do not respond. */
  116. bool isIncomingConnection;
  117. /**
  118. * If InterfaceController_PeerState_UNAUTHENTICATED, no permanent state will be kept.
  119. * During transition from HANDSHAKE to ESTABLISHED, a check is done for a registeration of a
  120. * node which is already registered in a different switch slot, if there is one and the
  121. * handshake completes, it will be moved.
  122. */
  123. enum InterfaceController_PeerState state;
  124. /**
  125. * The number of lost packets last time we checked.
  126. * _lastDrops and _lastPackets are the direct readings off of the ReplayProtector
  127. * so they will be reset to zero when the session resets. lastDrops and lastPackets
  128. * are monotonic and so probably what you want.
  129. */
  130. uint64_t _lastDrops;
  131. uint64_t _lastPackets;
  132. uint64_t lastDrops;
  133. uint64_t lastPackets;
  134. // traffic counters
  135. uint64_t bytesOut;
  136. uint64_t bytesIn;
  137. Identity
  138. };
  139. struct InterfaceController_pvt
  140. {
  141. /** Public functions and fields for this ifcontroller. */
  142. struct InterfaceController pub;
  143. struct Allocator* const alloc;
  144. Ca_t* const ca;
  145. /** Switch for adding nodes when they are discovered. */
  146. struct SwitchCore* const switchCore;
  147. struct Random* const rand;
  148. struct Log* const logger;
  149. struct EventBase* const eventBase;
  150. /** For communicating with the Pathfinder. */
  151. struct Iface eventEmitterIf;
  152. /** After this number of milliseconds, a neoghbor will be regarded as unresponsive. */
  153. uint32_t unresponsiveAfterMilliseconds;
  154. /** The number of milliseconds to wait before pinging. */
  155. uint32_t pingAfterMilliseconds;
  156. /** The number of milliseconds to let a ping go before timing it out. */
  157. uint32_t timeoutMilliseconds;
  158. /** After this number of milliseconds, an incoming connection is forgotten entirely. */
  159. uint32_t forgetAfterMilliseconds;
  160. /** How often to send beacon messages (milliseconds). */
  161. uint32_t beaconInterval;
  162. // Whether or not to create sessions using the noise protocol
  163. const bool enableNoise;
  164. /** The timeout event to use for pinging potentially unresponsive neighbors. */
  165. struct Timeout* const pingInterval;
  166. /** The timeout event for updating the link state to the pathfinders. */
  167. struct Timeout* const linkStateInterval;
  168. // Timeout for noise re-handshakes
  169. struct Timeout* const noiseHandshakeInterval;
  170. /** For pinging lazy/unresponsive nodes. */
  171. struct SwitchPinger* const switchPinger;
  172. struct ArrayList_OfIfaces* icis;
  173. /** Temporary allocator for allocating timeouts for sending beacon messages. */
  174. struct Allocator* beaconTimeoutAlloc;
  175. /** A password which is generated per-startup and sent out in beacon messages. */
  176. uint8_t beaconPassword[Headers_Beacon_PASSWORD_LEN];
  177. struct Headers_Beacon beacon;
  178. uint8_t ourPubKey[32];
  179. Identity
  180. };
  181. static bool knownIncompatibleVersion(uint32_t version)
  182. {
  183. if (!version) {
  184. return false;
  185. } else if (Defined(SUBNODE) && version < 21) {
  186. // Subnode doesn't talk to peers with less than v21
  187. return true;
  188. }
  189. return !Version_isCompatible(version, Version_CURRENT_PROTOCOL);
  190. }
  191. static void sendPeer(uint32_t pathfinderId,
  192. enum PFChan_Core ev,
  193. struct Peer* peer,
  194. uint16_t latency)
  195. {
  196. if (!peer->addr.protocolVersion || knownIncompatibleVersion(peer->addr.protocolVersion)) {
  197. // Don't know the protocol version, never add them
  198. return;
  199. }
  200. struct InterfaceController_pvt* ic = Identity_check(peer->ici->ic);
  201. struct Allocator* alloc = Allocator_child(ic->alloc);
  202. struct Message* msg = Message_new(PFChan_Node_SIZE, 512, alloc);
  203. struct PFChan_Node* node = (struct PFChan_Node*) msg->msgbytes;
  204. Bits_memcpy(node->ip6, peer->addr.ip6.bytes, 16);
  205. Bits_memcpy(node->publicKey, peer->addr.key, 32);
  206. node->path_be = Endian_hostToBigEndian64(peer->addr.path);
  207. node->version_be = Endian_hostToBigEndian32(peer->addr.protocolVersion);
  208. if (ev != PFChan_Core_PEER_GONE) {
  209. Assert_true(peer->addr.protocolVersion);
  210. node->metric_be =
  211. Endian_hostToBigEndian32(Metric_IC_PEER | (latency & Metric_IC_PEER_MASK));
  212. } else {
  213. node->metric_be = Endian_hostToBigEndian32(Metric_DEAD_LINK);
  214. }
  215. Er_assert(Message_epush32be(msg, pathfinderId));
  216. Er_assert(Message_epush32be(msg, ev));
  217. Iface_send(&ic->eventEmitterIf, msg);
  218. Allocator_free(alloc);
  219. }
  220. static void onPingResponse(struct SwitchPinger_Response* resp, void* onResponseContext)
  221. {
  222. if (SwitchPinger_Result_OK != resp->res) {
  223. return;
  224. }
  225. struct Peer* ep = Identity_check((struct Peer*) onResponseContext);
  226. struct InterfaceController_pvt* ic = Identity_check(ep->ici->ic);
  227. ep->addr.protocolVersion = resp->version;
  228. if (Defined(Log_DEBUG)) {
  229. String* addr = Address_toString(&ep->addr, resp->ping->pingAlloc);
  230. if (knownIncompatibleVersion(resp->version)) {
  231. Log_debug(ic->logger, "got switch pong from node [%s] with incompatible version",
  232. addr->bytes);
  233. } else if (ep->addr.path != resp->label) {
  234. uint8_t sl[20];
  235. AddrTools_printPath(sl, resp->label);
  236. Log_debug(ic->logger, "got switch pong from node [%s] mismatch label [%s]",
  237. addr->bytes, sl);
  238. } else {
  239. Log_debug(ic->logger, "got switch pong from node [%s]", addr->bytes);
  240. }
  241. }
  242. if (knownIncompatibleVersion(resp->version) || ep->addr.path != resp->label) {
  243. ep->state = InterfaceController_PeerState_INCOMPATIBLE;
  244. return;
  245. }
  246. if (ep->state == InterfaceController_PeerState_ESTABLISHED) {
  247. sendPeer(0xffffffff, PFChan_Core_PEER, ep, resp->milliseconds);
  248. }
  249. ep->timeOfLastPing = Time_currentTimeMilliseconds();
  250. if (Defined(Log_DEBUG)) {
  251. String* addr = Address_toString(&ep->addr, resp->ping->pingAlloc);
  252. Log_debug(ic->logger, "Received [%s] from lazy endpoint [%s], state: [%s]",
  253. SwitchPinger_resultString(resp->res)->bytes, addr->bytes,
  254. InterfaceController_stateString(ep->state));
  255. }
  256. }
  257. /*
  258. * Send a ping packet to one of the endpoints.
  259. */
  260. static void sendPing(struct Peer* ep)
  261. {
  262. struct InterfaceController_pvt* ic = Identity_check(ep->ici->ic);
  263. ep->pingCount++;
  264. struct SwitchPinger_Ping* ping =
  265. SwitchPinger_newPing(ep->addr.path,
  266. String_CONST(""),
  267. ic->timeoutMilliseconds,
  268. onPingResponse,
  269. ep->alloc,
  270. ic->switchPinger);
  271. if (!ping) {
  272. struct Allocator* alloc = Allocator_child(ep->alloc);
  273. Log_debug(ic->logger, "Sending switch ping to [%s] failed, out of ping slots",
  274. Address_toString(&ep->addr, alloc)->bytes);
  275. Allocator_free(alloc);
  276. } else {
  277. Log_debug(ic->logger, "Sending switch ping to [%s]",
  278. Address_toString(&ep->addr, ping->pingAlloc)->bytes);
  279. }
  280. if (ping) {
  281. ping->onResponseContext = ep;
  282. }
  283. }
  284. static void linkState(void* vic)
  285. {
  286. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) vic);
  287. uint32_t msgLen = 64;
  288. for (int i = 0; i < ic->icis->length; i++) {
  289. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  290. msgLen += PFChan_LinkState_Entry_SIZE * ici->peerMap.count;
  291. }
  292. struct Allocator* alloc = Allocator_child(ic->alloc);
  293. struct Message* msg = Message_new(0, msgLen, alloc);
  294. for (int i = 0; i < ic->icis->length; i++) {
  295. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  296. for (uint32_t i = 0; i < ici->peerMap.count; i++) {
  297. struct Peer* ep = ici->peerMap.values[i];
  298. RTypes_CryptoStats_t stats;
  299. Ca_stats(ep->caSession, &stats);
  300. uint64_t newDrops = 0;
  301. // Prevents invalid number when the session resets
  302. if (stats.lost_packets > ep->_lastDrops) {
  303. newDrops = stats.lost_packets - ep->_lastDrops;
  304. }
  305. ep->_lastDrops = stats.lost_packets;
  306. ep->lastDrops += newDrops;
  307. uint64_t newPackets = 0;
  308. if (stats.received_packets > ep->_lastPackets) {
  309. newPackets = stats.received_packets - ep->_lastPackets;
  310. }
  311. ep->_lastPackets = stats.received_packets;
  312. ep->lastPackets += newPackets;
  313. struct PFChan_LinkState_Entry e = {
  314. .peerLabel = ep->addr.path,
  315. .sumOfPackets = ep->lastPackets,
  316. .sumOfDrops = ep->lastDrops,
  317. .sumOfKb = (ep->bytesIn >> 10),
  318. };
  319. Er_assert(Message_epush(msg, &e, PFChan_LinkState_Entry_SIZE));
  320. }
  321. }
  322. if (Message_getLength(msg)) {
  323. Er_assert(Message_epush32be(msg, 0xffffffff));
  324. Er_assert(Message_epush32be(msg, PFChan_Core_LINK_STATE));
  325. Iface_send(&ic->eventEmitterIf, msg);
  326. }
  327. Allocator_free(alloc);
  328. }
  329. static void iciPing(struct InterfaceController_Iface_pvt* ici, struct InterfaceController_pvt* ic)
  330. {
  331. if (!ici->peerMap.count) { return; }
  332. uint64_t now = Time_currentTimeMilliseconds();
  333. // scan for endpoints have not sent anything recently.
  334. uint32_t startAt = ici->lastPeerPinged = (ici->lastPeerPinged + 1) % ici->peerMap.count;
  335. for (uint32_t i = startAt, count = 0; count < ici->peerMap.count;) {
  336. i = (i + 1) % ici->peerMap.count;
  337. count++;
  338. struct Peer* ep = ici->peerMap.values[i];
  339. if (knownIncompatibleVersion(ep->addr.protocolVersion)) {
  340. // This is a version mismatch, we have nothing to do with this node
  341. // but we keep the session in INCOMPATIBLE state to keep track of the
  342. // fact that we don't want to talk to it.
  343. ep->state = InterfaceController_PeerState_INCOMPATIBLE;
  344. continue;
  345. }
  346. uint8_t ipIfDebug[40];
  347. if (Defined(Log_DEBUG)) {
  348. Address_printIp(ipIfDebug, &ep->addr);
  349. }
  350. if (ep->addr.protocolVersion && now < ep->timeOfLastMessage + ic->pingAfterMilliseconds) {
  351. // It's sending traffic so leave it alone.
  352. // wait just a minute here !
  353. // There is a risk that the NodeStore somehow forgets about our peers while the peers
  354. // are still happily sending traffic. To break this bad cycle lets just send a PEER
  355. // message once per second for whichever peer is the first that we address.
  356. if (count == 1 && ep->state == InterfaceController_PeerState_ESTABLISHED) {
  357. // noisy
  358. //Log_debug(ic->logger, "Notifying about peer number [%d/%d] [%s]",
  359. // i, ici->peerMap.count, ipIfDebug);
  360. sendPeer(0xffffffff, PFChan_Core_PEER, ep, 0xffff);
  361. }
  362. continue;
  363. }
  364. if (now < ep->timeOfLastPing + ic->pingAfterMilliseconds) {
  365. // Possibly an out-of-date node which is mangling packets, don't ping too often
  366. // because it causes the RumorMill to be filled with this node over and over.
  367. continue;
  368. }
  369. if (ep->isIncomingConnection && now > ep->timeOfLastMessage + ic->forgetAfterMilliseconds) {
  370. Log_debug(ic->logger, "Unresponsive peer [%s] has not responded in [%u] "
  371. "seconds, dropping connection",
  372. ipIfDebug, ic->forgetAfterMilliseconds / 1024);
  373. sendPeer(0xffffffff, PFChan_Core_PEER_GONE, ep, 0xffff);
  374. Allocator_free(ep->alloc);
  375. continue;
  376. }
  377. bool unresponsive = (now > ep->timeOfLastMessage + ic->unresponsiveAfterMilliseconds);
  378. if (unresponsive) {
  379. // our link to the peer is broken...
  380. // Lets skip 87% of pings when they're really down.
  381. if (ep->pingCount % 8) {
  382. ep->pingCount++;
  383. continue;
  384. }
  385. sendPeer(0xffffffff, PFChan_Core_PEER_GONE, ep, 0xffff);
  386. ep->state = InterfaceController_PeerState_UNRESPONSIVE;
  387. }
  388. Log_debug(ic->logger,
  389. "Pinging %s peer [%s] lag [%u]",
  390. (unresponsive ? "unresponsive" : "lazy"),
  391. ipIfDebug,
  392. (uint32_t)((now - ep->timeOfLastMessage) / 1024));
  393. sendPing(ep);
  394. // we only ping one node
  395. return;
  396. }
  397. }
  398. /**
  399. * Check the table for nodes which might need to be pinged, ping a node if necessary.
  400. * If a node has not responded in unresponsiveAfterMilliseconds then mark them as unresponsive
  401. * and if the connection is incoming and the node has not responded in forgetAfterMilliseconds
  402. * then drop them entirely.
  403. * This is called every PING_INTERVAL_MILLISECONDS
  404. */
  405. static void pingCycle(void* vic)
  406. {
  407. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) vic);
  408. for (int i = 0; i < ic->icis->length; i++) {
  409. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  410. iciPing(ici, ic);
  411. }
  412. }
  413. static Iface_DEFUN afterEncrypt(struct Message* msg, struct Iface* ciphertext)
  414. {
  415. struct Peer* ep = Identity_containerOf(ciphertext, struct Peer, ciphertext);
  416. // push the lladdr...
  417. Er_assert(Message_epush(msg, ep->lladdr, ep->lladdr->addrLen));
  418. // very noisy
  419. if (Defined(Log_DEBUG) && false) {
  420. char* printedAddr =
  421. Hex_print(&ep->lladdr[1], ep->lladdr->addrLen - Sockaddr_OVERHEAD, Message_getAlloc(msg));
  422. Log_debug(ep->ici->ic->logger, "Outgoing message to [%s]", printedAddr);
  423. }
  424. return Iface_send(&ep->ici->pub.addrIf, msg);
  425. }
  426. // This is directly called from SwitchCore, message is not encrypted.
  427. static Iface_DEFUN sendFromSwitch(struct Message* msg, struct Iface* switchIf)
  428. {
  429. struct Peer* ep = Identity_check((struct Peer*) switchIf);
  430. // Once we know it to be an incompetible version, we quarentine it
  431. if (knownIncompatibleVersion(ep->addr.protocolVersion)) {
  432. if (Defined(Log_DEBUG)) {
  433. Log_debug(ep->ici->ic->logger, "[%s] DROP msg to node with incompat version [%d] ",
  434. Address_toString(&ep->addr, Message_getAlloc(msg))->bytes, ep->addr.protocolVersion);
  435. }
  436. ep->state = InterfaceController_PeerState_INCOMPATIBLE;
  437. return Error(msg, "UNHANDLED");
  438. }
  439. ep->bytesOut += Message_getLength(msg);
  440. Kbps_accumulate(&ep->sendBw, Time_currentTimeMilliseconds(), Message_getLength(msg));
  441. return Iface_next(&ep->plaintext, msg); // --> afterEncrypt
  442. }
  443. static int closeInterface(struct Allocator_OnFreeJob* job)
  444. {
  445. struct Peer* toClose = Identity_check((struct Peer*) job->userData);
  446. int index = Map_EndpointsBySockaddr_indexForHandle(toClose->handle, &toClose->ici->peerMap);
  447. if (index < 0 || toClose->ici->peerMap.values[index] != toClose) {
  448. // Happens if the ep was created as a result of handleUnexpectedIncoming
  449. return 0;
  450. }
  451. sendPeer(0xffffffff, PFChan_Core_PEER_GONE, toClose, 0xffff);
  452. Log_debug(toClose->ici->ic->logger,
  453. "Closing interface [%d] with handle [%u]", index, toClose->handle);
  454. Map_EndpointsBySockaddr_remove(index, &toClose->ici->peerMap);
  455. return 0;
  456. }
  457. static Iface_DEFUN afterDecrypt(struct Message* msg, struct Iface* plaintext);
  458. static struct Peer* mkEp(
  459. const struct Sockaddr* lladdr,
  460. struct InterfaceController_Iface_pvt* ici,
  461. uint8_t publicKey[32],
  462. bool authNeeded,
  463. const char* name,
  464. bool useNoise
  465. ) {
  466. struct Allocator* epAlloc = Allocator_child(ici->alloc);
  467. struct Peer* ep = Allocator_calloc(epAlloc, sizeof(struct Peer), 1);
  468. Identity_set(ep);
  469. ep->ici = ici;
  470. ep->lladdr = Sockaddr_clone(lladdr, epAlloc);
  471. ep->alloc = epAlloc;
  472. ep->state = InterfaceController_PeerState_UNAUTHENTICATED;
  473. ep->isIncomingConnection = false;
  474. ep->switchIf.send = sendFromSwitch;
  475. ep->ciphertext.send = afterEncrypt;
  476. ep->plaintext.send = afterDecrypt;
  477. useNoise = useNoise && ici->ic->enableNoise;
  478. ep->caSession = Ca_newSession(ici->ic->ca, epAlloc, publicKey, authNeeded, name, useNoise);
  479. Iface_plumb(ep->caSession->ciphertext, &ep->ciphertext);
  480. Iface_plumb(ep->caSession->plaintext, &ep->plaintext);
  481. Bits_memcpy(ep->addr.key, publicKey, 32);
  482. Address_getPrefix(&ep->addr);
  483. Allocator_onFree(epAlloc, closeInterface, ep);
  484. return ep;
  485. }
  486. static struct Peer* epFromSess(
  487. const struct Sockaddr* lladdr,
  488. struct InterfaceController_Iface_pvt* ici,
  489. Ca_Session_t* sess,
  490. Allocator_t* alloc
  491. ) {
  492. struct Peer* ep = Allocator_calloc(alloc, sizeof(struct Peer), 1);
  493. Identity_set(ep);
  494. ep->ici = ici;
  495. ep->lladdr = Sockaddr_clone(lladdr, alloc);
  496. ep->alloc = alloc;
  497. ep->state = InterfaceController_PeerState_UNAUTHENTICATED;
  498. ep->isIncomingConnection = true;
  499. ep->switchIf.send = sendFromSwitch;
  500. ep->ciphertext.send = afterEncrypt;
  501. ep->plaintext.send = afterDecrypt;
  502. ep->caSession = sess;
  503. Iface_plumb(ep->caSession->ciphertext, &ep->ciphertext);
  504. Iface_plumb(ep->caSession->plaintext, &ep->plaintext);
  505. Ca_getHerPubKey(sess, ep->addr.key);
  506. ep->addr.protocolVersion = Rffi_CryptoAuth2_cjdnsVer(sess);
  507. Address_getPrefix(&ep->addr);
  508. Allocator_onFree(alloc, closeInterface, ep);
  509. return ep;
  510. }
  511. /**
  512. * Expects [ struct LLAddress ][ beacon ]
  513. */
  514. static Iface_DEFUN handleBeacon(
  515. struct Message* msg,
  516. struct InterfaceController_Iface_pvt* ici,
  517. struct Sockaddr* lladdr)
  518. {
  519. struct InterfaceController_pvt* ic = ici->ic;
  520. if (!ici->pub.beaconState) {
  521. // accepting beacons disabled.
  522. Log_debug(ic->logger, "[%s] Dropping beacon because beaconing is disabled",
  523. ici->pub.name->bytes);
  524. return NULL;
  525. }
  526. if (Message_getLength(msg) < Headers_Beacon_SIZE) {
  527. Log_debug(ic->logger, "[%s] Dropping runt beacon", ici->pub.name->bytes);
  528. return Error(msg, "RUNT");
  529. }
  530. // clear the bcast flag
  531. lladdr->flags = 0;
  532. struct Headers_Beacon beacon;
  533. Er_assert(Message_epop(msg, &beacon, Headers_Beacon_SIZE));
  534. if (Defined(Log_DEBUG)) {
  535. char* content = Hex_print(&beacon, Headers_Beacon_SIZE, Message_getAlloc(msg));
  536. Log_debug(ici->ic->logger, "RECV BEACON CONTENT[%s]", content);
  537. }
  538. struct Address addr = {0};
  539. Bits_memcpy(addr.key, beacon.publicKey, 32);
  540. addr.protocolVersion = Endian_bigEndianToHost32(beacon.version_be);
  541. Address_getPrefix(&addr);
  542. String* printedAddr = NULL;
  543. if (Defined(Log_DEBUG)) {
  544. printedAddr = Address_toString(&addr, Message_getAlloc(msg));
  545. }
  546. if (!AddressCalc_validAddress(addr.ip6.bytes)) {
  547. Log_debug(ic->logger, "handleBeacon invalid key [%s]", printedAddr->bytes);
  548. return Error(msg, "INVALID");
  549. } else if (!Bits_memcmp(ic->ourPubKey, addr.key, 32)) {
  550. // receive beacon from self, drop silent
  551. return NULL;
  552. }
  553. if (knownIncompatibleVersion(addr.protocolVersion)) {
  554. if (Defined(Log_DEBUG)) {
  555. Log_debug(ic->logger, "[%s] DROP beacon from [%s] which was version [%d] "
  556. "our version is [%d] making them incompatable", ici->pub.name->bytes,
  557. printedAddr->bytes, addr.protocolVersion, Version_CURRENT_PROTOCOL);
  558. }
  559. return Error(msg, "UNHANDLED");
  560. }
  561. String* beaconPass = String_newBinary(beacon.password, Headers_Beacon_PASSWORD_LEN, Message_getAlloc(msg));
  562. int epIndex = Map_EndpointsBySockaddr_indexForKey(&lladdr, &ici->peerMap);
  563. if (epIndex > -1) {
  564. // The password might have changed!
  565. struct Peer* ep = ici->peerMap.values[epIndex];
  566. Ca_setAuth(beaconPass, String_CONST("Local Peers"), ep->caSession);
  567. return NULL;
  568. }
  569. bool useNoise = addr.protocolVersion >= 22;
  570. struct Peer* ep = mkEp(lladdr, ici, beacon.publicKey, false, "beacon_peer", useNoise);
  571. int setIndex = Map_EndpointsBySockaddr_put(&ep->lladdr, &ep, &ici->peerMap);
  572. ep->handle = ici->peerMap.handles[setIndex];
  573. // We make the connection ourselves but we still consider
  574. // it "incoming" because we replied to a beacon
  575. ep->isIncomingConnection = true;
  576. ep->addr.protocolVersion = addr.protocolVersion;
  577. Ca_setAuth(beaconPass, String_CONST("Local Peers"), ep->caSession);
  578. if (SwitchCore_addInterface(ic->switchCore, &ep->switchIf, ep->alloc, &ep->addr.path)) {
  579. Log_debug(ic->logger, "handleBeacon() SwitchCore out of space");
  580. Allocator_free(ep->alloc);
  581. return Error(msg, "UNHANDLED");
  582. }
  583. // We want the node to immedietly be pinged but we don't want it to appear unresponsive because
  584. // the pinger will only ping every (PING_INTERVAL * 8) so we set timeOfLastMessage to
  585. // (now - pingAfterMilliseconds - 1) so it will be considered a "lazy node".
  586. ep->timeOfLastMessage =
  587. Time_currentTimeMilliseconds() - ic->pingAfterMilliseconds - 1;
  588. Log_info(ic->logger, "Added peer [%s] from beacon",
  589. Address_toString(&ep->addr, Message_getAlloc(msg))->bytes);
  590. // Ping them immediately, this prevents beacon tests from taking 1 second each
  591. sendPing(ep);
  592. return NULL;
  593. }
  594. static Iface_DEFUN handleIncomingFromWire(struct Message* msg, struct Iface* addrIf)
  595. {
  596. struct InterfaceController_Iface_pvt* ici =
  597. Identity_containerOf(addrIf, struct InterfaceController_Iface_pvt, pub.addrIf);
  598. struct Sockaddr_storage lladdrStore;
  599. struct Sockaddr* lladdr = (struct Sockaddr*) &lladdrStore;
  600. {
  601. struct Sockaddr* lladdr0 = (struct Sockaddr*) msg->msgbytes;
  602. if (Message_getLength(msg) < Sockaddr_OVERHEAD || Message_getLength(msg) < lladdr0->addrLen) {
  603. Log_debug(ici->ic->logger, "DROP runt");
  604. return Error(msg, "RUNT");
  605. }
  606. Er_assert(Message_epop(msg, lladdr, lladdr0->addrLen));
  607. }
  608. Assert_true(!((uintptr_t)msg->msgbytes % 4) && "alignment fault");
  609. Assert_true(!((uintptr_t)lladdr->addrLen % 4) && "alignment fault");
  610. char* printedAddr = "<unknown>";
  611. if (Defined(Log_DEBUG)) {
  612. printedAddr = Hex_print(&lladdr[1], lladdr->addrLen - Sockaddr_OVERHEAD, Message_getAlloc(msg));
  613. }
  614. // noisy
  615. if (Defined(Log_DEBUG) && false) {
  616. Log_debug(ici->ic->logger, "Incoming message from [%s]", printedAddr);
  617. }
  618. if (lladdr->flags & Sockaddr_flags_BCAST) {
  619. return handleBeacon(msg, ici, lladdr);
  620. }
  621. if (Message_getLength(msg) < 4) {
  622. return Error(msg, "RUNT");
  623. }
  624. int epIndex = Map_EndpointsBySockaddr_indexForKey(&lladdr, &ici->peerMap);
  625. if (epIndex == -1) {
  626. // noise control message
  627. Er_assert(Message_epush(msg, NULL, 16));
  628. Sockaddr_asIp6(msg->msgbytes, lladdr);
  629. RTypes_CryptoAuth2_TryHandshake_Ret_t ret = { .code = 0 };
  630. Rffi_CryptoAuth2_tryHandshake(ici->ic->ca, msg, ici->alloc, true, &ret);
  631. if (ret.sess) {
  632. // We have a new session, setup the endpoint
  633. struct Peer* ep = epFromSess(lladdr, ici, ret.sess, ret.alloc);
  634. if (SwitchCore_addInterface(ici->ic->switchCore, &ep->switchIf, ep->alloc, &ep->addr.path)) {
  635. Log_debug(ici->ic->logger, "handleUnexpectedIncoming() SwitchCore out of space");
  636. Allocator_free(ep->alloc);
  637. return Error(msg, "UNHANDLED");
  638. }
  639. Assert_true(Map_EndpointsBySockaddr_indexForKey(&ep->lladdr, &ici->peerMap) == -1);
  640. int index = Map_EndpointsBySockaddr_put(&ep->lladdr, &ep, &ici->peerMap);
  641. Assert_true(index >= 0);
  642. ep->handle = ici->peerMap.handles[index];
  643. // We want the node to immedietly be pinged but we don't want it to appear unresponsive because
  644. // the pinger will only ping every (PING_INTERVAL * 8) so we set timeOfLastMessage to
  645. // (now - pingAfterMilliseconds - 1) so it will be considered a "lazy node".
  646. ep->timeOfLastMessage =
  647. Time_currentTimeMilliseconds() - ici->ic->pingAfterMilliseconds - 1;
  648. Log_info(ici->ic->logger, "Added peer [%s] from incoming message",
  649. Address_toString(&ep->addr, Message_getAlloc(msg))->bytes);
  650. if (ep->addr.protocolVersion) {
  651. // This will only work if the other end sent us their version (WG mode)
  652. sendPeer(0xffffffff, PFChan_Core_PEER, ep, 0xffff);
  653. } else {
  654. // We don't know their version, ping them to find out
  655. sendPing(ep);
  656. }
  657. if (ret.code == RTypes_CryptoAuth2_TryHandshake_Code_t_RecvPlaintext) {
  658. // receive the packet
  659. return afterDecrypt(msg, &ep->plaintext);
  660. }
  661. }
  662. if (ret.code == RTypes_CryptoAuth2_TryHandshake_Code_t_ReplyToPeer) {
  663. // Send back a reply to the node who sent us this packet
  664. Er_assert(Message_epush(msg, lladdr, lladdr->addrLen));
  665. return Iface_next(&ici->pub.addrIf, msg);
  666. }
  667. if (ret.code == RTypes_CryptoAuth2_TryHandshake_Code_t_Error) {
  668. Log_debug(ici->ic->logger, "Error on unexpected packet from [%s]: [%d]",
  669. printedAddr, ret.err);
  670. return Error(msg, "DECRYPT");
  671. }
  672. if (ret.code == RTypes_CryptoAuth2_TryHandshake_Code_t_Done) {
  673. // Nothing to do
  674. return NULL;
  675. }
  676. Assert_failure("Rffi_CryptoAuth2_tryHandshake() replied [%d]", ret.code);
  677. }
  678. struct Peer* ep = Identity_check((struct Peer*) ici->peerMap.values[epIndex]);
  679. // Once we know it to be an incompetible version, we quarentine it
  680. if (knownIncompatibleVersion(ep->addr.protocolVersion)) {
  681. if (Defined(Log_DEBUG)) {
  682. Log_debug(ici->ic->logger, "[%s] DROP msg from node with incompat version [%d] ",
  683. Address_toString(&ep->addr, Message_getAlloc(msg))->bytes, ep->addr.protocolVersion);
  684. }
  685. ep->state = InterfaceController_PeerState_INCOMPATIBLE;
  686. return NULL;
  687. }
  688. Ca_resetIfTimeout(ep->caSession);
  689. Er_assert(Message_epush(msg, NULL, 16));
  690. Sockaddr_asIp6(msg->msgbytes, lladdr);
  691. return Iface_next(&ep->ciphertext, msg); // -> afterDecrypt
  692. }
  693. // Expects result of CryptoAuth decrypt
  694. static Iface_DEFUN afterDecrypt(struct Message* msg, struct Iface* plaintext)
  695. {
  696. struct Peer* ep = Identity_containerOf(plaintext, struct Peer, plaintext);
  697. struct InterfaceController_Iface_pvt* ici = Identity_check(ep->ici);
  698. struct InterfaceController_pvt* ic = Identity_check(ici->ic);
  699. enum Ca_DecryptErr err = Er_assert(Message_epop32h(msg));
  700. if (err) {
  701. return Error(msg, "AUTHENTICATION");
  702. }
  703. Kbps_accumulate(&ep->recvBw, Time_currentTimeMilliseconds(), Message_getLength(msg));
  704. ep->bytesIn += Message_getLength(msg);
  705. int caState = Ca_getState(ep->caSession);
  706. if (caState != Ca_State_ESTABLISHED) {
  707. // prevent some kinds of nasty things which could be done with packet replay.
  708. // This is checking the message switch header and will drop it unless the label
  709. // directs it to *this* router.
  710. if (Message_getLength(msg) < 8 || msg->msgbytes[7] != 1) {
  711. Log_info(ic->logger, "DROP message because CA is not established.");
  712. return Error(msg, "UNHANDLED");
  713. } else {
  714. // When a "server" gets a new connection from a "client" the router doesn't
  715. // know about that client so if the client sends a packet to the server, the
  716. // server will be unable to handle it until the client has sent inter-router
  717. // communication to the server. Here we will ping the client so when the
  718. // server gets the ping response, it will insert the client into its table
  719. // and know its version.
  720. // prevent DoS by limiting the number of times this can be called per second
  721. // limit it to 7, this will affect innocent packets but it doesn't matter much
  722. // since this is mostly just an optimization and for keeping the tests happy.
  723. if ((ep->pingCount + 1) % 7) {
  724. sendPing(ep);
  725. }
  726. }
  727. } else {
  728. if (ep->state != caState) {
  729. sendPeer(0xffffffff, PFChan_Core_PEER, ep, 0xffff);
  730. }
  731. ep->timeOfLastMessage = Time_currentTimeMilliseconds();
  732. }
  733. ep->state = caState;
  734. Identity_check(ep);
  735. return Iface_next(&ep->switchIf, msg);
  736. }
  737. int InterfaceController_ifaceCount(struct InterfaceController* ifc)
  738. {
  739. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  740. return ic->icis->length;
  741. }
  742. struct InterfaceController_Iface* InterfaceController_getIface(struct InterfaceController* ifc,
  743. int ifNum)
  744. {
  745. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  746. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, ifNum);
  747. return (ici) ? &ici->pub : NULL;
  748. }
  749. struct InterfaceController_Iface* InterfaceController_newIface(struct InterfaceController* ifc,
  750. String* name,
  751. struct Allocator* alloc)
  752. {
  753. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  754. struct InterfaceController_Iface_pvt* ici =
  755. Allocator_calloc(alloc, sizeof(struct InterfaceController_Iface_pvt), 1);
  756. ici->pub.name = String_clone(name, alloc);
  757. ici->peerMap.allocator = alloc;
  758. ici->ic = ic;
  759. ici->alloc = alloc;
  760. ici->pub.addrIf.send = handleIncomingFromWire;
  761. ici->pub.ifNum = ArrayList_OfIfaces_add(ic->icis, ici);
  762. Identity_set(ici);
  763. return &ici->pub;
  764. }
  765. static void sendBeacon(struct InterfaceController_Iface_pvt* ici, struct Allocator* tempAlloc)
  766. {
  767. if (ici->pub.beaconState < InterfaceController_beaconState_newState_SEND) {
  768. Log_debug(ici->ic->logger, "sendBeacon(%s) -> beaconing disabled", ici->pub.name->bytes);
  769. return;
  770. }
  771. Log_debug(ici->ic->logger, "sendBeacon(%s)", ici->pub.name->bytes);
  772. struct Message* msg = Message_new(0, 128, tempAlloc);
  773. Er_assert(Message_epush(msg, &ici->ic->beacon, Headers_Beacon_SIZE));
  774. if (Defined(Log_DEBUG)) {
  775. char* content = Hex_print(msg->msgbytes, Message_getLength(msg), tempAlloc);
  776. Log_debug(ici->ic->logger, "SEND BEACON CONTENT[%s]", content);
  777. }
  778. struct Sockaddr sa = {
  779. .addrLen = Sockaddr_OVERHEAD,
  780. .flags = Sockaddr_flags_BCAST
  781. };
  782. Er_assert(Message_epush(msg, &sa, Sockaddr_OVERHEAD));
  783. Iface_send(&ici->pub.addrIf, msg);
  784. }
  785. static void handshakeCycle(void* vInterfaceController)
  786. {
  787. struct InterfaceController_pvt* ic =
  788. Identity_check((struct InterfaceController_pvt*) vInterfaceController);
  789. struct Allocator* alloc = Allocator_child(ic->alloc);
  790. for (int i = 0; i < ic->icis->length; i++) {
  791. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  792. for (uint32_t j = 0; j < ici->peerMap.count; j++) {
  793. struct Peer* ep = Identity_check((struct Peer*) ici->peerMap.values[j]);
  794. Message_t* msg = Rffi_CryptoAuth2_noiseTick(ep->caSession, alloc);
  795. if (msg != NULL) {
  796. Er_assert(Message_epush(msg, ep->lladdr, ep->lladdr->addrLen));
  797. Iface_send(&ep->ici->pub.addrIf, msg);
  798. }
  799. }
  800. }
  801. Allocator_free(alloc);
  802. }
  803. static void beaconInterval(void* vInterfaceController)
  804. {
  805. struct InterfaceController_pvt* ic =
  806. Identity_check((struct InterfaceController_pvt*) vInterfaceController);
  807. struct Allocator* alloc = Allocator_child(ic->alloc);
  808. for (int i = 0; i < ic->icis->length; i++) {
  809. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  810. sendBeacon(ici, alloc);
  811. }
  812. Allocator_free(alloc);
  813. if (ic->beaconTimeoutAlloc) {
  814. Allocator_free(ic->beaconTimeoutAlloc);
  815. }
  816. ic->beaconTimeoutAlloc = Allocator_child(ic->alloc);
  817. Timeout_setTimeout(
  818. beaconInterval, ic, ic->beaconInterval, ic->eventBase, ic->beaconTimeoutAlloc);
  819. }
  820. int InterfaceController_beaconState(struct InterfaceController* ifc,
  821. int interfaceNumber,
  822. int newState)
  823. {
  824. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  825. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, interfaceNumber);
  826. if (!ici) {
  827. return InterfaceController_beaconState_NO_SUCH_IFACE;
  828. }
  829. char* val = NULL;
  830. switch (newState) {
  831. default: return InterfaceController_beaconState_INVALID_STATE;
  832. case InterfaceController_beaconState_newState_OFF: val = "OFF"; break;
  833. case InterfaceController_beaconState_newState_ACCEPT: val = "ACCEPT"; break;
  834. case InterfaceController_beaconState_newState_SEND: val = "SEND"; break;
  835. }
  836. Log_debug(ic->logger, "InterfaceController_beaconState(%s, %s)", ici->pub.name->bytes, val);
  837. ici->pub.beaconState = newState;
  838. if (newState == InterfaceController_beaconState_newState_SEND) {
  839. // Send out a beacon right away so we don't have to wait.
  840. struct Allocator* alloc = Allocator_child(ici->alloc);
  841. sendBeacon(ici, alloc);
  842. Allocator_free(alloc);
  843. }
  844. return 0;
  845. }
  846. int InterfaceController_bootstrapPeer(struct InterfaceController* ifc,
  847. int interfaceNumber,
  848. uint8_t* herPublicKey,
  849. const struct Sockaddr* lladdrParm,
  850. String* password,
  851. String* login,
  852. String* user,
  853. int version)
  854. {
  855. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  856. Assert_true(herPublicKey);
  857. Assert_true(password);
  858. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, interfaceNumber);
  859. if (!ici) {
  860. return InterfaceController_bootstrapPeer_BAD_IFNUM;
  861. }
  862. Log_debug(ic->logger, "bootstrapPeer total [%u]", ici->peerMap.count);
  863. uint8_t ip6[16];
  864. AddressCalc_addressForPublicKey(ip6, herPublicKey);
  865. if (!AddressCalc_validAddress(ip6) || !Bits_memcmp(ic->ourPubKey, herPublicKey, 32)) {
  866. return InterfaceController_bootstrapPeer_BAD_KEY;
  867. }
  868. // We often don't know this, but in that case we will fallback to the old peering
  869. bool useNoise = version >= 22;
  870. struct Peer* ep = mkEp(lladdrParm, ici, herPublicKey, false, user ? user->bytes : NULL, useNoise);
  871. ep->addr.protocolVersion = version;
  872. int index = Map_EndpointsBySockaddr_put(&ep->lladdr, &ep, &ici->peerMap);
  873. Assert_true(index >= 0);
  874. ep->handle = ici->peerMap.handles[index];
  875. Ca_setAuth(password, login, ep->caSession);
  876. if (SwitchCore_addInterface(ic->switchCore, &ep->switchIf, ep->alloc, &ep->addr.path)) {
  877. Log_debug(ic->logger, "bootstrapPeer() SwitchCore out of space");
  878. Allocator_free(ep->alloc);
  879. return InterfaceController_bootstrapPeer_OUT_OF_SPACE;
  880. }
  881. // We want the node to immedietly be pinged but we don't want it to appear unresponsive because
  882. // the pinger will only ping every (PING_INTERVAL * 8) so we set timeOfLastMessage to
  883. // (now - pingAfterMilliseconds - 1) so it will be considered a "lazy node".
  884. ep->timeOfLastMessage =
  885. Time_currentTimeMilliseconds() - ic->pingAfterMilliseconds - 1;
  886. if (Defined(Log_INFO)) {
  887. struct Allocator* tempAlloc = Allocator_child(ep->alloc);
  888. String* addrStr = Address_toString(&ep->addr, tempAlloc);
  889. Log_info(ic->logger, "Adding peer [%s] from bootstrapPeer()", addrStr->bytes);
  890. Allocator_free(tempAlloc);
  891. }
  892. // We can't just add the node directly to the routing table because we do not know
  893. // the version. We'll send it a switch ping and when it responds, we will know it's
  894. // key (if we don't already) and version number.
  895. sendPing(ep);
  896. return 0;
  897. }
  898. int InterfaceController_getPeerStats(struct InterfaceController* ifController,
  899. struct Allocator* alloc,
  900. struct InterfaceController_PeerStats** statsOut)
  901. {
  902. struct InterfaceController_pvt* ic =
  903. Identity_check((struct InterfaceController_pvt*) ifController);
  904. int count = 0;
  905. for (int i = 0; i < ic->icis->length; i++) {
  906. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  907. count += ici->peerMap.count;
  908. }
  909. struct InterfaceController_PeerStats* stats =
  910. Allocator_calloc(alloc, sizeof(struct InterfaceController_PeerStats), count);
  911. uint32_t now = Time_currentTimeMilliseconds();
  912. int xcount = 0;
  913. for (int j = 0; j < ic->icis->length; j++) {
  914. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, j);
  915. for (int i = 0; i < (int)ici->peerMap.count; i++) {
  916. struct Peer* peer = Identity_check((struct Peer*) ici->peerMap.values[i]);
  917. struct InterfaceController_PeerStats* s = &stats[xcount];
  918. xcount++;
  919. s->ifNum = ici->pub.ifNum;
  920. s->lladdr = Sockaddr_clone(peer->lladdr, alloc);
  921. Bits_memcpy(&s->addr, &peer->addr, sizeof(struct Address));
  922. s->bytesOut = peer->bytesOut;
  923. s->bytesIn = peer->bytesIn;
  924. s->timeOfLastMessage = peer->timeOfLastMessage;
  925. s->state = peer->state;
  926. s->isIncomingConnection = peer->isIncomingConnection;
  927. s->user = Ca_getName(peer->caSession, alloc);
  928. RTypes_CryptoStats_t stats;
  929. Ca_stats(peer->caSession, &stats);
  930. s->duplicates = stats.duplicate_packets;
  931. s->receivedOutOfRange = stats.received_unexpected;
  932. s->noiseProto = stats.noise_proto;
  933. s->recvKbps = Kbps_accumulate(&peer->recvBw, now, Kbps_accumulate_NO_PACKET);
  934. s->sendKbps = Kbps_accumulate(&peer->sendBw, now, Kbps_accumulate_NO_PACKET);
  935. s->receivedPackets = peer->lastPackets;
  936. s->lostPackets = peer->lastDrops;
  937. }
  938. }
  939. Assert_true(xcount == count);
  940. *statsOut = stats;
  941. return count;
  942. }
  943. void InterfaceController_resetPeering(struct InterfaceController* ifController,
  944. uint8_t herPublicKey[32])
  945. {
  946. struct InterfaceController_pvt* ic =
  947. Identity_check((struct InterfaceController_pvt*) ifController);
  948. for (int j = 0; j < ic->icis->length; j++) {
  949. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, j);
  950. for (int i = 0; i < (int)ici->peerMap.count; i++) {
  951. struct Peer* peer = ici->peerMap.values[i];
  952. if (!herPublicKey || !Bits_memcmp(herPublicKey, peer->addr.key, 32)) {
  953. Ca_reset(peer->caSession);
  954. }
  955. }
  956. }
  957. }
  958. int InterfaceController_disconnectPeer(struct InterfaceController* ifController,
  959. uint8_t herPublicKey[32])
  960. {
  961. struct InterfaceController_pvt* ic =
  962. Identity_check((struct InterfaceController_pvt*) ifController);
  963. int count = 0;
  964. for (int j = 0; j < ic->icis->length; j++) {
  965. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, j);
  966. for (int i = 0; i < (int)ici->peerMap.count; i++) {
  967. struct Peer* peer = ici->peerMap.values[i];
  968. if (!Bits_memcmp(herPublicKey, peer->addr.key, 32)) {
  969. Allocator_free(peer->alloc);
  970. count++;
  971. }
  972. }
  973. }
  974. return count;
  975. }
  976. static Iface_DEFUN incomingFromEventEmitterIf(struct Message* msg, struct Iface* eventEmitterIf)
  977. {
  978. struct InterfaceController_pvt* ic =
  979. Identity_containerOf(eventEmitterIf, struct InterfaceController_pvt, eventEmitterIf);
  980. uint32_t peers = Er_assert(Message_epop32be(msg));
  981. Assert_true(peers == PFChan_Pathfinder_PEERS);
  982. uint32_t pathfinderId = Er_assert(Message_epop32be(msg));
  983. Assert_true(!Message_getLength(msg));
  984. for (int j = 0; j < ic->icis->length; j++) {
  985. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, j);
  986. for (int i = 0; i < (int)ici->peerMap.count; i++) {
  987. struct Peer* peer = Identity_check((struct Peer*) ici->peerMap.values[i]);
  988. if (peer->state != InterfaceController_PeerState_ESTABLISHED) { continue; }
  989. sendPeer(pathfinderId, PFChan_Core_PEER, peer, 0xffff);
  990. }
  991. }
  992. return NULL;
  993. }
  994. struct InterfaceController* InterfaceController_new(Ca_t* ca,
  995. struct SwitchCore* switchCore,
  996. struct Log* logger,
  997. struct EventBase* eventBase,
  998. struct SwitchPinger* switchPinger,
  999. struct Random* rand,
  1000. struct Allocator* allocator,
  1001. struct EventEmitter* ee,
  1002. bool enableNoise)
  1003. {
  1004. struct Allocator* alloc = Allocator_child(allocator);
  1005. struct InterfaceController_pvt* out =
  1006. Allocator_calloc(alloc, sizeof(struct InterfaceController_pvt), 1);
  1007. Bits_memcpy(out, (&(struct InterfaceController_pvt) {
  1008. .alloc = alloc,
  1009. .ca = ca,
  1010. .rand = rand,
  1011. .switchCore = switchCore,
  1012. .logger = logger,
  1013. .eventBase = eventBase,
  1014. .switchPinger = switchPinger,
  1015. .unresponsiveAfterMilliseconds = UNRESPONSIVE_AFTER_MILLISECONDS,
  1016. .pingAfterMilliseconds = PING_AFTER_MILLISECONDS,
  1017. .timeoutMilliseconds = TIMEOUT_MILLISECONDS,
  1018. .forgetAfterMilliseconds = FORGET_AFTER_MILLISECONDS,
  1019. .beaconInterval = BEACON_INTERVAL,
  1020. .enableNoise = enableNoise,
  1021. .linkStateInterval = Timeout_setInterval(
  1022. linkState,
  1023. out,
  1024. LINKSTATE_UPDATE_INTERVAL,
  1025. eventBase,
  1026. alloc),
  1027. .pingInterval = (switchPinger)
  1028. ? Timeout_setInterval(pingCycle,
  1029. out,
  1030. PING_INTERVAL_MILLISECONDS,
  1031. eventBase,
  1032. alloc)
  1033. : NULL,
  1034. .noiseHandshakeInterval = Timeout_setInterval(
  1035. handshakeCycle,
  1036. out,
  1037. HANDSHAKE_CYCLE_INTERVAL,
  1038. eventBase,
  1039. alloc)
  1040. }), sizeof(struct InterfaceController_pvt));
  1041. Identity_set(out);
  1042. out->icis = ArrayList_OfIfaces_new(alloc);
  1043. out->eventEmitterIf.send = incomingFromEventEmitterIf;
  1044. EventEmitter_regCore(ee, &out->eventEmitterIf, PFChan_Pathfinder_PEERS);
  1045. // Add the beaconing password.
  1046. Random_base32(rand, out->beacon.password, Headers_Beacon_PASSWORD_LEN);
  1047. String strPass = { .bytes=(char*)out->beacon.password, .len=Headers_Beacon_PASSWORD_LEN };
  1048. int ret = Ca_addUser(&strPass, String_CONST("Local Peers"), ca);
  1049. if (ret) {
  1050. Log_warn(logger, "Ca_addUser() returned [%d]", ret);
  1051. }
  1052. Ca_getPubKey(ca, out->ourPubKey);
  1053. Bits_memcpy(out->beacon.publicKey, out->ourPubKey, 32);
  1054. if (enableNoise) {
  1055. out->beacon.version_be = Endian_hostToBigEndian32(Version_CURRENT_PROTOCOL);
  1056. } else {
  1057. // this is mostly here for testing, we have to lie about our protocol version
  1058. out->beacon.version_be = Endian_hostToBigEndian32(21);
  1059. }
  1060. Timeout_setTimeout(beaconInterval, out, BEACON_INTERVAL, eventBase, alloc);
  1061. return &out->pub;
  1062. }