InterfaceController.c 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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;
  539. Bits_memset(&addr, 0, sizeof(struct Address));
  540. Bits_memcpy(addr.key, beacon.publicKey, 32);
  541. addr.protocolVersion = Endian_bigEndianToHost32(beacon.version_be);
  542. Address_getPrefix(&addr);
  543. String* printedAddr = NULL;
  544. if (Defined(Log_DEBUG)) {
  545. printedAddr = Address_toString(&addr, Message_getAlloc(msg));
  546. }
  547. if (!AddressCalc_validAddress(addr.ip6.bytes)) {
  548. Log_debug(ic->logger, "handleBeacon invalid key [%s]", printedAddr->bytes);
  549. return Error(msg, "INVALID");
  550. } else if (!Bits_memcmp(ic->ourPubKey, addr.key, 32)) {
  551. // receive beacon from self, drop silent
  552. return NULL;
  553. }
  554. if (knownIncompatibleVersion(addr.protocolVersion)) {
  555. if (Defined(Log_DEBUG)) {
  556. Log_debug(ic->logger, "[%s] DROP beacon from [%s] which was version [%d] "
  557. "our version is [%d] making them incompatable", ici->pub.name->bytes,
  558. printedAddr->bytes, addr.protocolVersion, Version_CURRENT_PROTOCOL);
  559. }
  560. return Error(msg, "UNHANDLED");
  561. }
  562. String* beaconPass = String_newBinary(beacon.password, Headers_Beacon_PASSWORD_LEN, Message_getAlloc(msg));
  563. int epIndex = Map_EndpointsBySockaddr_indexForKey(&lladdr, &ici->peerMap);
  564. if (epIndex > -1) {
  565. // The password might have changed!
  566. struct Peer* ep = ici->peerMap.values[epIndex];
  567. Ca_setAuth(beaconPass, String_CONST("Local Peers"), ep->caSession);
  568. return NULL;
  569. }
  570. bool useNoise = addr.protocolVersion >= 22;
  571. struct Peer* ep = mkEp(lladdr, ici, beacon.publicKey, false, "beacon_peer", useNoise);
  572. int setIndex = Map_EndpointsBySockaddr_put(&ep->lladdr, &ep, &ici->peerMap);
  573. ep->handle = ici->peerMap.handles[setIndex];
  574. // We make the connection ourselves but we still consider
  575. // it "incoming" because we replied to a beacon
  576. ep->isIncomingConnection = true;
  577. ep->addr.protocolVersion = addr.protocolVersion;
  578. Ca_setAuth(beaconPass, String_CONST("Local Peers"), ep->caSession);
  579. if (SwitchCore_addInterface(ic->switchCore, &ep->switchIf, ep->alloc, &ep->addr.path)) {
  580. Log_debug(ic->logger, "handleBeacon() SwitchCore out of space");
  581. Allocator_free(ep->alloc);
  582. return Error(msg, "UNHANDLED");
  583. }
  584. // We want the node to immedietly be pinged but we don't want it to appear unresponsive because
  585. // the pinger will only ping every (PING_INTERVAL * 8) so we set timeOfLastMessage to
  586. // (now - pingAfterMilliseconds - 1) so it will be considered a "lazy node".
  587. ep->timeOfLastMessage =
  588. Time_currentTimeMilliseconds() - ic->pingAfterMilliseconds - 1;
  589. Log_info(ic->logger, "Added peer [%s] from beacon",
  590. Address_toString(&ep->addr, Message_getAlloc(msg))->bytes);
  591. // Ping them immediately, this prevents beacon tests from taking 1 second each
  592. sendPing(ep);
  593. return NULL;
  594. }
  595. static Iface_DEFUN handleIncomingFromWire(struct Message* msg, struct Iface* addrIf)
  596. {
  597. struct InterfaceController_Iface_pvt* ici =
  598. Identity_containerOf(addrIf, struct InterfaceController_Iface_pvt, pub.addrIf);
  599. struct Sockaddr_storage lladdrStore;
  600. struct Sockaddr* lladdr = (struct Sockaddr*) &lladdrStore;
  601. {
  602. struct Sockaddr* lladdr0 = (struct Sockaddr*) msg->msgbytes;
  603. if (Message_getLength(msg) < Sockaddr_OVERHEAD || Message_getLength(msg) < lladdr0->addrLen) {
  604. Log_debug(ici->ic->logger, "DROP runt");
  605. return Error(msg, "RUNT");
  606. }
  607. Er_assert(Message_epop(msg, lladdr, lladdr0->addrLen));
  608. }
  609. Assert_true(!((uintptr_t)msg->msgbytes % 4) && "alignment fault");
  610. Assert_true(!((uintptr_t)lladdr->addrLen % 4) && "alignment fault");
  611. char* printedAddr = "<unknown>";
  612. if (Defined(Log_DEBUG)) {
  613. printedAddr = Hex_print(&lladdr[1], lladdr->addrLen - Sockaddr_OVERHEAD, Message_getAlloc(msg));
  614. }
  615. // noisy
  616. if (Defined(Log_DEBUG) && false) {
  617. Log_debug(ici->ic->logger, "Incoming message from [%s]", printedAddr);
  618. }
  619. if (lladdr->flags & Sockaddr_flags_BCAST) {
  620. return handleBeacon(msg, ici, lladdr);
  621. }
  622. if (Message_getLength(msg) < 4) {
  623. return Error(msg, "RUNT");
  624. }
  625. int epIndex = Map_EndpointsBySockaddr_indexForKey(&lladdr, &ici->peerMap);
  626. if (epIndex == -1) {
  627. // noise control message
  628. Er_assert(Message_epush(msg, NULL, 16));
  629. Sockaddr_asIp6(msg->msgbytes, lladdr);
  630. RTypes_CryptoAuth2_TryHandshake_Ret_t ret = { .code = 0 };
  631. Rffi_CryptoAuth2_tryHandshake(ici->ic->ca, msg, ici->alloc, true, &ret);
  632. if (ret.sess) {
  633. // We have a new session, setup the endpoint
  634. struct Peer* ep = epFromSess(lladdr, ici, ret.sess, ret.alloc);
  635. if (SwitchCore_addInterface(ici->ic->switchCore, &ep->switchIf, ep->alloc, &ep->addr.path)) {
  636. Log_debug(ici->ic->logger, "handleUnexpectedIncoming() SwitchCore out of space");
  637. Allocator_free(ep->alloc);
  638. return Error(msg, "UNHANDLED");
  639. }
  640. Assert_true(Map_EndpointsBySockaddr_indexForKey(&ep->lladdr, &ici->peerMap) == -1);
  641. int index = Map_EndpointsBySockaddr_put(&ep->lladdr, &ep, &ici->peerMap);
  642. Assert_true(index >= 0);
  643. ep->handle = ici->peerMap.handles[index];
  644. // We want the node to immedietly be pinged but we don't want it to appear unresponsive because
  645. // the pinger will only ping every (PING_INTERVAL * 8) so we set timeOfLastMessage to
  646. // (now - pingAfterMilliseconds - 1) so it will be considered a "lazy node".
  647. ep->timeOfLastMessage =
  648. Time_currentTimeMilliseconds() - ici->ic->pingAfterMilliseconds - 1;
  649. Log_info(ici->ic->logger, "Added peer [%s] from incoming message",
  650. Address_toString(&ep->addr, Message_getAlloc(msg))->bytes);
  651. if (ep->addr.protocolVersion) {
  652. // This will only work if the other end sent us their version (WG mode)
  653. sendPeer(0xffffffff, PFChan_Core_PEER, ep, 0xffff);
  654. } else {
  655. // We don't know their version, ping them to find out
  656. sendPing(ep);
  657. }
  658. if (ret.code == RTypes_CryptoAuth2_TryHandshake_Code_t_RecvPlaintext) {
  659. // receive the packet
  660. return afterDecrypt(msg, &ep->plaintext);
  661. }
  662. }
  663. if (ret.code == RTypes_CryptoAuth2_TryHandshake_Code_t_ReplyToPeer) {
  664. // Send back a reply to the node who sent us this packet
  665. Er_assert(Message_epush(msg, lladdr, lladdr->addrLen));
  666. return Iface_next(&ici->pub.addrIf, msg);
  667. }
  668. if (ret.code == RTypes_CryptoAuth2_TryHandshake_Code_t_Error) {
  669. Log_debug(ici->ic->logger, "Error on unexpected packet from [%s]: [%d]",
  670. printedAddr, ret.err);
  671. return Error(msg, "DECRYPT");
  672. }
  673. if (ret.code == RTypes_CryptoAuth2_TryHandshake_Code_t_Done) {
  674. // Nothing to do
  675. return NULL;
  676. }
  677. Assert_failure("Rffi_CryptoAuth2_tryHandshake() replied [%d]", ret.code);
  678. }
  679. struct Peer* ep = Identity_check((struct Peer*) ici->peerMap.values[epIndex]);
  680. // Once we know it to be an incompetible version, we quarentine it
  681. if (knownIncompatibleVersion(ep->addr.protocolVersion)) {
  682. if (Defined(Log_DEBUG)) {
  683. Log_debug(ici->ic->logger, "[%s] DROP msg from node with incompat version [%d] ",
  684. Address_toString(&ep->addr, Message_getAlloc(msg))->bytes, ep->addr.protocolVersion);
  685. }
  686. ep->state = InterfaceController_PeerState_INCOMPATIBLE;
  687. return NULL;
  688. }
  689. Ca_resetIfTimeout(ep->caSession);
  690. Er_assert(Message_epush(msg, NULL, 16));
  691. Sockaddr_asIp6(msg->msgbytes, lladdr);
  692. return Iface_next(&ep->ciphertext, msg); // -> afterDecrypt
  693. }
  694. // Expects result of CryptoAuth decrypt
  695. static Iface_DEFUN afterDecrypt(struct Message* msg, struct Iface* plaintext)
  696. {
  697. struct Peer* ep = Identity_containerOf(plaintext, struct Peer, plaintext);
  698. struct InterfaceController_Iface_pvt* ici = Identity_check(ep->ici);
  699. struct InterfaceController_pvt* ic = Identity_check(ici->ic);
  700. enum Ca_DecryptErr err = Er_assert(Message_epop32h(msg));
  701. if (err) {
  702. return Error(msg, "AUTHENTICATION");
  703. }
  704. Kbps_accumulate(&ep->recvBw, Time_currentTimeMilliseconds(), Message_getLength(msg));
  705. ep->bytesIn += Message_getLength(msg);
  706. int caState = Ca_getState(ep->caSession);
  707. if (caState != Ca_State_ESTABLISHED) {
  708. // prevent some kinds of nasty things which could be done with packet replay.
  709. // This is checking the message switch header and will drop it unless the label
  710. // directs it to *this* router.
  711. if (Message_getLength(msg) < 8 || msg->msgbytes[7] != 1) {
  712. Log_info(ic->logger, "DROP message because CA is not established.");
  713. return Error(msg, "UNHANDLED");
  714. } else {
  715. // When a "server" gets a new connection from a "client" the router doesn't
  716. // know about that client so if the client sends a packet to the server, the
  717. // server will be unable to handle it until the client has sent inter-router
  718. // communication to the server. Here we will ping the client so when the
  719. // server gets the ping response, it will insert the client into its table
  720. // and know its version.
  721. // prevent DoS by limiting the number of times this can be called per second
  722. // limit it to 7, this will affect innocent packets but it doesn't matter much
  723. // since this is mostly just an optimization and for keeping the tests happy.
  724. if ((ep->pingCount + 1) % 7) {
  725. sendPing(ep);
  726. }
  727. }
  728. } else {
  729. if (ep->state != caState) {
  730. sendPeer(0xffffffff, PFChan_Core_PEER, ep, 0xffff);
  731. }
  732. ep->timeOfLastMessage = Time_currentTimeMilliseconds();
  733. }
  734. ep->state = caState;
  735. Identity_check(ep);
  736. return Iface_next(&ep->switchIf, msg);
  737. }
  738. int InterfaceController_ifaceCount(struct InterfaceController* ifc)
  739. {
  740. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  741. return ic->icis->length;
  742. }
  743. struct InterfaceController_Iface* InterfaceController_getIface(struct InterfaceController* ifc,
  744. int ifNum)
  745. {
  746. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  747. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, ifNum);
  748. return (ici) ? &ici->pub : NULL;
  749. }
  750. struct InterfaceController_Iface* InterfaceController_newIface(struct InterfaceController* ifc,
  751. String* name,
  752. struct Allocator* alloc)
  753. {
  754. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  755. struct InterfaceController_Iface_pvt* ici =
  756. Allocator_calloc(alloc, sizeof(struct InterfaceController_Iface_pvt), 1);
  757. ici->pub.name = String_clone(name, alloc);
  758. ici->peerMap.allocator = alloc;
  759. ici->ic = ic;
  760. ici->alloc = alloc;
  761. ici->pub.addrIf.send = handleIncomingFromWire;
  762. ici->pub.ifNum = ArrayList_OfIfaces_add(ic->icis, ici);
  763. Identity_set(ici);
  764. return &ici->pub;
  765. }
  766. static void sendBeacon(struct InterfaceController_Iface_pvt* ici, struct Allocator* tempAlloc)
  767. {
  768. if (ici->pub.beaconState < InterfaceController_beaconState_newState_SEND) {
  769. Log_debug(ici->ic->logger, "sendBeacon(%s) -> beaconing disabled", ici->pub.name->bytes);
  770. return;
  771. }
  772. Log_debug(ici->ic->logger, "sendBeacon(%s)", ici->pub.name->bytes);
  773. struct Message* msg = Message_new(0, 128, tempAlloc);
  774. Er_assert(Message_epush(msg, &ici->ic->beacon, Headers_Beacon_SIZE));
  775. if (Defined(Log_DEBUG)) {
  776. char* content = Hex_print(msg->msgbytes, Message_getLength(msg), tempAlloc);
  777. Log_debug(ici->ic->logger, "SEND BEACON CONTENT[%s]", content);
  778. }
  779. struct Sockaddr sa = {
  780. .addrLen = Sockaddr_OVERHEAD,
  781. .flags = Sockaddr_flags_BCAST
  782. };
  783. Er_assert(Message_epush(msg, &sa, Sockaddr_OVERHEAD));
  784. Iface_send(&ici->pub.addrIf, msg);
  785. }
  786. static void handshakeCycle(void* vInterfaceController)
  787. {
  788. struct InterfaceController_pvt* ic =
  789. Identity_check((struct InterfaceController_pvt*) vInterfaceController);
  790. struct Allocator* alloc = Allocator_child(ic->alloc);
  791. for (int i = 0; i < ic->icis->length; i++) {
  792. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  793. for (uint32_t j = 0; j < ici->peerMap.count; j++) {
  794. struct Peer* ep = Identity_check((struct Peer*) ici->peerMap.values[j]);
  795. Message_t* msg = Rffi_CryptoAuth2_noiseTick(ep->caSession, alloc);
  796. if (msg != NULL) {
  797. Er_assert(Message_epush(msg, ep->lladdr, ep->lladdr->addrLen));
  798. Iface_send(&ep->ici->pub.addrIf, msg);
  799. }
  800. }
  801. }
  802. Allocator_free(alloc);
  803. }
  804. static void beaconInterval(void* vInterfaceController)
  805. {
  806. struct InterfaceController_pvt* ic =
  807. Identity_check((struct InterfaceController_pvt*) vInterfaceController);
  808. struct Allocator* alloc = Allocator_child(ic->alloc);
  809. for (int i = 0; i < ic->icis->length; i++) {
  810. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  811. sendBeacon(ici, alloc);
  812. }
  813. Allocator_free(alloc);
  814. if (ic->beaconTimeoutAlloc) {
  815. Allocator_free(ic->beaconTimeoutAlloc);
  816. }
  817. ic->beaconTimeoutAlloc = Allocator_child(ic->alloc);
  818. Timeout_setTimeout(
  819. beaconInterval, ic, ic->beaconInterval, ic->eventBase, ic->beaconTimeoutAlloc);
  820. }
  821. int InterfaceController_beaconState(struct InterfaceController* ifc,
  822. int interfaceNumber,
  823. int newState)
  824. {
  825. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  826. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, interfaceNumber);
  827. if (!ici) {
  828. return InterfaceController_beaconState_NO_SUCH_IFACE;
  829. }
  830. char* val = NULL;
  831. switch (newState) {
  832. default: return InterfaceController_beaconState_INVALID_STATE;
  833. case InterfaceController_beaconState_newState_OFF: val = "OFF"; break;
  834. case InterfaceController_beaconState_newState_ACCEPT: val = "ACCEPT"; break;
  835. case InterfaceController_beaconState_newState_SEND: val = "SEND"; break;
  836. }
  837. Log_debug(ic->logger, "InterfaceController_beaconState(%s, %s)", ici->pub.name->bytes, val);
  838. ici->pub.beaconState = newState;
  839. if (newState == InterfaceController_beaconState_newState_SEND) {
  840. // Send out a beacon right away so we don't have to wait.
  841. struct Allocator* alloc = Allocator_child(ici->alloc);
  842. sendBeacon(ici, alloc);
  843. Allocator_free(alloc);
  844. }
  845. return 0;
  846. }
  847. int InterfaceController_bootstrapPeer(struct InterfaceController* ifc,
  848. int interfaceNumber,
  849. uint8_t* herPublicKey,
  850. const struct Sockaddr* lladdrParm,
  851. String* password,
  852. String* login,
  853. String* user,
  854. int version)
  855. {
  856. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  857. Assert_true(herPublicKey);
  858. Assert_true(password);
  859. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, interfaceNumber);
  860. if (!ici) {
  861. return InterfaceController_bootstrapPeer_BAD_IFNUM;
  862. }
  863. Log_debug(ic->logger, "bootstrapPeer total [%u]", ici->peerMap.count);
  864. uint8_t ip6[16];
  865. AddressCalc_addressForPublicKey(ip6, herPublicKey);
  866. if (!AddressCalc_validAddress(ip6) || !Bits_memcmp(ic->ourPubKey, herPublicKey, 32)) {
  867. return InterfaceController_bootstrapPeer_BAD_KEY;
  868. }
  869. // We often don't know this, but in that case we will fallback to the old peering
  870. bool useNoise = version >= 22;
  871. struct Peer* ep = mkEp(lladdrParm, ici, herPublicKey, false, user ? user->bytes : NULL, useNoise);
  872. ep->addr.protocolVersion = version;
  873. int index = Map_EndpointsBySockaddr_put(&ep->lladdr, &ep, &ici->peerMap);
  874. Assert_true(index >= 0);
  875. ep->handle = ici->peerMap.handles[index];
  876. Ca_setAuth(password, login, ep->caSession);
  877. if (SwitchCore_addInterface(ic->switchCore, &ep->switchIf, ep->alloc, &ep->addr.path)) {
  878. Log_debug(ic->logger, "bootstrapPeer() SwitchCore out of space");
  879. Allocator_free(ep->alloc);
  880. return InterfaceController_bootstrapPeer_OUT_OF_SPACE;
  881. }
  882. // We want the node to immedietly be pinged but we don't want it to appear unresponsive because
  883. // the pinger will only ping every (PING_INTERVAL * 8) so we set timeOfLastMessage to
  884. // (now - pingAfterMilliseconds - 1) so it will be considered a "lazy node".
  885. ep->timeOfLastMessage =
  886. Time_currentTimeMilliseconds() - ic->pingAfterMilliseconds - 1;
  887. if (Defined(Log_INFO)) {
  888. struct Allocator* tempAlloc = Allocator_child(ep->alloc);
  889. String* addrStr = Address_toString(&ep->addr, tempAlloc);
  890. Log_info(ic->logger, "Adding peer [%s] from bootstrapPeer()", addrStr->bytes);
  891. Allocator_free(tempAlloc);
  892. }
  893. // We can't just add the node directly to the routing table because we do not know
  894. // the version. We'll send it a switch ping and when it responds, we will know it's
  895. // key (if we don't already) and version number.
  896. sendPing(ep);
  897. return 0;
  898. }
  899. int InterfaceController_getPeerStats(struct InterfaceController* ifController,
  900. struct Allocator* alloc,
  901. struct InterfaceController_PeerStats** statsOut)
  902. {
  903. struct InterfaceController_pvt* ic =
  904. Identity_check((struct InterfaceController_pvt*) ifController);
  905. int count = 0;
  906. for (int i = 0; i < ic->icis->length; i++) {
  907. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  908. count += ici->peerMap.count;
  909. }
  910. struct InterfaceController_PeerStats* stats =
  911. Allocator_calloc(alloc, sizeof(struct InterfaceController_PeerStats), count);
  912. uint32_t now = Time_currentTimeMilliseconds();
  913. int xcount = 0;
  914. for (int j = 0; j < ic->icis->length; j++) {
  915. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, j);
  916. for (int i = 0; i < (int)ici->peerMap.count; i++) {
  917. struct Peer* peer = Identity_check((struct Peer*) ici->peerMap.values[i]);
  918. struct InterfaceController_PeerStats* s = &stats[xcount];
  919. xcount++;
  920. s->ifNum = ici->pub.ifNum;
  921. s->lladdr = Sockaddr_clone(peer->lladdr, alloc);
  922. Bits_memcpy(&s->addr, &peer->addr, sizeof(struct Address));
  923. s->bytesOut = peer->bytesOut;
  924. s->bytesIn = peer->bytesIn;
  925. s->timeOfLastMessage = peer->timeOfLastMessage;
  926. s->state = peer->state;
  927. s->isIncomingConnection = peer->isIncomingConnection;
  928. s->user = Ca_getName(peer->caSession, alloc);
  929. RTypes_CryptoStats_t stats;
  930. Ca_stats(peer->caSession, &stats);
  931. s->duplicates = stats.duplicate_packets;
  932. s->receivedOutOfRange = stats.received_unexpected;
  933. s->noiseProto = stats.noise_proto;
  934. s->recvKbps = Kbps_accumulate(&peer->recvBw, now, Kbps_accumulate_NO_PACKET);
  935. s->sendKbps = Kbps_accumulate(&peer->sendBw, now, Kbps_accumulate_NO_PACKET);
  936. s->receivedPackets = peer->lastPackets;
  937. s->lostPackets = peer->lastDrops;
  938. }
  939. }
  940. Assert_true(xcount == count);
  941. *statsOut = stats;
  942. return count;
  943. }
  944. void InterfaceController_resetPeering(struct InterfaceController* ifController,
  945. uint8_t herPublicKey[32])
  946. {
  947. struct InterfaceController_pvt* ic =
  948. Identity_check((struct InterfaceController_pvt*) ifController);
  949. for (int j = 0; j < ic->icis->length; j++) {
  950. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, j);
  951. for (int i = 0; i < (int)ici->peerMap.count; i++) {
  952. struct Peer* peer = ici->peerMap.values[i];
  953. if (!herPublicKey || !Bits_memcmp(herPublicKey, peer->addr.key, 32)) {
  954. Ca_reset(peer->caSession);
  955. }
  956. }
  957. }
  958. }
  959. int InterfaceController_disconnectPeer(struct InterfaceController* ifController,
  960. uint8_t herPublicKey[32])
  961. {
  962. struct InterfaceController_pvt* ic =
  963. Identity_check((struct InterfaceController_pvt*) ifController);
  964. int count = 0;
  965. for (int j = 0; j < ic->icis->length; j++) {
  966. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, j);
  967. for (int i = 0; i < (int)ici->peerMap.count; i++) {
  968. struct Peer* peer = ici->peerMap.values[i];
  969. if (!Bits_memcmp(herPublicKey, peer->addr.key, 32)) {
  970. Allocator_free(peer->alloc);
  971. count++;
  972. }
  973. }
  974. }
  975. return count;
  976. }
  977. static Iface_DEFUN incomingFromEventEmitterIf(struct Message* msg, struct Iface* eventEmitterIf)
  978. {
  979. struct InterfaceController_pvt* ic =
  980. Identity_containerOf(eventEmitterIf, struct InterfaceController_pvt, eventEmitterIf);
  981. uint32_t peers = Er_assert(Message_epop32be(msg));
  982. Assert_true(peers == PFChan_Pathfinder_PEERS);
  983. uint32_t pathfinderId = Er_assert(Message_epop32be(msg));
  984. Assert_true(!Message_getLength(msg));
  985. for (int j = 0; j < ic->icis->length; j++) {
  986. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, j);
  987. for (int i = 0; i < (int)ici->peerMap.count; i++) {
  988. struct Peer* peer = Identity_check((struct Peer*) ici->peerMap.values[i]);
  989. if (peer->state != InterfaceController_PeerState_ESTABLISHED) { continue; }
  990. sendPeer(pathfinderId, PFChan_Core_PEER, peer, 0xffff);
  991. }
  992. }
  993. return NULL;
  994. }
  995. struct InterfaceController* InterfaceController_new(Ca_t* ca,
  996. struct SwitchCore* switchCore,
  997. struct Log* logger,
  998. struct EventBase* eventBase,
  999. struct SwitchPinger* switchPinger,
  1000. struct Random* rand,
  1001. struct Allocator* allocator,
  1002. struct EventEmitter* ee,
  1003. bool enableNoise)
  1004. {
  1005. struct Allocator* alloc = Allocator_child(allocator);
  1006. struct InterfaceController_pvt* out =
  1007. Allocator_calloc(alloc, sizeof(struct InterfaceController_pvt), 1);
  1008. Bits_memcpy(out, (&(struct InterfaceController_pvt) {
  1009. .alloc = alloc,
  1010. .ca = ca,
  1011. .rand = rand,
  1012. .switchCore = switchCore,
  1013. .logger = logger,
  1014. .eventBase = eventBase,
  1015. .switchPinger = switchPinger,
  1016. .unresponsiveAfterMilliseconds = UNRESPONSIVE_AFTER_MILLISECONDS,
  1017. .pingAfterMilliseconds = PING_AFTER_MILLISECONDS,
  1018. .timeoutMilliseconds = TIMEOUT_MILLISECONDS,
  1019. .forgetAfterMilliseconds = FORGET_AFTER_MILLISECONDS,
  1020. .beaconInterval = BEACON_INTERVAL,
  1021. .enableNoise = enableNoise,
  1022. .linkStateInterval = Timeout_setInterval(
  1023. linkState,
  1024. out,
  1025. LINKSTATE_UPDATE_INTERVAL,
  1026. eventBase,
  1027. alloc),
  1028. .pingInterval = (switchPinger)
  1029. ? Timeout_setInterval(pingCycle,
  1030. out,
  1031. PING_INTERVAL_MILLISECONDS,
  1032. eventBase,
  1033. alloc)
  1034. : NULL,
  1035. .noiseHandshakeInterval = Timeout_setInterval(
  1036. handshakeCycle,
  1037. out,
  1038. HANDSHAKE_CYCLE_INTERVAL,
  1039. eventBase,
  1040. alloc)
  1041. }), sizeof(struct InterfaceController_pvt));
  1042. Identity_set(out);
  1043. out->icis = ArrayList_OfIfaces_new(alloc);
  1044. out->eventEmitterIf.send = incomingFromEventEmitterIf;
  1045. EventEmitter_regCore(ee, &out->eventEmitterIf, PFChan_Pathfinder_PEERS);
  1046. // Add the beaconing password.
  1047. Random_base32(rand, out->beacon.password, Headers_Beacon_PASSWORD_LEN);
  1048. String strPass = { .bytes=(char*)out->beacon.password, .len=Headers_Beacon_PASSWORD_LEN };
  1049. int ret = Ca_addUser(&strPass, String_CONST("Local Peers"), ca);
  1050. if (ret) {
  1051. Log_warn(logger, "Ca_addUser() returned [%d]", ret);
  1052. }
  1053. Ca_getPubKey(ca, out->ourPubKey);
  1054. Bits_memcpy(out->beacon.publicKey, out->ourPubKey, 32);
  1055. if (enableNoise) {
  1056. out->beacon.version_be = Endian_hostToBigEndian32(Version_CURRENT_PROTOCOL);
  1057. } else {
  1058. // this is mostly here for testing, we have to lie about our protocol version
  1059. out->beacon.version_be = Endian_hostToBigEndian32(21);
  1060. }
  1061. Timeout_setTimeout(beaconInterval, out, BEACON_INTERVAL, eventBase, alloc);
  1062. return &out->pub;
  1063. }