GoGlue.cpp 24 KB

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