1
0

DefaultInterfaceController.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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 <http://www.gnu.org/licenses/>.
  14. */
  15. #include "crypto/AddressCalc.h"
  16. #include "crypto/CryptoAuth_pvt.h"
  17. #include "net/DefaultInterfaceController.h"
  18. #include "dht/dhtcore/RumorMill.h"
  19. #include "memory/Allocator.h"
  20. #include "net/SwitchPinger.h"
  21. #include "util/Base32.h"
  22. #include "util/Bits.h"
  23. #include "util/events/Time.h"
  24. #include "util/events/Timeout.h"
  25. #include "util/Identity.h"
  26. #include "util/version/Version.h"
  27. #include "util/AddrTools.h"
  28. #include "wire/Error.h"
  29. #include "wire/Message.h"
  30. #include <stddef.h> // offsetof
  31. /** After this number of milliseconds, a node will be regarded as unresponsive. */
  32. #define UNRESPONSIVE_AFTER_MILLISECONDS (20*1024)
  33. /**
  34. * After this number of milliseconds without a valid incoming message,
  35. * a peer is "lazy" and should be pinged.
  36. */
  37. #define PING_AFTER_MILLISECONDS (3*1024)
  38. /** How often to ping "lazy" peers, "unresponsive" peers are only pinged 20% of the time. */
  39. #define PING_INTERVAL_MILLISECONDS 1024
  40. /** The number of milliseconds to wait for a ping response. */
  41. #define TIMEOUT_MILLISECONDS (2*1024)
  42. /**
  43. * The number of seconds to wait before an unresponsive peer
  44. * making an incoming connection is forgotten.
  45. */
  46. #define FORGET_AFTER_MILLISECONDS (256*1024)
  47. /*--------------------Structs--------------------*/
  48. struct IFCPeer
  49. {
  50. /** The interface which is registered with the switch. */
  51. struct Interface switchIf;
  52. /** The internal (wrapped by CryptoAuth) interface. */
  53. struct Interface* cryptoAuthIf;
  54. /** The external (network side) interface. */
  55. struct Interface* external;
  56. /** The label for this endpoint, needed to ping the endpoint. */
  57. uint64_t switchLabel;
  58. /** Milliseconds since the epoch when the last *valid* message was received. */
  59. uint64_t timeOfLastMessage;
  60. /** The handle which can be used to look up this endpoint in the endpoint set. */
  61. uint32_t handle;
  62. /** True if we should forget about the peer if they do not respond. */
  63. bool isIncomingConnection : 1;
  64. /**
  65. * If InterfaceController_PeerState_UNAUTHENTICATED, no permanent state will be kept.
  66. * During transition from HANDSHAKE to ESTABLISHED, a check is done for a registeration of a
  67. * node which is already registered in a different switch slot, if there is one and the
  68. * handshake completes, it will be moved.
  69. */
  70. int state : 31;
  71. // traffic counters
  72. uint64_t bytesOut;
  73. uint64_t bytesIn;
  74. Identity
  75. };
  76. #define Map_NAME OfIFCPeerByExernalIf
  77. #define Map_ENABLE_HANDLES
  78. #define Map_KEY_TYPE struct Interface*
  79. #define Map_VALUE_TYPE struct IFCPeer*
  80. #include "util/Map.h"
  81. struct Context
  82. {
  83. /** Public functions and fields for this ifcontroller. */
  84. struct InterfaceController pub;
  85. /** Used to get a peer by its handle. */
  86. struct Map_OfIFCPeerByExernalIf peerMap;
  87. struct Allocator* const allocator;
  88. struct CryptoAuth* const ca;
  89. /** Switch for adding nodes when they are discovered. */
  90. struct SwitchCore* const switchCore;
  91. /** Router needed to inject newly added nodes to bootstrap the system. */
  92. struct RouterModule* const routerModule;
  93. struct RumorMill* const rumorMill;
  94. struct Log* const logger;
  95. struct EventBase* const eventBase;
  96. /** After this number of milliseconds, a neoghbor will be regarded as unresponsive. */
  97. uint32_t unresponsiveAfterMilliseconds;
  98. /** The number of milliseconds to wait before pinging. */
  99. uint32_t pingAfterMilliseconds;
  100. /** The number of milliseconds to let a ping go before timing it out. */
  101. uint32_t timeoutMilliseconds;
  102. /** After this number of milliseconds, an incoming connection is forgotten entirely. */
  103. uint32_t forgetAfterMilliseconds;
  104. /** A counter to allow for 3/4 of all pings to be skipped when a node is definitely down. */
  105. uint32_t pingCount;
  106. /** The timeout event to use for pinging potentially unresponsive neighbors. */
  107. struct Timeout* const pingInterval;
  108. /** For pinging lazy/unresponsive nodes. */
  109. struct SwitchPinger* const switchPinger;
  110. /** A password which is generated per-startup and sent out in beacon messages. */
  111. uint8_t beaconPassword[Headers_Beacon_PASSWORD_LEN];
  112. Identity
  113. };
  114. //---------------//
  115. static inline struct Context* ifcontrollerForPeer(struct IFCPeer* ep)
  116. {
  117. return Identity_check((struct Context*) ep->switchIf.senderContext);
  118. }
  119. static void onPingResponse(enum SwitchPinger_Result result,
  120. uint64_t label,
  121. String* data,
  122. uint32_t millisecondsLag,
  123. uint32_t version,
  124. void* onResponseContext)
  125. {
  126. if (SwitchPinger_Result_OK != result) {
  127. return;
  128. }
  129. struct IFCPeer* ep = Identity_check((struct IFCPeer*) onResponseContext);
  130. struct Context* ic = ifcontrollerForPeer(ep);
  131. struct Address addr;
  132. Bits_memset(&addr, 0, sizeof(struct Address));
  133. Bits_memcpyConst(addr.key, CryptoAuth_getHerPublicKey(ep->cryptoAuthIf), 32);
  134. addr.path = ep->switchLabel;
  135. Log_debug(ic->logger, "got switch pong from node with version [%d]", version);
  136. addr.protocolVersion = version;
  137. struct Node_Two* nn = RouterModule_nodeForPath(label, ic->routerModule);
  138. if (!nn) {
  139. RumorMill_addNode(ic->rumorMill, &addr);
  140. } else if (!nn->bestParent) {
  141. RouterModule_peerIsReachable(label, millisecondsLag, ic->routerModule);
  142. }
  143. #ifdef Log_DEBUG
  144. // This will be false if it times out.
  145. //Assert_true(label == ep->switchLabel);
  146. uint8_t path[20];
  147. AddrTools_printPath(path, label);
  148. uint8_t sl[20];
  149. AddrTools_printPath(sl, ep->switchLabel);
  150. Log_debug(ic->logger, "Received [%s] from lazy endpoint [%s] [%s]",
  151. SwitchPinger_resultString(result)->bytes, path, sl);
  152. #endif
  153. }
  154. // Called from the pingInteral timeout.
  155. static void pingCallback(void* vic)
  156. {
  157. struct Context* ic = Identity_check((struct Context*) vic);
  158. uint64_t now = Time_currentTimeMilliseconds(ic->eventBase);
  159. ic->pingCount++;
  160. // scan for endpoints have not sent anything recently.
  161. for (uint32_t i = 0; i < ic->peerMap.count; i++) {
  162. struct IFCPeer* ep = ic->peerMap.values[i];
  163. // This is here because of a pathological state where the connection is in ESTABLISHED
  164. // state but the *direct peer* has somehow been dropped from the routing table.
  165. // TODO: understand the cause of this issue rather than checking for it once per second.
  166. struct Node_Two* peerNode = RouterModule_nodeForPath(ep->switchLabel, ic->routerModule);
  167. if (now > ep->timeOfLastMessage + ic->pingAfterMilliseconds
  168. || !peerNode
  169. || !peerNode->bestParent)
  170. {
  171. #ifdef Log_DEBUG
  172. uint8_t key[56];
  173. Base32_encode(key, 56, CryptoAuth_getHerPublicKey(ep->cryptoAuthIf), 32);
  174. #endif
  175. if (ep->isIncomingConnection
  176. && now > ep->timeOfLastMessage + ic->forgetAfterMilliseconds)
  177. {
  178. Log_debug(ic->logger, "Unresponsive peer [%s.k] has not responded in [%u] "
  179. "seconds, dropping connection",
  180. key, ic->forgetAfterMilliseconds / 1024);
  181. Allocator_free(ep->external->allocator);
  182. return;
  183. }
  184. bool unresponsive = (now > ep->timeOfLastMessage + ic->unresponsiveAfterMilliseconds);
  185. if (unresponsive) {
  186. // flush the peer from the table...
  187. RouterModule_brokenPath(ep->switchLabel, ic->routerModule);
  188. // Lets skip 87% of pings when they're really down.
  189. if (ic->pingCount % 8) {
  190. continue;
  191. }
  192. ep->state = InterfaceController_PeerState_UNRESPONSIVE;
  193. }
  194. struct SwitchPinger_Ping* ping =
  195. SwitchPinger_newPing(ep->switchLabel,
  196. String_CONST(""),
  197. ic->timeoutMilliseconds,
  198. onPingResponse,
  199. ic->allocator,
  200. ic->switchPinger);
  201. #ifdef Log_DEBUG
  202. uint32_t lag = (now - ep->timeOfLastMessage) / 1024;
  203. #endif
  204. if (!ping) {
  205. Log_debug(ic->logger,
  206. "Failed to ping %s peer [%s.k] lag [%u], out of ping slots.",
  207. (unresponsive ? "unresponsive" : "lazy"), key, lag);
  208. return;
  209. }
  210. ping->onResponseContext = ep;
  211. Log_debug(ic->logger,
  212. "Pinging %s peer [%s.k] lag [%u]",
  213. (unresponsive ? "unresponsive" : "lazy"), key, lag);
  214. }
  215. }
  216. }
  217. /** If there's already an endpoint with the same public key, merge the new one with the old one. */
  218. static void moveEndpointIfNeeded(struct IFCPeer* ep, struct Context* ic)
  219. {
  220. Log_debug(ic->logger, "Checking for old sessions to merge with.");
  221. uint8_t* key = CryptoAuth_getHerPublicKey(ep->cryptoAuthIf);
  222. for (uint32_t i = 0; i < ic->peerMap.count; i++) {
  223. struct IFCPeer* thisEp = ic->peerMap.values[i];
  224. uint8_t* thisKey = CryptoAuth_getHerPublicKey(thisEp->cryptoAuthIf);
  225. if (thisEp != ep && !Bits_memcmp(thisKey, key, 32)) {
  226. Log_info(ic->logger, "Moving endpoint to merge new session with old.");
  227. ep->switchLabel = thisEp->switchLabel;
  228. SwitchCore_swapInterfaces(&thisEp->switchIf, &ep->switchIf);
  229. Allocator_free(thisEp->external->allocator);
  230. return;
  231. }
  232. }
  233. }
  234. // Incoming message which has passed through the cryptoauth and needs to be forwarded to the switch.
  235. static uint8_t receivedAfterCryptoAuth(struct Message* msg, struct Interface* cryptoAuthIf)
  236. {
  237. struct IFCPeer* ep = Identity_check((struct IFCPeer*) cryptoAuthIf->receiverContext);
  238. struct Context* ic = ifcontrollerForPeer(ep);
  239. ep->bytesIn += msg->length;
  240. if (ep->state < InterfaceController_PeerState_ESTABLISHED) {
  241. if (CryptoAuth_getState(cryptoAuthIf) >= CryptoAuth_HANDSHAKE3) {
  242. moveEndpointIfNeeded(ep, ic);
  243. ep->state = InterfaceController_PeerState_ESTABLISHED;
  244. } else {
  245. ep->state = InterfaceController_PeerState_HANDSHAKE;
  246. // prevent some kinds of nasty things which could be done with packet replay.
  247. // This is checking the message switch header and will drop it unless the label
  248. // directs it to *this* router.
  249. if (msg->length < 8 || msg->bytes[7] != 1) {
  250. Log_info(ic->logger, "DROP message because CA is not established.");
  251. return Error_NONE;
  252. } else {
  253. // When a "server" gets a new connection from a "client" the router doesn't
  254. // know about that client so if the client sends a packet to the server, the
  255. // server will be unable to handle it until the client has sent inter-router
  256. // communication to the server. Here we will ping the client so when the
  257. // server gets the ping response, it will insert the client into its table
  258. // and know its version.
  259. // prevent DoS by limiting the number of times this can be called per second
  260. // limit it to 7, this will affect innocent packets but it doesn't matter much
  261. // since this is mostly just an optimization and for keeping the tests happy.
  262. if ((ic->pingCount + 1) % 7) {
  263. pingCallback(ic);
  264. }
  265. }
  266. }
  267. } else if (ep->state == InterfaceController_PeerState_UNRESPONSIVE
  268. && CryptoAuth_getState(cryptoAuthIf) >= CryptoAuth_HANDSHAKE3)
  269. {
  270. ep->state = InterfaceController_PeerState_ESTABLISHED;
  271. } else {
  272. ep->timeOfLastMessage = Time_currentTimeMilliseconds(ic->eventBase);
  273. }
  274. return ep->switchIf.receiveMessage(msg, &ep->switchIf);
  275. }
  276. // This is directly called from SwitchCore, message is not encrypted.
  277. static uint8_t sendFromSwitch(struct Message* msg, struct Interface* switchIf)
  278. {
  279. struct IFCPeer* ep = Identity_check((struct IFCPeer*) switchIf);
  280. ep->bytesOut += msg->length;
  281. struct Context* ic = ifcontrollerForPeer(ep);
  282. uint8_t ret;
  283. uint64_t now = Time_currentTimeMilliseconds(ic->eventBase);
  284. if (now - ep->timeOfLastMessage > ic->unresponsiveAfterMilliseconds) {
  285. // XXX: This is a hack because if the time of last message exceeds the
  286. // unresponsive time, we need to send back an error and that means
  287. // mangling the message which would otherwise be in the queue.
  288. struct Allocator* tempAlloc = Allocator_child(ic->allocator);
  289. struct Message* toSend = Message_clone(msg, tempAlloc);
  290. ret = Interface_sendMessage(ep->cryptoAuthIf, toSend);
  291. Allocator_free(tempAlloc);
  292. } else {
  293. ret = Interface_sendMessage(ep->cryptoAuthIf, msg);
  294. }
  295. // If this node is unresponsive then return an error.
  296. if (ret || now - ep->timeOfLastMessage > ic->unresponsiveAfterMilliseconds) {
  297. return ret ? ret : Error_UNDELIVERABLE;
  298. } else {
  299. /* Way way way too much noise
  300. Log_debug(ic->logger, "Sending to neighbor, last message from this node was [%u] ms ago.",
  301. (now - ep->timeOfLastMessage));
  302. */
  303. }
  304. return Error_NONE;
  305. }
  306. static int closeInterface(struct Allocator_OnFreeJob* job)
  307. {
  308. struct IFCPeer* toClose = Identity_check((struct IFCPeer*) job->userData);
  309. struct Context* ic = ifcontrollerForPeer(toClose);
  310. // flush the peer from the table...
  311. RouterModule_brokenPath(toClose->switchLabel, ic->routerModule);
  312. int index = Map_OfIFCPeerByExernalIf_indexForHandle(toClose->handle, &ic->peerMap);
  313. Assert_true(index >= 0);
  314. Map_OfIFCPeerByExernalIf_remove(index, &ic->peerMap);
  315. return 0;
  316. }
  317. static int registerPeer(struct InterfaceController* ifController,
  318. uint8_t herPublicKey[32],
  319. String* password,
  320. bool requireAuth,
  321. bool isIncomingConnection,
  322. struct Interface* externalInterface)
  323. {
  324. struct Context* ic = Identity_check((struct Context*) ifController);
  325. if (Map_OfIFCPeerByExernalIf_indexForKey(&externalInterface, &ic->peerMap) > -1) {
  326. return 0;
  327. }
  328. Log_debug(ic->logger, "registerPeer [%p] total [%u]",
  329. (void*)externalInterface, ic->peerMap.count);
  330. uint8_t ip6[16];
  331. if (herPublicKey) {
  332. AddressCalc_addressForPublicKey(ip6, herPublicKey);
  333. if (!AddressCalc_validAddress(ip6)) {
  334. return InterfaceController_registerPeer_BAD_KEY;
  335. }
  336. if (!Bits_memcmp(ic->ca->publicKey, herPublicKey, 32)) {
  337. // can't link with yourself, wiseguy
  338. return InterfaceController_registerPeer_BAD_KEY;
  339. }
  340. } else {
  341. Assert_always(requireAuth);
  342. }
  343. struct Allocator* epAllocator = externalInterface->allocator;
  344. struct IFCPeer* ep = Allocator_calloc(epAllocator, sizeof(struct IFCPeer), 1);
  345. ep->bytesOut = 0;
  346. ep->bytesIn = 0;
  347. ep->external = externalInterface;
  348. int setIndex = Map_OfIFCPeerByExernalIf_put(&externalInterface, &ep, &ic->peerMap);
  349. ep->handle = ic->peerMap.handles[setIndex];
  350. Identity_set(ep);
  351. Allocator_onFree(epAllocator, closeInterface, ep);
  352. // If the other end need not supply a valid password to connect
  353. // we will set the connection state to HANDSHAKE because we don't
  354. // want the connection to be trashed after the first invalid packet.
  355. if (!requireAuth) {
  356. ep->state = InterfaceController_PeerState_HANDSHAKE;
  357. }
  358. ep->cryptoAuthIf = CryptoAuth_wrapInterface(externalInterface,
  359. herPublicKey,
  360. NULL,
  361. requireAuth,
  362. "outer",
  363. ic->ca);
  364. ep->cryptoAuthIf->receiveMessage = receivedAfterCryptoAuth;
  365. ep->cryptoAuthIf->receiverContext = ep;
  366. // Always use authType 1 until something else comes along, then we'll have to refactor.
  367. if (password) {
  368. CryptoAuth_setAuth(password, 1, ep->cryptoAuthIf);
  369. }
  370. ep->isIncomingConnection = isIncomingConnection;
  371. Bits_memcpyConst(&ep->switchIf, (&(struct Interface) {
  372. .sendMessage = sendFromSwitch,
  373. // ifcontrollerForPeer uses this.
  374. // sendFromSwitch relies on the fact that the
  375. // switchIf is the same memory location as the Peer.
  376. .senderContext = ic,
  377. .allocator = epAllocator
  378. }), sizeof(struct Interface));
  379. int ret = SwitchCore_addInterface(&ep->switchIf, 0, &ep->switchLabel, ic->switchCore);
  380. if (ret) {
  381. return (ret == SwitchCore_addInterface_OUT_OF_SPACE)
  382. ? InterfaceController_registerPeer_OUT_OF_SPACE
  383. : InterfaceController_registerPeer_INTERNAL;
  384. }
  385. // We want the node to immedietly be pinged but we don't want it to appear unresponsive because
  386. // the pinger will only ping every (PING_INTERVAL * 8) so we set timeOfLastMessage to
  387. // (now - pingAfterMilliseconds - 1) so it will be considered a "lazy node".
  388. ep->timeOfLastMessage =
  389. Time_currentTimeMilliseconds(ic->eventBase) - ic->pingAfterMilliseconds - 1;
  390. if (herPublicKey) {
  391. #ifdef Log_INFO
  392. uint8_t printAddr[60];
  393. AddrTools_printIp(printAddr, ip6);
  394. Log_info(ic->logger, "Adding peer [%s]", printAddr);
  395. #endif
  396. // Kick the ping callback so that the node will be pinged ASAP.
  397. pingCallback(ic);
  398. }
  399. return 0;
  400. }
  401. static enum InterfaceController_PeerState getPeerState(struct Interface* iface)
  402. {
  403. struct Interface* cryptoAuthIf = CryptoAuth_getConnectedInterface(iface);
  404. struct IFCPeer* p = Identity_check((struct IFCPeer*) cryptoAuthIf->receiverContext);
  405. return p->state;
  406. }
  407. static void populateBeacon(struct InterfaceController* ifc, struct Headers_Beacon* beacon)
  408. {
  409. struct Context* ic = Identity_check((struct Context*) ifc);
  410. beacon->version_be = Endian_hostToBigEndian32(Version_CURRENT_PROTOCOL);
  411. Bits_memcpyConst(beacon->password, ic->beaconPassword, Headers_Beacon_PASSWORD_LEN);
  412. Bits_memcpyConst(beacon->publicKey, ic->ca->publicKey, 32);
  413. }
  414. static int getPeerStats(struct InterfaceController* ifController,
  415. struct Allocator* alloc,
  416. struct InterfaceController_peerStats** statsOut)
  417. {
  418. struct Context* ic = Identity_check((struct Context*) ifController);
  419. int count = ic->peerMap.count;
  420. struct InterfaceController_peerStats* stats =
  421. Allocator_malloc(alloc, sizeof(struct InterfaceController_peerStats)*count);
  422. for (int i = 0; i < count; i++) {
  423. struct IFCPeer* peer = ic->peerMap.values[i];
  424. struct InterfaceController_peerStats* s = &stats[i];
  425. s->pubKey = CryptoAuth_getHerPublicKey(peer->cryptoAuthIf);
  426. s->bytesOut = peer->bytesOut;
  427. s->bytesIn = peer->bytesIn;
  428. s->timeOfLastMessage = peer->timeOfLastMessage;
  429. s->state = peer->state;
  430. s->switchLabel = peer->switchLabel;
  431. s->isIncomingConnection = peer->isIncomingConnection;
  432. s->user = NULL;
  433. if (s->isIncomingConnection) {
  434. s->user = CryptoAuth_getUser(peer->cryptoAuthIf);
  435. }
  436. struct ReplayProtector* rp = CryptoAuth_getReplayProtector(peer->cryptoAuthIf);
  437. s->duplicates = rp->duplicates;
  438. s->lostPackets = rp->lostPackets;
  439. s->receivedOutOfRange = rp->receivedOutOfRange;
  440. }
  441. *statsOut = stats;
  442. return count;
  443. }
  444. static int disconnectPeer(struct InterfaceController* ifController, uint8_t herPublicKey[32])
  445. {
  446. struct Context* ic = Identity_check((struct Context*) ifController);
  447. for (uint32_t i = 0; i < ic->peerMap.count; i++) {
  448. struct IFCPeer* peer = ic->peerMap.values[i];
  449. if (!Bits_memcmp(herPublicKey, CryptoAuth_getHerPublicKey(peer->cryptoAuthIf), 32)) {
  450. Allocator_free(peer->external->allocator);
  451. return 0;
  452. }
  453. }
  454. return InterfaceController_disconnectPeer_NOTFOUND;
  455. }
  456. struct InterfaceController* DefaultInterfaceController_new(struct CryptoAuth* ca,
  457. struct SwitchCore* switchCore,
  458. struct RouterModule* routerModule,
  459. struct RumorMill* rumorMill,
  460. struct Log* logger,
  461. struct EventBase* eventBase,
  462. struct SwitchPinger* switchPinger,
  463. struct Random* rand,
  464. struct Allocator* allocator)
  465. {
  466. struct Context* out = Allocator_malloc(allocator, sizeof(struct Context));
  467. Bits_memcpyConst(out, (&(struct Context) {
  468. .pub = {
  469. .registerPeer = registerPeer,
  470. .disconnectPeer = disconnectPeer,
  471. .getPeerState = getPeerState,
  472. .populateBeacon = populateBeacon,
  473. .getPeerStats = getPeerStats,
  474. },
  475. .peerMap = {
  476. .allocator = allocator
  477. },
  478. .allocator = allocator,
  479. .ca = ca,
  480. .switchCore = switchCore,
  481. .routerModule = routerModule,
  482. .rumorMill = rumorMill,
  483. .logger = logger,
  484. .eventBase = eventBase,
  485. .switchPinger = switchPinger,
  486. .unresponsiveAfterMilliseconds = UNRESPONSIVE_AFTER_MILLISECONDS,
  487. .pingAfterMilliseconds = PING_AFTER_MILLISECONDS,
  488. .timeoutMilliseconds = TIMEOUT_MILLISECONDS,
  489. .forgetAfterMilliseconds = FORGET_AFTER_MILLISECONDS,
  490. .pingInterval = (switchPinger)
  491. ? Timeout_setInterval(pingCallback,
  492. out,
  493. PING_INTERVAL_MILLISECONDS,
  494. eventBase,
  495. allocator)
  496. : NULL
  497. }), sizeof(struct Context));
  498. Identity_set(out);
  499. // Add the beaconing password.
  500. Random_bytes(rand, out->beaconPassword, Headers_Beacon_PASSWORD_LEN);
  501. String strPass = { .bytes=(char*)out->beaconPassword, .len=Headers_Beacon_PASSWORD_LEN };
  502. int ret = CryptoAuth_addUser(&strPass, 1, String_CONST("Local Peers"), ca);
  503. if (ret) {
  504. Log_warn(logger, "CryptoAuth_addUser() returned [%d]", ret);
  505. }
  506. return &out->pub;
  507. }