InterfaceController.c 38 KB

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