1
0

DefaultInterfaceController.c 22 KB

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