1
0

InterfaceController.c 38 KB

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