root.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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. #include "../node/Constants.hpp"
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <unistd.h>
  17. #include <string.h>
  18. #include <fcntl.h>
  19. #include <signal.h>
  20. #include <sys/stat.h>
  21. #include <sys/types.h>
  22. #include <sys/socket.h>
  23. #include <sys/select.h>
  24. #include <sys/time.h>
  25. #include <sys/un.h>
  26. #include <sys/ioctl.h>
  27. #include <arpa/inet.h>
  28. #include <netinet/in.h>
  29. #include <netinet/ip.h>
  30. #include <netinet/ip6.h>
  31. #include <netinet/tcp.h>
  32. #include "../ext/json/json.hpp"
  33. #include "../node/Packet.hpp"
  34. #include "../node/Utils.hpp"
  35. #include "../node/Address.hpp"
  36. #include "../node/Identity.hpp"
  37. #include "../node/InetAddress.hpp"
  38. #include "../node/Mutex.hpp"
  39. #include "../node/SharedPtr.hpp"
  40. #include "../node/MulticastGroup.hpp"
  41. #include "../osdep/OSUtils.hpp"
  42. #include <string>
  43. #include <thread>
  44. #include <map>
  45. #include <set>
  46. #include <vector>
  47. #include <iostream>
  48. #include <unordered_map>
  49. #include <unordered_set>
  50. #include <vector>
  51. #include <atomic>
  52. #include <mutex>
  53. using namespace ZeroTier;
  54. using json = nlohmann::json;
  55. //////////////////////////////////////////////////////////////////////////////
  56. //////////////////////////////////////////////////////////////////////////////
  57. struct IdentityHasher { ZT_ALWAYS_INLINE std::size_t operator()(const Identity &id) const { return (std::size_t)id.hashCode(); } };
  58. struct AddressHasher { ZT_ALWAYS_INLINE std::size_t operator()(const Address &a) const { return (std::size_t)a.toInt(); } };
  59. struct InetAddressHasher { ZT_ALWAYS_INLINE std::size_t operator()(const InetAddress &ip) const { return (std::size_t)ip.hashCode(); } };
  60. struct MulticastGroupHasher { ZT_ALWAYS_INLINE std::size_t operator()(const MulticastGroup &mg) const { return (std::size_t)mg.hashCode(); } };
  61. struct RendezvousKey
  62. {
  63. RendezvousKey(const Address &aa,const Address &bb)
  64. {
  65. if (aa > bb) {
  66. a = aa;
  67. b = bb;
  68. } else {
  69. a = bb;
  70. b = aa;
  71. }
  72. }
  73. Address a,b;
  74. ZT_ALWAYS_INLINE bool operator==(const RendezvousKey &k) const { return ((a == k.a)&&(b == k.b)); }
  75. ZT_ALWAYS_INLINE bool operator!=(const RendezvousKey &k) const { return ((a != k.a)||(b != k.b)); }
  76. struct Hasher { ZT_ALWAYS_INLINE std::size_t operator()(const RendezvousKey &k) const { return (std::size_t)(k.a.toInt() ^ k.b.toInt()); } };
  77. };
  78. struct RootPeer
  79. {
  80. Identity id;
  81. uint8_t key[32];
  82. InetAddress ip4,ip6;
  83. int64_t lastReceive;
  84. int64_t lastSync;
  85. AtomicCounter __refCount;
  86. ZT_ALWAYS_INLINE ~RootPeer() { Utils::burn(key,sizeof(key)); }
  87. };
  88. static Identity self;
  89. static std::atomic_bool run;
  90. static json config;
  91. static std::unordered_map< uint64_t,std::unordered_map< MulticastGroup,std::unordered_map< Address,int64_t,AddressHasher >,MulticastGroupHasher > > multicastSubscriptions;
  92. static std::unordered_map< Identity,SharedPtr<RootPeer>,IdentityHasher > peersByIdentity;
  93. static std::unordered_map< Address,std::set< SharedPtr<RootPeer> >,AddressHasher > peersByVirtAddr;
  94. static std::unordered_map< InetAddress,std::set< SharedPtr<RootPeer> >,InetAddressHasher > peersByPhysAddr;
  95. static std::unordered_map< RendezvousKey,int64_t,RendezvousKey::Hasher > lastRendezvous;
  96. static std::mutex multicastSubscriptions_l;
  97. static std::mutex peersByIdentity_l;
  98. static std::mutex peersByVirtAddr_l;
  99. static std::mutex peersByPhysAddr_l;
  100. static std::mutex lastRendezvous_l;
  101. //////////////////////////////////////////////////////////////////////////////
  102. //////////////////////////////////////////////////////////////////////////////
  103. static void handlePacket(const int v4s,const int v6s,const InetAddress *const ip,Packet &pkt)
  104. {
  105. char ipstr[128],ipstr2[128],astr[32],astr2[32],tmpstr[256];
  106. const bool fragment = pkt[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR;
  107. const Address source(pkt.source());
  108. const Address dest(pkt.destination());
  109. const int64_t now = OSUtils::now();
  110. // See if this is destined for us and isn't a fragment / fragmented. (No packets
  111. // understood by the root are fragments/fragmented.)
  112. if ((!fragment)&&(!pkt.fragmented())&&(dest == self.address())) {
  113. SharedPtr<RootPeer> peer;
  114. // If this is an un-encrypted HELLO, either learn a new peer or verify
  115. // that this is a peer we already know.
  116. if ((pkt.cipher() == ZT_PROTO_CIPHER_SUITE__POLY1305_NONE)&&(pkt.verb() == Packet::VERB_HELLO)) {
  117. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  118. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  119. Identity id;
  120. if (id.deserialize(pkt,ZT_PROTO_VERB_HELLO_IDX_IDENTITY)) {
  121. {
  122. auto pById = peersByIdentity.find(id);
  123. if (pById != peersByIdentity.end()) {
  124. peer = pById->second;
  125. //printf("%s has %s (known (1))" ZT_EOL_S,ip->toString(ipstr),source().toString(astr));
  126. }
  127. }
  128. if (peer) {
  129. if (!pkt.dearmor(peer->key)) {
  130. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  131. return;
  132. }
  133. } else {
  134. peer.set(new RootPeer);
  135. if (self.agree(id,peer->key)) {
  136. if (pkt.dearmor(peer->key)) {
  137. peer->id = id;
  138. peer->lastSync = 0;
  139. peersByIdentity.emplace(id,peer);
  140. peersByVirtAddr[id.address()].emplace(peer);
  141. } else {
  142. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  143. return;
  144. }
  145. } else {
  146. printf("%s HELLO rejected: key agreement failed" ZT_EOL_S,ip->toString(ipstr));
  147. return;
  148. }
  149. }
  150. }
  151. }
  152. // If it wasn't a HELLO, check to see if any known identities for the sender's
  153. // short ZT address successfully decrypt the packet.
  154. if (!peer) {
  155. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  156. auto peers = peersByVirtAddr.find(source);
  157. if (peers != peersByVirtAddr.end()) {
  158. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  159. if (pkt.dearmor((*p)->key)) {
  160. peer = (*p);
  161. //printf("%s has %s (known (2))" ZT_EOL_S,ip->toString(ipstr),source().toString(astr));
  162. break;
  163. }
  164. }
  165. }
  166. }
  167. // If we found the peer, update IP and/or time and handle certain key packet types that the
  168. // root must concern itself with.
  169. if (peer) {
  170. InetAddress *const peerIp = ip->isV4() ? &(peer->ip4) : &(peer->ip6);
  171. if (*peerIp != ip) {
  172. std::lock_guard<std::mutex> pbp_l(peersByPhysAddr_l);
  173. if (*peerIp) {
  174. auto prev = peersByPhysAddr.find(*peerIp);
  175. if (prev != peersByPhysAddr.end()) {
  176. prev->second.erase(peer);
  177. if (prev->second.empty())
  178. peersByPhysAddr.erase(prev);
  179. }
  180. }
  181. *peerIp = ip;
  182. peersByPhysAddr[ip].emplace(peer);
  183. }
  184. const int64_t now = OSUtils::now();
  185. peer->lastReceive = now;
  186. switch(pkt.verb()) {
  187. case Packet::VERB_HELLO:
  188. try {
  189. const uint64_t origId = pkt.packetId();
  190. const uint64_t ts = pkt.template at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  191. pkt.reset(source,self.address(),Packet::VERB_OK);
  192. pkt.append((uint8_t)Packet::VERB_HELLO);
  193. pkt.append(origId);
  194. pkt.append(ts);
  195. pkt.append((uint8_t)ZT_PROTO_VERSION);
  196. pkt.append((uint8_t)0);
  197. pkt.append((uint8_t)0);
  198. pkt.append((uint16_t)0);
  199. ip->serialize(pkt);
  200. pkt.armor(peer->key,true);
  201. sendto(ip->isV4() ? v4s : v6s,pkt.data(),pkt.size(),0,(const struct sockaddr *)ip,(socklen_t)((ip->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  202. //printf("%s <- OK(HELLO)" ZT_EOL_S,ip->toString(ipstr));
  203. } catch ( ... ) {
  204. printf("* unexpected exception handling HELLO from %s" ZT_EOL_S,ip->toString(ipstr));
  205. }
  206. break;
  207. case Packet::VERB_MULTICAST_LIKE:
  208. try {
  209. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  210. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;(ptr+18)<=pkt.size();ptr+=18) {
  211. const uint64_t nwid = pkt.template at<uint64_t>(ptr);
  212. const MulticastGroup mg(MAC(pkt.field(ptr + 8,6),6),pkt.template at<uint32_t>(ptr + 14));
  213. multicastSubscriptions[nwid][mg][peer->id.address()] = now;
  214. //printf("%s subscribes to %s/%.8lx on network %.16llx" ZT_EOL_S,ip->toString(ipstr),mg.mac().toString(tmpstr),(unsigned long)mg.adi(),(unsigned long long)nwid);
  215. }
  216. } catch ( ... ) {
  217. printf("* unexpected exception handling MULTICAST_LIKE from %s" ZT_EOL_S,ip->toString(ipstr));
  218. }
  219. break;
  220. case Packet::VERB_MULTICAST_GATHER:
  221. try {
  222. const uint64_t nwid = pkt.template at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  223. const unsigned int flags = pkt[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  224. 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));
  225. unsigned int gatherLimit = pkt.template at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  226. if (gatherLimit > 255)
  227. gatherLimit = 255;
  228. const uint64_t origId = pkt.packetId();
  229. pkt.reset(source,self.address(),Packet::VERB_OK);
  230. pkt.append((uint8_t)Packet::VERB_MULTICAST_GATHER);
  231. pkt.append(origId);
  232. pkt.append(nwid);
  233. mg.mac().appendTo(pkt);
  234. pkt.append((uint32_t)mg.adi());
  235. {
  236. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  237. auto forNet = multicastSubscriptions.find(nwid);
  238. if (forNet != multicastSubscriptions.end()) {
  239. auto forGroup = forNet->second.find(mg);
  240. if (forGroup != forNet->second.end()) {
  241. pkt.append((uint32_t)forGroup->second.size());
  242. pkt.append((uint16_t)std::min(std::min((unsigned int)forGroup->second.size(),(unsigned int)65535),gatherLimit));
  243. auto g = forGroup->second.begin();
  244. unsigned int l = 0;
  245. for(;((l<gatherLimit)&&(g!=forGroup->second.end()));++l,++g)
  246. g->first.appendTo(pkt);
  247. if (l > 0) {
  248. sendto(ip->isV4() ? v4s : v6s,pkt.data(),pkt.size(),0,(const struct sockaddr *)ip,(socklen_t)((ip->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  249. //printf("%s gathered %u subscribers to %s/%.8lx on network %.16llx" ZT_EOL_S,ip->toString(ipstr),l,mg.mac().toString(tmpstr),(unsigned long)mg.adi(),(unsigned long long)nwid);
  250. }
  251. }
  252. }
  253. }
  254. } catch ( ... ) {
  255. printf("* unexpected exception handling MULTICAST_GATHER from %s" ZT_EOL_S,ip->toString(ipstr));
  256. }
  257. break;
  258. default:
  259. break;
  260. }
  261. return;
  262. }
  263. }
  264. // If we made it here, we are forwarding this packet to someone else and also possibly
  265. // sending a RENDEZVOUS message.
  266. bool introduce = false;
  267. {
  268. RendezvousKey rk(source,dest);
  269. std::lock_guard<std::mutex> l(lastRendezvous_l);
  270. int64_t &lr = lastRendezvous[rk];
  271. if ((now - lr) >= 45000) {
  272. lr = now;
  273. introduce = true;
  274. }
  275. }
  276. std::vector< std::pair< InetAddress *,SharedPtr<RootPeer> > > toAddrs;
  277. {
  278. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  279. auto peers = peersByVirtAddr.find(dest);
  280. if (peers != peersByVirtAddr.end()) {
  281. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  282. if ((now - (*p)->lastReceive) < ZT_PEER_ACTIVITY_TIMEOUT) {
  283. if ((*p)->ip6) {
  284. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*p)->ip6),*p));
  285. } else if ((*p)->ip4) {
  286. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*p)->ip4),*p));
  287. }
  288. }
  289. }
  290. }
  291. }
  292. if (toAddrs.empty()) {
  293. //printf("%s not forwarding to %s: no destinations found" ZT_EOL_S,ip->toString(ipstr),dest().toString(astr));
  294. return;
  295. }
  296. if (introduce) {
  297. std::lock_guard<std::mutex> l(peersByVirtAddr_l);
  298. auto sources = peersByVirtAddr.find(source);
  299. if (sources != peersByVirtAddr.end()) {
  300. for(auto a=sources->second.begin();a!=sources->second.end();++a) {
  301. for(auto b=toAddrs.begin();b!=toAddrs.end();++b) {
  302. if (((*a)->ip6)&&(b->second->ip6)) {
  303. //printf("* introducing %s(%s) to %s(%s)" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),b->second->ip6.toString(ipstr2),dest.toString(astr2));
  304. // Introduce source to destination (V6)
  305. Packet outp(source,self.address(),Packet::VERB_RENDEZVOUS);
  306. outp.append((uint8_t)0);
  307. dest.appendTo(outp);
  308. outp.append((uint16_t)b->second->ip6.port());
  309. outp.append((uint8_t)16);
  310. outp.append((const uint8_t *)b->second->ip6.rawIpData(),16);
  311. outp.armor((*a)->key,true);
  312. sendto(v6s,pkt.data(),pkt.size(),0,(const struct sockaddr *)&((*a)->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  313. // Introduce destination to source (V6)
  314. outp.reset(dest,self.address(),Packet::VERB_RENDEZVOUS);
  315. outp.append((uint8_t)0);
  316. source.appendTo(outp);
  317. outp.append((uint16_t)ip->port());
  318. outp.append((uint8_t)16);
  319. outp.append((const uint8_t *)ip->rawIpData(),16);
  320. outp.armor(b->second->key,true);
  321. sendto(v6s,pkt.data(),pkt.size(),0,(const struct sockaddr *)&(b->second->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  322. } else if (((*a)->ip4)&&(b->second->ip4)) {
  323. //printf("* introducing %s(%s) to %s(%s)" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),b->second->ip4.toString(ipstr2),dest.toString(astr2));
  324. // Introduce source to destination (V4)
  325. Packet outp(source,self.address(),Packet::VERB_RENDEZVOUS);
  326. outp.append((uint8_t)0);
  327. dest.appendTo(outp);
  328. outp.append((uint16_t)b->second->ip4.port());
  329. outp.append((uint8_t)4);
  330. outp.append((const uint8_t *)b->second->ip4.rawIpData(),4);
  331. outp.armor((*a)->key,true);
  332. sendto(v4s,pkt.data(),pkt.size(),0,(const struct sockaddr *)&((*a)->ip4),(socklen_t)sizeof(struct sockaddr_in));
  333. // Introduce destination to source (V4)
  334. outp.reset(dest,self.address(),Packet::VERB_RENDEZVOUS);
  335. outp.append((uint8_t)0);
  336. source.appendTo(outp);
  337. outp.append((uint16_t)ip->port());
  338. outp.append((uint8_t)4);
  339. outp.append((const uint8_t *)ip->rawIpData(),4);
  340. outp.armor(b->second->key,true);
  341. sendto(v4s,pkt.data(),pkt.size(),0,(const struct sockaddr *)&(b->second->ip4),(socklen_t)sizeof(struct sockaddr_in));
  342. }
  343. }
  344. }
  345. }
  346. }
  347. if (fragment) {
  348. if (reinterpret_cast<Packet::Fragment *>(&pkt)->incrementHops() >= ZT_PROTO_MAX_HOPS) {
  349. printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  350. return;
  351. }
  352. } else {
  353. if (pkt.incrementHops() >= ZT_PROTO_MAX_HOPS) {
  354. printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  355. return;
  356. }
  357. }
  358. for(auto i=toAddrs.begin();i!=toAddrs.end();++i) {
  359. //printf("%s -> %s for %s" ZT_EOL_S,ip->toString(ipstr),i->toString(ipstr2),dest().toString(astr));
  360. sendto(i->first->isV4() ? v4s : v6s,pkt.data(),pkt.size(),0,(const struct sockaddr *)i->first,(socklen_t)((i->first->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  361. }
  362. }
  363. //////////////////////////////////////////////////////////////////////////////
  364. //////////////////////////////////////////////////////////////////////////////
  365. static int bindSocket(struct sockaddr *bindAddr)
  366. {
  367. int s = socket(bindAddr->sa_family,SOCK_DGRAM,0);
  368. if (s < 0) {
  369. close(s);
  370. return -1;
  371. }
  372. int f = 131072;
  373. setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&f,sizeof(f));
  374. f = 131072;
  375. setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&f,sizeof(f));
  376. if (bindAddr->sa_family == AF_INET6) {
  377. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  378. #ifdef IPV6_MTU_DISCOVER
  379. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  380. #endif
  381. #ifdef IPV6_DONTFRAG
  382. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,&f,sizeof(f));
  383. #endif
  384. }
  385. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  386. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEPORT,(void *)&f,sizeof(f));
  387. f = 1; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(void *)&f,sizeof(f));
  388. #ifdef IP_DONTFRAG
  389. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  390. #endif
  391. #ifdef IP_MTU_DISCOVER
  392. f = IP_PMTUDISC_DONT; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  393. #endif
  394. #ifdef SO_NO_CHECK
  395. if (bindAddr->sa_family == AF_INET) {
  396. f = 1; setsockopt(s,SOL_SOCKET,SO_NO_CHECK,(void *)&f,sizeof(f));
  397. }
  398. #endif
  399. if (bind(s,bindAddr,(bindAddr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
  400. close(s);
  401. return -1;
  402. }
  403. return s;
  404. }
  405. static void shutdownSigHandler(int sig) { run = false; }
  406. int main(int argc,char **argv)
  407. {
  408. signal(SIGTERM,shutdownSigHandler);
  409. signal(SIGINT,shutdownSigHandler);
  410. signal(SIGQUIT,shutdownSigHandler);
  411. signal(SIGPIPE,SIG_IGN);
  412. signal(SIGUSR1,SIG_IGN);
  413. signal(SIGUSR2,SIG_IGN);
  414. signal(SIGCHLD,SIG_IGN);
  415. if (argc < 3) {
  416. printf("Usage: zerotier-root <identity.secret> <config path>" ZT_EOL_S);
  417. return 1;
  418. }
  419. {
  420. std::string myIdStr;
  421. if (!OSUtils::readFile(argv[1],myIdStr)) {
  422. printf("FATAL: cannot read identity.secret at %s" ZT_EOL_S,argv[1]);
  423. return 1;
  424. }
  425. if (!self.fromString(myIdStr.c_str())) {
  426. printf("FATAL: cannot read identity.secret at %s (invalid identity)" ZT_EOL_S,argv[1]);
  427. return 1;
  428. }
  429. if (!self.hasPrivate()) {
  430. printf("FATAL: cannot read identity.secret at %s (missing secret key)" ZT_EOL_S,argv[1]);
  431. return 1;
  432. }
  433. }
  434. {
  435. std::string configStr;
  436. if (!OSUtils::readFile(argv[2],configStr)) {
  437. printf("FATAL: cannot read config file at %s" ZT_EOL_S,argv[2]);
  438. return 1;
  439. }
  440. try {
  441. config = json::parse(configStr);
  442. } catch (std::exception &exc) {
  443. printf("FATAL: config file at %s invalid: %s" ZT_EOL_S,argv[2],exc.what());
  444. return 1;
  445. } catch ( ... ) {
  446. printf("FATAL: config file at %s invalid: unknown exception" ZT_EOL_S,argv[2]);
  447. return 1;
  448. }
  449. if (!config.is_object()) {
  450. printf("FATAL: config file at %s invalid: does not contain a JSON object" ZT_EOL_S,argv[2]);
  451. return 1;
  452. }
  453. }
  454. int port = ZT_DEFAULT_PORT;
  455. try {
  456. int port = config["port"];
  457. if ((port <= 0)||(port > 65535)) {
  458. printf("FATAL: invalid port in config file %d" ZT_EOL_S,port);
  459. return 1;
  460. }
  461. } catch ( ... ) {
  462. port = ZT_DEFAULT_PORT;
  463. }
  464. unsigned int ncores = std::thread::hardware_concurrency();
  465. if (ncores == 0) ncores = 1;
  466. run = true;
  467. std::vector<std::thread> threads;
  468. std::vector<int> sockets;
  469. for(unsigned int tn=0;tn<ncores;++tn) {
  470. struct sockaddr_in6 in6;
  471. memset(&in6,0,sizeof(in6));
  472. in6.sin6_family = AF_INET6;
  473. in6.sin6_port = htons((uint16_t)port);
  474. const int s6 = bindSocket((struct sockaddr *)&in6);
  475. if (s6 < 0) {
  476. std::cout << "ERROR: unable to bind to port " << ZT_DEFAULT_PORT << ZT_EOL_S;
  477. exit(1);
  478. }
  479. struct sockaddr_in in4;
  480. memset(&in4,0,sizeof(in4));
  481. in4.sin_family = AF_INET;
  482. in4.sin_port = htons((uint16_t)port);
  483. const int s4 = bindSocket((struct sockaddr *)&in4);
  484. if (s4 < 0) {
  485. std::cout << "ERROR: unable to bind to port " << ZT_DEFAULT_PORT << ZT_EOL_S;
  486. exit(1);
  487. }
  488. sockets.push_back(s6);
  489. sockets.push_back(s4);
  490. threads.push_back(std::thread([s4,s6]() {
  491. struct sockaddr_in6 in6;
  492. Packet pkt;
  493. memset(&in6,0,sizeof(in6));
  494. for(;;) {
  495. socklen_t sl = sizeof(in6);
  496. const int pl = (int)recvfrom(s6,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in6,&sl);
  497. if (pl > 0) {
  498. if (pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  499. try {
  500. pkt.setSize((unsigned int)pl);
  501. handlePacket(s4,s6,reinterpret_cast<const InetAddress *>(&in6),pkt);
  502. } catch ( ... ) {
  503. char ipstr[128];
  504. printf("* unexpected exception handling packet from %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in6)->toString(ipstr));
  505. }
  506. }
  507. } else {
  508. break;
  509. }
  510. }
  511. }));
  512. threads.push_back(std::thread([s4,s6]() {
  513. struct sockaddr_in in4;
  514. Packet pkt;
  515. memset(&in4,0,sizeof(in4));
  516. for(;;) {
  517. socklen_t sl = sizeof(in4);
  518. const int pl = (int)recvfrom(s4,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in4,&sl);
  519. if (pl > 0) {
  520. if (pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  521. try {
  522. pkt.setSize((unsigned int)pl);
  523. handlePacket(s4,s6,reinterpret_cast<const InetAddress *>(&in4),pkt);
  524. } catch ( ... ) {
  525. char ipstr[128];
  526. printf("* unexpected exception handling packet from %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in4)->toString(ipstr));
  527. }
  528. }
  529. } else {
  530. break;
  531. }
  532. }
  533. }));
  534. }
  535. int64_t lastCleanedMulticastSubscriptions = 0;
  536. int64_t lastCleanedPeers = 0;
  537. while (run) {
  538. peersByIdentity_l.lock();
  539. peersByPhysAddr_l.lock();
  540. printf("*** have %lu peers at %lu physical endpoints" ZT_EOL_S,(unsigned long)peersByIdentity.size(),(unsigned long)peersByPhysAddr.size());
  541. peersByPhysAddr_l.unlock();
  542. peersByIdentity_l.unlock();
  543. sleep(1);
  544. const int64_t now = OSUtils::now();
  545. if ((now - lastCleanedMulticastSubscriptions) > 120000) {
  546. lastCleanedMulticastSubscriptions = now;
  547. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  548. for(auto a=multicastSubscriptions.begin();a!=multicastSubscriptions.end();) {
  549. for(auto b=a->second.begin();b!=a->second.end();) {
  550. for(auto c=b->second.begin();c!=b->second.end();) {
  551. if ((now - c->second) > ZT_MULTICAST_LIKE_EXPIRE)
  552. b->second.erase(c++);
  553. else ++c;
  554. }
  555. if (b->second.empty())
  556. a->second.erase(b++);
  557. else ++b;
  558. }
  559. if (a->second.empty())
  560. multicastSubscriptions.erase(a++);
  561. else ++a;
  562. }
  563. }
  564. if ((now - lastCleanedPeers) > 120000) {
  565. lastCleanedPeers = now;
  566. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  567. for(auto p=peersByIdentity.begin();p!=peersByIdentity.end();) {
  568. if ((now - p->second->lastReceive) > ZT_PEER_ACTIVITY_TIMEOUT) {
  569. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  570. std::lock_guard<std::mutex> pbp_l(peersByPhysAddr_l);
  571. auto pbv = peersByVirtAddr.find(p->second->id.address());
  572. if (pbv != peersByVirtAddr.end()) {
  573. pbv->second.erase(p->second);
  574. if (pbv->second.empty())
  575. peersByVirtAddr.erase(pbv);
  576. }
  577. if (p->second->ip4) {
  578. auto pbp = peersByPhysAddr.find(p->second->ip4);
  579. if (pbp != peersByPhysAddr.end()) {
  580. pbp->second.erase(p->second);
  581. if (pbp->second.empty())
  582. peersByPhysAddr.erase(pbp);
  583. }
  584. }
  585. if (p->second->ip6) {
  586. auto pbp = peersByPhysAddr.find(p->second->ip6);
  587. if (pbp != peersByPhysAddr.end()) {
  588. pbp->second.erase(p->second);
  589. if (pbp->second.empty())
  590. peersByPhysAddr.erase(pbp);
  591. }
  592. }
  593. peersByIdentity.erase(p++);
  594. } else ++p;
  595. }
  596. }
  597. }
  598. for(auto s=sockets.begin();s!=sockets.end();++s) {
  599. shutdown(*s,SHUT_RDWR);
  600. close(*s);
  601. }
  602. for(auto t=threads.begin();t!=threads.end();++t)
  603. t->join();
  604. return 0;
  605. }