root.cpp 30 KB

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