GoGlue.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  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 vergnn 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "GoGlue.h"
  14. #include "../../node/Constants.hpp"
  15. #include "../../node/InetAddress.hpp"
  16. #include "../../node/Node.hpp"
  17. #include "../../node/Utils.hpp"
  18. #include "../../node/MAC.hpp"
  19. #include "../../node/Address.hpp"
  20. #include "../../node/Locator.hpp"
  21. #include "../../osdep/OSUtils.hpp"
  22. #include "../../osdep/EthernetTap.hpp"
  23. #include "../../osdep/ManagedRoute.hpp"
  24. #include <string.h>
  25. #include <stdlib.h>
  26. #include <errno.h>
  27. #ifndef __WINDOWS__
  28. #include <errno.h>
  29. #include <signal.h>
  30. #include <unistd.h>
  31. #include <fcntl.h>
  32. #include <sys/time.h>
  33. #include <sys/types.h>
  34. #include <sys/select.h>
  35. #include <sys/socket.h>
  36. #include <sys/un.h>
  37. #include <arpa/inet.h>
  38. #include <netinet/in.h>
  39. #include <netinet/ip6.h>
  40. #include <netinet/tcp.h>
  41. #ifdef __BSD__
  42. #include <net/if.h>
  43. #endif
  44. #ifdef __LINUX__
  45. #ifndef IPV6_DONTFRAG
  46. #define IPV6_DONTFRAG 62
  47. #endif
  48. #endif
  49. #endif // !__WINDOWS__
  50. #include <thread>
  51. #include <mutex>
  52. #include <map>
  53. #include <vector>
  54. #include <array>
  55. #include <set>
  56. #include <memory>
  57. #include <atomic>
  58. #ifdef __WINDOWS__
  59. #define SETSOCKOPT_FLAG_TYPE BOOL
  60. #define SETSOCKOPT_FLAG_TRUE TRUE
  61. #define SETSOCKOPT_FLAG_FALSE FALSE
  62. #else
  63. #define SETSOCKOPT_FLAG_TYPE int
  64. #define SETSOCKOPT_FLAG_TRUE 1
  65. #define SETSOCKOPT_FLAG_FALSE 0
  66. #endif
  67. #ifndef MSG_DONTWAIT
  68. #define MSG_DONTWAIT 0
  69. #endif
  70. using namespace ZeroTier;
  71. struct ZT_GoNodeThread
  72. {
  73. std::string ip;
  74. int port;
  75. int af;
  76. std::atomic<bool> run;
  77. std::thread thr;
  78. };
  79. struct ZT_GoNode_Impl
  80. {
  81. Node *node;
  82. volatile int64_t nextBackgroundTaskDeadline;
  83. std::string path;
  84. std::atomic<bool> run;
  85. std::map< ZT_SOCKET,ZT_GoNodeThread > threads;
  86. std::mutex threads_l;
  87. std::map< uint64_t,std::shared_ptr<EthernetTap> > taps;
  88. std::mutex taps_l;
  89. std::thread backgroundTaskThread;
  90. };
  91. static const std::string defaultHomePath(OSUtils::platformDefaultHomePath());
  92. const char *ZT_PLATFORM_DEFAULT_HOMEPATH = defaultHomePath.c_str();
  93. /****************************************************************************/
  94. /* These functions are implemented in Go in pkg/ztnode/node-callbacks.go */
  95. extern "C" int goPathCheckFunc(ZT_GoNode *,uint64_t,int,const void *,int);
  96. extern "C" int goPathLookupFunc(ZT_GoNode *,uint64_t,int,int *,uint8_t [16],int *);
  97. extern "C" void goStateObjectPutFunc(ZT_GoNode *,int,const uint64_t [2],const void *,int);
  98. extern "C" int goStateObjectGetFunc(ZT_GoNode *,int,const uint64_t [2],void *,unsigned int);
  99. extern "C" void goDNSResolverFunc(ZT_GoNode *,const uint8_t *,int,const char *,uintptr_t);
  100. extern "C" void goVirtualNetworkConfigFunc(ZT_GoNode *,ZT_GoTap *,uint64_t,int,const ZT_VirtualNetworkConfig *);
  101. extern "C" void goZtEvent(ZT_GoNode *,int,const void *);
  102. extern "C" void goHandleTapAddedMulticastGroup(ZT_GoNode *,ZT_GoTap *,uint64_t,uint64_t,uint32_t);
  103. extern "C" void goHandleTapRemovedMulticastGroup(ZT_GoNode *,ZT_GoTap *,uint64_t,uint64_t,uint32_t);
  104. static void ZT_GoNode_VirtualNetworkConfigFunction(
  105. ZT_Node *node,
  106. void *uptr,
  107. void *tptr,
  108. uint64_t nwid,
  109. void **nptr,
  110. enum ZT_VirtualNetworkConfigOperation op,
  111. const ZT_VirtualNetworkConfig *cfg)
  112. {
  113. goVirtualNetworkConfigFunc(reinterpret_cast<ZT_GoNode *>(uptr),reinterpret_cast<ZT_GoTap *>(*nptr),nwid,op,cfg);
  114. }
  115. static void ZT_GoNode_VirtualNetworkFrameFunction(
  116. ZT_Node *node,
  117. void *uptr,
  118. void *tptr,
  119. uint64_t nwid,
  120. void **nptr,
  121. uint64_t srcMac,
  122. uint64_t destMac,
  123. unsigned int etherType,
  124. unsigned int vlanId,
  125. const void *data,
  126. unsigned int len)
  127. {
  128. if (*nptr)
  129. reinterpret_cast<EthernetTap *>(*nptr)->put(MAC(srcMac),MAC(destMac),etherType,data,len);
  130. }
  131. static void ZT_GoNode_EventCallback(
  132. ZT_Node *node,
  133. void *uptr,
  134. void *tptr,
  135. enum ZT_Event et,
  136. const void *data)
  137. {
  138. goZtEvent(reinterpret_cast<ZT_GoNode *>(uptr),et,data);
  139. }
  140. static void ZT_GoNode_StatePutFunction(
  141. ZT_Node *node,
  142. void *uptr,
  143. void *tptr,
  144. enum ZT_StateObjectType objType,
  145. const uint64_t id[2],
  146. const void *data,
  147. int len)
  148. {
  149. goStateObjectPutFunc(reinterpret_cast<ZT_GoNode *>(uptr),objType,id,data,len);
  150. }
  151. static int ZT_GoNode_StateGetFunction(
  152. ZT_Node *node,
  153. void *uptr,
  154. void *tptr,
  155. enum ZT_StateObjectType objType,
  156. const uint64_t id[2],
  157. void *buf,
  158. unsigned int buflen)
  159. {
  160. return goStateObjectGetFunc(
  161. reinterpret_cast<ZT_GoNode *>(uptr),
  162. (int)objType,
  163. id,
  164. buf,
  165. buflen);
  166. }
  167. static ZT_ALWAYS_INLINE void doUdpSend(ZT_SOCKET sock,const struct sockaddr_storage *addr,const void *data,const unsigned int len,const unsigned int ipTTL)
  168. {
  169. switch(addr->ss_family) {
  170. case AF_INET:
  171. if ((ipTTL > 0)&&(ipTTL < 255)) {
  172. #ifdef __WINDOWS__
  173. DWORD tmp = (DWORD)ipTTL;
  174. #else
  175. int tmp = (int)ipTTL;
  176. #endif
  177. setsockopt(sock,IPPROTO_IP,IP_TTL,&tmp,sizeof(tmp));
  178. sendto(sock,data,len,MSG_DONTWAIT,(const sockaddr *)addr,sizeof(struct sockaddr_in));
  179. tmp = 255;
  180. setsockopt(sock,IPPROTO_IP,IP_TTL,&tmp,sizeof(tmp));
  181. } else {
  182. sendto(sock,data,len,MSG_DONTWAIT,(const sockaddr *)addr,sizeof(struct sockaddr_in));
  183. }
  184. break;
  185. case AF_INET6:
  186. // The ipTTL option isn't currently used with IPv6. It's only used
  187. // with IPv4 "firewall opener" / "NAT buster" preamble packets as part
  188. // of IPv4 NAT traversal.
  189. sendto(sock,data,len,MSG_DONTWAIT,(const sockaddr *)addr,sizeof(struct sockaddr_in6));
  190. break;
  191. }
  192. }
  193. static int ZT_GoNode_WirePacketSendFunction(
  194. ZT_Node *node,
  195. void *uptr,
  196. void *tptr,
  197. int64_t localSocket,
  198. const struct sockaddr_storage *addr,
  199. const void *data,
  200. unsigned int len,
  201. unsigned int ipTTL)
  202. {
  203. if ((localSocket != -1)&&(localSocket != ZT_INVALID_SOCKET)) {
  204. doUdpSend((ZT_SOCKET)localSocket,addr,data,len,ipTTL);
  205. } else {
  206. ZT_GoNode *const gn = reinterpret_cast<ZT_GoNode *>(uptr);
  207. std::set<std::string> ipsSentFrom;
  208. std::lock_guard<std::mutex> l(gn->threads_l);
  209. for(auto t=gn->threads.begin();t!=gn->threads.end();++t) {
  210. if (t->second.af == addr->ss_family) {
  211. if (ipsSentFrom.insert(t->second.ip).second) {
  212. doUdpSend(t->first,addr,data,len,ipTTL);
  213. }
  214. }
  215. }
  216. }
  217. return 0;
  218. }
  219. static int ZT_GoNode_PathCheckFunction(
  220. ZT_Node *node,
  221. void *uptr,
  222. void *tptr,
  223. uint64_t ztAddress,
  224. int64_t localSocket,
  225. const struct sockaddr_storage *sa)
  226. {
  227. switch(sa->ss_family) {
  228. case AF_INET:
  229. return goPathCheckFunc(
  230. reinterpret_cast<ZT_GoNode *>(uptr),
  231. ztAddress,
  232. AF_INET,
  233. &(reinterpret_cast<const struct sockaddr_in *>(sa)->sin_addr.s_addr),
  234. Utils::ntoh((uint16_t)reinterpret_cast<const struct sockaddr_in *>(sa)->sin_port));
  235. case AF_INET6:
  236. return goPathCheckFunc(
  237. reinterpret_cast<ZT_GoNode *>(uptr),
  238. ztAddress,
  239. AF_INET6,
  240. reinterpret_cast<const struct sockaddr_in6 *>(sa)->sin6_addr.s6_addr,
  241. Utils::ntoh((uint16_t)reinterpret_cast<const struct sockaddr_in6 *>(sa)->sin6_port));
  242. }
  243. return 0;
  244. }
  245. static int ZT_GoNode_PathLookupFunction(
  246. ZT_Node *node,
  247. void *uptr,
  248. void *tptr,
  249. uint64_t ztAddress,
  250. int desiredAddressFamily,
  251. struct sockaddr_storage *sa)
  252. {
  253. int family = 0;
  254. uint8_t ip[16];
  255. int port = 0;
  256. const int result = goPathLookupFunc(
  257. reinterpret_cast<ZT_GoNode *>(uptr),
  258. ztAddress,
  259. desiredAddressFamily,
  260. &family,
  261. ip,
  262. &port
  263. );
  264. if (result != 0) {
  265. switch(family) {
  266. case AF_INET:
  267. reinterpret_cast<struct sockaddr_in *>(sa)->sin_family = AF_INET;
  268. memcpy(&(reinterpret_cast<struct sockaddr_in *>(sa)->sin_addr.s_addr),ip,4);
  269. reinterpret_cast<struct sockaddr_in *>(sa)->sin_port = Utils::hton((uint16_t)port);
  270. return 1;
  271. case AF_INET6:
  272. reinterpret_cast<struct sockaddr_in6 *>(sa)->sin6_family = AF_INET6;
  273. memcpy(reinterpret_cast<struct sockaddr_in6 *>(sa)->sin6_addr.s6_addr,ip,16);
  274. reinterpret_cast<struct sockaddr_in6 *>(sa)->sin6_port = Utils::hton((uint16_t)port);
  275. return 1;
  276. }
  277. }
  278. return 0;
  279. }
  280. static void ZT_GoNode_DNSResolver(
  281. ZT_Node *node,
  282. void *uptr,
  283. void *tptr,
  284. const enum ZT_DNSRecordType *types,
  285. unsigned int numTypes,
  286. const char *name,
  287. uintptr_t requestId)
  288. {
  289. uint8_t t[256];
  290. for(unsigned int i=0;(i<numTypes)&&(i<256);++i) t[i] = (uint8_t)types[i];
  291. goDNSResolverFunc(reinterpret_cast<ZT_GoNode *>(uptr),t,(int)numTypes,name,requestId);
  292. }
  293. /****************************************************************************/
  294. extern "C" ZT_GoNode *ZT_GoNode_new(const char *workingPath)
  295. {
  296. try {
  297. struct ZT_Node_Callbacks cb;
  298. cb.statePutFunction = &ZT_GoNode_StatePutFunction;
  299. cb.stateGetFunction = &ZT_GoNode_StateGetFunction;
  300. cb.wirePacketSendFunction = &ZT_GoNode_WirePacketSendFunction;
  301. cb.virtualNetworkFrameFunction = &ZT_GoNode_VirtualNetworkFrameFunction;
  302. cb.virtualNetworkConfigFunction = &ZT_GoNode_VirtualNetworkConfigFunction;
  303. cb.eventCallback = &ZT_GoNode_EventCallback;
  304. cb.dnsResolver = &ZT_GoNode_DNSResolver;
  305. cb.pathCheckFunction = &ZT_GoNode_PathCheckFunction;
  306. cb.pathLookupFunction = &ZT_GoNode_PathLookupFunction;
  307. ZT_GoNode_Impl *gn = new ZT_GoNode_Impl;
  308. const int64_t now = OSUtils::now();
  309. gn->node = new Node(reinterpret_cast<void *>(gn),nullptr,&cb,now);
  310. gn->nextBackgroundTaskDeadline = now;
  311. gn->path = workingPath;
  312. gn->run = true;
  313. gn->backgroundTaskThread = std::thread([gn] {
  314. int64_t lastCheckedTaps = 0;
  315. while (gn->run) {
  316. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  317. const int64_t now = OSUtils::now();
  318. if (now >= gn->nextBackgroundTaskDeadline)
  319. gn->node->processBackgroundTasks(nullptr,now,&(gn->nextBackgroundTaskDeadline));
  320. if ((now - lastCheckedTaps) > 10000) {
  321. lastCheckedTaps = now;
  322. std::vector<MulticastGroup> added,removed;
  323. std::lock_guard<std::mutex> tl(gn->taps_l);
  324. for(auto t=gn->taps.begin();t!=gn->taps.end();++t) {
  325. added.clear();
  326. removed.clear();
  327. t->second->scanMulticastGroups(added,removed);
  328. for(auto g=added.begin();g!=added.end();++g)
  329. goHandleTapAddedMulticastGroup(gn,(ZT_GoTap *)t->second.get(),t->first,g->mac().toInt(),g->adi());
  330. for(auto g=removed.begin();g!=removed.end();++g)
  331. goHandleTapRemovedMulticastGroup(gn,(ZT_GoTap *)t->second.get(),t->first,g->mac().toInt(),g->adi());
  332. t->second->syncRoutes();
  333. }
  334. }
  335. }
  336. });
  337. return gn;
  338. } catch ( ... ) {
  339. fprintf(stderr,"FATAL: unable to create new instance of Node (out of memory?)" ZT_EOL_S);
  340. exit(1);
  341. }
  342. }
  343. extern "C" void ZT_GoNode_delete(ZT_GoNode *gn)
  344. {
  345. gn->run = false;
  346. gn->threads_l.lock();
  347. for(auto t=gn->threads.begin();t!=gn->threads.end();++t) {
  348. t->second.run = false;
  349. shutdown(t->first,SHUT_RDWR);
  350. close(t->first);
  351. t->second.thr.join();
  352. }
  353. gn->threads_l.unlock();
  354. gn->taps_l.lock();
  355. for(auto t=gn->taps.begin();t!=gn->taps.end();++t)
  356. gn->node->leave(t->first,nullptr,nullptr);
  357. gn->taps.clear();
  358. gn->taps_l.unlock();
  359. gn->backgroundTaskThread.join();
  360. delete gn->node;
  361. delete gn;
  362. }
  363. extern "C" ZT_Node *ZT_GoNode_getNode(ZT_GoNode *gn)
  364. {
  365. return gn->node;
  366. }
  367. // Sets flags and socket options common to both IPv4 and IPv6 UDP sockets
  368. static void setCommonUdpSocketSettings(ZT_SOCKET udpSock,const char *dev)
  369. {
  370. int bufSize = 1048576;
  371. while (bufSize > 131072) {
  372. if (setsockopt(udpSock,SOL_SOCKET,SO_RCVBUF,(const char *)&bufSize,sizeof(bufSize)) == 0)
  373. break;
  374. bufSize -= 131072;
  375. }
  376. bufSize = 1048576;
  377. while (bufSize > 131072) {
  378. if (setsockopt(udpSock,SOL_SOCKET,SO_SNDBUF,(const char *)&bufSize,sizeof(bufSize)) == 0)
  379. break;
  380. bufSize -= 131072;
  381. }
  382. SETSOCKOPT_FLAG_TYPE fl;
  383. #ifdef SO_REUSEPORT
  384. fl = SETSOCKOPT_FLAG_TRUE;
  385. setsockopt(udpSock,SOL_SOCKET,SO_REUSEPORT,(void *)&fl,sizeof(fl));
  386. #endif
  387. #ifndef __LINUX__ // linux wants just SO_REUSEPORT
  388. fl = SETSOCKOPT_FLAG_TRUE;
  389. setsockopt(udpSock,SOL_SOCKET,SO_REUSEADDR,(void *)&fl,sizeof(fl));
  390. #endif
  391. fl = SETSOCKOPT_FLAG_TRUE;
  392. setsockopt(udpSock,SOL_SOCKET,SO_BROADCAST,(void *)&fl,sizeof(fl));
  393. #ifdef IP_DONTFRAG
  394. fl = SETSOCKOPT_FLAG_FALSE;
  395. setsockopt(udpSock,IPPROTO_IP,IP_DONTFRAG,(void *)&fl,sizeof(fl));
  396. #endif
  397. #ifdef IP_MTU_DISCOVER
  398. fl = SETSOCKOPT_FLAG_FALSE;
  399. setsockopt(udpSock,IPPROTO_IP,IP_MTU_DISCOVER,(void *)&fl,sizeof(fl));
  400. #endif
  401. #ifdef SO_BINDTODEVICE
  402. if ((dev)&&(strlen(dev)))
  403. setsockopt(udpSock,SOL_SOCKET,SO_BINDTODEVICE,dev,strlen(dev));
  404. #endif
  405. #if defined(__BSD__) && defined(IP_BOUND_IF)
  406. if ((dev)&&(strlen(dev))) {
  407. int idx = if_nametoindex(dev);
  408. if (idx != 0)
  409. setsockopt(udpSock,IPPROTO_IP,IP_BOUND_IF,(void *)&idx,sizeof(idx));
  410. }
  411. #endif
  412. }
  413. extern "C" int ZT_GoNode_phyStartListen(ZT_GoNode *gn,const char *dev,const char *ip,const int port)
  414. {
  415. if (strchr(ip,':')) {
  416. struct sockaddr_in6 in6;
  417. memset(&in6,0,sizeof(in6));
  418. in6.sin6_family = AF_INET6;
  419. if (inet_pton(AF_INET6,ip,&(in6.sin6_addr)) <= 0)
  420. return errno;
  421. in6.sin6_port = htons((uint16_t)port);
  422. ZT_SOCKET udpSock = socket(AF_INET6,SOCK_DGRAM,0);
  423. if (udpSock == ZT_INVALID_SOCKET)
  424. return errno;
  425. setCommonUdpSocketSettings(udpSock,dev);
  426. SETSOCKOPT_FLAG_TYPE fl = SETSOCKOPT_FLAG_TRUE;
  427. setsockopt(udpSock,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&fl,sizeof(fl));
  428. #ifdef IPV6_DONTFRAG
  429. fl = SETSOCKOPT_FLAG_FALSE;
  430. setsockopt(udpSock,IPPROTO_IPV6,IPV6_DONTFRAG,&fl,sizeof(fl));
  431. #endif
  432. if (bind(udpSock,reinterpret_cast<const struct sockaddr *>(&in6),sizeof(in6)) != 0)
  433. return errno;
  434. {
  435. std::lock_guard<std::mutex> l(gn->threads_l);
  436. ZT_GoNodeThread &gnt = gn->threads[udpSock];
  437. gnt.ip = ip;
  438. gnt.port = port;
  439. gnt.af = AF_INET6;
  440. gnt.run = true;
  441. gnt.thr = std::thread([udpSock,gn,&gnt] {
  442. struct sockaddr_in6 in6;
  443. socklen_t salen;
  444. char buf[16384];
  445. while (gnt.run) {
  446. salen = sizeof(in6);
  447. int s = (int)recvfrom(udpSock,buf,sizeof(buf),0,reinterpret_cast<struct sockaddr *>(&in6),&salen);
  448. if (s > 0) {
  449. gn->node->processWirePacket(&gnt,OSUtils::now(),(int64_t)udpSock,reinterpret_cast<const struct sockaddr_storage *>(&in6),buf,(unsigned int)s,&(gn->nextBackgroundTaskDeadline));
  450. } else {
  451. // If something goes bad with this socket such as its interface vanishing, it
  452. // will eventually be closed by higher level (Go) code. Until then prevent the
  453. // system from consuming too much CPU.
  454. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  455. }
  456. }
  457. });
  458. }
  459. } else {
  460. struct sockaddr_in in;
  461. memset(&in,0,sizeof(in));
  462. in.sin_family = AF_INET;
  463. if (inet_pton(AF_INET,ip,&(in.sin_addr)) <= 0)
  464. return errno;
  465. in.sin_port = htons((uint16_t)port);
  466. ZT_SOCKET udpSock = socket(AF_INET,SOCK_DGRAM,0);
  467. if (udpSock == ZT_INVALID_SOCKET)
  468. return errno;
  469. setCommonUdpSocketSettings(udpSock,dev);
  470. #ifdef SO_NO_CHECK
  471. SETSOCKOPT_FLAG_TYPE fl = SETSOCKOPT_FLAG_TRUE;
  472. setsockopt(udpSock,SOL_SOCKET,SO_NO_CHECK,&fl,sizeof(fl));
  473. #endif
  474. if (bind(udpSock,reinterpret_cast<const struct sockaddr *>(&in),sizeof(in)) != 0)
  475. return errno;
  476. {
  477. std::lock_guard<std::mutex> l(gn->threads_l);
  478. ZT_GoNodeThread &gnt = gn->threads[udpSock];
  479. gnt.ip = ip;
  480. gnt.port = port;
  481. gnt.af = AF_INET6;
  482. gnt.run = true;
  483. gnt.thr = std::thread([udpSock,gn,&gnt] {
  484. struct sockaddr_in in4;
  485. socklen_t salen;
  486. char buf[16384];
  487. while (gnt.run) {
  488. salen = sizeof(in4);
  489. int s = (int)recvfrom(udpSock,buf,sizeof(buf),0,reinterpret_cast<struct sockaddr *>(&in4),&salen);
  490. if (s > 0) {
  491. gn->node->processWirePacket(&gnt,OSUtils::now(),(int64_t)udpSock,reinterpret_cast<const struct sockaddr_storage *>(&in4),buf,(unsigned int)s,&(gn->nextBackgroundTaskDeadline));
  492. }
  493. }
  494. });
  495. }
  496. }
  497. return 0;
  498. }
  499. extern "C" int ZT_GoNode_phyStopListen(ZT_GoNode *gn,const char *dev,const char *ip,const int port)
  500. {
  501. {
  502. std::lock_guard<std::mutex> l(gn->threads_l);
  503. for(auto t=gn->threads.begin();t!=gn->threads.end();) {
  504. if ((t->second.ip == ip)&&(t->second.port == port)) {
  505. t->second.run = false;
  506. shutdown(t->first,SHUT_RDWR);
  507. close(t->first);
  508. t->second.thr.join();
  509. gn->threads.erase(t++);
  510. } else ++t;
  511. }
  512. }
  513. return 0;
  514. }
  515. static void tapFrameHandler(void *uptr,void *tptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
  516. {
  517. ZT_GoNode *const gn = reinterpret_cast<ZT_GoNode *>(uptr);
  518. gn->node->processVirtualNetworkFrame(tptr,OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&(gn->nextBackgroundTaskDeadline));
  519. }
  520. extern "C" ZT_GoTap *ZT_GoNode_join(ZT_GoNode *gn,uint64_t nwid)
  521. {
  522. try {
  523. std::lock_guard<std::mutex> l(gn->taps_l);
  524. auto existingTap = gn->taps.find(nwid);
  525. if (existingTap != gn->taps.end())
  526. return (ZT_GoTap *)existingTap->second.get();
  527. char tmp[256];
  528. OSUtils::ztsnprintf(tmp,sizeof(tmp),"ZeroTier Network %.16llx",(unsigned long long)nwid);
  529. std::shared_ptr<EthernetTap> tap(EthernetTap::newInstance(nullptr,gn->path.c_str(),MAC(Address(gn->node->address()),nwid),ZT_DEFAULT_MTU,0,nwid,tmp,&tapFrameHandler,gn));
  530. if (!tap)
  531. return nullptr;
  532. gn->taps[nwid] = tap;
  533. gn->node->join(nwid,tap.get(),nullptr);
  534. return (ZT_GoTap *)tap.get();
  535. } catch ( ... ) {
  536. return nullptr;
  537. }
  538. }
  539. extern "C" void ZT_GoNode_leave(ZT_GoNode *gn,uint64_t nwid)
  540. {
  541. std::lock_guard<std::mutex> l(gn->taps_l);
  542. auto existingTap = gn->taps.find(nwid);
  543. if (existingTap != gn->taps.end()) {
  544. gn->node->leave(nwid,nullptr,nullptr);
  545. gn->taps.erase(existingTap);
  546. }
  547. }
  548. /****************************************************************************/
  549. extern "C" void ZT_GoTap_setEnabled(ZT_GoTap *tap,int enabled)
  550. {
  551. reinterpret_cast<EthernetTap *>(tap)->setEnabled(enabled != 0);
  552. }
  553. extern "C" int ZT_GoTap_addIp(ZT_GoTap *tap,int af,const void *ip,int netmaskBits)
  554. {
  555. switch(af) {
  556. case AF_INET:
  557. return (reinterpret_cast<EthernetTap *>(tap)->addIp(InetAddress(ip,4,(unsigned int)netmaskBits)) ? 1 : 0);
  558. case AF_INET6:
  559. return (reinterpret_cast<EthernetTap *>(tap)->addIp(InetAddress(ip,16,(unsigned int)netmaskBits)) ? 1 : 0);
  560. }
  561. return 0;
  562. }
  563. extern "C" int ZT_GoTap_removeIp(ZT_GoTap *tap,int af,const void *ip,int netmaskBits)
  564. {
  565. switch(af) {
  566. case AF_INET:
  567. return (reinterpret_cast<EthernetTap *>(tap)->removeIp(InetAddress(ip,4,(unsigned int)netmaskBits)) ? 1 : 0);
  568. case AF_INET6:
  569. return (reinterpret_cast<EthernetTap *>(tap)->removeIp(InetAddress(ip,16,(unsigned int)netmaskBits)) ? 1 : 0);
  570. }
  571. return 0;
  572. }
  573. extern "C" int ZT_GoTap_ips(ZT_GoTap *tap,void *buf,unsigned int bufSize)
  574. {
  575. auto ips = reinterpret_cast<EthernetTap *>(tap)->ips();
  576. unsigned int p = 0;
  577. uint8_t *const b = reinterpret_cast<uint8_t *>(buf);
  578. for(auto ip=ips.begin();ip!=ips.end();++ip) {
  579. if ((p + 6) > bufSize)
  580. break;
  581. const uint8_t *const ipd = reinterpret_cast<const uint8_t *>(ip->rawIpData());
  582. if (ip->isV4()) {
  583. b[p++] = AF_INET;
  584. b[p++] = ipd[0];
  585. b[p++] = ipd[1];
  586. b[p++] = ipd[2];
  587. b[p++] = ipd[3];
  588. b[p++] = (uint8_t)ip->netmaskBits();
  589. } else if (ip->isV6()) {
  590. if ((p + 18) <= bufSize) {
  591. b[p++] = AF_INET6;
  592. for(int j=0;j<16;++j)
  593. b[p++] = ipd[j];
  594. b[p++] = (uint8_t)ip->netmaskBits();
  595. }
  596. }
  597. }
  598. return (int)p;
  599. }
  600. extern "C" void ZT_GoTap_deviceName(ZT_GoTap *tap,char nbuf[256])
  601. {
  602. Utils::scopy(nbuf,256,reinterpret_cast<EthernetTap *>(tap)->deviceName().c_str());
  603. }
  604. extern "C" void ZT_GoTap_setFriendlyName(ZT_GoTap *tap,const char *friendlyName)
  605. {
  606. reinterpret_cast<EthernetTap *>(tap)->setFriendlyName(friendlyName);
  607. }
  608. extern "C" void ZT_GoTap_setMtu(ZT_GoTap *tap,unsigned int mtu)
  609. {
  610. reinterpret_cast<EthernetTap *>(tap)->setMtu(mtu);
  611. }
  612. extern "C" int ZT_GoTap_addRoute(ZT_GoTap *tap,int targetAf,const void *targetIp,int targetNetmaskBits,int viaAf,const void *viaIp,unsigned int metric)
  613. {
  614. InetAddress target,via;
  615. switch(targetAf) {
  616. case AF_INET:
  617. target.set(targetIp,4,(unsigned int)targetNetmaskBits);
  618. break;
  619. case AF_INET6:
  620. target.set(targetIp,16,(unsigned int)targetNetmaskBits);
  621. break;
  622. }
  623. switch(viaAf) {
  624. case AF_INET:
  625. via.set(viaIp,4,0);
  626. break;
  627. case AF_INET6:
  628. via.set(viaIp,16,0);
  629. break;
  630. }
  631. return reinterpret_cast<EthernetTap *>(tap)->addRoute(target,via,metric);
  632. }
  633. extern "C" int ZT_GoTap_removeRoute(ZT_GoTap *tap,int targetAf,const void *targetIp,int targetNetmaskBits,int viaAf,const void *viaIp,unsigned int metric)
  634. {
  635. InetAddress target,via;
  636. switch(targetAf) {
  637. case AF_INET:
  638. target.set(targetIp,4,(unsigned int)targetNetmaskBits);
  639. break;
  640. case AF_INET6:
  641. target.set(targetIp,16,(unsigned int)targetNetmaskBits);
  642. break;
  643. }
  644. switch(viaAf) {
  645. case AF_INET:
  646. via.set(viaIp,4,0);
  647. break;
  648. case AF_INET6:
  649. via.set(viaIp,16,0);
  650. break;
  651. }
  652. return reinterpret_cast<EthernetTap *>(tap)->removeRoute(target,via,metric);
  653. }
  654. /****************************************************************************/
  655. extern "C" const char *ZT_GoIdentity_generate(int type)
  656. {
  657. Identity id;
  658. id.generate((Identity::Type)type);
  659. char *tmp = (char *)malloc(ZT_IDENTITY_STRING_BUFFER_LENGTH);
  660. if (tmp)
  661. id.toString(true,tmp);
  662. return tmp;
  663. }
  664. extern "C" int ZT_GoIdentity_validate(const char *idStr)
  665. {
  666. Identity id;
  667. if (!id.fromString(idStr))
  668. return 0;
  669. if (!id.locallyValidate())
  670. return 0;
  671. return 1;
  672. }
  673. extern "C" int ZT_GoIdentity_sign(const char *idStr,const void *data,unsigned int len,void *sigbuf,unsigned int sigbuflen)
  674. {
  675. Identity id;
  676. if (!id.fromString(idStr))
  677. return 0;
  678. return (int)id.sign(data,len,sigbuf,sigbuflen);
  679. }
  680. extern "C" int ZT_GoIdentity_verify(const char *idStr,const void *data,unsigned int len,const void *sig,unsigned int siglen)
  681. {
  682. Identity id;
  683. if (!id.fromString(idStr))
  684. return 0;
  685. return id.verify(data,len,sig,siglen) ? 1 : 0;
  686. }
  687. /****************************************************************************/
  688. extern "C" int ZT_GoLocator_makeSecureDNSName(char *name,unsigned int nameBufSize,uint8_t *privateKey,unsigned int privateKeyBufSize)
  689. {
  690. if ((privateKeyBufSize < ZT_ECC384_PRIVATE_KEY_SIZE)||(nameBufSize < 256))
  691. return -1;
  692. uint8_t pub[ZT_ECC384_PUBLIC_KEY_SIZE];
  693. ECC384GenerateKey(pub,privateKey);
  694. const Str n(Locator::makeSecureDnsName(pub));
  695. if (n.length() >= nameBufSize)
  696. return -1;
  697. Utils::scopy(name,nameBufSize,n.c_str());
  698. return ZT_ECC384_PRIVATE_KEY_SIZE;
  699. }
  700. extern "C" int ZT_GoLocator_makeLocator(
  701. uint8_t *buf,
  702. unsigned int bufSize,
  703. int64_t ts,
  704. const char *id,
  705. const struct sockaddr_storage *physicalAddresses,
  706. unsigned int physicalAddressCount,
  707. const char **virtualAddresses,
  708. unsigned int virtualAddressCount)
  709. {
  710. Locator loc;
  711. for(unsigned int i=0;i<physicalAddressCount;++i) {
  712. loc.add(*reinterpret_cast<const InetAddress *>(physicalAddresses + i));
  713. }
  714. for(unsigned int i=0;i<virtualAddressCount;++i) {
  715. Identity id;
  716. if (!id.fromString(virtualAddresses[i]))
  717. return -1;
  718. loc.add(id);
  719. }
  720. Identity signingId;
  721. if (!signingId.fromString(id))
  722. return -1;
  723. if (!signingId.hasPrivate())
  724. return -1;
  725. if (!loc.finish(signingId,ts))
  726. return -1;
  727. Buffer<65536> *tmp = new Buffer<65536>();
  728. loc.serialize(*tmp);
  729. if (tmp->size() > bufSize) {
  730. delete tmp;
  731. return -1;
  732. }
  733. memcpy(buf,tmp->data(),tmp->size());
  734. int s = (int)tmp->size();
  735. delete tmp;
  736. return s;
  737. }
  738. extern "C" int ZT_GoLocator_decodeLocator(const uint8_t *locatorBytes,unsigned int locatorSize,struct ZT_GoLocator_Info *info)
  739. {
  740. Locator loc;
  741. if (!loc.deserialize(locatorBytes,locatorSize))
  742. return -1;
  743. if (!loc.verify())
  744. return -2;
  745. loc.id().toString(false,info->id);
  746. info->phyCount = 0;
  747. info->virtCount = 0;
  748. for(auto p=loc.phy().begin();p!=loc.phy().end();++p)
  749. memcpy(&(info->phy[info->phyCount++]),&(*p),sizeof(struct sockaddr_storage));
  750. for(auto v=loc.virt().begin();v!=loc.virt().end();++v)
  751. v->toString(false,info->virt[info->virtCount++]);
  752. return 1;
  753. }
  754. int ZT_GoLocator_makeSignedTxtRecords(
  755. const uint8_t *locator,
  756. unsigned int locatorSize,
  757. const char *name,
  758. const uint8_t *privateKey,
  759. unsigned int privateKeySize,
  760. char results[256][256])
  761. {
  762. if (privateKeySize != ZT_ECC384_PRIVATE_KEY_SIZE)
  763. return -1;
  764. Locator loc;
  765. if (!loc.deserialize(locator,locatorSize))
  766. return -1;
  767. std::vector<Str> r(loc.makeTxtRecords(privateKey));
  768. if (r.size() > 256)
  769. return -1;
  770. for(unsigned long i=0;i<r.size();++i)
  771. Utils::scopy(results[i],256,r[i].c_str());
  772. return (int)r.size();
  773. }