1
0

InterfaceController.c 40 KB

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