1
0

InterfaceController.c 47 KB

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