root.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include "../node/Constants.hpp"
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <unistd.h>
  30. #include <string.h>
  31. #include <fcntl.h>
  32. #include <signal.h>
  33. #include <sys/stat.h>
  34. #include <sys/types.h>
  35. #include <sys/socket.h>
  36. #include <sys/select.h>
  37. #include <sys/time.h>
  38. #include <sys/un.h>
  39. #include <sys/ioctl.h>
  40. #include <arpa/inet.h>
  41. #include <netinet/in.h>
  42. #include <netinet/ip.h>
  43. #include <netinet/ip6.h>
  44. #include <netinet/tcp.h>
  45. #include "../node/Packet.hpp"
  46. #include "../node/Utils.hpp"
  47. #include "../node/Address.hpp"
  48. #include "../node/Identity.hpp"
  49. #include "../node/InetAddress.hpp"
  50. #include "../node/Mutex.hpp"
  51. #include "../node/SharedPtr.hpp"
  52. #include "../node/MulticastGroup.hpp"
  53. #include "../osdep/OSUtils.hpp"
  54. #include <string>
  55. #include <thread>
  56. #include <map>
  57. #include <set>
  58. #include <vector>
  59. #include <iostream>
  60. #include <unordered_map>
  61. #include <unordered_set>
  62. #include <vector>
  63. #include <atomic>
  64. #include <mutex>
  65. using namespace ZeroTier;
  66. struct IdentityHasher { ZT_ALWAYS_INLINE std::size_t operator()(const Identity &id) const { return (std::size_t)id.hashCode(); } };
  67. struct AddressHasher { ZT_ALWAYS_INLINE std::size_t operator()(const Address &a) const { return (std::size_t)a.toInt(); } };
  68. struct InetAddressHasher { ZT_ALWAYS_INLINE std::size_t operator()(const InetAddress &ip) const { return (std::size_t)ip.hashCode(); } };
  69. struct MulticastGroupHasher { ZT_ALWAYS_INLINE std::size_t operator()(const MulticastGroup &mg) const { return (std::size_t)mg.hashCode(); } };
  70. struct PeerInfo
  71. {
  72. Identity id;
  73. uint8_t key[32];
  74. InetAddress ip4,ip6;
  75. int64_t lastReceive;
  76. AtomicCounter __refCount;
  77. ZT_ALWAYS_INLINE ~PeerInfo() { Utils::burn(key,sizeof(key)); }
  78. };
  79. static Identity self;
  80. static std::atomic_bool run;
  81. static std::vector< SharedPtr<PeerInfo> > newPeers;
  82. static std::unordered_map< uint64_t,std::unordered_map< MulticastGroup,std::unordered_map< Address,int64_t,AddressHasher >,MulticastGroupHasher > > multicastSubscriptions;
  83. static std::unordered_map< Identity,SharedPtr<PeerInfo>,IdentityHasher > peersByIdentity;
  84. static std::unordered_map< Address,std::set< SharedPtr<PeerInfo> >,AddressHasher > peersByVirtAddr;
  85. static std::unordered_map< InetAddress,std::set< SharedPtr<PeerInfo> >,InetAddressHasher > peersByPhysAddr;
  86. static std::mutex newPeers_l;
  87. static std::mutex multicastSubscriptions_l;
  88. static std::mutex peersByIdentity_l;
  89. static std::mutex peersByVirtAddr_l;
  90. static std::mutex peersByPhysAddr_l;
  91. static void handlePacket(const int sock,const InetAddress *const ip,Packet &pkt)
  92. {
  93. char ipstr[128],ipstr2[128],astr[32],tmpstr[256];
  94. const bool fragment = pkt[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR;
  95. // See if this is destined for us and isn't a fragment / fragmented. (No packets
  96. // understood by the root are fragments/fragmented.)
  97. if ((!fragment)&&(!pkt.fragmented())&&(pkt.destination() == self.address())) {
  98. SharedPtr<PeerInfo> peer;
  99. // If this is an un-encrypted HELLO, either learn a new peer or verify
  100. // that this is a peer we already know.
  101. if ((pkt.cipher() == ZT_PROTO_CIPHER_SUITE__POLY1305_NONE)&&(pkt.verb() == Packet::VERB_HELLO)) {
  102. Identity id;
  103. if (id.deserialize(pkt,ZT_PROTO_VERB_HELLO_IDX_IDENTITY)) {
  104. {
  105. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  106. auto pById = peersByIdentity.find(id);
  107. if (pById != peersByIdentity.end()) {
  108. peer = pById->second;
  109. //printf("%s has %s (known (1))" ZT_EOL_S,ip->toString(ipstr),pkt.source().toString(astr));
  110. }
  111. }
  112. if (peer) {
  113. if (!pkt.dearmor(peer->key)) {
  114. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  115. return;
  116. }
  117. } else {
  118. peer.set(new PeerInfo);
  119. if (self.agree(id,peer->key)) {
  120. if (pkt.dearmor(peer->key)) {
  121. peer->id = id;
  122. {
  123. std::lock_guard<std::mutex> np_l(newPeers_l);
  124. newPeers.push_back(peer);
  125. }
  126. {
  127. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  128. peersByIdentity.emplace(id,peer);
  129. }
  130. {
  131. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  132. peersByVirtAddr[id.address()].emplace(peer);
  133. }
  134. } else {
  135. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  136. return;
  137. }
  138. } else {
  139. printf("%s HELLO rejected: key agreement failed" ZT_EOL_S,ip->toString(ipstr));
  140. return;
  141. }
  142. }
  143. }
  144. }
  145. // If it wasn't a HELLO, check to see if any known identities for the sender's
  146. // short ZT address successfully decrypt the packet.
  147. if (!peer) {
  148. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  149. auto peers = peersByVirtAddr.find(pkt.source());
  150. if (peers != peersByVirtAddr.end()) {
  151. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  152. if (pkt.dearmor((*p)->key)) {
  153. peer = (*p);
  154. //printf("%s has %s (known (2))" ZT_EOL_S,ip->toString(ipstr),pkt.source().toString(astr));
  155. break;
  156. }
  157. }
  158. }
  159. }
  160. // If we found the peer, update IP and/or time.
  161. if (peer) {
  162. InetAddress *const peerIp = (ip->ss_family == AF_INET) ? &(peer->ip4) : &(peer->ip6);
  163. if (*peerIp != ip) {
  164. std::lock_guard<std::mutex> pbp_l(peersByPhysAddr_l);
  165. if (*peerIp) {
  166. auto prev = peersByPhysAddr.find(*peerIp);
  167. if (prev != peersByPhysAddr.end()) {
  168. prev->second.erase(peer);
  169. if (prev->second.empty())
  170. peersByPhysAddr.erase(prev);
  171. }
  172. }
  173. *peerIp = ip;
  174. peersByPhysAddr[ip].emplace(peer);
  175. }
  176. const int64_t now = OSUtils::now();
  177. peer->lastReceive = now;
  178. switch(pkt.verb()) {
  179. case Packet::VERB_HELLO: {
  180. const uint64_t origId = pkt.packetId();
  181. const uint64_t ts = pkt.template at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  182. pkt.reset(pkt.source(),self.address(),Packet::VERB_OK);
  183. pkt.append((uint8_t)Packet::VERB_HELLO);
  184. pkt.append(origId);
  185. pkt.append(ts);
  186. pkt.append((uint8_t)ZT_PROTO_VERSION);
  187. pkt.append((uint8_t)0);
  188. pkt.append((uint8_t)0);
  189. pkt.append((uint16_t)0);
  190. ip->serialize(pkt);
  191. pkt.armor(peer->key,true);
  192. sendto(sock,pkt.data(),pkt.size(),0,(const struct sockaddr *)ip,(socklen_t)((ip->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  193. //printf("%s <- OK(HELLO)" ZT_EOL_S,ip->toString(ipstr));
  194. } break;
  195. case Packet::VERB_MULTICAST_LIKE: {
  196. printf("LIKE\n");
  197. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  198. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;(ptr+18)<=pkt.size();ptr+=18) {
  199. const uint64_t nwid = pkt.template at<uint64_t>(ptr);
  200. const MulticastGroup mg(MAC(pkt.field(ptr + 8,6),6),pkt.template at<uint32_t>(ptr + 14));
  201. multicastSubscriptions[nwid][mg][peer->id.address()] = now;
  202. printf("%s subscribes to %s/%.8lx on network %.16llx" ZT_EOL_S,ip->toString(ipstr),mg.mac().toString(tmpstr),(unsigned long)mg.adi(),(unsigned long long)nwid);
  203. }
  204. } break;
  205. case Packet::VERB_MULTICAST_GATHER: {
  206. const uint64_t nwid = pkt.template at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  207. const unsigned int flags = pkt[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  208. 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));
  209. unsigned int gatherLimit = pkt.template at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  210. if (gatherLimit > 255)
  211. gatherLimit = 255;
  212. const uint64_t origId = pkt.packetId();
  213. pkt.reset(pkt.source(),self.address(),Packet::VERB_OK);
  214. pkt.append((uint8_t)Packet::VERB_MULTICAST_GATHER);
  215. pkt.append(origId);
  216. pkt.append(nwid);
  217. mg.mac().appendTo(pkt);
  218. pkt.append((uint32_t)mg.adi());
  219. {
  220. std::lock_guard<std::mutex> l(multicastSubscriptions_l);
  221. auto forNet = multicastSubscriptions.find(nwid);
  222. if (forNet != multicastSubscriptions.end()) {
  223. auto forGroup = forNet->second.find(mg);
  224. if (forGroup != forNet->second.end()) {
  225. pkt.append((uint32_t)forGroup->second.size());
  226. pkt.append((uint16_t)std::min(std::min((unsigned int)forGroup->second.size(),(unsigned int)65535),gatherLimit));
  227. auto g = forGroup->second.begin();
  228. unsigned int l = 0;
  229. for(;((l<gatherLimit)&&(g!=forGroup->second.end()));++l,++g)
  230. g->first.appendTo(pkt);
  231. if (l > 0) {
  232. sendto(sock,pkt.data(),pkt.size(),0,(const struct sockaddr *)ip,(socklen_t)((ip->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  233. printf("%s gathered %u subscribers to %s/%.8lx on network %.16llx" ZT_EOL_S,ip->toString(ipstr),l,mg.mac().toString(tmpstr),(unsigned long)mg.adi(),(unsigned long long)nwid);
  234. }
  235. }
  236. }
  237. }
  238. } break;
  239. default:
  240. break;
  241. }
  242. return;
  243. }
  244. }
  245. std::vector<InetAddress> toAddrs;
  246. {
  247. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  248. auto peers = peersByVirtAddr.find(pkt.destination());
  249. if (peers != peersByVirtAddr.end()) {
  250. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  251. if ((*p)->ip6)
  252. toAddrs.push_back((*p)->ip6);
  253. else if ((*p)->ip4)
  254. toAddrs.push_back((*p)->ip4);
  255. }
  256. }
  257. }
  258. if (toAddrs.empty()) {
  259. printf("%s not forwarding to %s: no destinations found" ZT_EOL_S,ip->toString(ipstr),pkt.destination().toString(astr));
  260. return;
  261. }
  262. if (fragment) {
  263. if (reinterpret_cast<Packet::Fragment *>(&pkt)->incrementHops() >= ZT_PROTO_MAX_HOPS) {
  264. printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),pkt.destination().toString(astr));
  265. return;
  266. }
  267. } else {
  268. if (pkt.incrementHops() >= ZT_PROTO_MAX_HOPS) {
  269. printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),pkt.destination().toString(astr));
  270. return;
  271. }
  272. }
  273. for(auto i=toAddrs.begin();i!=toAddrs.end();++i) {
  274. printf("%s -> %s for %s" ZT_EOL_S,ip->toString(ipstr),i->toString(ipstr2),pkt.destination().toString(astr));
  275. sendto(sock,pkt.data(),pkt.size(),0,(const struct sockaddr *)&(*i),(socklen_t)((i->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  276. }
  277. }
  278. static int bindSocket(struct sockaddr *bindAddr)
  279. {
  280. int s = socket(bindAddr->sa_family,SOCK_DGRAM,0);
  281. if (s < 0) {
  282. close(s);
  283. return -1;
  284. }
  285. int f = 131072;
  286. setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&f,sizeof(f));
  287. f = 131072;
  288. setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&f,sizeof(f));
  289. if (bindAddr->sa_family == AF_INET6) {
  290. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  291. #ifdef IPV6_MTU_DISCOVER
  292. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  293. #endif
  294. #ifdef IPV6_DONTFRAG
  295. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,&f,sizeof(f));
  296. #endif
  297. }
  298. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  299. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEPORT,(void *)&f,sizeof(f));
  300. f = 1; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(void *)&f,sizeof(f));
  301. #ifdef IP_DONTFRAG
  302. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  303. #endif
  304. #ifdef IP_MTU_DISCOVER
  305. f = IP_PMTUDISC_DONT; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  306. #endif
  307. #ifdef SO_NO_CHECK
  308. if (bindAddr->sa_family == AF_INET) {
  309. f = 1; setsockopt(s,SOL_SOCKET,SO_NO_CHECK,(void *)&f,sizeof(f));
  310. }
  311. #endif
  312. if (bind(s,bindAddr,(bindAddr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
  313. close(s);
  314. return -1;
  315. }
  316. return s;
  317. }
  318. void shutdownSigHandler(int sig)
  319. {
  320. run = false;
  321. }
  322. int main(int argc,char **argv)
  323. {
  324. signal(SIGTERM,shutdownSigHandler);
  325. signal(SIGINT,shutdownSigHandler);
  326. signal(SIGQUIT,shutdownSigHandler);
  327. signal(SIGPIPE,SIG_IGN);
  328. signal(SIGUSR1,SIG_IGN);
  329. signal(SIGUSR2,SIG_IGN);
  330. if (argc < 2) {
  331. printf("Usage: zerotier-root <identity.secret> [<port>]" ZT_EOL_S);
  332. return 1;
  333. }
  334. std::string myIdStr;
  335. if (!OSUtils::readFile(argv[1],myIdStr)) {
  336. printf("FATAL: cannot read identity.secret at %s" ZT_EOL_S,argv[1]);
  337. return 1;
  338. }
  339. if (!self.fromString(myIdStr.c_str())) {
  340. printf("FATAL: cannot read identity.secret at %s (invalid identity)" ZT_EOL_S,argv[1]);
  341. return 1;
  342. }
  343. if (!self.hasPrivate()) {
  344. printf("FATAL: cannot read identity.secret at %s (missing secret key)" ZT_EOL_S,argv[1]);
  345. return 1;
  346. }
  347. unsigned int ncores = std::thread::hardware_concurrency();
  348. if (ncores == 0) ncores = 1;
  349. run = true;
  350. std::vector<int> sockets;
  351. std::vector<std::thread> threads;
  352. for(unsigned int tn=0;tn<ncores;++tn) {
  353. struct sockaddr_in6 in6;
  354. memset(&in6,0,sizeof(in6));
  355. in6.sin6_family = AF_INET6;
  356. in6.sin6_port = htons(ZT_DEFAULT_PORT);
  357. const int s6 = bindSocket((struct sockaddr *)&in6);
  358. if (s6 < 0) {
  359. std::cout << "ERROR: unable to bind to port " << ZT_DEFAULT_PORT << ZT_EOL_S;
  360. exit(1);
  361. }
  362. struct sockaddr_in in4;
  363. memset(&in4,0,sizeof(in4));
  364. in4.sin_family = AF_INET;
  365. in4.sin_port = htons(ZT_DEFAULT_PORT);
  366. const int s4 = bindSocket((struct sockaddr *)&in4);
  367. if (s4 < 0) {
  368. std::cout << "ERROR: unable to bind to port " << ZT_DEFAULT_PORT << ZT_EOL_S;
  369. exit(1);
  370. }
  371. sockets.push_back(s6);
  372. sockets.push_back(s4);
  373. threads.push_back(std::thread([s6]() {
  374. struct sockaddr_in6 in6;
  375. Packet pkt;
  376. memset(&in6,0,sizeof(in6));
  377. for(;;) {
  378. socklen_t sl = sizeof(in6);
  379. const int pl = (int)recvfrom(s6,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in6,&sl);
  380. if (pl > 0) {
  381. try {
  382. pkt.setSize((unsigned int)pl);
  383. handlePacket(s6,reinterpret_cast<const InetAddress *>(&in6),pkt);
  384. } catch ( ... ) {
  385. printf("* unexpected exception" ZT_EOL_S);
  386. }
  387. } else {
  388. break;
  389. }
  390. }
  391. }));
  392. threads.push_back(std::thread([s4]() {
  393. struct sockaddr_in in4;
  394. Packet pkt;
  395. memset(&in4,0,sizeof(in4));
  396. for(;;) {
  397. socklen_t sl = sizeof(in4);
  398. const int pl = (int)recvfrom(s4,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in4,&sl);
  399. if (pl > 0) {
  400. try {
  401. pkt.setSize((unsigned int)pl);
  402. handlePacket(s4,reinterpret_cast<const InetAddress *>(&in4),pkt);
  403. } catch ( ... ) {
  404. printf("* unexpected exception" ZT_EOL_S);
  405. }
  406. } else {
  407. break;
  408. }
  409. }
  410. }));
  411. }
  412. while (run) {
  413. peersByIdentity_l.lock();
  414. printf("* have %lu peers" ZT_EOL_S,(unsigned long)peersByIdentity.size());
  415. peersByIdentity_l.unlock();
  416. sleep(1);
  417. }
  418. for(auto s=sockets.begin();s!=sockets.end();++s) {
  419. shutdown(*s,SHUT_RDWR);
  420. close(*s);
  421. }
  422. for(auto t=threads.begin();t!=threads.end();++t)
  423. t->join();
  424. return 0;
  425. }