root.cpp 21 KB

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