GoGlue.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. /*
  2. * Copyright (c)2013-2020 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: 2025-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. #ifndef _WIN32_WINNT
  14. #define _WIN32_WINNT 0x06010000
  15. #endif
  16. #include "GoGlue.h"
  17. #include "../core/Constants.hpp"
  18. #include "../core/InetAddress.hpp"
  19. #include "../core/Node.hpp"
  20. #include "../core/Utils.hpp"
  21. #include "../core/MAC.hpp"
  22. #include "../core/Address.hpp"
  23. #include "../core/Containers.hpp"
  24. #include "../core/Certificate.hpp"
  25. #include "../osdep/OSUtils.hpp"
  26. #include "../osdep/EthernetTap.hpp"
  27. #ifndef __WINDOWS__
  28. #include <unistd.h>
  29. #include <sys/socket.h>
  30. #include <sys/un.h>
  31. #include <sys/types.h>
  32. #include <sys/ioctl.h>
  33. #include <ifaddrs.h>
  34. #include <net/if.h>
  35. #include <netinet/in.h>
  36. #ifdef __BSD__
  37. #include <netinet6/in6_var.h>
  38. #endif
  39. #include <arpa/inet.h>
  40. #include <errno.h>
  41. #ifdef __LINUX__
  42. #ifndef IPV6_DONTFRAG
  43. #define IPV6_DONTFRAG 62
  44. #endif
  45. #endif
  46. #endif // !__WINDOWS__
  47. #include <thread>
  48. #include <mutex>
  49. #include <memory>
  50. #include <atomic>
  51. #ifdef __WINDOWS__
  52. #define SETSOCKOPT_FLAG_TYPE BOOL
  53. #define SETSOCKOPT_FLAG_TRUE TRUE
  54. #define SETSOCKOPT_FLAG_FALSE FALSE
  55. #else
  56. #define SETSOCKOPT_FLAG_TYPE int
  57. #define SETSOCKOPT_FLAG_TRUE 1
  58. #define SETSOCKOPT_FLAG_FALSE 0
  59. #endif
  60. #ifndef MSG_DONTWAIT
  61. #define MSG_DONTWAIT 0
  62. #endif
  63. using namespace ZeroTier;
  64. struct ZT_GoNodeThread
  65. {
  66. String ip;
  67. int port;
  68. int af;
  69. bool primary;
  70. std::atomic< bool > run;
  71. std::thread thr;
  72. };
  73. struct ZT_GoNode_Impl
  74. {
  75. void *goUserPtr;
  76. Node *node;
  77. volatile int64_t nextBackgroundTaskDeadline;
  78. String path;
  79. std::atomic< bool > run;
  80. Map< ZT_SOCKET, ZT_GoNodeThread > threads;
  81. Map< uint64_t, std::shared_ptr< EthernetTap > > taps;
  82. std::mutex threads_l;
  83. std::mutex taps_l;
  84. std::thread backgroundTaskThread;
  85. };
  86. static const String defaultHomePath(OSUtils::platformDefaultHomePath());
  87. const char *const ZT_PLATFORM_DEFAULT_HOMEPATH = defaultHomePath.c_str();
  88. // These are implemented in Go code.
  89. extern "C" int goPathCheckFunc(void *, const ZT_Identity *, int, const void *, int);
  90. extern "C" int goPathLookupFunc(void *, uint64_t, int, const ZT_Identity *, int *, uint8_t [16], int *);
  91. extern "C" void goStateObjectPutFunc(void *, int, const uint64_t *, const void *, int);
  92. extern "C" int goStateObjectGetFunc(void *, int, const uint64_t *, void **);
  93. extern "C" void goVirtualNetworkConfigFunc(void *, ZT_GoTap *, uint64_t, int, const ZT_VirtualNetworkConfig *);
  94. extern "C" void goZtEvent(void *, int, const void *);
  95. extern "C" void goHandleTapAddedMulticastGroup(void *, ZT_GoTap *, uint64_t, uint64_t, uint32_t);
  96. extern "C" void goHandleTapRemovedMulticastGroup(void *, ZT_GoTap *, uint64_t, uint64_t, uint32_t);
  97. static void ZT_GoNode_VirtualNetworkConfigFunction(
  98. ZT_Node *node,
  99. void *uptr,
  100. void *tptr,
  101. uint64_t nwid,
  102. void **nptr,
  103. enum ZT_VirtualNetworkConfigOperation op,
  104. const ZT_VirtualNetworkConfig *cfg)
  105. {
  106. goVirtualNetworkConfigFunc(reinterpret_cast<ZT_GoNode *>(uptr)->goUserPtr, reinterpret_cast<ZT_GoTap *>(*nptr), nwid, op, cfg);
  107. }
  108. static void ZT_GoNode_VirtualNetworkFrameFunction(
  109. ZT_Node *node,
  110. void *uptr,
  111. void *tptr,
  112. uint64_t nwid,
  113. void **nptr,
  114. uint64_t srcMac,
  115. uint64_t destMac,
  116. unsigned int etherType,
  117. unsigned int vlanId,
  118. const void *data,
  119. unsigned int len)
  120. {
  121. if (*nptr)
  122. reinterpret_cast<EthernetTap *>(*nptr)->put(MAC(srcMac), MAC(destMac), etherType, data, len);
  123. }
  124. static void ZT_GoNode_EventCallback(
  125. ZT_Node *node,
  126. void *uptr,
  127. void *tptr,
  128. enum ZT_Event et,
  129. const void *data)
  130. {
  131. goZtEvent(reinterpret_cast<ZT_GoNode *>(uptr)->goUserPtr, et, data);
  132. }
  133. static void ZT_GoNode_StatePutFunction(
  134. ZT_Node *node,
  135. void *uptr,
  136. void *tptr,
  137. enum ZT_StateObjectType objType,
  138. const uint64_t id[2],
  139. const void *data,
  140. int len)
  141. {
  142. goStateObjectPutFunc(
  143. reinterpret_cast<ZT_GoNode *>(uptr)->goUserPtr,
  144. objType,
  145. id,
  146. data,
  147. len);
  148. }
  149. static void _freeFunc(void *p)
  150. { if (p) free(p); }
  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 **data,
  158. void (**freeFunc)(void *))
  159. {
  160. *freeFunc = &_freeFunc;
  161. return goStateObjectGetFunc(
  162. reinterpret_cast<ZT_GoNode *>(uptr)->goUserPtr,
  163. (int)objType,
  164. id,
  165. data);
  166. }
  167. static ZT_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 (unlikely((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, reinterpret_cast<const char *>(&tmp), sizeof(tmp));
  178. sendto(sock, reinterpret_cast<const char *>(data), len, MSG_DONTWAIT, (const sockaddr *)addr, sizeof(struct sockaddr_in));
  179. tmp = 255;
  180. setsockopt(sock, IPPROTO_IP, IP_TTL, reinterpret_cast<const char *>(&tmp), sizeof(tmp));
  181. } else {
  182. sendto(sock, reinterpret_cast<const char *>(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, reinterpret_cast<const char *>(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 (likely(localSocket > 0)) {
  204. doUdpSend((ZT_SOCKET)localSocket, addr, data, len, ipTTL);
  205. } else {
  206. ZT_GoNode *const gn = reinterpret_cast<ZT_GoNode *>(uptr);
  207. std::lock_guard< std::mutex > l(gn->threads_l);
  208. for (auto t = gn->threads.begin(); t != gn->threads.end(); ++t) {
  209. if ((t->second.af == addr->ss_family) && (t->second.primary)) {
  210. doUdpSend(t->first, addr, data, len, ipTTL);
  211. break;
  212. }
  213. }
  214. }
  215. return 0;
  216. }
  217. static int ZT_GoNode_PathCheckFunction(
  218. ZT_Node *node,
  219. void *uptr,
  220. void *tptr,
  221. uint64_t ztAddress,
  222. const ZT_Identity *id,
  223. int64_t localSocket,
  224. const struct sockaddr_storage *sa)
  225. {
  226. switch (sa->ss_family) {
  227. case AF_INET:
  228. return goPathCheckFunc(
  229. reinterpret_cast<ZT_GoNode *>(uptr)->goUserPtr,
  230. id,
  231. AF_INET,
  232. &(reinterpret_cast<const struct sockaddr_in *>(sa)->sin_addr.s_addr),
  233. Utils::ntoh((uint16_t)reinterpret_cast<const struct sockaddr_in *>(sa)->sin_port));
  234. case AF_INET6:
  235. return goPathCheckFunc(
  236. reinterpret_cast<ZT_GoNode *>(uptr)->goUserPtr,
  237. id,
  238. AF_INET6,
  239. reinterpret_cast<const struct sockaddr_in6 *>(sa)->sin6_addr.s6_addr,
  240. Utils::ntoh((uint16_t)reinterpret_cast<const struct sockaddr_in6 *>(sa)->sin6_port));
  241. }
  242. return 0;
  243. }
  244. static int ZT_GoNode_PathLookupFunction(
  245. ZT_Node *node,
  246. void *uptr,
  247. void *tptr,
  248. uint64_t ztAddress,
  249. const ZT_Identity *id,
  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)->goUserPtr,
  258. ztAddress,
  259. desiredAddressFamily,
  260. id,
  261. &family,
  262. ip,
  263. &port
  264. );
  265. if (result != 0) {
  266. switch (family) {
  267. case AF_INET:
  268. reinterpret_cast<struct sockaddr_in *>(sa)->sin_family = AF_INET;
  269. memcpy(&(reinterpret_cast<struct sockaddr_in *>(sa)->sin_addr.s_addr), ip, 4);
  270. reinterpret_cast<struct sockaddr_in *>(sa)->sin_port = Utils::hton((uint16_t)port);
  271. return 1;
  272. case AF_INET6:
  273. reinterpret_cast<struct sockaddr_in6 *>(sa)->sin6_family = AF_INET6;
  274. memcpy(reinterpret_cast<struct sockaddr_in6 *>(sa)->sin6_addr.s6_addr, ip, 16);
  275. reinterpret_cast<struct sockaddr_in6 *>(sa)->sin6_port = Utils::hton((uint16_t)port);
  276. return 1;
  277. }
  278. }
  279. return 0;
  280. }
  281. extern "C" ZT_GoNode *ZT_GoNode_new(const char *workingPath, uintptr_t userPtr)
  282. {
  283. try {
  284. struct ZT_Node_Callbacks cb;
  285. cb.statePutFunction = &ZT_GoNode_StatePutFunction;
  286. cb.stateGetFunction = &ZT_GoNode_StateGetFunction;
  287. cb.wirePacketSendFunction = &ZT_GoNode_WirePacketSendFunction;
  288. cb.virtualNetworkFrameFunction = &ZT_GoNode_VirtualNetworkFrameFunction;
  289. cb.virtualNetworkConfigFunction = &ZT_GoNode_VirtualNetworkConfigFunction;
  290. cb.eventCallback = &ZT_GoNode_EventCallback;
  291. cb.pathCheckFunction = &ZT_GoNode_PathCheckFunction;
  292. cb.pathLookupFunction = &ZT_GoNode_PathLookupFunction;
  293. ZT_GoNode_Impl *gn = new ZT_GoNode_Impl;
  294. const int64_t now = OSUtils::now();
  295. gn->goUserPtr = reinterpret_cast<void *>(userPtr);
  296. gn->node = new Node(reinterpret_cast<void *>(gn), nullptr, &cb, now);
  297. gn->nextBackgroundTaskDeadline = now;
  298. gn->path = workingPath;
  299. gn->run = true;
  300. gn->backgroundTaskThread = std::thread([gn] {
  301. int64_t lastCheckedTaps = 0;
  302. while (gn->run) {
  303. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  304. const int64_t now = OSUtils::now();
  305. if (now >= gn->nextBackgroundTaskDeadline)
  306. gn->node->processBackgroundTasks(nullptr, now, &(gn->nextBackgroundTaskDeadline));
  307. if ((now - lastCheckedTaps) > 10000) {
  308. lastCheckedTaps = now;
  309. std::vector< MulticastGroup > added, removed;
  310. std::lock_guard< std::mutex > tl(gn->taps_l);
  311. for (auto t = gn->taps.begin(); t != gn->taps.end(); ++t) {
  312. added.clear();
  313. removed.clear();
  314. t->second->scanMulticastGroups(added, removed);
  315. for (auto g = added.begin(); g != added.end(); ++g)
  316. goHandleTapAddedMulticastGroup(gn, (ZT_GoTap *)t->second.get(), t->first, g->mac().toInt(), g->adi());
  317. for (auto g = removed.begin(); g != removed.end(); ++g)
  318. goHandleTapRemovedMulticastGroup(gn, (ZT_GoTap *)t->second.get(), t->first, g->mac().toInt(), g->adi());
  319. }
  320. }
  321. }
  322. });
  323. return gn;
  324. } catch (...) {
  325. fprintf(stderr, "FATAL: unable to create new instance of Node (out of memory?)" ZT_EOL_S);
  326. exit(1);
  327. }
  328. }
  329. extern "C" void ZT_GoNode_delete(ZT_GoNode *gn)
  330. {
  331. gn->run = false;
  332. gn->threads_l.lock();
  333. for (auto t = gn->threads.begin(); t != gn->threads.end(); ++t) {
  334. t->second.run = false;
  335. #ifdef __WINDOWS__
  336. shutdown(t->first, SD_BOTH);
  337. closesocket(t->first);
  338. #else
  339. shutdown(t->first, SHUT_RDWR);
  340. close(t->first);
  341. #endif
  342. t->second.thr.join();
  343. }
  344. gn->threads_l.unlock();
  345. gn->taps_l.lock();
  346. for (auto t = gn->taps.begin(); t != gn->taps.end(); ++t)
  347. gn->node->leave(t->first, nullptr, nullptr);
  348. gn->taps.clear();
  349. gn->taps_l.unlock();
  350. gn->backgroundTaskThread.join();
  351. gn->node->shutdown(nullptr);
  352. delete gn->node;
  353. delete gn;
  354. }
  355. extern "C" ZT_Node *ZT_GoNode_getNode(ZT_GoNode *gn)
  356. {
  357. return gn->node;
  358. }
  359. static void setCommonUdpSocketSettings(ZT_SOCKET udpSock, const char *dev)
  360. {
  361. int bufSize = 1048576;
  362. while (bufSize > 131072) {
  363. if (setsockopt(udpSock, SOL_SOCKET, SO_RCVBUF, (const char *)&bufSize, sizeof(bufSize)) == 0)
  364. break;
  365. bufSize -= 131072;
  366. }
  367. bufSize = 1048576;
  368. while (bufSize > 131072) {
  369. if (setsockopt(udpSock, SOL_SOCKET, SO_SNDBUF, (const char *)&bufSize, sizeof(bufSize)) == 0)
  370. break;
  371. bufSize -= 131072;
  372. }
  373. SETSOCKOPT_FLAG_TYPE fl;
  374. #ifdef SO_REUSEPORT
  375. fl = SETSOCKOPT_FLAG_TRUE;
  376. setsockopt(udpSock, SOL_SOCKET, SO_REUSEPORT, &fl, sizeof(fl));
  377. #endif
  378. #ifndef __LINUX__ // linux wants just SO_REUSEPORT
  379. fl = SETSOCKOPT_FLAG_TRUE;
  380. setsockopt(udpSock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char *>(&fl), sizeof(fl));
  381. #endif
  382. fl = SETSOCKOPT_FLAG_TRUE;
  383. setsockopt(udpSock, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<const char *>(&fl), sizeof(fl));
  384. #ifdef IP_DONTFRAG
  385. fl = SETSOCKOPT_FLAG_FALSE;
  386. setsockopt(udpSock,IPPROTO_IP,IP_DONTFRAG,&fl,sizeof(fl));
  387. #endif
  388. #ifdef IP_MTU_DISCOVER
  389. fl = SETSOCKOPT_FLAG_FALSE;
  390. setsockopt(udpSock,IPPROTO_IP,IP_MTU_DISCOVER,&fl,sizeof(fl));
  391. #endif
  392. #ifdef SO_BINDTODEVICE
  393. if ((dev)&&(strlen(dev)))
  394. setsockopt(udpSock,SOL_SOCKET,SO_BINDTODEVICE,dev,strlen(dev));
  395. #endif
  396. #if defined(__BSD__) && defined(IP_BOUND_IF)
  397. if ((dev) && (strlen(dev))) {
  398. int idx = if_nametoindex(dev);
  399. if (idx != 0)
  400. setsockopt(udpSock, IPPROTO_IP, IP_BOUND_IF, (void *)&idx, sizeof(idx));
  401. }
  402. #endif
  403. }
  404. extern "C" int ZT_GoNode_phyStartListen(ZT_GoNode *gn, const char *dev, const char *ip, const int port, const int primary)
  405. {
  406. if (strchr(ip, ':')) {
  407. struct sockaddr_in6 in6;
  408. memset(&in6, 0, sizeof(in6));
  409. in6.sin6_family = AF_INET6;
  410. if (inet_pton(AF_INET6, ip, &(in6.sin6_addr)) <= 0)
  411. return errno;
  412. in6.sin6_port = htons((uint16_t)port);
  413. ZT_SOCKET udpSock = socket(AF_INET6, SOCK_DGRAM, 0);
  414. if (udpSock == ZT_INVALID_SOCKET)
  415. return errno;
  416. setCommonUdpSocketSettings(udpSock, dev);
  417. SETSOCKOPT_FLAG_TYPE fl = SETSOCKOPT_FLAG_TRUE;
  418. setsockopt(udpSock, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&fl, sizeof(fl));
  419. #ifdef IPV6_DONTFRAG
  420. fl = SETSOCKOPT_FLAG_FALSE;
  421. setsockopt(udpSock, IPPROTO_IPV6, IPV6_DONTFRAG, reinterpret_cast<const char *>(&fl), sizeof(fl));
  422. #endif
  423. if (bind(udpSock, reinterpret_cast<const struct sockaddr *>(&in6), sizeof(in6)) != 0)
  424. return errno;
  425. {
  426. std::lock_guard< std::mutex > l(gn->threads_l);
  427. ZT_GoNodeThread &gnt = gn->threads[udpSock];
  428. gnt.ip = ip;
  429. gnt.port = port;
  430. gnt.af = AF_INET6;
  431. gnt.primary = (primary != 0);
  432. gnt.run = true;
  433. gnt.thr = std::thread([udpSock, gn, &gnt] {
  434. struct sockaddr_in6 in6;
  435. socklen_t salen;
  436. while (gnt.run) {
  437. salen = sizeof(in6);
  438. void *buf = ZT_getBuffer();
  439. if (buf) {
  440. int s = (int)recvfrom(udpSock, reinterpret_cast<char *>(buf), 16384, 0, reinterpret_cast<struct sockaddr *>(&in6), &salen);
  441. if (s > 0) {
  442. ZT_Node_processWirePacket(
  443. reinterpret_cast<ZT_Node *>(gn->node),
  444. nullptr,
  445. OSUtils::now(),
  446. (int64_t)udpSock,
  447. reinterpret_cast<const struct sockaddr_storage *>(&in6),
  448. buf,
  449. (unsigned int)s,
  450. 1,
  451. &(gn->nextBackgroundTaskDeadline));
  452. } else {
  453. ZT_freeBuffer(buf);
  454. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  455. }
  456. }
  457. }
  458. });
  459. }
  460. } else {
  461. struct sockaddr_in in;
  462. memset(&in, 0, sizeof(in));
  463. in.sin_family = AF_INET;
  464. if (inet_pton(AF_INET, ip, &(in.sin_addr)) <= 0)
  465. return errno;
  466. in.sin_port = htons((uint16_t)port);
  467. ZT_SOCKET udpSock = socket(AF_INET, SOCK_DGRAM, 0);
  468. if (udpSock == ZT_INVALID_SOCKET)
  469. return errno;
  470. setCommonUdpSocketSettings(udpSock, dev);
  471. #ifdef SO_NO_CHECK
  472. SETSOCKOPT_FLAG_TYPE fl = SETSOCKOPT_FLAG_TRUE;
  473. setsockopt(udpSock,SOL_SOCKET,SO_NO_CHECK,&fl,sizeof(fl));
  474. #endif
  475. if (bind(udpSock, reinterpret_cast<const struct sockaddr *>(&in), sizeof(in)) != 0)
  476. return errno;
  477. {
  478. std::lock_guard< std::mutex > l(gn->threads_l);
  479. ZT_GoNodeThread &gnt = gn->threads[udpSock];
  480. gnt.ip = ip;
  481. gnt.port = port;
  482. gnt.af = AF_INET6;
  483. gnt.primary = (primary != 0);
  484. gnt.run = true;
  485. gnt.thr = std::thread([udpSock, gn, &gnt] {
  486. struct sockaddr_in in4;
  487. socklen_t salen;
  488. while (gnt.run) {
  489. salen = sizeof(in4);
  490. void *buf = ZT_getBuffer();
  491. if (buf) {
  492. int s = (int)recvfrom(udpSock, reinterpret_cast<char *>(buf), sizeof(buf), 0, reinterpret_cast<struct sockaddr *>(&in4), &salen);
  493. if (s > 0) {
  494. ZT_Node_processWirePacket(
  495. reinterpret_cast<ZT_Node *>(gn->node),
  496. nullptr,
  497. OSUtils::now(),
  498. (int64_t)udpSock,
  499. reinterpret_cast<const struct sockaddr_storage *>(&in4),
  500. buf,
  501. (unsigned int)s,
  502. 1,
  503. &(gn->nextBackgroundTaskDeadline));
  504. } else {
  505. ZT_freeBuffer(buf);
  506. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  507. }
  508. }
  509. }
  510. });
  511. }
  512. }
  513. return 0;
  514. }
  515. extern "C" int ZT_GoNode_phyStopListen(ZT_GoNode *gn, const char *dev, const char *ip, const int port)
  516. {
  517. {
  518. std::lock_guard< std::mutex > l(gn->threads_l);
  519. for (auto t = gn->threads.begin(); t != gn->threads.end();) {
  520. if ((t->second.ip == ip) && (t->second.port == port)) {
  521. t->second.run = false;
  522. #ifdef __WINDOWS__
  523. shutdown(t->first, SD_BOTH);
  524. closesocket(t->first);
  525. #else
  526. shutdown(t->first, SHUT_RDWR);
  527. close(t->first);
  528. #endif
  529. t->second.thr.join();
  530. gn->threads.erase(t++);
  531. } else ++t;
  532. }
  533. }
  534. return 0;
  535. }
  536. 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)
  537. {
  538. ZT_Node_processVirtualNetworkFrame(
  539. reinterpret_cast<ZT_Node *>(reinterpret_cast<ZT_GoNode *>(uptr)->node),
  540. tptr,
  541. OSUtils::now(),
  542. nwid,
  543. from.toInt(),
  544. to.toInt(),
  545. etherType,
  546. vlanId,
  547. data,
  548. len,
  549. 0,
  550. &(reinterpret_cast<ZT_GoNode *>(uptr)->nextBackgroundTaskDeadline));
  551. }
  552. extern "C" ZT_GoTap *ZT_GoNode_join(ZT_GoNode *gn, uint64_t nwid, const ZT_Fingerprint *const controllerFingerprint)
  553. {
  554. try {
  555. std::lock_guard< std::mutex > l(gn->taps_l);
  556. auto existingTap = gn->taps.find(nwid);
  557. if (existingTap != gn->taps.end())
  558. return (ZT_GoTap *)existingTap->second.get();
  559. char tmp[256];
  560. OSUtils::ztsnprintf(tmp, sizeof(tmp), "ZeroTier Network %.16llx", (unsigned long long)nwid);
  561. 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));
  562. if (!tap)
  563. return nullptr;
  564. gn->taps[nwid] = tap;
  565. gn->node->join(nwid, controllerFingerprint, tap.get(), nullptr);
  566. return (ZT_GoTap *)tap.get();
  567. } catch (...) {
  568. return nullptr;
  569. }
  570. }
  571. extern "C" void ZT_GoNode_leave(ZT_GoNode *gn, uint64_t nwid)
  572. {
  573. std::lock_guard< std::mutex > l(gn->taps_l);
  574. auto existingTap = gn->taps.find(nwid);
  575. if (existingTap != gn->taps.end()) {
  576. gn->node->leave(nwid, nullptr, nullptr);
  577. gn->taps.erase(existingTap);
  578. }
  579. }
  580. extern "C" void ZT_GoTap_setEnabled(ZT_GoTap *tap, int enabled)
  581. {
  582. reinterpret_cast<EthernetTap *>(tap)->setEnabled(enabled != 0);
  583. }
  584. extern "C" int ZT_GoTap_addIp(ZT_GoTap *tap, int af, const void *ip, int netmaskBits)
  585. {
  586. switch (af) {
  587. case AF_INET:
  588. return (reinterpret_cast<EthernetTap *>(tap)->addIp(InetAddress(ip, 4, (unsigned int)netmaskBits)) ? 1 : 0);
  589. case AF_INET6:
  590. return (reinterpret_cast<EthernetTap *>(tap)->addIp(InetAddress(ip, 16, (unsigned int)netmaskBits)) ? 1 : 0);
  591. }
  592. return 0;
  593. }
  594. extern "C" int ZT_GoTap_removeIp(ZT_GoTap *tap, int af, const void *ip, int netmaskBits)
  595. {
  596. switch (af) {
  597. case AF_INET:
  598. return (reinterpret_cast<EthernetTap *>(tap)->removeIp(InetAddress(ip, 4, (unsigned int)netmaskBits)) ? 1 : 0);
  599. case AF_INET6:
  600. return (reinterpret_cast<EthernetTap *>(tap)->removeIp(InetAddress(ip, 16, (unsigned int)netmaskBits)) ? 1 : 0);
  601. }
  602. return 0;
  603. }
  604. extern "C" int ZT_GoTap_ips(ZT_GoTap *tap, void *buf, unsigned int bufSize)
  605. {
  606. auto ips = reinterpret_cast<EthernetTap *>(tap)->ips();
  607. unsigned int p = 0;
  608. uint8_t *const b = reinterpret_cast<uint8_t *>(buf);
  609. for (auto ip = ips.begin(); ip != ips.end(); ++ip) {
  610. if ((p + 6) > bufSize)
  611. break;
  612. const uint8_t *const ipd = reinterpret_cast<const uint8_t *>(ip->rawIpData());
  613. if (ip->isV4()) {
  614. b[p++] = AF_INET;
  615. b[p++] = ipd[0];
  616. b[p++] = ipd[1];
  617. b[p++] = ipd[2];
  618. b[p++] = ipd[3];
  619. b[p++] = (uint8_t)ip->netmaskBits();
  620. } else if (ip->isV6()) {
  621. if ((p + 18) <= bufSize) {
  622. b[p++] = AF_INET6;
  623. for (int j = 0; j < 16; ++j)
  624. b[p++] = ipd[j];
  625. b[p++] = (uint8_t)ip->netmaskBits();
  626. }
  627. }
  628. }
  629. return (int)p;
  630. }
  631. extern "C" void ZT_GoTap_deviceName(ZT_GoTap *tap, char nbuf[256])
  632. {
  633. Utils::scopy(nbuf, 256, reinterpret_cast<EthernetTap *>(tap)->deviceName().c_str());
  634. }
  635. extern "C" void ZT_GoTap_setFriendlyName(ZT_GoTap *tap, const char *friendlyName)
  636. {
  637. reinterpret_cast<EthernetTap *>(tap)->setFriendlyName(friendlyName);
  638. }
  639. extern "C" void ZT_GoTap_setMtu(ZT_GoTap *tap, unsigned int mtu)
  640. {
  641. reinterpret_cast<EthernetTap *>(tap)->setMtu(mtu);
  642. }
  643. #if defined(IFA_F_SECONDARY) && !defined(IFA_F_TEMPORARY)
  644. #define IFA_F_TEMPORARY IFA_F_SECONDARY
  645. #endif
  646. extern "C" int ZT_isTemporaryV6Address(const char *ifname, const struct sockaddr_storage *a)
  647. {
  648. #if defined(IN6_IFF_TEMPORARY) && defined(SIOCGIFAFLAG_IN6)
  649. static ZT_SOCKET s_tmpV6Socket = ZT_INVALID_SOCKET;
  650. static std::mutex s_lock;
  651. std::lock_guard< std::mutex > l(s_lock);
  652. if (s_tmpV6Socket == ZT_INVALID_SOCKET) {
  653. s_tmpV6Socket = socket(AF_INET6, SOCK_DGRAM, 0);
  654. if (s_tmpV6Socket <= 0)
  655. return 0;
  656. }
  657. struct in6_ifreq ifr;
  658. memset(&ifr, 0, sizeof(ifr));
  659. strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
  660. memcpy(&(ifr.ifr_addr), a, sizeof(sockaddr_in6));
  661. if (ioctl(s_tmpV6Socket, SIOCGIFAFLAG_IN6, &ifr) < 0) {
  662. return 0;
  663. }
  664. return ((ifr.ifr_ifru.ifru_flags6 & IN6_IFF_TEMPORARY) != 0) ? 1 : 0;
  665. #else
  666. return 0;
  667. #endif
  668. }
  669. extern "C" void *ZT_malloc(unsigned long s)
  670. { return (void *)malloc((size_t)s); }