root.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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()));++g) {
  319. if (g->first != source) {
  320. ++l;
  321. g->first.appendTo(pkt);
  322. }
  323. }
  324. if (l > 0) {
  325. pkt.setAt<uint16_t>(countAt,(uint16_t)l);
  326. pkt.armor(peer->key,true);
  327. 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)));
  328. peer->lastSend = now;
  329. //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);
  330. }
  331. }
  332. }
  333. }
  334. } catch ( ... ) {
  335. printf("* unexpected exception handling MULTICAST_GATHER from %s" ZT_EOL_S,ip->toString(ipstr));
  336. }
  337. break;
  338. default:
  339. break;
  340. }
  341. return;
  342. }
  343. }
  344. // If we made it here, we are forwarding this packet to someone else and also possibly
  345. // sending a RENDEZVOUS message.
  346. bool introduce = false;
  347. if (!fragment) {
  348. RendezvousKey rk(source,dest);
  349. std::lock_guard<std::mutex> l(lastRendezvous_l);
  350. int64_t &lr = lastRendezvous[rk];
  351. if ((now - lr) >= 45000) {
  352. lr = now;
  353. introduce = true;
  354. }
  355. }
  356. std::vector< std::pair< InetAddress *,SharedPtr<RootPeer> > > toAddrs;
  357. {
  358. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  359. auto peers = peersByVirtAddr.find(dest);
  360. if (peers != peersByVirtAddr.end()) {
  361. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  362. if ((*p)->ip4) {
  363. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*p)->ip4),*p));
  364. } else if ((*p)->ip6) {
  365. toAddrs.push_back(std::pair< InetAddress *,SharedPtr<RootPeer> >(&((*p)->ip6),*p));
  366. }
  367. }
  368. }
  369. }
  370. if (toAddrs.empty()) {
  371. //printf("%s not forwarding to %s: no destinations found" ZT_EOL_S,ip->toString(ipstr),dest().toString(astr));
  372. return;
  373. }
  374. if (introduce) {
  375. std::lock_guard<std::mutex> l(peersByVirtAddr_l);
  376. auto sources = peersByVirtAddr.find(source);
  377. if (sources != peersByVirtAddr.end()) {
  378. for(auto a=sources->second.begin();a!=sources->second.end();++a) {
  379. for(auto b=toAddrs.begin();b!=toAddrs.end();++b) {
  380. if (((*a)->ip6)&&(b->second->ip6)) {
  381. //printf("* introducing %s(%s) to %s(%s)" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),b->second->ip6.toString(ipstr2),dest.toString(astr2));
  382. // Introduce source to destination (V6)
  383. Packet outp(source,self.address(),Packet::VERB_RENDEZVOUS);
  384. outp.append((uint8_t)0);
  385. dest.appendTo(outp);
  386. outp.append((uint16_t)b->second->ip6.port());
  387. outp.append((uint8_t)16);
  388. outp.append((const uint8_t *)b->second->ip6.rawIpData(),16);
  389. outp.armor((*a)->key,true);
  390. sendto(v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&((*a)->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  391. (*a)->lastSend = now;
  392. // Introduce destination to source (V6)
  393. outp.reset(dest,self.address(),Packet::VERB_RENDEZVOUS);
  394. outp.append((uint8_t)0);
  395. source.appendTo(outp);
  396. outp.append((uint16_t)ip->port());
  397. outp.append((uint8_t)16);
  398. outp.append((const uint8_t *)ip->rawIpData(),16);
  399. outp.armor(b->second->key,true);
  400. sendto(v6s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&(b->second->ip6),(socklen_t)sizeof(struct sockaddr_in6));
  401. b->second->lastSend = now;
  402. }
  403. if (((*a)->ip4)&&(b->second->ip4)) {
  404. //printf("* introducing %s(%s) to %s(%s)" ZT_EOL_S,ip->toString(ipstr),source.toString(astr),b->second->ip4.toString(ipstr2),dest.toString(astr2));
  405. // Introduce source to destination (V4)
  406. Packet outp(source,self.address(),Packet::VERB_RENDEZVOUS);
  407. outp.append((uint8_t)0);
  408. dest.appendTo(outp);
  409. outp.append((uint16_t)b->second->ip4.port());
  410. outp.append((uint8_t)4);
  411. outp.append((const uint8_t *)b->second->ip4.rawIpData(),4);
  412. outp.armor((*a)->key,true);
  413. sendto(v4s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&((*a)->ip4),(socklen_t)sizeof(struct sockaddr_in));
  414. (*a)->lastSend = now;
  415. // Introduce destination to source (V4)
  416. outp.reset(dest,self.address(),Packet::VERB_RENDEZVOUS);
  417. outp.append((uint8_t)0);
  418. source.appendTo(outp);
  419. outp.append((uint16_t)ip->port());
  420. outp.append((uint8_t)4);
  421. outp.append((const uint8_t *)ip->rawIpData(),4);
  422. outp.armor(b->second->key,true);
  423. sendto(v4s,outp.data(),outp.size(),SENDTO_FLAGS,(const struct sockaddr *)&(b->second->ip4),(socklen_t)sizeof(struct sockaddr_in));
  424. b->second->lastSend = now;
  425. }
  426. }
  427. }
  428. }
  429. }
  430. if (fragment) {
  431. if (reinterpret_cast<Packet::Fragment *>(&pkt)->incrementHops() >= ZT_PROTO_MAX_HOPS) {
  432. printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  433. return;
  434. }
  435. } else {
  436. if (pkt.incrementHops() >= ZT_PROTO_MAX_HOPS) {
  437. printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),dest.toString(astr));
  438. return;
  439. }
  440. }
  441. for(auto i=toAddrs.begin();i!=toAddrs.end();++i) {
  442. //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());
  443. 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) {
  444. printf("* write error forwarding packet to %s: %s" ZT_EOL_S,i->first->toString(ipstr),strerror(errno));
  445. } else {
  446. i->second->lastSend = now;
  447. }
  448. }
  449. }
  450. //////////////////////////////////////////////////////////////////////////////
  451. //////////////////////////////////////////////////////////////////////////////
  452. static int bindSocket(struct sockaddr *const bindAddr)
  453. {
  454. const int s = socket(bindAddr->sa_family,SOCK_DGRAM,0);
  455. if (s < 0) {
  456. close(s);
  457. return -1;
  458. }
  459. int f = 1048576;
  460. while (f > 16384) {
  461. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&f,sizeof(f)) == 0)
  462. break;
  463. f -= 16384;
  464. }
  465. f = 1048576;
  466. while (f > 16384) {
  467. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&f,sizeof(f)) == 0)
  468. break;
  469. f -= 16384;
  470. }
  471. if (bindAddr->sa_family == AF_INET6) {
  472. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  473. #ifdef IPV6_MTU_DISCOVER
  474. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  475. #endif
  476. #ifdef IPV6_DONTFRAG
  477. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,&f,sizeof(f));
  478. #endif
  479. }
  480. #ifdef IP_DONTFRAG
  481. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  482. #endif
  483. #ifdef IP_MTU_DISCOVER
  484. f = IP_PMTUDISC_DONT; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  485. #endif
  486. #ifdef SO_NO_CHECK
  487. if (bindAddr->sa_family == AF_INET) {
  488. f = 1; setsockopt(s,SOL_SOCKET,SO_NO_CHECK,(void *)&f,sizeof(f));
  489. }
  490. #endif
  491. #if defined(SO_REUSEPORT)
  492. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEPORT,(void *)&f,sizeof(f));
  493. #endif
  494. #ifndef __LINUX__ // linux wants just SO_REUSEPORT
  495. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  496. #endif
  497. if (bind(s,bindAddr,(bindAddr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
  498. close(s);
  499. //printf("%s\n",strerror(errno));
  500. return -1;
  501. }
  502. return s;
  503. }
  504. static void shutdownSigHandler(int sig) { run = false; }
  505. int main(int argc,char **argv)
  506. {
  507. signal(SIGTERM,shutdownSigHandler);
  508. signal(SIGINT,shutdownSigHandler);
  509. signal(SIGQUIT,shutdownSigHandler);
  510. signal(SIGPIPE,SIG_IGN);
  511. signal(SIGUSR1,SIG_IGN);
  512. signal(SIGUSR2,SIG_IGN);
  513. signal(SIGCHLD,SIG_IGN);
  514. if (argc < 3) {
  515. printf("Usage: zerotier-root <identity.secret> <config path>" ZT_EOL_S);
  516. return 1;
  517. }
  518. {
  519. std::string myIdStr;
  520. if (!OSUtils::readFile(argv[1],myIdStr)) {
  521. printf("FATAL: cannot read identity.secret at %s" ZT_EOL_S,argv[1]);
  522. return 1;
  523. }
  524. if (!self.fromString(myIdStr.c_str())) {
  525. printf("FATAL: cannot read identity.secret at %s (invalid identity)" ZT_EOL_S,argv[1]);
  526. return 1;
  527. }
  528. if (!self.hasPrivate()) {
  529. printf("FATAL: cannot read identity.secret at %s (missing secret key)" ZT_EOL_S,argv[1]);
  530. return 1;
  531. }
  532. }
  533. {
  534. std::string configStr;
  535. if (!OSUtils::readFile(argv[2],configStr)) {
  536. printf("FATAL: cannot read config file at %s" ZT_EOL_S,argv[2]);
  537. return 1;
  538. }
  539. try {
  540. config = json::parse(configStr);
  541. } catch (std::exception &exc) {
  542. printf("FATAL: config file at %s invalid: %s" ZT_EOL_S,argv[2],exc.what());
  543. return 1;
  544. } catch ( ... ) {
  545. printf("FATAL: config file at %s invalid: unknown exception" ZT_EOL_S,argv[2]);
  546. return 1;
  547. }
  548. if (!config.is_object()) {
  549. printf("FATAL: config file at %s invalid: does not contain a JSON object" ZT_EOL_S,argv[2]);
  550. return 1;
  551. }
  552. }
  553. int port = ZT_DEFAULT_PORT;
  554. int httpPort = ZT_DEFAULT_PORT;
  555. try {
  556. port = config["port"];
  557. if ((port <= 0)||(port > 65535)) {
  558. printf("FATAL: invalid port in config file %d" ZT_EOL_S,port);
  559. return 1;
  560. }
  561. } catch ( ... ) {
  562. port = ZT_DEFAULT_PORT;
  563. }
  564. try {
  565. httpPort = config["httpPort"];
  566. if ((httpPort <= 0)||(httpPort > 65535)) {
  567. printf("FATAL: invalid HTTP port in config file %d" ZT_EOL_S,httpPort);
  568. return 1;
  569. }
  570. } catch ( ... ) {
  571. httpPort = ZT_DEFAULT_PORT;
  572. }
  573. try {
  574. statsRoot = config["statsRoot"];
  575. while ((statsRoot.length() > 0)&&(statsRoot[statsRoot.length()-1] == ZT_PATH_SEPARATOR))
  576. statsRoot = statsRoot.substr(0,statsRoot.length()-1);
  577. if (statsRoot.length() > 0)
  578. OSUtils::mkdir(statsRoot);
  579. } catch ( ... ) {
  580. statsRoot = "";
  581. }
  582. unsigned int ncores = std::thread::hardware_concurrency();
  583. if (ncores == 0) ncores = 1;
  584. run = true;
  585. std::vector<std::thread> threads;
  586. std::vector<int> sockets;
  587. for(unsigned int tn=0;tn<ncores;++tn) {
  588. struct sockaddr_in6 in6;
  589. memset(&in6,0,sizeof(in6));
  590. in6.sin6_family = AF_INET6;
  591. in6.sin6_port = htons((uint16_t)port);
  592. const int s6 = bindSocket((struct sockaddr *)&in6);
  593. if (s6 < 0) {
  594. std::cout << "ERROR: unable to bind to port " << port << ZT_EOL_S;
  595. exit(1);
  596. }
  597. struct sockaddr_in in4;
  598. memset(&in4,0,sizeof(in4));
  599. in4.sin_family = AF_INET;
  600. in4.sin_port = htons((uint16_t)port);
  601. const int s4 = bindSocket((struct sockaddr *)&in4);
  602. if (s4 < 0) {
  603. std::cout << "ERROR: unable to bind to port " << port << ZT_EOL_S;
  604. exit(1);
  605. }
  606. sockets.push_back(s6);
  607. sockets.push_back(s4);
  608. threads.push_back(std::thread([s6,s4]() {
  609. struct sockaddr_in6 in6;
  610. Packet pkt;
  611. memset(&in6,0,sizeof(in6));
  612. for(;;) {
  613. socklen_t sl = sizeof(in6);
  614. const int pl = (int)recvfrom(s6,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in6,&sl);
  615. if (pl > 0) {
  616. if (pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  617. try {
  618. pkt.setSize((unsigned int)pl);
  619. handlePacket(s4,s6,reinterpret_cast<const InetAddress *>(&in6),pkt);
  620. } catch ( ... ) {
  621. char ipstr[128];
  622. printf("* unexpected exception handling packet from %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in6)->toString(ipstr));
  623. }
  624. }
  625. } else {
  626. break;
  627. }
  628. }
  629. }));
  630. threads.push_back(std::thread([s6,s4]() {
  631. struct sockaddr_in in4;
  632. Packet pkt;
  633. memset(&in4,0,sizeof(in4));
  634. for(;;) {
  635. socklen_t sl = sizeof(in4);
  636. const int pl = (int)recvfrom(s4,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in4,&sl);
  637. if (pl > 0) {
  638. if (pl >= ZT_PROTO_MIN_FRAGMENT_LENGTH) {
  639. try {
  640. pkt.setSize((unsigned int)pl);
  641. handlePacket(s4,s6,reinterpret_cast<const InetAddress *>(&in4),pkt);
  642. } catch ( ... ) {
  643. char ipstr[128];
  644. printf("* unexpected exception handling packet from %s" ZT_EOL_S,reinterpret_cast<const InetAddress *>(&in4)->toString(ipstr));
  645. }
  646. }
  647. } else {
  648. break;
  649. }
  650. }
  651. }));
  652. }
  653. httplib::Server apiServ;
  654. threads.push_back(std::thread([&apiServ,httpPort]() {
  655. apiServ.Get("/",[](const httplib::Request &req,httplib::Response &res) {
  656. std::ostringstream o;
  657. std::lock_guard<std::mutex> l0(peersByIdentity_l);
  658. std::lock_guard<std::mutex> l1(peersByPhysAddr_l);
  659. o << "ZeroTier Root Server " << ZEROTIER_ONE_VERSION_MAJOR << '.' << ZEROTIER_ONE_VERSION_MINOR << '.' << ZEROTIER_ONE_VERSION_REVISION << ZT_EOL_S;
  660. o << "(c)2019 ZeroTier, Inc." ZT_EOL_S "Licensed under the ZeroTier BSL 1.1" ZT_EOL_S ZT_EOL_S;
  661. o << "Peers Online: " << peersByIdentity.size() << ZT_EOL_S;
  662. o << "Physical Addresses: " << peersByPhysAddr.size() << ZT_EOL_S;
  663. res.set_content(o.str(),"text/plain");
  664. });
  665. apiServ.Get("/peer",[](const httplib::Request &req,httplib::Response &res) {
  666. char tmp[256];
  667. std::ostringstream o;
  668. o << '[';
  669. {
  670. bool first = true;
  671. std::lock_guard<std::mutex> l(peersByIdentity_l);
  672. for(auto p=peersByIdentity.begin();p!=peersByIdentity.end();++p) {
  673. if (first)
  674. first = false;
  675. else o << ',';
  676. o <<
  677. "{\"address\":\"" << p->first.address().toString(tmp) << "\""
  678. ",\"latency\":-1"
  679. ",\"paths\":[";
  680. if (p->second->ip4) {
  681. o <<
  682. "{\"active\":true"
  683. ",\"address\":\"" << p->second->ip4.toIpString(tmp) << "\\/" << p->second->ip4.port() << "\""
  684. ",\"expired\":false"
  685. ",\"lastReceive\":" << p->second->lastReceive <<
  686. ",\"lastSend\":" << p->second->lastSend <<
  687. ",\"preferred\":true"
  688. ",\"trustedPathId\":0}";
  689. }
  690. if (p->second->ip6) {
  691. if (p->second->ip4)
  692. o << ',';
  693. o <<
  694. "{\"active\":true"
  695. ",\"address\":\"" << p->second->ip6.toIpString(tmp) << "\\/" << p->second->ip6.port() << "\""
  696. ",\"expired\":false"
  697. ",\"lastReceive\":" << p->second->lastReceive <<
  698. ",\"lastSend\":" << p->second->lastSend <<
  699. ",\"preferred\":" << ((p->second->ip4) ? "false" : "true") <<
  700. ",\"trustedPathId\":0}";
  701. }
  702. o << "]"
  703. ",\"role\":\"LEAF\""
  704. ",\"version\":\"" << p->second->vMajor << '.' << p->second->vMinor << '.' << p->second->vRev << "\""
  705. ",\"versionMajor\":" << p->second->vMajor <<
  706. ",\"versionMinor\":" << p->second->vMinor <<
  707. ",\"versionRev\":" << p->second->vRev << "}";
  708. }
  709. }
  710. o << ']';
  711. res.set_content(o.str(),"application/json");
  712. });
  713. apiServ.listen("127.0.0.1",httpPort,0);
  714. }));
  715. int64_t lastCleanedMulticastSubscriptions = 0;
  716. int64_t lastCleanedPeers = 0;
  717. int64_t lastWroteStats = 0;
  718. while (run) {
  719. //peersByIdentity_l.lock();
  720. //peersByPhysAddr_l.lock();
  721. //printf("*** have %lu peers at %lu physical endpoints" ZT_EOL_S,(unsigned long)peersByIdentity.size(),(unsigned long)peersByPhysAddr.size());
  722. //peersByPhysAddr_l.unlock();
  723. //peersByIdentity_l.unlock();
  724. sleep(1);
  725. const int64_t now = OSUtils::now();
  726. if ((now - lastCleanedMulticastSubscriptions) > 120000) {
  727. lastCleanedMulticastSubscriptions = now;
  728. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  729. for(auto a=multicastSubscriptions.begin();a!=multicastSubscriptions.end();) {
  730. for(auto b=a->second.begin();b!=a->second.end();) {
  731. for(auto c=b->second.begin();c!=b->second.end();) {
  732. if ((now - c->second) > ZT_MULTICAST_LIKE_EXPIRE)
  733. b->second.erase(c++);
  734. else ++c;
  735. }
  736. if (b->second.empty())
  737. a->second.erase(b++);
  738. else ++b;
  739. }
  740. if (a->second.empty())
  741. multicastSubscriptions.erase(a++);
  742. else ++a;
  743. }
  744. }
  745. if ((now - lastCleanedPeers) > 120000) {
  746. lastCleanedPeers = now;
  747. {
  748. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  749. for(auto p=peersByIdentity.begin();p!=peersByIdentity.end();) {
  750. if ((now - p->second->lastReceive) > ZT_PEER_ACTIVITY_TIMEOUT) {
  751. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  752. std::lock_guard<std::mutex> pbp_l(peersByPhysAddr_l);
  753. auto pbv = peersByVirtAddr.find(p->second->id.address());
  754. if (pbv != peersByVirtAddr.end()) {
  755. pbv->second.erase(p->second);
  756. if (pbv->second.empty())
  757. peersByVirtAddr.erase(pbv);
  758. }
  759. if (p->second->ip4) {
  760. auto pbp = peersByPhysAddr.find(p->second->ip4);
  761. if (pbp != peersByPhysAddr.end()) {
  762. pbp->second.erase(p->second);
  763. if (pbp->second.empty())
  764. peersByPhysAddr.erase(pbp);
  765. }
  766. }
  767. if (p->second->ip6) {
  768. auto pbp = peersByPhysAddr.find(p->second->ip6);
  769. if (pbp != peersByPhysAddr.end()) {
  770. pbp->second.erase(p->second);
  771. if (pbp->second.empty())
  772. peersByPhysAddr.erase(pbp);
  773. }
  774. }
  775. peersByIdentity.erase(p++);
  776. } else ++p;
  777. }
  778. }
  779. {
  780. std::lock_guard<std::mutex> l(lastRendezvous_l);
  781. for(auto lr=lastRendezvous.begin();lr!=lastRendezvous.end();) {
  782. if ((now - lr->second) > ZT_PEER_ACTIVITY_TIMEOUT)
  783. lastRendezvous.erase(lr++);
  784. else ++lr;
  785. }
  786. }
  787. }
  788. if (((now - lastWroteStats) > 15000)&&(statsRoot.length() > 0)) {
  789. lastWroteStats = now;
  790. std::string peersFilePath(statsRoot);
  791. peersFilePath.append("/peers.tmp");
  792. FILE *pf = fopen(peersFilePath.c_str(),"wb");
  793. if (pf) {
  794. std::vector< SharedPtr<RootPeer> > sp;
  795. {
  796. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  797. sp.reserve(peersByIdentity.size());
  798. for(auto p=peersByIdentity.begin();p!=peersByIdentity.end();++p) {
  799. sp.push_back(p->second);
  800. }
  801. }
  802. std::sort(sp.begin(),sp.end(),[](const SharedPtr<RootPeer> &a,const SharedPtr<RootPeer> &b) { return (a->id < b->id); });
  803. char ip4[128],ip6[128];
  804. for(auto p=sp.begin();p!=sp.end();++p) {
  805. if ((*p)->ip4) {
  806. (*p)->ip4.toString(ip4);
  807. } else {
  808. ip4[0] = '-';
  809. ip4[1] = 0;
  810. }
  811. if ((*p)->ip6) {
  812. (*p)->ip6.toString(ip6);
  813. } else {
  814. ip6[0] = '-';
  815. ip6[1] = 0;
  816. }
  817. 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);
  818. }
  819. fclose(pf);
  820. std::string peersFilePath2(statsRoot);
  821. peersFilePath2.append("/peers");
  822. OSUtils::rm(peersFilePath2);
  823. OSUtils::rename(peersFilePath.c_str(),peersFilePath2.c_str());
  824. }
  825. }
  826. }
  827. apiServ.stop();
  828. for(auto s=sockets.begin();s!=sockets.end();++s) {
  829. shutdown(*s,SHUT_RDWR);
  830. close(*s);
  831. }
  832. for(auto t=threads.begin();t!=threads.end();++t)
  833. t->join();
  834. return 0;
  835. }