root.cpp 39 KB

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