InterfaceController.c 39 KB

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