root.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. if (!pkt.uncompress()) {
  139. printf("%s HELLO rejected: decompression failed" ZT_EOL_S,ip->toString(ipstr));
  140. return;
  141. }
  142. peer->id = id;
  143. peer->lastReceive = now;
  144. peer->lastSync = 0;
  145. peersByIdentity.emplace(id,peer);
  146. peersByVirtAddr[id.address()].emplace(peer);
  147. } else {
  148. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  149. return;
  150. }
  151. } else {
  152. printf("%s HELLO rejected: key agreement failed" ZT_EOL_S,ip->toString(ipstr));
  153. return;
  154. }
  155. }
  156. }
  157. }
  158. // If it wasn't a HELLO, check to see if any known identities for the sender's
  159. // short ZT address successfully decrypt the packet.
  160. if (!peer) {
  161. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  162. auto peers = peersByVirtAddr.find(source);
  163. if (peers != peersByVirtAddr.end()) {
  164. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  165. if (pkt.dearmor((*p)->key)) {
  166. if (!pkt.uncompress()) {
  167. printf("%s packet rejected: decompression failed" ZT_EOL_S,ip->toString(ipstr));
  168. return;
  169. }
  170. peer = (*p);
  171. //printf("%s has %s (known (2))" ZT_EOL_S,ip->toString(ipstr),source().toString(astr));
  172. break;
  173. }
  174. }
  175. }
  176. }
  177. // If we found the peer, update IP and/or time and handle certain key packet types that the
  178. // root must concern itself with.
  179. if (peer) {
  180. InetAddress *const peerIp = ip->isV4() ? &(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(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)));
  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][source] = now;
  224. //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);
  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. const unsigned int countAt = pkt.size();
  253. pkt.addSize(2);
  254. unsigned int l = 0;
  255. for(auto g=forGroup->second.begin();((l<gatherLimit)&&(g!=forGroup->second.end()));++l,++g) {
  256. if (g->first != source)
  257. g->first.appendTo(pkt);
  258. }
  259. if (l > 0) {
  260. pkt.setAt<uint16_t>(countAt,(uint16_t)l);
  261. pkt.armor(peer->key,true);
  262. sendto(ip->isV4() ? v4s : v6s,pkt.data(),pkt.size(),0,(const struct sockaddr *)ip,(socklen_t)(ip->isV4() ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  263. //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);
  264. }
  265. }
  266. }
  267. }
  268. } catch ( ... ) {
  269. printf("* unexpected exception handling MULTICAST_GATHER from %s" ZT_EOL_S,ip->toString(ipstr));
  270. }
  271. break;
  272. default:
  273. break;
  274. }
  275. return;
  276. }
  277. }
  278. // If we made it here, we are forwarding this packet to someone else and also possibly
  279. // sending a RENDEZVOUS message.
  280. bool introduce = false;
  281. {
  282. RendezvousKey rk(source,dest);
  283. std::lock_guard<std::mutex> l(lastRendezvous_l);
  284. int64_t &lr = lastRendezvous[rk];
  285. if ((now - lr) >= 45000) {
  286. lr = now;
  287. introduce = true;
  288. }
  289. }
  290. std::vector< std::pair< InetAddress *,SharedPtr<RootPeer> > > toAddrs;
  291. {
  292. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  293. auto peers = peersByVirtAddr.find(dest);
  294. if (peers != peersByVirtAddr.end()) {
  295. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  296. if ((*p)->ip6) {
  297. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*p)->ip6),*p));
  298. } else if ((*p)->ip4) {
  299. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*p)->ip4),*p));
  300. }
  301. }
  302. }
  303. }
  304. if (toAddrs.empty()) {
  305. //printf("%s not forwarding to %s: no destinations found" ZT_EOL_S,ip->toString(ipstr),dest().toString(astr));
  306. return;
  307. }
  308. if (introduce) {
  309. std::lock_guard<std::mutex> l(peersByVirtAddr_l);
  310. auto sources = peersByVirtAddr.find(source);
  311. if (sources != peersByVirtAddr.end()) {
  312. for(auto a=sources->second.begin();a!=sources->second.end();++a) {
  313. for(auto b=toAddrs.begin();b!=toAddrs.end();++b) {
  314. if (((*a)->ip6)&&(b->second->ip6)) {
  315. //printf("* introducing %s(%s) to %s(%s)" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),b->second->ip6.toString(ipstr2),dest.toString(astr2));
  316. // Introduce source to destination (V6)
  317. Packet outp(source,self.address(),Packet::VERB_RENDEZVOUS);
  318. outp.append((uint8_t)0);
  319. dest.appendTo(outp);
  320. outp.append((uint16_t)b->second->ip6.port());
  321. outp.append((uint8_t)16);
  322. outp.append((const uint8_t *)b->second->ip6.rawIpData(),16);
  323. outp.armor((*a)->key,true);
  324. sendto(v6s,pkt.data(),pkt.size(),0,(const struct sockaddr *)&((*a)->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  325. // Introduce destination to source (V6)
  326. outp.reset(dest,self.address(),Packet::VERB_RENDEZVOUS);
  327. outp.append((uint8_t)0);
  328. source.appendTo(outp);
  329. outp.append((uint16_t)ip->port());
  330. outp.append((uint8_t)16);
  331. outp.append((const uint8_t *)ip->rawIpData(),16);
  332. outp.armor(b->second->key,true);
  333. sendto(v6s,pkt.data(),pkt.size(),0,(const struct sockaddr *)&(b->second->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  334. } else if (((*a)->ip4)&&(b->second->ip4)) {
  335. //printf("* introducing %s(%s) to %s(%s)" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),b->second->ip4.toString(ipstr2),dest.toString(astr2));
  336. // Introduce source to destination (V4)
  337. Packet outp(source,self.address(),Packet::VERB_RENDEZVOUS);
  338. outp.append((uint8_t)0);
  339. dest.appendTo(outp);
  340. outp.append((uint16_t)b->second->ip4.port());
  341. outp.append((uint8_t)4);
  342. outp.append((const uint8_t *)b->second->ip4.rawIpData(),4);
  343. outp.armor((*a)->key,true);
  344. sendto(v4s,pkt.data(),pkt.size(),0,(const struct sockaddr *)&((*a)->ip4),(socklen_t)sizeof(struct sockaddr_in));
  345. // Introduce destination to source (V4)
  346. outp.reset(dest,self.address(),Packet::VERB_RENDEZVOUS);
  347. outp.append((uint8_t)0);
  348. source.appendTo(outp);
  349. outp.append((uint16_t)ip->port());
  350. outp.append((uint8_t)4);
  351. outp.append((const uint8_t *)ip->rawIpData(),4);
  352. outp.armor(b->second->key,true);
  353. sendto(v4s,pkt.data(),pkt.size(),0,(const struct sockaddr *)&(b->second->ip4),(socklen_t)sizeof(struct sockaddr_in));
  354. }
  355. }
  356. }
  357. }
  358. }
  359. if (fragment) {
  360. if (reinterpret_cast<Packet::Fragment *>(&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. } else {
  365. if (pkt.incrementHops() >= ZT_PROTO_MAX_HOPS) {
  366. printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  367. return;
  368. }
  369. }
  370. for(auto i=toAddrs.begin();i!=toAddrs.end();++i) {
  371. //printf("%s -> %s for %s -> %s" ZT_EOL_S,ip->toString(ipstr),i->first->toString(ipstr2),source.toString(astr),dest.toString(astr2));
  372. 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)));
  373. }
  374. }
  375. //////////////////////////////////////////////////////////////////////////////
  376. //////////////////////////////////////////////////////////////////////////////
  377. static int bindSocket(struct sockaddr *bindAddr)
  378. {
  379. int s = socket(bindAddr->sa_family,SOCK_DGRAM,0);
  380. if (s < 0) {
  381. close(s);
  382. return -1;
  383. }
  384. int f = 1048576;
  385. while (f > 16384) {
  386. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&f,sizeof(f)) == 0)
  387. break;
  388. f -= 16384;
  389. }
  390. f = 1048576;
  391. while (f > 16384) {
  392. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&f,sizeof(f)) == 0)
  393. break;
  394. f -= 16384;
  395. }
  396. if (bindAddr->sa_family == AF_INET6) {
  397. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  398. #ifdef IPV6_MTU_DISCOVER
  399. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  400. #endif
  401. #ifdef IPV6_DONTFRAG
  402. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,&f,sizeof(f));
  403. #endif
  404. }
  405. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  406. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEPORT,(void *)&f,sizeof(f));
  407. f = 1; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(void *)&f,sizeof(f));
  408. #ifdef IP_DONTFRAG
  409. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  410. #endif
  411. #ifdef IP_MTU_DISCOVER
  412. f = IP_PMTUDISC_DONT; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  413. #endif
  414. #ifdef SO_NO_CHECK
  415. if (bindAddr->sa_family == AF_INET) {
  416. f = 1; setsockopt(s,SOL_SOCKET,SO_NO_CHECK,(void *)&f,sizeof(f));
  417. }
  418. #endif
  419. if (bind(s,bindAddr,(bindAddr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
  420. close(s);
  421. return -1;
  422. }
  423. return s;
  424. }
  425. static void shutdownSigHandler(int sig) { run = false; }
  426. int main(int argc,char **argv)
  427. {
  428. signal(SIGTERM,shutdownSigHandler);
  429. signal(SIGINT,shutdownSigHandler);
  430. signal(SIGQUIT,shutdownSigHandler);
  431. signal(SIGPIPE,SIG_IGN);
  432. signal(SIGUSR1,SIG_IGN);
  433. signal(SIGUSR2,SIG_IGN);
  434. signal(SIGCHLD,SIG_IGN);
  435. if (argc < 3) {
  436. printf("Usage: zerotier-root <identity.secret> <config path>" ZT_EOL_S);
  437. return 1;
  438. }
  439. {
  440. std::string myIdStr;
  441. if (!OSUtils::readFile(argv[1],myIdStr)) {
  442. printf("FATAL: cannot read identity.secret at %s" ZT_EOL_S,argv[1]);
  443. return 1;
  444. }
  445. if (!self.fromString(myIdStr.c_str())) {
  446. printf("FATAL: cannot read identity.secret at %s (invalid identity)" ZT_EOL_S,argv[1]);
  447. return 1;
  448. }
  449. if (!self.hasPrivate()) {
  450. printf("FATAL: cannot read identity.secret at %s (missing secret key)" ZT_EOL_S,argv[1]);
  451. return 1;
  452. }
  453. }
  454. {
  455. std::string configStr;
  456. if (!OSUtils::readFile(argv[2],configStr)) {
  457. printf("FATAL: cannot read config file at %s" ZT_EOL_S,argv[2]);
  458. return 1;
  459. }
  460. try {
  461. config = json::parse(configStr);
  462. } catch (std::exception &exc) {
  463. printf("FATAL: config file at %s invalid: %s" ZT_EOL_S,argv[2],exc.what());
  464. return 1;
  465. } catch ( ... ) {
  466. printf("FATAL: config file at %s invalid: unknown exception" ZT_EOL_S,argv[2]);
  467. return 1;
  468. }
  469. if (!config.is_object()) {
  470. printf("FATAL: config file at %s invalid: does not contain a JSON object" ZT_EOL_S,argv[2]);
  471. return 1;
  472. }
  473. }
  474. int port = ZT_DEFAULT_PORT;
  475. try {
  476. int port = config["port"];
  477. if ((port <= 0)||(port > 65535)) {
  478. printf("FATAL: invalid port in config file %d" ZT_EOL_S,port);
  479. return 1;
  480. }
  481. } catch ( ... ) {
  482. port = ZT_DEFAULT_PORT;
  483. }
  484. unsigned int ncores = std::thread::hardware_concurrency();
  485. if (ncores == 0) ncores = 1;
  486. run = true;
  487. std::vector<std::thread> threads;
  488. std::vector<int> sockets;
  489. for(unsigned int tn=0;tn<ncores;++tn) {
  490. struct sockaddr_in6 in6;
  491. memset(&in6,0,sizeof(in6));
  492. in6.sin6_family = AF_INET6;
  493. in6.sin6_port = htons((uint16_t)port);
  494. const int s6 = bindSocket((struct sockaddr *)&in6);
  495. if (s6 < 0) {
  496. std::cout << "ERROR: unable to bind to port " << ZT_DEFAULT_PORT << ZT_EOL_S;
  497. exit(1);
  498. }
  499. struct sockaddr_in in4;
  500. memset(&in4,0,sizeof(in4));
  501. in4.sin_family = AF_INET;
  502. in4.sin_port = htons((uint16_t)port);
  503. const int s4 = bindSocket((struct sockaddr *)&in4);
  504. if (s4 < 0) {
  505. std::cout << "ERROR: unable to bind to port " << ZT_DEFAULT_PORT << ZT_EOL_S;
  506. exit(1);
  507. }
  508. sockets.push_back(s6);
  509. sockets.push_back(s4);
  510. threads.push_back(std::thread([s4,s6]() {
  511. struct sockaddr_in6 in6;
  512. Packet pkt;
  513. memset(&in6,0,sizeof(in6));
  514. for(;;) {
  515. socklen_t sl = sizeof(in6);
  516. const int pl = (int)recvfrom(s6,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in6,&sl);
  517. if (pl > 0) {
  518. if (pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  519. try {
  520. pkt.setSize((unsigned int)pl);
  521. handlePacket(s4,s6,reinterpret_cast<const InetAddress *>(&in6),pkt);
  522. } catch ( ... ) {
  523. char ipstr[128];
  524. printf("* unexpected exception handling packet from %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in6)->toString(ipstr));
  525. }
  526. }
  527. } else {
  528. break;
  529. }
  530. }
  531. }));
  532. threads.push_back(std::thread([s4,s6]() {
  533. struct sockaddr_in in4;
  534. Packet pkt;
  535. memset(&in4,0,sizeof(in4));
  536. for(;;) {
  537. socklen_t sl = sizeof(in4);
  538. const int pl = (int)recvfrom(s4,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in4,&sl);
  539. if (pl > 0) {
  540. if (pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  541. try {
  542. pkt.setSize((unsigned int)pl);
  543. handlePacket(s4,s6,reinterpret_cast<const InetAddress *>(&in4),pkt);
  544. } catch ( ... ) {
  545. char ipstr[128];
  546. printf("* unexpected exception handling packet from %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in4)->toString(ipstr));
  547. }
  548. }
  549. } else {
  550. break;
  551. }
  552. }
  553. }));
  554. }
  555. int64_t lastCleanedMulticastSubscriptions = 0;
  556. int64_t lastCleanedPeers = 0;
  557. while (run) {
  558. peersByIdentity_l.lock();
  559. peersByPhysAddr_l.lock();
  560. printf("*** have %lu peers at %lu physical endpoints" ZT_EOL_S,(unsigned long)peersByIdentity.size(),(unsigned long)peersByPhysAddr.size());
  561. peersByPhysAddr_l.unlock();
  562. peersByIdentity_l.unlock();
  563. sleep(1);
  564. const int64_t now = OSUtils::now();
  565. if ((now - lastCleanedMulticastSubscriptions) > 120000) {
  566. lastCleanedMulticastSubscriptions = now;
  567. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  568. for(auto a=multicastSubscriptions.begin();a!=multicastSubscriptions.end();) {
  569. for(auto b=a->second.begin();b!=a->second.end();) {
  570. for(auto c=b->second.begin();c!=b->second.end();) {
  571. if ((now - c->second) > ZT_MULTICAST_LIKE_EXPIRE)
  572. b->second.erase(c++);
  573. else ++c;
  574. }
  575. if (b->second.empty())
  576. a->second.erase(b++);
  577. else ++b;
  578. }
  579. if (a->second.empty())
  580. multicastSubscriptions.erase(a++);
  581. else ++a;
  582. }
  583. }
  584. if ((now - lastCleanedPeers) > 120000) {
  585. lastCleanedPeers = now;
  586. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  587. for(auto p=peersByIdentity.begin();p!=peersByIdentity.end();) {
  588. if ((now - p->second->lastReceive) > ZT_PEER_ACTIVITY_TIMEOUT) {
  589. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  590. std::lock_guard<std::mutex> pbp_l(peersByPhysAddr_l);
  591. auto pbv = peersByVirtAddr.find(p->second->id.address());
  592. if (pbv != peersByVirtAddr.end()) {
  593. pbv->second.erase(p->second);
  594. if (pbv->second.empty())
  595. peersByVirtAddr.erase(pbv);
  596. }
  597. if (p->second->ip4) {
  598. auto pbp = peersByPhysAddr.find(p->second->ip4);
  599. if (pbp != peersByPhysAddr.end()) {
  600. pbp->second.erase(p->second);
  601. if (pbp->second.empty())
  602. peersByPhysAddr.erase(pbp);
  603. }
  604. }
  605. if (p->second->ip6) {
  606. auto pbp = peersByPhysAddr.find(p->second->ip6);
  607. if (pbp != peersByPhysAddr.end()) {
  608. pbp->second.erase(p->second);
  609. if (pbp->second.empty())
  610. peersByPhysAddr.erase(pbp);
  611. }
  612. }
  613. peersByIdentity.erase(p++);
  614. } else ++p;
  615. }
  616. }
  617. }
  618. for(auto s=sockets.begin();s!=sockets.end();++s) {
  619. shutdown(*s,SHUT_RDWR);
  620. close(*s);
  621. }
  622. for(auto t=threads.begin();t!=threads.end();++t)
  623. t->join();
  624. return 0;
  625. }