InterfaceController.c 48 KB

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