InterfaceController.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "crypto/AddressCalc.h"
  16. #include "crypto/CryptoAuth_pvt.h"
  17. #include "interface/Iface.h"
  18. #include "net/InterfaceController.h"
  19. #include "memory/Allocator.h"
  20. #include "net/SwitchPinger.h"
  21. #include "wire/PFChan.h"
  22. #include "net/EventEmitter.h"
  23. #include "util/Base32.h"
  24. #include "util/Bits.h"
  25. #include "util/events/Time.h"
  26. #include "util/events/Timeout.h"
  27. #include "util/Identity.h"
  28. #include "util/version/Version.h"
  29. #include "util/AddrTools.h"
  30. #include "util/Defined.h"
  31. #include "util/Checksum.h"
  32. #include "util/Hex.h"
  33. #include "util/Kbps.h"
  34. #include "wire/Error.h"
  35. #include "wire/Message.h"
  36. #include "wire/Headers.h"
  37. #include "wire/Metric.h"
  38. /** After this number of milliseconds, a node will be regarded as unresponsive. */
  39. #define UNRESPONSIVE_AFTER_MILLISECONDS (20*1024)
  40. /**
  41. * After this number of milliseconds without a valid incoming message,
  42. * a peer is "lazy" and should be pinged.
  43. */
  44. #define PING_AFTER_MILLISECONDS (3*1024)
  45. /** How often to ping "lazy" peers, "unresponsive" peers are only pinged 20% of the time. */
  46. #define PING_INTERVAL_MILLISECONDS 1024
  47. /** The number of milliseconds to wait for a ping response. */
  48. #define TIMEOUT_MILLISECONDS (2*1024)
  49. /**
  50. * The number of seconds to wait before an unresponsive peer
  51. * making an incoming connection is forgotten.
  52. */
  53. #define FORGET_AFTER_MILLISECONDS (256*1024)
  54. /** Wait 32 seconds between sending beacon messages. */
  55. #define BEACON_INTERVAL 32768
  56. /** Every 3 seconds inform the pathfinder of the current link states. */
  57. #define LINKSTATE_UPDATE_INTERVAL 3000
  58. // ---------------- Map ----------------
  59. #define Map_NAME EndpointsBySockaddr
  60. #define Map_ENABLE_HANDLES
  61. #define Map_KEY_TYPE struct Sockaddr*
  62. #define Map_VALUE_TYPE struct Peer*
  63. #define Map_USE_HASH
  64. #define Map_USE_COMPARATOR
  65. #include "util/Map.h"
  66. static inline uint32_t Map_EndpointsBySockaddr_hash(struct Sockaddr** key)
  67. {
  68. return Sockaddr_hash(*key);
  69. }
  70. static inline int Map_EndpointsBySockaddr_compare(struct Sockaddr** keyA, struct Sockaddr** keyB)
  71. {
  72. return Sockaddr_compare(*keyA, *keyB);
  73. }
  74. // ---------------- EndMap ----------------
  75. #define ArrayList_TYPE struct InterfaceController_Iface_pvt
  76. #define ArrayList_NAME OfIfaces
  77. #include "util/ArrayList.h"
  78. struct InterfaceController_pvt;
  79. struct InterfaceController_Iface_pvt
  80. {
  81. struct InterfaceController_Iface pub;
  82. struct Map_EndpointsBySockaddr peerMap;
  83. /** The number of the next peer to try pinging, this iterates through the list of peers. */
  84. uint32_t lastPeerPinged;
  85. struct InterfaceController_pvt* ic;
  86. struct Allocator* alloc;
  87. Identity
  88. };
  89. struct Peer
  90. {
  91. /** The interface which is registered with the switch. */
  92. struct Iface switchIf;
  93. struct Iface plaintext;
  94. struct Iface ciphertext;
  95. struct Allocator* alloc;
  96. struct CryptoAuth_Session* caSession;
  97. struct Kbps sendBw;
  98. struct Kbps recvBw;
  99. /** The interface which this peer belongs to. */
  100. struct InterfaceController_Iface_pvt* ici;
  101. /** The address within the interface of this peer. */
  102. struct Sockaddr* lladdr;
  103. struct Address addr;
  104. /** Milliseconds since the epoch when the last *valid* message was received. */
  105. uint64_t timeOfLastMessage;
  106. /** Time when the last switch ping response was received from this node. */
  107. uint64_t timeOfLastPing;
  108. /** A counter to allow for 3/4 of all pings to be skipped when a node is definitely down. */
  109. uint32_t pingCount;
  110. /** The handle which can be used to look up this endpoint in the endpoint set. */
  111. uint32_t handle;
  112. /** True if we should forget about the peer if they do not respond. */
  113. bool isIncomingConnection;
  114. /**
  115. * If InterfaceController_PeerState_UNAUTHENTICATED, no permanent state will be kept.
  116. * During transition from HANDSHAKE to ESTABLISHED, a check is done for a registeration of a
  117. * node which is already registered in a different switch slot, if there is one and the
  118. * handshake completes, it will be moved.
  119. */
  120. enum InterfaceController_PeerState state;
  121. /**
  122. * The number of lost packets last time we checked.
  123. * _lastDrops and _lastPackets are the direct readings off of the ReplayProtector
  124. * so they will be reset to zero when the session resets. lastDrops and lastPackets
  125. * are monotonic and so probably what you want.
  126. */
  127. uint64_t _lastDrops;
  128. uint64_t _lastPackets;
  129. uint64_t lastDrops;
  130. uint64_t lastPackets;
  131. // traffic counters
  132. uint64_t bytesOut;
  133. uint64_t bytesIn;
  134. Identity
  135. };
  136. struct InterfaceController_pvt
  137. {
  138. /** Public functions and fields for this ifcontroller. */
  139. struct InterfaceController pub;
  140. struct Allocator* const alloc;
  141. struct CryptoAuth* const ca;
  142. /** Switch for adding nodes when they are discovered. */
  143. struct SwitchCore* const switchCore;
  144. struct Random* const rand;
  145. struct Log* const logger;
  146. struct EventBase* const eventBase;
  147. /** For communicating with the Pathfinder. */
  148. struct Iface eventEmitterIf;
  149. /** After this number of milliseconds, a neoghbor will be regarded as unresponsive. */
  150. uint32_t unresponsiveAfterMilliseconds;
  151. /** The number of milliseconds to wait before pinging. */
  152. uint32_t pingAfterMilliseconds;
  153. /** The number of milliseconds to let a ping go before timing it out. */
  154. uint32_t timeoutMilliseconds;
  155. /** After this number of milliseconds, an incoming connection is forgotten entirely. */
  156. uint32_t forgetAfterMilliseconds;
  157. /** How often to send beacon messages (milliseconds). */
  158. uint32_t beaconInterval;
  159. /** The timeout event to use for pinging potentially unresponsive neighbors. */
  160. struct Timeout* const pingInterval;
  161. /** The timeout event for updating the link state to the pathfinders. */
  162. struct Timeout* const linkStateInterval;
  163. /** For pinging lazy/unresponsive nodes. */
  164. struct SwitchPinger* const switchPinger;
  165. struct ArrayList_OfIfaces* icis;
  166. /** Temporary allocator for allocating timeouts for sending beacon messages. */
  167. struct Allocator* beaconTimeoutAlloc;
  168. /** A password which is generated per-startup and sent out in beacon messages. */
  169. uint8_t beaconPassword[Headers_Beacon_PASSWORD_LEN];
  170. struct Headers_Beacon beacon;
  171. uint8_t ourPubKey[32];
  172. Identity
  173. };
  174. static bool knownIncompatibleVersion(uint32_t version)
  175. {
  176. if (!version) {
  177. return false;
  178. } else if (Defined(SUBNODE) && version < 21) {
  179. // Subnode doesn't talk to peers with less than v21
  180. return true;
  181. }
  182. return !Version_isCompatible(version, Version_CURRENT_PROTOCOL);
  183. }
  184. static void sendPeer(uint32_t pathfinderId,
  185. enum PFChan_Core ev,
  186. struct Peer* peer,
  187. uint16_t latency)
  188. {
  189. if (!peer->addr.protocolVersion || knownIncompatibleVersion(peer->addr.protocolVersion)) {
  190. // Don't know the protocol version, never add them
  191. return;
  192. }
  193. struct InterfaceController_pvt* ic = Identity_check(peer->ici->ic);
  194. struct Allocator* alloc = Allocator_child(ic->alloc);
  195. struct Message* msg = Message_new(PFChan_Node_SIZE, 512, alloc);
  196. struct PFChan_Node* node = (struct PFChan_Node*) msg->msgbytes;
  197. Bits_memcpy(node->ip6, peer->addr.ip6.bytes, 16);
  198. Bits_memcpy(node->publicKey, peer->addr.key, 32);
  199. node->path_be = Endian_hostToBigEndian64(peer->addr.path);
  200. node->version_be = Endian_hostToBigEndian32(peer->addr.protocolVersion);
  201. if (ev != PFChan_Core_PEER_GONE) {
  202. Assert_true(peer->addr.protocolVersion);
  203. node->metric_be =
  204. Endian_hostToBigEndian32(Metric_IC_PEER | (latency & Metric_IC_PEER_MASK));
  205. } else {
  206. node->metric_be = Endian_hostToBigEndian32(Metric_DEAD_LINK);
  207. }
  208. Er_assert(Message_epush32be(msg, pathfinderId));
  209. Er_assert(Message_epush32be(msg, ev));
  210. Iface_send(&ic->eventEmitterIf, msg);
  211. Allocator_free(alloc);
  212. }
  213. static void onPingResponse(struct SwitchPinger_Response* resp, void* onResponseContext)
  214. {
  215. if (SwitchPinger_Result_OK != resp->res) {
  216. return;
  217. }
  218. struct Peer* ep = Identity_check((struct Peer*) onResponseContext);
  219. struct InterfaceController_pvt* ic = Identity_check(ep->ici->ic);
  220. ep->addr.protocolVersion = resp->version;
  221. if (Defined(Log_DEBUG)) {
  222. String* addr = Address_toString(&ep->addr, resp->ping->pingAlloc);
  223. if (knownIncompatibleVersion(resp->version)) {
  224. Log_debug(ic->logger, "got switch pong from node [%s] with incompatible version",
  225. addr->bytes);
  226. } else if (ep->addr.path != resp->label) {
  227. uint8_t sl[20];
  228. AddrTools_printPath(sl, resp->label);
  229. Log_debug(ic->logger, "got switch pong from node [%s] mismatch label [%s]",
  230. addr->bytes, sl);
  231. } else {
  232. Log_debug(ic->logger, "got switch pong from node [%s]", addr->bytes);
  233. }
  234. }
  235. if (knownIncompatibleVersion(resp->version) || ep->addr.path != resp->label) {
  236. ep->state = InterfaceController_PeerState_INCOMPATIBLE;
  237. return;
  238. }
  239. if (ep->state == InterfaceController_PeerState_ESTABLISHED) {
  240. sendPeer(0xffffffff, PFChan_Core_PEER, ep, resp->milliseconds);
  241. }
  242. ep->timeOfLastPing = Time_currentTimeMilliseconds(ic->eventBase);
  243. if (Defined(Log_DEBUG)) {
  244. String* addr = Address_toString(&ep->addr, resp->ping->pingAlloc);
  245. Log_debug(ic->logger, "Received [%s] from lazy endpoint [%s]",
  246. SwitchPinger_resultString(resp->res)->bytes, addr->bytes);
  247. }
  248. }
  249. /*
  250. * Send a ping packet to one of the endpoints.
  251. */
  252. static void sendPing(struct Peer* ep)
  253. {
  254. struct InterfaceController_pvt* ic = Identity_check(ep->ici->ic);
  255. ep->pingCount++;
  256. struct SwitchPinger_Ping* ping =
  257. SwitchPinger_newPing(ep->addr.path,
  258. String_CONST(""),
  259. ic->timeoutMilliseconds,
  260. onPingResponse,
  261. ep->alloc,
  262. ic->switchPinger);
  263. if (!ping) {
  264. struct Allocator* alloc = Allocator_child(ep->alloc);
  265. Log_debug(ic->logger, "Sending switch ping to [%s] failed, out of ping slots",
  266. Address_toString(&ep->addr, alloc)->bytes);
  267. Allocator_free(alloc);
  268. } else {
  269. Log_debug(ic->logger, "Sending switch ping to [%s]",
  270. Address_toString(&ep->addr, ping->pingAlloc)->bytes);
  271. }
  272. if (ping) {
  273. ping->onResponseContext = ep;
  274. }
  275. }
  276. static void linkState(void* vic)
  277. {
  278. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) vic);
  279. uint32_t msgLen = 64;
  280. for (int i = 0; i < ic->icis->length; i++) {
  281. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  282. msgLen += PFChan_LinkState_Entry_SIZE * ici->peerMap.count;
  283. }
  284. struct Allocator* alloc = Allocator_child(ic->alloc);
  285. struct Message* msg = Message_new(0, msgLen, alloc);
  286. for (int i = 0; i < ic->icis->length; i++) {
  287. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  288. for (uint32_t i = 0; i < ici->peerMap.count; i++) {
  289. struct Peer* ep = ici->peerMap.values[i];
  290. RTypes_CryptoStats_t stats;
  291. CryptoAuth_stats(ep->caSession, &stats);
  292. uint64_t newDrops = 0;
  293. // Prevents invalid number when the session resets
  294. if (stats.lost_packets > ep->_lastDrops) {
  295. newDrops = stats.lost_packets - ep->_lastDrops;
  296. }
  297. ep->_lastDrops = stats.lost_packets;
  298. ep->lastDrops += newDrops;
  299. uint64_t newPackets = 0;
  300. if (stats.received_packets > ep->_lastPackets) {
  301. newPackets = stats.received_packets - ep->_lastPackets;
  302. }
  303. ep->_lastPackets = stats.received_packets;
  304. ep->lastPackets += newPackets;
  305. struct PFChan_LinkState_Entry e = {
  306. .peerLabel = ep->addr.path,
  307. .sumOfPackets = ep->lastPackets,
  308. .sumOfDrops = ep->lastDrops,
  309. .sumOfKb = (ep->bytesIn >> 10),
  310. };
  311. Er_assert(Message_epush(msg, &e, PFChan_LinkState_Entry_SIZE));
  312. }
  313. }
  314. if (Message_getLength(msg)) {
  315. Er_assert(Message_epush32be(msg, 0xffffffff));
  316. Er_assert(Message_epush32be(msg, PFChan_Core_LINK_STATE));
  317. Iface_send(&ic->eventEmitterIf, msg);
  318. }
  319. Allocator_free(alloc);
  320. }
  321. static void iciPing(struct InterfaceController_Iface_pvt* ici, struct InterfaceController_pvt* ic)
  322. {
  323. if (!ici->peerMap.count) { return; }
  324. uint64_t now = Time_currentTimeMilliseconds(ic->eventBase);
  325. // scan for endpoints have not sent anything recently.
  326. uint32_t startAt = ici->lastPeerPinged = (ici->lastPeerPinged + 1) % ici->peerMap.count;
  327. for (uint32_t i = startAt, count = 0; count < ici->peerMap.count;) {
  328. i = (i + 1) % ici->peerMap.count;
  329. count++;
  330. struct Peer* ep = ici->peerMap.values[i];
  331. if (knownIncompatibleVersion(ep->addr.protocolVersion)) {
  332. // This is a version mismatch, we have nothing to do with this node
  333. // but we keep the session in INCOMPATIBLE state to keep track of the
  334. // fact that we don't want to talk to it.
  335. ep->state = InterfaceController_PeerState_INCOMPATIBLE;
  336. continue;
  337. }
  338. uint8_t ipIfDebug[40];
  339. if (Defined(Log_DEBUG)) {
  340. Address_printIp(ipIfDebug, &ep->addr);
  341. }
  342. if (ep->addr.protocolVersion && now < ep->timeOfLastMessage + ic->pingAfterMilliseconds) {
  343. // It's sending traffic so leave it alone.
  344. // wait just a minute here !
  345. // There is a risk that the NodeStore somehow forgets about our peers while the peers
  346. // are still happily sending traffic. To break this bad cycle lets just send a PEER
  347. // message once per second for whichever peer is the first that we address.
  348. if (count == 1 && ep->state == InterfaceController_PeerState_ESTABLISHED) {
  349. // noisy
  350. //Log_debug(ic->logger, "Notifying about peer number [%d/%d] [%s]",
  351. // i, ici->peerMap.count, ipIfDebug);
  352. sendPeer(0xffffffff, PFChan_Core_PEER, ep, 0xffff);
  353. }
  354. continue;
  355. }
  356. if (now < ep->timeOfLastPing + ic->pingAfterMilliseconds) {
  357. // Possibly an out-of-date node which is mangling packets, don't ping too often
  358. // because it causes the RumorMill to be filled with this node over and over.
  359. continue;
  360. }
  361. if (ep->isIncomingConnection && now > ep->timeOfLastMessage + ic->forgetAfterMilliseconds) {
  362. Log_debug(ic->logger, "Unresponsive peer [%s] has not responded in [%u] "
  363. "seconds, dropping connection",
  364. ipIfDebug, ic->forgetAfterMilliseconds / 1024);
  365. sendPeer(0xffffffff, PFChan_Core_PEER_GONE, ep, 0xffff);
  366. Allocator_free(ep->alloc);
  367. continue;
  368. }
  369. bool unresponsive = (now > ep->timeOfLastMessage + ic->unresponsiveAfterMilliseconds);
  370. if (unresponsive) {
  371. // our link to the peer is broken...
  372. // Lets skip 87% of pings when they're really down.
  373. if (ep->pingCount % 8) {
  374. ep->pingCount++;
  375. continue;
  376. }
  377. sendPeer(0xffffffff, PFChan_Core_PEER_GONE, ep, 0xffff);
  378. ep->state = InterfaceController_PeerState_UNRESPONSIVE;
  379. }
  380. Log_debug(ic->logger,
  381. "Pinging %s peer [%s] lag [%u]",
  382. (unresponsive ? "unresponsive" : "lazy"),
  383. ipIfDebug,
  384. (uint32_t)((now - ep->timeOfLastMessage) / 1024));
  385. sendPing(ep);
  386. // we only ping one node
  387. return;
  388. }
  389. }
  390. /**
  391. * Check the table for nodes which might need to be pinged, ping a node if necessary.
  392. * If a node has not responded in unresponsiveAfterMilliseconds then mark them as unresponsive
  393. * and if the connection is incoming and the node has not responded in forgetAfterMilliseconds
  394. * then drop them entirely.
  395. * This is called every PING_INTERVAL_MILLISECONDS
  396. */
  397. static void pingCycle(void* vic)
  398. {
  399. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) vic);
  400. for (int i = 0; i < ic->icis->length; i++) {
  401. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  402. iciPing(ici, ic);
  403. }
  404. }
  405. static Iface_DEFUN afterEncrypt(struct Message* msg, struct Iface* ciphertext)
  406. {
  407. struct Peer* ep = Identity_containerOf(ciphertext, struct Peer, ciphertext);
  408. // push the lladdr...
  409. Er_assert(Message_epush(msg, ep->lladdr, ep->lladdr->addrLen));
  410. // very noisy
  411. if (Defined(Log_DEBUG) && false) {
  412. char* printedAddr =
  413. Hex_print(&ep->lladdr[1], ep->lladdr->addrLen - Sockaddr_OVERHEAD, Message_getAlloc(msg));
  414. Log_debug(ep->ici->ic->logger, "Outgoing message to [%s]", printedAddr);
  415. }
  416. return Iface_send(&ep->ici->pub.addrIf, msg);
  417. }
  418. // This is directly called from SwitchCore, message is not encrypted.
  419. static Iface_DEFUN sendFromSwitch(struct Message* msg, struct Iface* switchIf)
  420. {
  421. struct Peer* ep = Identity_check((struct Peer*) switchIf);
  422. // Once we know it to be an incompetible version, we quarentine it
  423. if (knownIncompatibleVersion(ep->addr.protocolVersion)) {
  424. if (Defined(Log_DEBUG)) {
  425. Log_debug(ep->ici->ic->logger, "[%s] DROP msg to node with incompat version [%d] ",
  426. Address_toString(&ep->addr, Message_getAlloc(msg))->bytes, ep->addr.protocolVersion);
  427. }
  428. ep->state = InterfaceController_PeerState_INCOMPATIBLE;
  429. return Error(UNHANDLED);
  430. }
  431. ep->bytesOut += Message_getLength(msg);
  432. Kbps_accumulate(&ep->sendBw, Time_currentTimeMilliseconds(ep->ici->ic->eventBase), Message_getLength(msg));
  433. return Iface_next(&ep->plaintext, msg); // --> afterEncrypt
  434. }
  435. static int closeInterface(struct Allocator_OnFreeJob* job)
  436. {
  437. struct Peer* toClose = Identity_check((struct Peer*) job->userData);
  438. int index = Map_EndpointsBySockaddr_indexForHandle(toClose->handle, &toClose->ici->peerMap);
  439. if (index < 0 || toClose->ici->peerMap.values[index] != toClose) {
  440. // Happens if the ep was created as a result of handleUnexpectedIncoming
  441. return 0;
  442. }
  443. sendPeer(0xffffffff, PFChan_Core_PEER_GONE, toClose, 0xffff);
  444. Log_debug(toClose->ici->ic->logger,
  445. "Closing interface [%d] with handle [%u]", index, toClose->handle);
  446. Map_EndpointsBySockaddr_remove(index, &toClose->ici->peerMap);
  447. return 0;
  448. }
  449. static Iface_DEFUN afterDecrypt(struct Message* msg, struct Iface* plaintext);
  450. static struct Peer* mkEp(
  451. const struct Sockaddr* lladdr,
  452. struct InterfaceController_Iface_pvt* ici,
  453. uint8_t publicKey[32],
  454. bool authNeeded,
  455. const char* name
  456. ) {
  457. struct Allocator* epAlloc = Allocator_child(ici->alloc);
  458. struct Peer* ep = Allocator_calloc(epAlloc, sizeof(struct Peer), 1);
  459. Identity_set(ep);
  460. ep->ici = ici;
  461. ep->lladdr = Sockaddr_clone(lladdr, epAlloc);
  462. ep->alloc = epAlloc;
  463. ep->state = InterfaceController_PeerState_UNAUTHENTICATED;
  464. ep->isIncomingConnection = true;
  465. ep->switchIf.send = sendFromSwitch;
  466. ep->ciphertext.send = afterEncrypt;
  467. ep->plaintext.send = afterDecrypt;
  468. ep->caSession = CryptoAuth_newSession(ici->ic->ca, epAlloc, publicKey, authNeeded, name);
  469. Iface_plumb(&ep->caSession->ciphertext, &ep->ciphertext);
  470. Iface_plumb(&ep->caSession->plaintext, &ep->plaintext);
  471. Bits_memcpy(ep->addr.key, publicKey, 32);
  472. Address_getPrefix(&ep->addr);
  473. Allocator_onFree(epAlloc, closeInterface, ep);
  474. return ep;
  475. }
  476. /**
  477. * Expects [ struct LLAddress ][ beacon ]
  478. */
  479. static Iface_DEFUN handleBeacon(struct Message* msg, struct InterfaceController_Iface_pvt* ici)
  480. {
  481. struct InterfaceController_pvt* ic = ici->ic;
  482. if (!ici->pub.beaconState) {
  483. // accepting beacons disabled.
  484. Log_debug(ic->logger, "[%s] Dropping beacon because beaconing is disabled",
  485. ici->pub.name->bytes);
  486. return Error(NONE);
  487. }
  488. if (Message_getLength(msg) < Sockaddr_OVERHEAD) {
  489. Log_debug(ic->logger, "[%s] Dropping runt beacon", ici->pub.name->bytes);
  490. return Error(RUNT);
  491. }
  492. struct Sockaddr* lladdrInmsg = (struct Sockaddr*) msg->msgbytes;
  493. if (Message_getLength(msg) < lladdrInmsg->addrLen + Headers_Beacon_SIZE) {
  494. Log_debug(ic->logger, "[%s] Dropping runt beacon", ici->pub.name->bytes);
  495. return Error(RUNT);
  496. }
  497. // clear the bcast flag
  498. lladdrInmsg->flags = 0;
  499. Er_assert(Message_eshift(msg, -lladdrInmsg->addrLen));
  500. struct Headers_Beacon beacon;
  501. Er_assert(Message_epop(msg, &beacon, Headers_Beacon_SIZE));
  502. if (Defined(Log_DEBUG)) {
  503. char* content = Hex_print(&beacon, Headers_Beacon_SIZE, Message_getAlloc(msg));
  504. Log_debug(ici->ic->logger, "RECV BEACON CONTENT[%s]", content);
  505. }
  506. struct Address addr;
  507. Bits_memset(&addr, 0, sizeof(struct Address));
  508. Bits_memcpy(addr.key, beacon.publicKey, 32);
  509. addr.protocolVersion = Endian_bigEndianToHost32(beacon.version_be);
  510. Address_getPrefix(&addr);
  511. String* printedAddr = NULL;
  512. if (Defined(Log_DEBUG)) {
  513. printedAddr = Address_toString(&addr, Message_getAlloc(msg));
  514. }
  515. if (!AddressCalc_validAddress(addr.ip6.bytes)) {
  516. Log_debug(ic->logger, "handleBeacon invalid key [%s]", printedAddr->bytes);
  517. return Error(INVALID);
  518. } else if (!Bits_memcmp(ic->ourPubKey, addr.key, 32)) {
  519. // receive beacon from self, drop silent
  520. return Error(NONE);
  521. }
  522. if (knownIncompatibleVersion(addr.protocolVersion)) {
  523. if (Defined(Log_DEBUG)) {
  524. Log_debug(ic->logger, "[%s] DROP beacon from [%s] which was version [%d] "
  525. "our version is [%d] making them incompatable", ici->pub.name->bytes,
  526. printedAddr->bytes, addr.protocolVersion, Version_CURRENT_PROTOCOL);
  527. }
  528. return Error(UNHANDLED);
  529. }
  530. String* beaconPass = String_newBinary(beacon.password, Headers_Beacon_PASSWORD_LEN, Message_getAlloc(msg));
  531. int epIndex = Map_EndpointsBySockaddr_indexForKey(&lladdrInmsg, &ici->peerMap);
  532. if (epIndex > -1) {
  533. // The password might have changed!
  534. struct Peer* ep = ici->peerMap.values[epIndex];
  535. CryptoAuth_setAuth(beaconPass, NULL, ep->caSession);
  536. return Error(NONE);
  537. }
  538. struct Peer* ep = mkEp(lladdrInmsg, ici, beacon.publicKey, false, "beacon_peer");
  539. int setIndex = Map_EndpointsBySockaddr_put(&ep->lladdr, &ep, &ici->peerMap);
  540. ep->handle = ici->peerMap.handles[setIndex];
  541. // We make the connection ourselves but we still consider
  542. // it "incoming" because we replied to a beacon
  543. ep->isIncomingConnection = true;
  544. ep->addr.protocolVersion = addr.protocolVersion;
  545. CryptoAuth_setAuth(beaconPass, NULL, ep->caSession);
  546. if (SwitchCore_addInterface(ic->switchCore, &ep->switchIf, ep->alloc, &ep->addr.path)) {
  547. Log_debug(ic->logger, "handleBeacon() SwitchCore out of space");
  548. Allocator_free(ep->alloc);
  549. return Error(UNHANDLED);
  550. }
  551. // We want the node to immedietly be pinged but we don't want it to appear unresponsive because
  552. // the pinger will only ping every (PING_INTERVAL * 8) so we set timeOfLastMessage to
  553. // (now - pingAfterMilliseconds - 1) so it will be considered a "lazy node".
  554. ep->timeOfLastMessage =
  555. Time_currentTimeMilliseconds(ic->eventBase) - ic->pingAfterMilliseconds - 1;
  556. Log_info(ic->logger, "Added peer [%s] from beacon",
  557. Address_toString(&ep->addr, Message_getAlloc(msg))->bytes);
  558. // Ping them immediately, this prevents beacon tests from taking 1 second each
  559. sendPing(ep);
  560. return Error(NONE);
  561. }
  562. /**
  563. * Incoming message from someone we don't know, maybe someone responding to a beacon?
  564. * expects: [ struct LLAddress ][ content ]
  565. */
  566. static Iface_DEFUN handleUnexpectedIncoming(struct Message* msg,
  567. struct InterfaceController_Iface_pvt* ici)
  568. {
  569. struct Sockaddr* lladdr = (struct Sockaddr*) msg->msgbytes;
  570. Er_assert(Message_eshift(msg, -lladdr->addrLen));
  571. if (Message_getLength(msg) < CryptoHeader_SIZE) {
  572. return Error(RUNT);
  573. }
  574. Assert_true(!((uintptr_t)msg->msgbytes % 4) && "alignment fault");
  575. struct CryptoHeader* ch = (struct CryptoHeader*) msg->msgbytes;
  576. if (ch->nonce & Endian_bigEndianToHost32(~1)) {
  577. // This cuts down on processing and logger noise because any packet
  578. // which is not a setup packet will be summarily dropped.
  579. return Error(INVALID);
  580. }
  581. struct Peer* ep = mkEp(lladdr, ici, ch->publicKey, true, "incoming");
  582. ep->isIncomingConnection = true;
  583. if (!AddressCalc_validAddress(ep->addr.ip6.bytes)) {
  584. Allocator_free(ep->alloc);
  585. return Error(INVALID);
  586. }
  587. uint32_t nonce = Endian_bigEndianToHost32(ch->nonce);
  588. Er_assert(Message_epushAd(msg, &nonce, sizeof nonce));
  589. bool unexpected = true;
  590. Er_assert(Message_epushAd(msg, &unexpected, sizeof unexpected));
  591. return Iface_next(&ep->ciphertext, msg); // --> afterDecrypt
  592. }
  593. static Iface_DEFUN handleIncomingFromWire(struct Message* msg, struct Iface* addrIf)
  594. {
  595. struct InterfaceController_Iface_pvt* ici =
  596. Identity_containerOf(addrIf, struct InterfaceController_Iface_pvt, pub.addrIf);
  597. struct Sockaddr* lladdr = (struct Sockaddr*) msg->msgbytes;
  598. if (Message_getLength(msg) < Sockaddr_OVERHEAD || Message_getLength(msg) < lladdr->addrLen) {
  599. Log_debug(ici->ic->logger, "DROP runt");
  600. return Error(RUNT);
  601. }
  602. Assert_true(!((uintptr_t)msg->msgbytes % 4) && "alignment fault");
  603. Assert_true(!((uintptr_t)lladdr->addrLen % 4) && "alignment fault");
  604. // noisy
  605. if (Defined(Log_DEBUG) && false) {
  606. char* printedAddr = Hex_print(&lladdr[1], lladdr->addrLen - Sockaddr_OVERHEAD, Message_getAlloc(msg));
  607. Log_debug(ici->ic->logger, "Incoming message from [%s]", printedAddr);
  608. }
  609. if (lladdr->flags & Sockaddr_flags_BCAST) {
  610. return handleBeacon(msg, ici);
  611. }
  612. int epIndex = Map_EndpointsBySockaddr_indexForKey(&lladdr, &ici->peerMap);
  613. if (epIndex == -1) {
  614. return handleUnexpectedIncoming(msg, ici);
  615. }
  616. struct Peer* ep = Identity_check((struct Peer*) ici->peerMap.values[epIndex]);
  617. Er_assert(Message_eshift(msg, -lladdr->addrLen));
  618. // Once we know it to be an incompetible version, we quarentine it
  619. if (knownIncompatibleVersion(ep->addr.protocolVersion)) {
  620. if (Defined(Log_DEBUG)) {
  621. Log_debug(ici->ic->logger, "[%s] DROP msg from node with incompat version [%d] ",
  622. Address_toString(&ep->addr, Message_getAlloc(msg))->bytes, ep->addr.protocolVersion);
  623. }
  624. ep->state = InterfaceController_PeerState_INCOMPATIBLE;
  625. return Error(NONE);
  626. }
  627. CryptoAuth_resetIfTimeout(ep->caSession);
  628. uint32_t nonce = Endian_bigEndianToHost32( ((uint32_t*)msg->msgbytes)[0] );
  629. Er_assert(Message_epushAd(msg, &nonce, sizeof nonce));
  630. bool unexpected = false;
  631. Er_assert(Message_epushAd(msg, &unexpected, sizeof unexpected));
  632. return Iface_next(&ep->ciphertext, msg); // -> afterDecrypt
  633. }
  634. // Expects result of CryptoAuth decrypt
  635. // Additional data: [unexpected][nonce]
  636. static Iface_DEFUN afterDecrypt(struct Message* msg, struct Iface* plaintext)
  637. {
  638. bool unexpected = false;
  639. Er_assert(Message_epopAd(msg, &unexpected, sizeof unexpected));
  640. uint32_t nonce = 0;
  641. Er_assert(Message_epopAd(msg, &nonce, sizeof nonce));
  642. struct Peer* ep = Identity_containerOf(plaintext, struct Peer, plaintext);
  643. struct InterfaceController_Iface_pvt* ici = Identity_check(ep->ici);
  644. struct InterfaceController_pvt* ic = Identity_check(ici->ic);
  645. enum CryptoAuth_DecryptErr err = Er_assert(Message_epop32h(msg));
  646. if (err) {
  647. if (unexpected) {
  648. // We got an unexpected message and it did not validate, drop the allocator
  649. Allocator_free(ep->alloc);
  650. }
  651. return Error(AUTHENTICATION);
  652. } else if (unexpected) {
  653. // We got an unexpected message and it's valid, load the peer
  654. if (SwitchCore_addInterface(ic->switchCore, &ep->switchIf, ep->alloc, &ep->addr.path)) {
  655. Log_debug(ic->logger, "handleUnexpectedIncoming() SwitchCore out of space");
  656. Allocator_free(ep->alloc);
  657. return Error(UNHANDLED);
  658. }
  659. // TODO(cjd): when this becomes threaded, there will be a race here
  660. Assert_true(Map_EndpointsBySockaddr_indexForKey(&ep->lladdr, &ici->peerMap) == -1);
  661. int index = Map_EndpointsBySockaddr_put(&ep->lladdr, &ep, &ici->peerMap);
  662. Assert_true(index >= 0);
  663. ep->handle = ici->peerMap.handles[index];
  664. // We want the node to immedietly be pinged but we don't want it to appear unresponsive because
  665. // the pinger will only ping every (PING_INTERVAL * 8) so we set timeOfLastMessage to
  666. // (now - pingAfterMilliseconds - 1) so it will be considered a "lazy node".
  667. ep->timeOfLastMessage =
  668. Time_currentTimeMilliseconds(ic->eventBase) - ic->pingAfterMilliseconds - 1;
  669. Log_info(ic->logger, "Added peer [%s] from incoming message",
  670. Address_toString(&ep->addr, Message_getAlloc(msg))->bytes);
  671. }
  672. Kbps_accumulate(&ep->recvBw, Time_currentTimeMilliseconds(ic->eventBase), Message_getLength(msg));
  673. ep->bytesIn += Message_getLength(msg);
  674. int caState = CryptoAuth_getState(ep->caSession);
  675. if (caState != CryptoAuth_State_ESTABLISHED) {
  676. // prevent some kinds of nasty things which could be done with packet replay.
  677. // This is checking the message switch header and will drop it unless the label
  678. // directs it to *this* router.
  679. if (Message_getLength(msg) < 8 || msg->msgbytes[7] != 1) {
  680. Log_info(ic->logger, "DROP message because CA is not established.");
  681. return Error(UNHANDLED);
  682. } else {
  683. // When a "server" gets a new connection from a "client" the router doesn't
  684. // know about that client so if the client sends a packet to the server, the
  685. // server will be unable to handle it until the client has sent inter-router
  686. // communication to the server. Here we will ping the client so when the
  687. // server gets the ping response, it will insert the client into its table
  688. // and know its version.
  689. // prevent DoS by limiting the number of times this can be called per second
  690. // limit it to 7, this will affect innocent packets but it doesn't matter much
  691. // since this is mostly just an optimization and for keeping the tests happy.
  692. if ((ep->pingCount + 1) % 7) {
  693. sendPing(ep);
  694. }
  695. }
  696. } else {
  697. if (ep->state != caState) {
  698. sendPeer(0xffffffff, PFChan_Core_PEER, ep, 0xffff);
  699. }
  700. ep->timeOfLastMessage = Time_currentTimeMilliseconds(ic->eventBase);
  701. }
  702. ep->state = caState;
  703. Identity_check(ep);
  704. Assert_true(!(Message_getCapacity(msg) % 4));
  705. return Iface_next(&ep->switchIf, msg);
  706. }
  707. int InterfaceController_ifaceCount(struct InterfaceController* ifc)
  708. {
  709. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  710. return ic->icis->length;
  711. }
  712. struct InterfaceController_Iface* InterfaceController_getIface(struct InterfaceController* ifc,
  713. int ifNum)
  714. {
  715. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  716. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, ifNum);
  717. return (ici) ? &ici->pub : NULL;
  718. }
  719. struct InterfaceController_Iface* InterfaceController_newIface(struct InterfaceController* ifc,
  720. String* name,
  721. struct Allocator* alloc)
  722. {
  723. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  724. struct InterfaceController_Iface_pvt* ici =
  725. Allocator_calloc(alloc, sizeof(struct InterfaceController_Iface_pvt), 1);
  726. ici->pub.name = String_clone(name, alloc);
  727. ici->peerMap.allocator = alloc;
  728. ici->ic = ic;
  729. ici->alloc = alloc;
  730. ici->pub.addrIf.send = handleIncomingFromWire;
  731. ici->pub.ifNum = ArrayList_OfIfaces_add(ic->icis, ici);
  732. Identity_set(ici);
  733. return &ici->pub;
  734. }
  735. static void sendBeacon(struct InterfaceController_Iface_pvt* ici, struct Allocator* tempAlloc)
  736. {
  737. if (ici->pub.beaconState < InterfaceController_beaconState_newState_SEND) {
  738. Log_debug(ici->ic->logger, "sendBeacon(%s) -> beaconing disabled", ici->pub.name->bytes);
  739. return;
  740. }
  741. Log_debug(ici->ic->logger, "sendBeacon(%s)", ici->pub.name->bytes);
  742. struct Message* msg = Message_new(0, 128, tempAlloc);
  743. Er_assert(Message_epush(msg, &ici->ic->beacon, Headers_Beacon_SIZE));
  744. if (Defined(Log_DEBUG)) {
  745. char* content = Hex_print(msg->msgbytes, Message_getLength(msg), tempAlloc);
  746. Log_debug(ici->ic->logger, "SEND BEACON CONTENT[%s]", content);
  747. }
  748. struct Sockaddr sa = {
  749. .addrLen = Sockaddr_OVERHEAD,
  750. .flags = Sockaddr_flags_BCAST
  751. };
  752. Er_assert(Message_epush(msg, &sa, Sockaddr_OVERHEAD));
  753. Iface_send(&ici->pub.addrIf, msg);
  754. }
  755. static void beaconInterval(void* vInterfaceController)
  756. {
  757. struct InterfaceController_pvt* ic =
  758. Identity_check((struct InterfaceController_pvt*) vInterfaceController);
  759. struct Allocator* alloc = Allocator_child(ic->alloc);
  760. for (int i = 0; i < ic->icis->length; i++) {
  761. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  762. sendBeacon(ici, alloc);
  763. }
  764. Allocator_free(alloc);
  765. if (ic->beaconTimeoutAlloc) {
  766. Allocator_free(ic->beaconTimeoutAlloc);
  767. }
  768. ic->beaconTimeoutAlloc = Allocator_child(ic->alloc);
  769. Timeout_setTimeout(
  770. beaconInterval, ic, ic->beaconInterval, ic->eventBase, ic->beaconTimeoutAlloc);
  771. }
  772. int InterfaceController_beaconState(struct InterfaceController* ifc,
  773. int interfaceNumber,
  774. int newState)
  775. {
  776. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  777. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, interfaceNumber);
  778. if (!ici) {
  779. return InterfaceController_beaconState_NO_SUCH_IFACE;
  780. }
  781. char* val = NULL;
  782. switch (newState) {
  783. default: return InterfaceController_beaconState_INVALID_STATE;
  784. case InterfaceController_beaconState_newState_OFF: val = "OFF"; break;
  785. case InterfaceController_beaconState_newState_ACCEPT: val = "ACCEPT"; break;
  786. case InterfaceController_beaconState_newState_SEND: val = "SEND"; break;
  787. }
  788. Log_debug(ic->logger, "InterfaceController_beaconState(%s, %s)", ici->pub.name->bytes, val);
  789. ici->pub.beaconState = newState;
  790. if (newState == InterfaceController_beaconState_newState_SEND) {
  791. // Send out a beacon right away so we don't have to wait.
  792. struct Allocator* alloc = Allocator_child(ici->alloc);
  793. sendBeacon(ici, alloc);
  794. Allocator_free(alloc);
  795. }
  796. return 0;
  797. }
  798. int InterfaceController_bootstrapPeer(struct InterfaceController* ifc,
  799. int interfaceNumber,
  800. uint8_t* herPublicKey,
  801. const struct Sockaddr* lladdrParm,
  802. String* password,
  803. String* login,
  804. String* user)
  805. {
  806. struct InterfaceController_pvt* ic = Identity_check((struct InterfaceController_pvt*) ifc);
  807. Assert_true(herPublicKey);
  808. Assert_true(password);
  809. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, interfaceNumber);
  810. if (!ici) {
  811. return InterfaceController_bootstrapPeer_BAD_IFNUM;
  812. }
  813. Log_debug(ic->logger, "bootstrapPeer total [%u]", ici->peerMap.count);
  814. uint8_t ip6[16];
  815. AddressCalc_addressForPublicKey(ip6, herPublicKey);
  816. if (!AddressCalc_validAddress(ip6) || !Bits_memcmp(ic->ourPubKey, herPublicKey, 32)) {
  817. return InterfaceController_bootstrapPeer_BAD_KEY;
  818. }
  819. struct Peer* ep = mkEp(lladdrParm, ici, herPublicKey, false, user ? user->bytes : NULL);
  820. int index = Map_EndpointsBySockaddr_put(&ep->lladdr, &ep, &ici->peerMap);
  821. Assert_true(index >= 0);
  822. ep->handle = ici->peerMap.handles[index];
  823. CryptoAuth_setAuth(password, login, ep->caSession);
  824. if (SwitchCore_addInterface(ic->switchCore, &ep->switchIf, ep->alloc, &ep->addr.path)) {
  825. Log_debug(ic->logger, "bootstrapPeer() SwitchCore out of space");
  826. Allocator_free(ep->alloc);
  827. return InterfaceController_bootstrapPeer_OUT_OF_SPACE;
  828. }
  829. // We want the node to immedietly be pinged but we don't want it to appear unresponsive because
  830. // the pinger will only ping every (PING_INTERVAL * 8) so we set timeOfLastMessage to
  831. // (now - pingAfterMilliseconds - 1) so it will be considered a "lazy node".
  832. ep->timeOfLastMessage =
  833. Time_currentTimeMilliseconds(ic->eventBase) - ic->pingAfterMilliseconds - 1;
  834. if (Defined(Log_INFO)) {
  835. struct Allocator* tempAlloc = Allocator_child(ep->alloc);
  836. String* addrStr = Address_toString(&ep->addr, tempAlloc);
  837. Log_info(ic->logger, "Adding peer [%s] from bootstrapPeer()", addrStr->bytes);
  838. Allocator_free(tempAlloc);
  839. }
  840. // We can't just add the node directly to the routing table because we do not know
  841. // the version. We'll send it a switch ping and when it responds, we will know it's
  842. // key (if we don't already) and version number.
  843. sendPing(ep);
  844. return 0;
  845. }
  846. int InterfaceController_getPeerStats(struct InterfaceController* ifController,
  847. struct Allocator* alloc,
  848. struct InterfaceController_PeerStats** statsOut)
  849. {
  850. struct InterfaceController_pvt* ic =
  851. Identity_check((struct InterfaceController_pvt*) ifController);
  852. int count = 0;
  853. for (int i = 0; i < ic->icis->length; i++) {
  854. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, i);
  855. count += ici->peerMap.count;
  856. }
  857. struct InterfaceController_PeerStats* stats =
  858. Allocator_calloc(alloc, sizeof(struct InterfaceController_PeerStats), count);
  859. uint32_t now = Time_currentTimeMilliseconds(ic->eventBase);
  860. int xcount = 0;
  861. for (int j = 0; j < ic->icis->length; j++) {
  862. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, j);
  863. for (int i = 0; i < (int)ici->peerMap.count; i++) {
  864. struct Peer* peer = Identity_check((struct Peer*) ici->peerMap.values[i]);
  865. struct InterfaceController_PeerStats* s = &stats[xcount];
  866. xcount++;
  867. s->ifNum = ici->pub.ifNum;
  868. s->lladdr = Sockaddr_clone(peer->lladdr, alloc);
  869. Bits_memcpy(&s->addr, &peer->addr, sizeof(struct Address));
  870. s->bytesOut = peer->bytesOut;
  871. s->bytesIn = peer->bytesIn;
  872. s->timeOfLastMessage = peer->timeOfLastMessage;
  873. s->state = peer->state;
  874. s->isIncomingConnection = peer->isIncomingConnection;
  875. s->user = CryptoAuth_getName(peer->caSession, alloc);
  876. RTypes_CryptoStats_t stats;
  877. CryptoAuth_stats(peer->caSession, &stats);
  878. s->duplicates = stats.duplicate_packets;
  879. s->receivedOutOfRange = stats.received_unexpected;
  880. s->recvKbps = Kbps_accumulate(&peer->recvBw, now, Kbps_accumulate_NO_PACKET);
  881. s->sendKbps = Kbps_accumulate(&peer->sendBw, now, Kbps_accumulate_NO_PACKET);
  882. s->receivedPackets = peer->lastPackets;
  883. s->lostPackets = peer->lastDrops;
  884. }
  885. }
  886. Assert_true(xcount == count);
  887. *statsOut = stats;
  888. return count;
  889. }
  890. void InterfaceController_resetPeering(struct InterfaceController* ifController,
  891. uint8_t herPublicKey[32])
  892. {
  893. struct InterfaceController_pvt* ic =
  894. Identity_check((struct InterfaceController_pvt*) ifController);
  895. for (int j = 0; j < ic->icis->length; j++) {
  896. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, j);
  897. for (int i = 0; i < (int)ici->peerMap.count; i++) {
  898. struct Peer* peer = ici->peerMap.values[i];
  899. if (!herPublicKey || !Bits_memcmp(herPublicKey, peer->addr.key, 32)) {
  900. CryptoAuth_reset(peer->caSession);
  901. }
  902. }
  903. }
  904. }
  905. int InterfaceController_disconnectPeer(struct InterfaceController* ifController,
  906. uint8_t herPublicKey[32])
  907. {
  908. struct InterfaceController_pvt* ic =
  909. Identity_check((struct InterfaceController_pvt*) ifController);
  910. int count = 0;
  911. for (int j = 0; j < ic->icis->length; j++) {
  912. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, j);
  913. for (int i = 0; i < (int)ici->peerMap.count; i++) {
  914. struct Peer* peer = ici->peerMap.values[i];
  915. if (!Bits_memcmp(herPublicKey, peer->addr.key, 32)) {
  916. Allocator_free(peer->alloc);
  917. count++;
  918. }
  919. }
  920. }
  921. return count;
  922. }
  923. static Iface_DEFUN incomingFromEventEmitterIf(struct Message* msg, struct Iface* eventEmitterIf)
  924. {
  925. struct InterfaceController_pvt* ic =
  926. Identity_containerOf(eventEmitterIf, struct InterfaceController_pvt, eventEmitterIf);
  927. uint32_t peers = Er_assert(Message_epop32be(msg));
  928. Assert_true(peers == PFChan_Pathfinder_PEERS);
  929. uint32_t pathfinderId = Er_assert(Message_epop32be(msg));
  930. Assert_true(!Message_getLength(msg));
  931. for (int j = 0; j < ic->icis->length; j++) {
  932. struct InterfaceController_Iface_pvt* ici = ArrayList_OfIfaces_get(ic->icis, j);
  933. for (int i = 0; i < (int)ici->peerMap.count; i++) {
  934. struct Peer* peer = Identity_check((struct Peer*) ici->peerMap.values[i]);
  935. if (peer->state != InterfaceController_PeerState_ESTABLISHED) { continue; }
  936. sendPeer(pathfinderId, PFChan_Core_PEER, peer, 0xffff);
  937. }
  938. }
  939. return Error(NONE);
  940. }
  941. struct InterfaceController* InterfaceController_new(struct CryptoAuth* ca,
  942. struct SwitchCore* switchCore,
  943. struct Log* logger,
  944. struct EventBase* eventBase,
  945. struct SwitchPinger* switchPinger,
  946. struct Random* rand,
  947. struct Allocator* allocator,
  948. struct EventEmitter* ee)
  949. {
  950. struct Allocator* alloc = Allocator_child(allocator);
  951. struct InterfaceController_pvt* out =
  952. Allocator_calloc(alloc, sizeof(struct InterfaceController_pvt), 1);
  953. Bits_memcpy(out, (&(struct InterfaceController_pvt) {
  954. .alloc = alloc,
  955. .ca = ca,
  956. .rand = rand,
  957. .switchCore = switchCore,
  958. .logger = logger,
  959. .eventBase = eventBase,
  960. .switchPinger = switchPinger,
  961. .unresponsiveAfterMilliseconds = UNRESPONSIVE_AFTER_MILLISECONDS,
  962. .pingAfterMilliseconds = PING_AFTER_MILLISECONDS,
  963. .timeoutMilliseconds = TIMEOUT_MILLISECONDS,
  964. .forgetAfterMilliseconds = FORGET_AFTER_MILLISECONDS,
  965. .beaconInterval = BEACON_INTERVAL,
  966. .linkStateInterval = Timeout_setInterval(
  967. linkState,
  968. out,
  969. LINKSTATE_UPDATE_INTERVAL,
  970. eventBase,
  971. alloc),
  972. .pingInterval = (switchPinger)
  973. ? Timeout_setInterval(pingCycle,
  974. out,
  975. PING_INTERVAL_MILLISECONDS,
  976. eventBase,
  977. alloc)
  978. : NULL
  979. }), sizeof(struct InterfaceController_pvt));
  980. Identity_set(out);
  981. out->icis = ArrayList_OfIfaces_new(alloc);
  982. out->eventEmitterIf.send = incomingFromEventEmitterIf;
  983. EventEmitter_regCore(ee, &out->eventEmitterIf, PFChan_Pathfinder_PEERS);
  984. // Add the beaconing password.
  985. Random_base32(rand, out->beacon.password, Headers_Beacon_PASSWORD_LEN);
  986. String strPass = { .bytes=(char*)out->beacon.password, .len=Headers_Beacon_PASSWORD_LEN };
  987. int ret = CryptoAuth_addUser(&strPass, String_CONST("Local Peers"), ca);
  988. if (ret) {
  989. Log_warn(logger, "CryptoAuth_addUser() returned [%d]", ret);
  990. }
  991. CryptoAuth_getPubKey(ca, out->ourPubKey);
  992. Bits_memcpy(out->beacon.publicKey, out->ourPubKey, 32);
  993. out->beacon.version_be = Endian_hostToBigEndian32(Version_CURRENT_PROTOCOL);
  994. Timeout_setTimeout(beaconInterval, out, BEACON_INTERVAL, eventBase, alloc);
  995. return &out->pub;
  996. }