root.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. /*
  14. * This is a high-throughput minimal root server. It implements only
  15. * those functions of a ZT node that a root must perform and does so
  16. * using highly efficient multithreaded I/O code. It's only been
  17. * thoroughly tested on Linux but should also run on BSDs.
  18. *
  19. * Root configuration file format (JSON):
  20. *
  21. * {
  22. * "name": Name of this root for documentation/UI purposes (string)
  23. * "port": UDP port (int)
  24. * "httpPort": Local HTTP port for basic stats (int)
  25. * "relayMaxHops": Max hops (up to 7)
  26. * "statsRoot": If present, path to periodically save stats files (string)
  27. * "siblings": [
  28. * {
  29. * "name": Sibling name for UI/documentation purposes (string)
  30. * "id": Full public identity of subling (string)
  31. * "ip": IP address of sibling (string)
  32. * "port": port of subling (for ZeroTier UDP) (int)
  33. * }, ...
  34. * ]
  35. * }
  36. *
  37. * The only required field is port. If statsRoot is present then files
  38. * are periodically written there containing the root's current state.
  39. * It should be a memory filesystem like /dev/shm on Linux as these
  40. * files are large and rewritten frequently and do not need to be
  41. * persisted.
  42. *
  43. * Siblings are other root servers that should receive packets to peers
  44. * that we can't find. This can occur due to e.g. network topology
  45. * hiccups, IP blockages, etc. Siblings are used in the order in which
  46. * they appear with the first alive sibling being used.
  47. */
  48. #include <Constants.hpp>
  49. #include <stdio.h>
  50. #include <stdlib.h>
  51. #include <unistd.h>
  52. #include <string.h>
  53. #include <fcntl.h>
  54. #include <signal.h>
  55. #include <errno.h>
  56. #include <sys/stat.h>
  57. #include <sys/types.h>
  58. #include <sys/socket.h>
  59. #include <sys/select.h>
  60. #include <sys/time.h>
  61. #include <sys/un.h>
  62. #include <sys/ioctl.h>
  63. #include <arpa/inet.h>
  64. #include <netinet/in.h>
  65. #include <netinet/ip.h>
  66. #include <netinet/ip6.h>
  67. #include <netinet/tcp.h>
  68. #include <netinet/udp.h>
  69. #include <json.hpp>
  70. #include <httplib.h>
  71. #include <Packet.hpp>
  72. #include <Utils.hpp>
  73. #include <Address.hpp>
  74. #include <Identity.hpp>
  75. #include <InetAddress.hpp>
  76. #include <Mutex.hpp>
  77. #include <SharedPtr.hpp>
  78. #include <MulticastGroup.hpp>
  79. #include <CertificateOfMembership.hpp>
  80. #include <OSUtils.hpp>
  81. #include <Meter.hpp>
  82. #include <string>
  83. #include <thread>
  84. #include <map>
  85. #include <set>
  86. #include <vector>
  87. #include <iostream>
  88. #include <unordered_map>
  89. #include <unordered_set>
  90. #include <vector>
  91. #include <atomic>
  92. #include <mutex>
  93. #include <sstream>
  94. using namespace ZeroTier;
  95. using json = nlohmann::json;
  96. #ifdef MSG_DONTWAIT
  97. #define SENDTO_FLAGS MSG_DONTWAIT
  98. #else
  99. #define SENDTO_FLAGS 0
  100. #endif
  101. //////////////////////////////////////////////////////////////////////////////
  102. //////////////////////////////////////////////////////////////////////////////
  103. // Hashers for std::unordered_map
  104. struct IdentityHasher { ZT_ALWAYS_INLINE std::size_t operator()(const Identity &id) const { return (std::size_t)id.hashCode(); } };
  105. struct AddressHasher { ZT_ALWAYS_INLINE std::size_t operator()(const Address &a) const { return (std::size_t)a.toInt(); } };
  106. struct InetAddressHasher { ZT_ALWAYS_INLINE std::size_t operator()(const InetAddress &ip) const { return (std::size_t)ip.hashCode(); } };
  107. struct MulticastGroupHasher { ZT_ALWAYS_INLINE std::size_t operator()(const MulticastGroup &mg) const { return (std::size_t)mg.hashCode(); } };
  108. // An ordered tuple key representing an introduction of one peer to another
  109. struct RendezvousKey
  110. {
  111. RendezvousKey(const Address &aa,const Address &bb)
  112. {
  113. if (aa > bb) {
  114. a = aa;
  115. b = bb;
  116. } else {
  117. a = bb;
  118. b = aa;
  119. }
  120. }
  121. Address a,b;
  122. ZT_ALWAYS_INLINE bool operator==(const RendezvousKey &k) const { return ((a == k.a)&&(b == k.b)); }
  123. ZT_ALWAYS_INLINE bool operator!=(const RendezvousKey &k) const { return ((a != k.a)||(b != k.b)); }
  124. struct Hasher { ZT_ALWAYS_INLINE std::size_t operator()(const RendezvousKey &k) const { return (std::size_t)(k.a.toInt() ^ k.b.toInt()); } };
  125. };
  126. /**
  127. * RootPeer is a normal peer known to this root
  128. *
  129. * This can also be a sibling root, which is itself a peer. Sibling roots
  130. * are sent HELLO while for other peers we only listen for HELLO.
  131. */
  132. struct RootPeer
  133. {
  134. ZT_ALWAYS_INLINE RootPeer() : lastSend(0),lastReceive(0),lastSync(0),lastEcho(0),lastHello(0),vMajor(-1),vMinor(-1),vRev(-1),sibling(false) {}
  135. ZT_ALWAYS_INLINE ~RootPeer() { Utils::burn(key,sizeof(key)); }
  136. Identity id; // Identity
  137. uint8_t key[32]; // Shared secret key
  138. InetAddress ip4,ip6; // IPv4 and IPv6 addresses
  139. int64_t lastSend; // Time of last send (any packet)
  140. int64_t lastReceive; // Time of last receive (any packet)
  141. int64_t lastSync; // Time of last data synchronization with LF or other root state backend (currently unused)
  142. int64_t lastEcho; // Time of last received ECHO
  143. int64_t lastHello; // Time of last received HELLO
  144. int vMajor,vMinor,vRev; // Peer version or -1,-1,-1 if unknown
  145. bool sibling; // If true, this is a sibling root that will get forwards we don't know where to send
  146. std::mutex lock;
  147. AtomicCounter __refCount;
  148. };
  149. static int64_t startTime;
  150. static std::vector<int> ports;
  151. static int relayMaxHops = 0;
  152. static Identity self;
  153. static std::atomic_bool run;
  154. static json config;
  155. static std::string statsRoot;
  156. static Meter inputRate;
  157. static Meter outputRate;
  158. static Meter forwardRate;
  159. static Meter siblingForwardRate;
  160. static Meter discardedForwardRate;
  161. static std::vector< SharedPtr<RootPeer> > siblings;
  162. static std::unordered_map< uint64_t,std::unordered_map< MulticastGroup,std::unordered_map< Address,int64_t,AddressHasher >,MulticastGroupHasher > > multicastSubscriptions;
  163. static std::unordered_map< Identity,SharedPtr<RootPeer>,IdentityHasher > peersByIdentity;
  164. static std::unordered_map< Address,std::set< SharedPtr<RootPeer> >,AddressHasher > peersByVirtAddr;
  165. static std::unordered_map< InetAddress,std::set< SharedPtr<RootPeer> >,InetAddressHasher > peersByPhysAddr;
  166. static std::unordered_map< RendezvousKey,int64_t,RendezvousKey::Hasher > lastRendezvous;
  167. static std::mutex siblings_l;
  168. static std::mutex multicastSubscriptions_l;
  169. static std::mutex peersByIdentity_l;
  170. static std::mutex peersByVirtAddr_l;
  171. static std::mutex peersByPhysAddr_l;
  172. static std::mutex lastRendezvous_l;
  173. //////////////////////////////////////////////////////////////////////////////
  174. //////////////////////////////////////////////////////////////////////////////
  175. static void handlePacket(const int v4s,const int v6s,const InetAddress *const ip,Packet &pkt)
  176. {
  177. char ipstr[128],ipstr2[128],astr[32],astr2[32],tmpstr[256];
  178. const bool fragment = pkt[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR;
  179. const Address source(pkt.source());
  180. const Address dest(pkt.destination());
  181. const int64_t now = OSUtils::now();
  182. inputRate.log(now,pkt.size());
  183. if ((!fragment)&&(!pkt.fragmented())&&(dest == self.address())) {
  184. SharedPtr<RootPeer> peer;
  185. // If this is an un-encrypted HELLO, either learn a new peer or verify
  186. // that this is a peer we already know.
  187. if ((pkt.cipher() == ZT_PROTO_CIPHER_SUITE__POLY1305_NONE)&&(pkt.verb() == Packet::VERB_HELLO)) {
  188. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  189. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  190. Identity id;
  191. if (id.deserialize(pkt,ZT_PROTO_VERB_HELLO_IDX_IDENTITY)) {
  192. {
  193. auto pById = peersByIdentity.find(id);
  194. if (pById != peersByIdentity.end()) {
  195. peer = pById->second;
  196. //printf("%s has %s (known (1))" ZT_EOL_S,ip->toString(ipstr),source().toString(astr));
  197. }
  198. }
  199. if (peer) {
  200. if (!pkt.dearmor(peer->key)) {
  201. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  202. return;
  203. }
  204. } else {
  205. peer.set(new RootPeer);
  206. if (self.agree(id,peer->key)) {
  207. if (pkt.dearmor(peer->key)) {
  208. if (!pkt.uncompress()) {
  209. printf("%s HELLO rejected: decompression failed" ZT_EOL_S,ip->toString(ipstr));
  210. return;
  211. }
  212. peer->id = id;
  213. peer->lastReceive = now;
  214. peersByIdentity.emplace(id,peer);
  215. peersByVirtAddr[id.address()].emplace(peer);
  216. } else {
  217. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  218. return;
  219. }
  220. } else {
  221. printf("%s HELLO rejected: key agreement failed" ZT_EOL_S,ip->toString(ipstr));
  222. return;
  223. }
  224. }
  225. }
  226. }
  227. // If it wasn't a HELLO, check to see if any known identities for the sender's
  228. // short ZT address successfully decrypt the packet.
  229. if (!peer) {
  230. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  231. auto peers = peersByVirtAddr.find(source);
  232. if (peers != peersByVirtAddr.end()) {
  233. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  234. if (pkt.dearmor((*p)->key)) {
  235. if (!pkt.uncompress()) {
  236. printf("%s packet rejected: decompression failed" ZT_EOL_S,ip->toString(ipstr));
  237. return;
  238. }
  239. peer = (*p);
  240. //printf("%s has %s (known (2))" ZT_EOL_S,ip->toString(ipstr),source().toString(astr));
  241. break;
  242. }
  243. }
  244. }
  245. }
  246. // If we found the peer, update IP and/or time and handle certain key packet types that the
  247. // root must concern itself with.
  248. if (peer) {
  249. std::lock_guard<std::mutex> pl(peer->lock);
  250. InetAddress *const peerIp = ip->isV4() ? &(peer->ip4) : &(peer->ip6);
  251. if (*peerIp != ip) {
  252. std::lock_guard<std::mutex> pbp_l(peersByPhysAddr_l);
  253. if (*peerIp) {
  254. auto prev = peersByPhysAddr.find(*peerIp);
  255. if (prev != peersByPhysAddr.end()) {
  256. prev->second.erase(peer);
  257. if (prev->second.empty())
  258. peersByPhysAddr.erase(prev);
  259. }
  260. }
  261. *peerIp = ip;
  262. peersByPhysAddr[ip].emplace(peer);
  263. }
  264. const int64_t now = OSUtils::now();
  265. peer->lastReceive = now;
  266. switch(pkt.verb()) {
  267. case Packet::VERB_HELLO:
  268. try {
  269. if ((now - peer->lastHello) > 1000) {
  270. peer->lastHello = now;
  271. peer->vMajor = (int)pkt[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  272. peer->vMinor = (int)pkt[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  273. peer->vRev = (int)pkt.template at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  274. const uint64_t origId = pkt.packetId();
  275. const uint64_t ts = pkt.template at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  276. pkt.reset(source,self.address(),Packet::VERB_OK);
  277. pkt.append((uint8_t)Packet::VERB_HELLO);
  278. pkt.append(origId);
  279. pkt.append(ts);
  280. pkt.append((uint8_t)ZT_PROTO_VERSION);
  281. pkt.append((uint8_t)0);
  282. pkt.append((uint8_t)0);
  283. pkt.append((uint16_t)0);
  284. ip->serialize(pkt);
  285. pkt.armor(peer->key,true);
  286. sendto(ip->isV4() ? v4s : v6s,pkt.data(),pkt.size(),SENDTO_FLAGS,(const struct sockaddr *)ip,(socklen_t)((ip->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  287. outputRate.log(now,pkt.size());
  288. peer->lastSend = now;
  289. }
  290. } catch ( ... ) {
  291. printf("* unexpected exception handling HELLO from %s" ZT_EOL_S,ip->toString(ipstr));
  292. }
  293. break;
  294. case Packet::VERB_ECHO:
  295. try {
  296. if ((now - peer->lastEcho) > 1000) {
  297. peer->lastEcho = now;
  298. Packet outp(source,self.address(),Packet::VERB_OK);
  299. outp.append((uint8_t)Packet::VERB_ECHO);
  300. outp.append(pkt.packetId());
  301. outp.append(((const uint8_t *)pkt.data()) + ZT_PACKET_IDX_PAYLOAD,pkt.size() - ZT_PACKET_IDX_PAYLOAD);
  302. outp.compress();
  303. outp.armor(peer->key,true);
  304. sendto(ip->isV4() ? v4s : v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)ip,(socklen_t)((ip->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  305. outputRate.log(now,outp.size());
  306. peer->lastSend = now;
  307. }
  308. } catch ( ... ) {
  309. printf("* unexpected exception handling ECHO from %s" ZT_EOL_S,ip->toString(ipstr));
  310. }
  311. case Packet::VERB_WHOIS:
  312. try {
  313. std::vector< SharedPtr<RootPeer> > results;
  314. {
  315. std::lock_guard<std::mutex> l(peersByVirtAddr_l);
  316. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;(ptr+ZT_ADDRESS_LENGTH)<=pkt.size();ptr+=ZT_ADDRESS_LENGTH) {
  317. auto peers = peersByVirtAddr.find(Address(pkt.field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH));
  318. if (peers != peersByVirtAddr.end()) {
  319. for(auto p=peers->second.begin();p!=peers->second.end();++p)
  320. results.push_back(*p);
  321. }
  322. }
  323. }
  324. if (!results.empty()) {
  325. const uint64_t origId = pkt.packetId();
  326. pkt.reset(source,self.address(),Packet::VERB_OK);
  327. pkt.append((uint8_t)Packet::VERB_WHOIS);
  328. pkt.append(origId);
  329. for(auto p=results.begin();p!=results.end();++p)
  330. (*p)->id.serialize(pkt,false);
  331. pkt.armor(peer->key,true);
  332. sendto(ip->isV4() ? v4s : v6s,pkt.data(),pkt.size(),SENDTO_FLAGS,(const struct sockaddr *)ip,(socklen_t)((ip->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  333. outputRate.log(now,pkt.size());
  334. peer->lastSend = now;
  335. }
  336. } catch ( ... ) {
  337. printf("* unexpected exception handling ECHO from %s" ZT_EOL_S,ip->toString(ipstr));
  338. }
  339. case Packet::VERB_MULTICAST_LIKE:
  340. try {
  341. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  342. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;(ptr+18)<=pkt.size();ptr+=18) {
  343. const uint64_t nwid = pkt.template at<uint64_t>(ptr);
  344. const MulticastGroup mg(MAC(pkt.field(ptr + 8,6),6),pkt.template at<uint32_t>(ptr + 14));
  345. multicastSubscriptions[nwid][mg][source] = now;
  346. //printf("%s %s subscribes to %s/%.8lx on network %.16llx" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),mg.mac().toString(tmpstr),(unsigned long)mg.adi(),(unsigned long long)nwid);
  347. }
  348. } catch ( ... ) {
  349. printf("* unexpected exception handling MULTICAST_LIKE from %s" ZT_EOL_S,ip->toString(ipstr));
  350. }
  351. break;
  352. case Packet::VERB_MULTICAST_GATHER:
  353. try {
  354. const uint64_t nwid = pkt.template at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  355. //const unsigned int flags = pkt[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  356. const MulticastGroup mg(MAC(pkt.field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC,6),6),pkt.template at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  357. unsigned int gatherLimit = pkt.template at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  358. if (gatherLimit > 255)
  359. gatherLimit = 255;
  360. const uint64_t origId = pkt.packetId();
  361. pkt.reset(source,self.address(),Packet::VERB_OK);
  362. pkt.append((uint8_t)Packet::VERB_MULTICAST_GATHER);
  363. pkt.append(origId);
  364. pkt.append(nwid);
  365. mg.mac().appendTo(pkt);
  366. pkt.append((uint32_t)mg.adi());
  367. {
  368. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  369. auto forNet = multicastSubscriptions.find(nwid);
  370. if (forNet != multicastSubscriptions.end()) {
  371. auto forGroup = forNet->second.find(mg);
  372. if (forGroup != forNet->second.end()) {
  373. pkt.append((uint32_t)forGroup->second.size());
  374. const unsigned int countAt = pkt.size();
  375. pkt.addSize(2);
  376. unsigned int l = 0;
  377. for(auto g=forGroup->second.begin();((l<gatherLimit)&&(g!=forGroup->second.end()));++g) {
  378. if (g->first != source) {
  379. ++l;
  380. g->first.appendTo(pkt);
  381. }
  382. }
  383. if (l > 0) {
  384. pkt.setAt<uint16_t>(countAt,(uint16_t)l);
  385. pkt.armor(peer->key,true);
  386. sendto(ip->isV4() ? v4s : v6s,pkt.data(),pkt.size(),SENDTO_FLAGS,(const struct sockaddr *)ip,(socklen_t)(ip->isV4() ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  387. outputRate.log(now,pkt.size());
  388. peer->lastSend = now;
  389. //printf("%s %s gathered %u subscribers to %s/%.8lx on network %.16llx" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),l,mg.mac().toString(tmpstr),(unsigned long)mg.adi(),(unsigned long long)nwid);
  390. }
  391. }
  392. }
  393. }
  394. } catch ( ... ) {
  395. printf("* unexpected exception handling MULTICAST_GATHER from %s" ZT_EOL_S,ip->toString(ipstr));
  396. }
  397. break;
  398. default:
  399. break;
  400. }
  401. return;
  402. }
  403. }
  404. // If we made it here, we are forwarding this packet to someone else and also possibly
  405. // sending a RENDEZVOUS message.
  406. bool introduce = false;
  407. if (fragment) {
  408. if ((int)reinterpret_cast<Packet::Fragment *>(&pkt)->incrementHops() > relayMaxHops) {
  409. //printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  410. discardedForwardRate.log(now,pkt.size());
  411. return;
  412. }
  413. } else {
  414. if ((int)pkt.incrementHops() > relayMaxHops) {
  415. //printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  416. discardedForwardRate.log(now,pkt.size());
  417. return;
  418. }
  419. RendezvousKey rk(source,dest);
  420. std::lock_guard<std::mutex> l(lastRendezvous_l);
  421. int64_t &lr = lastRendezvous[rk];
  422. if ((now - lr) >= 45000) {
  423. lr = now;
  424. introduce = true;
  425. }
  426. }
  427. std::vector< std::pair< InetAddress *,SharedPtr<RootPeer> > > toAddrs;
  428. {
  429. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  430. auto peers = peersByVirtAddr.find(dest);
  431. if (peers != peersByVirtAddr.end()) {
  432. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  433. if ((*p)->ip4) {
  434. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*p)->ip4),*p));
  435. } else if ((*p)->ip6) {
  436. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*p)->ip6),*p));
  437. }
  438. }
  439. }
  440. }
  441. if (toAddrs.empty()) {
  442. std::lock_guard<std::mutex> sib_l(siblings_l);
  443. for(auto s=siblings.begin();s!=siblings.end();++s) {
  444. if (((now - (*s)->lastReceive) < (ZT_PEER_PING_PERIOD * 2))&&((*s)->sibling)) {
  445. if ((*s)->ip4) {
  446. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*s)->ip4),*s));
  447. } else if ((*s)->ip6) {
  448. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*s)->ip6),*s));
  449. }
  450. }
  451. }
  452. }
  453. if (toAddrs.empty()) {
  454. discardedForwardRate.log(now,pkt.size());
  455. return;
  456. }
  457. if (introduce) {
  458. std::lock_guard<std::mutex> l(peersByVirtAddr_l);
  459. auto sources = peersByVirtAddr.find(source);
  460. if (sources != peersByVirtAddr.end()) {
  461. for(auto a=sources->second.begin();a!=sources->second.end();++a) {
  462. for(auto b=toAddrs.begin();b!=toAddrs.end();++b) {
  463. if (((*a)->ip6)&&(b->second->ip6)) {
  464. //printf("* introducing %s(%s) to %s(%s)" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),b->second->ip6.toString(ipstr2),dest.toString(astr2));
  465. // Introduce source to destination (V6)
  466. Packet outp(source,self.address(),Packet::VERB_RENDEZVOUS);
  467. outp.append((uint8_t)0);
  468. dest.appendTo(outp);
  469. outp.append((uint16_t)b->second->ip6.port());
  470. outp.append((uint8_t)16);
  471. outp.append((const uint8_t *)b->second->ip6.rawIpData(),16);
  472. outp.armor((*a)->key,true);
  473. sendto(v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&((*a)->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  474. outputRate.log(now,outp.size());
  475. (*a)->lastSend = now;
  476. // Introduce destination to source (V6)
  477. outp.reset(dest,self.address(),Packet::VERB_RENDEZVOUS);
  478. outp.append((uint8_t)0);
  479. source.appendTo(outp);
  480. outp.append((uint16_t)ip->port());
  481. outp.append((uint8_t)16);
  482. outp.append((const uint8_t *)ip->rawIpData(),16);
  483. outp.armor(b->second->key,true);
  484. sendto(v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&(b->second->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  485. outputRate.log(now,outp.size());
  486. b->second->lastSend = now;
  487. }
  488. if (((*a)->ip4)&&(b->second->ip4)) {
  489. //printf("* introducing %s(%s) to %s(%s)" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),b->second->ip4.toString(ipstr2),dest.toString(astr2));
  490. // Introduce source to destination (V4)
  491. Packet outp(source,self.address(),Packet::VERB_RENDEZVOUS);
  492. outp.append((uint8_t)0);
  493. dest.appendTo(outp);
  494. outp.append((uint16_t)b->second->ip4.port());
  495. outp.append((uint8_t)4);
  496. outp.append((const uint8_t *)b->second->ip4.rawIpData(),4);
  497. outp.armor((*a)->key,true);
  498. sendto(v4s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&((*a)->ip4),(socklen_t)sizeof(struct sockaddr_in));
  499. outputRate.log(now,outp.size());
  500. (*a)->lastSend = now;
  501. // Introduce destination to source (V4)
  502. outp.reset(dest,self.address(),Packet::VERB_RENDEZVOUS);
  503. outp.append((uint8_t)0);
  504. source.appendTo(outp);
  505. outp.append((uint16_t)ip->port());
  506. outp.append((uint8_t)4);
  507. outp.append((const uint8_t *)ip->rawIpData(),4);
  508. outp.armor(b->second->key,true);
  509. sendto(v4s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&(b->second->ip4),(socklen_t)sizeof(struct sockaddr_in));
  510. outputRate.log(now,outp.size());
  511. b->second->lastSend = now;
  512. }
  513. }
  514. }
  515. }
  516. }
  517. for(auto i=toAddrs.begin();i!=toAddrs.end();++i) {
  518. //printf("%s -> %s for %s -> %s (%u bytes)" ZT_EOL_S,ip->toString(ipstr),i->first->toString(ipstr2),source.toString(astr),dest.toString(astr2),pkt.size());
  519. if (sendto(i->first->isV4() ? v4s : v6s,pkt.data(),pkt.size(),SENDTO_FLAGS,(const struct sockaddr *)i->first,(socklen_t)(i->first->isV4() ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) > 0) {
  520. outputRate.log(now,pkt.size());
  521. forwardRate.log(now,pkt.size());
  522. if (i->second->sibling)
  523. siblingForwardRate.log(now,pkt.size());
  524. i->second->lastSend = now;
  525. }
  526. }
  527. }
  528. //////////////////////////////////////////////////////////////////////////////
  529. //////////////////////////////////////////////////////////////////////////////
  530. static int bindSocket(struct sockaddr *const bindAddr)
  531. {
  532. const int s = socket(bindAddr->sa_family,SOCK_DGRAM,0);
  533. if (s < 0) {
  534. close(s);
  535. return -1;
  536. }
  537. int f = 1048576;
  538. while (f > 16384) {
  539. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&f,sizeof(f)) == 0)
  540. break;
  541. f -= 16384;
  542. }
  543. f = 1048576;
  544. while (f > 16384) {
  545. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&f,sizeof(f)) == 0)
  546. break;
  547. f -= 16384;
  548. }
  549. if (bindAddr->sa_family == AF_INET6) {
  550. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  551. #ifdef IPV6_MTU_DISCOVER
  552. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  553. #endif
  554. #ifdef IPV6_DONTFRAG
  555. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,&f,sizeof(f));
  556. #endif
  557. }
  558. #ifdef IP_DONTFRAG
  559. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  560. #endif
  561. #ifdef IP_MTU_DISCOVER
  562. f = IP_PMTUDISC_DONT; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  563. #endif
  564. #ifdef SO_NO_CHECK
  565. if (bindAddr->sa_family == AF_INET) {
  566. f = 1; setsockopt(s,SOL_SOCKET,SO_NO_CHECK,(void *)&f,sizeof(f));
  567. }
  568. #endif
  569. #if defined(SO_REUSEPORT)
  570. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEPORT,(void *)&f,sizeof(f));
  571. #endif
  572. #ifndef __LINUX__ // linux wants just SO_REUSEPORT
  573. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  574. #endif
  575. if (bind(s,bindAddr,(bindAddr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
  576. close(s);
  577. //printf("%s\n",strerror(errno));
  578. return -1;
  579. }
  580. return s;
  581. }
  582. static void shutdownSigHandler(int sig) { run = false; }
  583. int main(int argc,char **argv)
  584. {
  585. signal(SIGTERM,shutdownSigHandler);
  586. signal(SIGINT,shutdownSigHandler);
  587. signal(SIGQUIT,shutdownSigHandler);
  588. signal(SIGPIPE,SIG_IGN);
  589. signal(SIGUSR1,SIG_IGN);
  590. signal(SIGUSR2,SIG_IGN);
  591. signal(SIGCHLD,SIG_IGN);
  592. startTime = OSUtils::now();
  593. if (argc < 3) {
  594. printf("Usage: zerotier-root <identity.secret> <config path>" ZT_EOL_S);
  595. return 1;
  596. }
  597. {
  598. std::string myIdStr;
  599. if (!OSUtils::readFile(argv[1],myIdStr)) {
  600. printf("FATAL: cannot read identity.secret at %s" ZT_EOL_S,argv[1]);
  601. return 1;
  602. }
  603. if (!self.fromString(myIdStr.c_str())) {
  604. printf("FATAL: cannot read identity.secret at %s (invalid identity)" ZT_EOL_S,argv[1]);
  605. return 1;
  606. }
  607. if (!self.hasPrivate()) {
  608. printf("FATAL: cannot read identity.secret at %s (missing secret key)" ZT_EOL_S,argv[1]);
  609. return 1;
  610. }
  611. }
  612. {
  613. std::string configStr;
  614. if (!OSUtils::readFile(argv[2],configStr)) {
  615. printf("FATAL: cannot read config file at %s" ZT_EOL_S,argv[2]);
  616. return 1;
  617. }
  618. try {
  619. config = json::parse(configStr);
  620. } catch (std::exception &exc) {
  621. printf("FATAL: config file at %s invalid: %s" ZT_EOL_S,argv[2],exc.what());
  622. return 1;
  623. } catch ( ... ) {
  624. printf("FATAL: config file at %s invalid: unknown exception" ZT_EOL_S,argv[2]);
  625. return 1;
  626. }
  627. if (!config.is_object()) {
  628. printf("FATAL: config file at %s invalid: does not contain a JSON object" ZT_EOL_S,argv[2]);
  629. return 1;
  630. }
  631. }
  632. try {
  633. auto jport = config["port"];
  634. if (jport.is_array()) {
  635. for(long i=0;i<(long)jport.size();++i) {
  636. int port = jport[i];
  637. if ((port <= 0)||(port > 65535)) {
  638. printf("FATAL: invalid port in config file %d" ZT_EOL_S,port);
  639. return 1;
  640. }
  641. ports.push_back(port);
  642. }
  643. } else {
  644. int port = jport;
  645. if ((port <= 0)||(port > 65535)) {
  646. printf("FATAL: invalid port in config file %d" ZT_EOL_S,port);
  647. return 1;
  648. }
  649. ports.push_back(port);
  650. }
  651. } catch ( ... ) {}
  652. if (ports.empty())
  653. ports.push_back(ZT_DEFAULT_PORT);
  654. std::sort(ports.begin(),ports.end());
  655. int httpPort = ZT_DEFAULT_PORT;
  656. try {
  657. httpPort = config["httpPort"];
  658. if ((httpPort <= 0)||(httpPort > 65535)) {
  659. printf("FATAL: invalid HTTP port in config file %d" ZT_EOL_S,httpPort);
  660. return 1;
  661. }
  662. } catch ( ... ) {
  663. httpPort = ZT_DEFAULT_PORT;
  664. }
  665. try {
  666. statsRoot = config["statsRoot"];
  667. while ((statsRoot.length() > 0)&&(statsRoot[statsRoot.length()-1] == ZT_PATH_SEPARATOR))
  668. statsRoot = statsRoot.substr(0,statsRoot.length()-1);
  669. if (statsRoot.length() > 0)
  670. OSUtils::mkdir(statsRoot);
  671. } catch ( ... ) {
  672. statsRoot = "";
  673. }
  674. relayMaxHops = ZT_RELAY_MAX_HOPS;
  675. try {
  676. relayMaxHops = config["relayMaxHops"];
  677. if (relayMaxHops > ZT_PROTO_MAX_HOPS)
  678. relayMaxHops = ZT_PROTO_MAX_HOPS;
  679. else if (relayMaxHops < 0)
  680. relayMaxHops = 0;
  681. } catch ( ... ) {
  682. relayMaxHops = ZT_RELAY_MAX_HOPS;
  683. }
  684. try {
  685. auto sibs = config["siblings"];
  686. if (sibs.is_array()) {
  687. for(long i=0;i<(long)sibs.size();++i) {
  688. auto sib = sibs[i];
  689. if (sib.is_object()) {
  690. std::string idStr = sib["id"];
  691. std::string ipStr = sib["ip"];
  692. Identity id;
  693. if (!id.fromString(idStr.c_str())) {
  694. printf("FATAL: invalid JSON while parsing siblings section in config file: invalid identity in sibling entry" ZT_EOL_S);
  695. return 1;
  696. }
  697. InetAddress ip;
  698. if (!ip.fromString(ipStr.c_str())) {
  699. printf("FATAL: invalid JSON while parsing siblings section in config file: invalid IP address in sibling entry" ZT_EOL_S);
  700. return 1;
  701. }
  702. ip.setPort((unsigned int)sib["port"]);
  703. SharedPtr<RootPeer> rp(new RootPeer);
  704. rp->id = id;
  705. if (!self.agree(id,rp->key)) {
  706. printf("FATAL: invalid JSON while parsing siblings section in config file: invalid identity in sibling entry (unable to execute key agreement)" ZT_EOL_S);
  707. return 1;
  708. }
  709. if (ip.isV4()) {
  710. rp->ip4 = ip;
  711. } else if (ip.isV6()) {
  712. rp->ip6 = ip;
  713. } else {
  714. printf("FATAL: invalid JSON while parsing siblings section in config file: invalid IP address in sibling entry" ZT_EOL_S);
  715. return 1;
  716. }
  717. rp->sibling = true;
  718. siblings.push_back(rp);
  719. peersByIdentity[id] = rp;
  720. peersByVirtAddr[id.address()].insert(rp);
  721. peersByPhysAddr[ip].insert(rp);
  722. } else {
  723. printf("FATAL: invalid JSON while parsing siblings section in config file: sibling entry is not a JSON object" ZT_EOL_S);
  724. return 1;
  725. }
  726. }
  727. } else {
  728. printf("FATAL: invalid JSON while parsing siblings section in config file: siblings is not a JSON array" ZT_EOL_S);
  729. return 1;
  730. }
  731. } catch ( ... ) {
  732. printf("FATAL: invalid JSON while parsing siblings section in config file: parse error" ZT_EOL_S);
  733. return 1;
  734. }
  735. unsigned int ncores = std::thread::hardware_concurrency();
  736. if (ncores == 0) ncores = 1;
  737. run = true;
  738. std::vector<std::thread> threads;
  739. std::vector<int> sockets;
  740. int v4Sock = -1,v6Sock = -1;
  741. for(auto port=ports.begin();port!=ports.end();++port) {
  742. for(unsigned int tn=0;tn<ncores;++tn) {
  743. struct sockaddr_in6 in6;
  744. memset(&in6,0,sizeof(in6));
  745. in6.sin6_family = AF_INET6;
  746. in6.sin6_port = htons((uint16_t)*port);
  747. const int s6 = bindSocket((struct sockaddr *)&in6);
  748. if (s6 < 0) {
  749. std::cout << "ERROR: unable to bind to port " << *port << ZT_EOL_S;
  750. exit(1);
  751. }
  752. struct sockaddr_in in4;
  753. memset(&in4,0,sizeof(in4));
  754. in4.sin_family = AF_INET;
  755. in4.sin_port = htons((uint16_t)*port);
  756. const int s4 = bindSocket((struct sockaddr *)&in4);
  757. if (s4 < 0) {
  758. std::cout << "ERROR: unable to bind to port " << *port << ZT_EOL_S;
  759. exit(1);
  760. }
  761. sockets.push_back(s6);
  762. sockets.push_back(s4);
  763. if (v4Sock < 0) v4Sock = s4;
  764. if (v6Sock < 0) v6Sock = s6;
  765. threads.push_back(std::thread([s6,s4]() {
  766. struct sockaddr_in6 in6;
  767. Packet pkt;
  768. memset(&in6,0,sizeof(in6));
  769. for(;;) {
  770. socklen_t sl = sizeof(in6);
  771. const int pl = (int)recvfrom(s6,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in6,&sl);
  772. if (pl > 0) {
  773. if (pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  774. try {
  775. pkt.setSize((unsigned int)pl);
  776. handlePacket(s4,s6,reinterpret_cast<const InetAddress *>(&in6),pkt);
  777. } catch ( ... ) {
  778. char ipstr[128];
  779. printf("* unexpected exception handling packet from %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in6)->toString(ipstr));
  780. }
  781. }
  782. } else {
  783. break;
  784. }
  785. }
  786. }));
  787. threads.push_back(std::thread([s6,s4]() {
  788. struct sockaddr_in in4;
  789. Packet pkt;
  790. memset(&in4,0,sizeof(in4));
  791. for(;;) {
  792. socklen_t sl = sizeof(in4);
  793. const int pl = (int)recvfrom(s4,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in4,&sl);
  794. if (pl > 0) {
  795. if (pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  796. try {
  797. pkt.setSize((unsigned int)pl);
  798. handlePacket(s4,s6,reinterpret_cast<const InetAddress *>(&in4),pkt);
  799. } catch ( ... ) {
  800. char ipstr[128];
  801. printf("* unexpected exception handling packet from %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in4)->toString(ipstr));
  802. }
  803. }
  804. } else {
  805. break;
  806. }
  807. }
  808. }));
  809. }
  810. }
  811. // Minimal local API for use with monitoring clients, etc.
  812. httplib::Server apiServ;
  813. threads.push_back(std::thread([&apiServ,httpPort]() {
  814. apiServ.Get("/",[](const httplib::Request &req,httplib::Response &res) {
  815. std::ostringstream o;
  816. std::lock_guard<std::mutex> l0(peersByIdentity_l);
  817. std::lock_guard<std::mutex> l1(peersByPhysAddr_l);
  818. o << "ZeroTier Root Server " << ZEROTIER_ONE_VERSION_MAJOR << '.' << ZEROTIER_ONE_VERSION_MINOR << '.' << ZEROTIER_ONE_VERSION_REVISION << ZT_EOL_S;
  819. o << "(c)2019 ZeroTier, Inc." ZT_EOL_S "Licensed under the ZeroTier BSL 1.1" ZT_EOL_S ZT_EOL_S;
  820. o << "Peers Online: " << peersByIdentity.size() << ZT_EOL_S;
  821. o << "Physical Addresses: " << peersByPhysAddr.size() << ZT_EOL_S;
  822. res.set_content(o.str(),"text/plain");
  823. });
  824. apiServ.Get("/peer",[](const httplib::Request &req,httplib::Response &res) {
  825. char tmp[256];
  826. std::ostringstream o;
  827. o << '[';
  828. {
  829. bool first = true;
  830. std::lock_guard<std::mutex> l(peersByIdentity_l);
  831. for(auto p=peersByIdentity.begin();p!=peersByIdentity.end();++p) {
  832. if (first)
  833. first = false;
  834. else o << ',';
  835. o <<
  836. "{\"address\":\"" << p->first.address().toString(tmp) << "\""
  837. ",\"latency\":-1"
  838. ",\"paths\":[";
  839. if (p->second->ip4) {
  840. o <<
  841. "{\"active\":true"
  842. ",\"address\":\"" << p->second->ip4.toIpString(tmp) << "\\/" << p->second->ip4.port() << "\""
  843. ",\"expired\":false"
  844. ",\"lastReceive\":" << p->second->lastReceive <<
  845. ",\"lastSend\":" << p->second->lastSend <<
  846. ",\"preferred\":true"
  847. ",\"trustedPathId\":0}";
  848. }
  849. if (p->second->ip6) {
  850. if (p->second->ip4)
  851. o << ',';
  852. o <<
  853. "{\"active\":true"
  854. ",\"address\":\"" << p->second->ip6.toIpString(tmp) << "\\/" << p->second->ip6.port() << "\""
  855. ",\"expired\":false"
  856. ",\"lastReceive\":" << p->second->lastReceive <<
  857. ",\"lastSend\":" << p->second->lastSend <<
  858. ",\"preferred\":" << ((p->second->ip4) ? "false" : "true") <<
  859. ",\"trustedPathId\":0}";
  860. }
  861. o << "]"
  862. ",\"role\":\"LEAF\""
  863. ",\"version\":\"" << p->second->vMajor << '.' << p->second->vMinor << '.' << p->second->vRev << "\""
  864. ",\"versionMajor\":" << p->second->vMajor <<
  865. ",\"versionMinor\":" << p->second->vMinor <<
  866. ",\"versionRev\":" << p->second->vRev << "}";
  867. }
  868. }
  869. o << ']';
  870. res.set_content(o.str(),"application/json");
  871. });
  872. apiServ.listen("127.0.0.1",httpPort,0);
  873. }));
  874. // In the main thread periodically clean stuff up
  875. int64_t lastCleaned = 0;
  876. int64_t lastWroteStats = 0;
  877. int64_t lastPingedSiblings = 0;
  878. while (run) {
  879. //peersByIdentity_l.lock();
  880. //peersByPhysAddr_l.lock();
  881. //printf("*** have %lu peers at %lu physical endpoints" ZT_EOL_S,(unsigned long)peersByIdentity.size(),(unsigned long)peersByPhysAddr.size());
  882. //peersByPhysAddr_l.unlock();
  883. //peersByIdentity_l.unlock();
  884. sleep(1);
  885. const int64_t now = OSUtils::now();
  886. // Send HELLO to sibling roots
  887. if ((now - lastPingedSiblings) >= ZT_PEER_PING_PERIOD) {
  888. lastPingedSiblings = now;
  889. std::lock_guard<std::mutex> l(siblings_l);
  890. for(auto s=siblings.begin();s!=siblings.end();++s) {
  891. const InetAddress *ip = nullptr;
  892. socklen_t sl = 0;
  893. Packet outp((*s)->id.address(),self.address(),Packet::VERB_HELLO);
  894. outp.append((uint8_t)ZT_PROTO_VERSION);
  895. outp.append((uint8_t)ZEROTIER_ONE_VERSION_MAJOR);
  896. outp.append((uint8_t)ZEROTIER_ONE_VERSION_MINOR);
  897. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  898. outp.append((uint64_t)now);
  899. self.serialize(outp,false);
  900. if ((*s)->ip4) {
  901. (*s)->ip4.serialize(outp);
  902. ip = &((*s)->ip4);
  903. sl = sizeof(struct sockaddr_in);
  904. } else if ((*s)->ip6) {
  905. (*s)->ip6.serialize(outp);
  906. ip = &((*s)->ip6);
  907. sl = sizeof(struct sockaddr_in6);
  908. }
  909. if (ip) {
  910. outp.armor((*s)->key,false);
  911. sendto(ip->isV4() ? v4Sock : v6Sock,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)ip,sl);
  912. }
  913. }
  914. }
  915. if ((now - lastCleaned) > 120000) {
  916. lastCleaned = now;
  917. // Old multicast subscription cleanup
  918. {
  919. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  920. for(auto a=multicastSubscriptions.begin();a!=multicastSubscriptions.end();) {
  921. for(auto b=a->second.begin();b!=a->second.end();) {
  922. for(auto c=b->second.begin();c!=b->second.end();) {
  923. if ((now - c->second) > ZT_MULTICAST_LIKE_EXPIRE)
  924. b->second.erase(c++);
  925. else ++c;
  926. }
  927. if (b->second.empty())
  928. a->second.erase(b++);
  929. else ++b;
  930. }
  931. if (a->second.empty())
  932. multicastSubscriptions.erase(a++);
  933. else ++a;
  934. }
  935. }
  936. // Remove expired peers
  937. {
  938. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  939. for(auto p=peersByIdentity.begin();p!=peersByIdentity.end();) {
  940. if (((now - p->second->lastReceive) > ZT_PEER_ACTIVITY_TIMEOUT)&&(!p->second->sibling)) {
  941. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  942. std::lock_guard<std::mutex> pbp_l(peersByPhysAddr_l);
  943. auto pbv = peersByVirtAddr.find(p->second->id.address());
  944. if (pbv != peersByVirtAddr.end()) {
  945. pbv->second.erase(p->second);
  946. if (pbv->second.empty())
  947. peersByVirtAddr.erase(pbv);
  948. }
  949. if (p->second->ip4) {
  950. auto pbp = peersByPhysAddr.find(p->second->ip4);
  951. if (pbp != peersByPhysAddr.end()) {
  952. pbp->second.erase(p->second);
  953. if (pbp->second.empty())
  954. peersByPhysAddr.erase(pbp);
  955. }
  956. }
  957. if (p->second->ip6) {
  958. auto pbp = peersByPhysAddr.find(p->second->ip6);
  959. if (pbp != peersByPhysAddr.end()) {
  960. pbp->second.erase(p->second);
  961. if (pbp->second.empty())
  962. peersByPhysAddr.erase(pbp);
  963. }
  964. }
  965. peersByIdentity.erase(p++);
  966. } else ++p;
  967. }
  968. }
  969. // Remove old rendezvous tracking entries
  970. {
  971. std::lock_guard<std::mutex> l(lastRendezvous_l);
  972. for(auto lr=lastRendezvous.begin();lr!=lastRendezvous.end();) {
  973. if ((now - lr->second) > ZT_PEER_ACTIVITY_TIMEOUT)
  974. lastRendezvous.erase(lr++);
  975. else ++lr;
  976. }
  977. }
  978. }
  979. // Write stats if configured to do so
  980. if (((now - lastWroteStats) > 15000)&&(statsRoot.length() > 0)) {
  981. lastWroteStats = now;
  982. std::string peersFilePath(statsRoot);
  983. peersFilePath.append("/.peers.tmp");
  984. FILE *pf = fopen(peersFilePath.c_str(),"wb");
  985. if (pf) {
  986. std::vector< SharedPtr<RootPeer> > sp;
  987. {
  988. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  989. sp.reserve(peersByIdentity.size());
  990. for(auto p=peersByIdentity.begin();p!=peersByIdentity.end();++p) {
  991. sp.push_back(p->second);
  992. }
  993. }
  994. std::sort(sp.begin(),sp.end(),[](const SharedPtr<RootPeer> &a,const SharedPtr<RootPeer> &b) { return (a->id < b->id); });
  995. char ip4[128],ip6[128];
  996. for(auto p=sp.begin();p!=sp.end();++p) {
  997. if ((*p)->ip4) {
  998. (*p)->ip4.toString(ip4);
  999. } else {
  1000. ip4[0] = '-';
  1001. ip4[1] = 0;
  1002. }
  1003. if ((*p)->ip6) {
  1004. (*p)->ip6.toString(ip6);
  1005. } else {
  1006. ip6[0] = '-';
  1007. ip6[1] = 0;
  1008. }
  1009. fprintf(pf,"%.10llx %21s %45s %5.4f %d.%d.%d" ZT_EOL_S,(unsigned long long)(*p)->id.address().toInt(),ip4,ip6,fabs((double)(now - (*p)->lastReceive) / 1000.0),(*p)->vMajor,(*p)->vMinor,(*p)->vRev);
  1010. }
  1011. fclose(pf);
  1012. std::string peersFilePath2(statsRoot);
  1013. peersFilePath2.append("/peers");
  1014. OSUtils::rm(peersFilePath2);
  1015. OSUtils::rename(peersFilePath.c_str(),peersFilePath2.c_str());
  1016. }
  1017. std::string statsFilePath(statsRoot);
  1018. statsFilePath.append("/.stats.tmp");
  1019. FILE *sf = fopen(statsFilePath.c_str(),"wb");
  1020. if (sf) {
  1021. fprintf(sf,"Uptime (seconds) : %ld" ZT_EOL_S,(long)((now - startTime) / 1000));
  1022. peersByIdentity_l.lock();
  1023. fprintf(sf,"Peers : %llu" ZT_EOL_S,(unsigned long long)peersByIdentity.size());
  1024. peersByVirtAddr_l.lock();
  1025. fprintf(sf,"Virtual Address Collisions : %llu" ZT_EOL_S,(unsigned long long)(peersByIdentity.size() - peersByVirtAddr.size()));
  1026. peersByVirtAddr_l.unlock();
  1027. peersByIdentity_l.unlock();
  1028. peersByPhysAddr_l.lock();
  1029. fprintf(sf,"Physical Endpoints : %llu" ZT_EOL_S,(unsigned long long)peersByPhysAddr.size());
  1030. peersByPhysAddr_l.unlock();
  1031. lastRendezvous_l.lock();
  1032. fprintf(sf,"Recent P2P Graph Edges : %llu" ZT_EOL_S,(unsigned long long)lastRendezvous.size());
  1033. lastRendezvous_l.unlock();
  1034. fprintf(sf,"Input BPS : %.4f" ZT_EOL_S,inputRate.perSecond(now));
  1035. fprintf(sf,"Output BPS : %.4f" ZT_EOL_S,outputRate.perSecond(now));
  1036. fprintf(sf,"Forwarded BPS : %.4f" ZT_EOL_S,forwardRate.perSecond(now));
  1037. fprintf(sf,"Sibling Forwarded BPS : %.4f" ZT_EOL_S,siblingForwardRate.perSecond(now));
  1038. fprintf(sf,"Discarded Forward BPS : %.4f" ZT_EOL_S,discardedForwardRate.perSecond(now));
  1039. fclose(sf);
  1040. std::string statsFilePath2(statsRoot);
  1041. statsFilePath2.append("/stats");
  1042. OSUtils::rm(statsFilePath2);
  1043. OSUtils::rename(statsFilePath.c_str(),statsFilePath2.c_str());
  1044. }
  1045. }
  1046. }
  1047. // If we received a kill signal, close everything and wait
  1048. // for threads to die before exiting.
  1049. apiServ.stop();
  1050. for(auto s=sockets.begin();s!=sockets.end();++s) {
  1051. shutdown(*s,SHUT_RDWR);
  1052. close(*s);
  1053. }
  1054. for(auto t=threads.begin();t!=threads.end();++t)
  1055. t->join();
  1056. return 0;
  1057. }