root.cpp 23 KB

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