root.cpp 27 KB

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