OSXEthernetTap.cpp.utun-work-in-progress 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdint.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <errno.h>
  32. #include <unistd.h>
  33. #include <signal.h>
  34. #include <fcntl.h>
  35. #include <sys/types.h>
  36. #include <sys/stat.h>
  37. #include <sys/ioctl.h>
  38. #include <sys/wait.h>
  39. #include <sys/select.h>
  40. #include <sys/cdefs.h>
  41. #include <sys/uio.h>
  42. #include <sys/param.h>
  43. #include <sys/sysctl.h>
  44. #include <sys/ioctl.h>
  45. #include <sys/socket.h>
  46. #include <sys/sys_domain.h>
  47. #include <sys/kern_control.h>
  48. #include <net/if_utun.h>
  49. #include <netinet/in.h>
  50. #include <arpa/inet.h>
  51. #include <net/route.h>
  52. #include <net/if.h>
  53. #include <net/if_arp.h>
  54. #include <net/if_dl.h>
  55. #include <net/if_media.h>
  56. #include <netinet6/in6_var.h>
  57. #include <netinet/in_var.h>
  58. #include <netinet/icmp6.h>
  59. // OSX compile fix... in6_var defines this in a struct which namespaces it for C++ ... why?!?
  60. struct prf_ra {
  61. u_char onlink : 1;
  62. u_char autonomous : 1;
  63. u_char reserved : 6;
  64. } prf_ra;
  65. #include <netinet6/nd6.h>
  66. #include <ifaddrs.h>
  67. // These are KERNEL_PRIVATE... why?
  68. #ifndef SIOCAUTOCONF_START
  69. #define SIOCAUTOCONF_START _IOWR('i', 132, struct in6_ifreq) /* accept rtadvd on this interface */
  70. #endif
  71. #ifndef SIOCAUTOCONF_STOP
  72. #define SIOCAUTOCONF_STOP _IOWR('i', 133, struct in6_ifreq) /* stop accepting rtadv for this interface */
  73. #endif
  74. // --------------------------------------------------------------------------
  75. // --------------------------------------------------------------------------
  76. // This source is from:
  77. // http://www.opensource.apple.com/source/Libinfo/Libinfo-406.17/gen.subproj/getifmaddrs.c?txt
  78. // It's here because OSX 10.6 does not have this convenience function.
  79. #define SALIGN (sizeof(uint32_t) - 1)
  80. #define SA_RLEN(sa) ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : \
  81. (SALIGN + 1))
  82. #define MAX_SYSCTL_TRY 5
  83. #define RTA_MASKS (RTA_GATEWAY | RTA_IFP | RTA_IFA)
  84. /* FreeBSD uses NET_RT_IFMALIST and RTM_NEWMADDR from <sys/socket.h> */
  85. /* We can use NET_RT_IFLIST2 and RTM_NEWMADDR2 on Darwin */
  86. //#define DARWIN_COMPAT
  87. //#ifdef DARWIN_COMPAT
  88. #define GIM_SYSCTL_MIB NET_RT_IFLIST2
  89. #define GIM_RTM_ADDR RTM_NEWMADDR2
  90. //#else
  91. //#define GIM_SYSCTL_MIB NET_RT_IFMALIST
  92. //#define GIM_RTM_ADDR RTM_NEWMADDR
  93. //#endif
  94. // Not in 10.6 includes so use our own
  95. struct _intl_ifmaddrs {
  96. struct _intl_ifmaddrs *ifma_next;
  97. struct sockaddr *ifma_name;
  98. struct sockaddr *ifma_addr;
  99. struct sockaddr *ifma_lladdr;
  100. };
  101. static inline int _intl_getifmaddrs(struct _intl_ifmaddrs **pif)
  102. {
  103. int icnt = 1;
  104. int dcnt = 0;
  105. int ntry = 0;
  106. size_t len;
  107. size_t needed;
  108. int mib[6];
  109. int i;
  110. char *buf;
  111. char *data;
  112. char *next;
  113. char *p;
  114. struct ifma_msghdr2 *ifmam;
  115. struct _intl_ifmaddrs *ifa, *ift;
  116. struct rt_msghdr *rtm;
  117. struct sockaddr *sa;
  118. mib[0] = CTL_NET;
  119. mib[1] = PF_ROUTE;
  120. mib[2] = 0; /* protocol */
  121. mib[3] = 0; /* wildcard address family */
  122. mib[4] = GIM_SYSCTL_MIB;
  123. mib[5] = 0; /* no flags */
  124. do {
  125. if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
  126. return (-1);
  127. if ((buf = (char *)malloc(needed)) == NULL)
  128. return (-1);
  129. if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
  130. if (errno != ENOMEM || ++ntry >= MAX_SYSCTL_TRY) {
  131. free(buf);
  132. return (-1);
  133. }
  134. free(buf);
  135. buf = NULL;
  136. }
  137. } while (buf == NULL);
  138. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  139. rtm = (struct rt_msghdr *)(void *)next;
  140. if (rtm->rtm_version != RTM_VERSION)
  141. continue;
  142. switch (rtm->rtm_type) {
  143. case GIM_RTM_ADDR:
  144. ifmam = (struct ifma_msghdr2 *)(void *)rtm;
  145. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  146. break;
  147. icnt++;
  148. p = (char *)(ifmam + 1);
  149. for (i = 0; i < RTAX_MAX; i++) {
  150. if ((RTA_MASKS & ifmam->ifmam_addrs &
  151. (1 << i)) == 0)
  152. continue;
  153. sa = (struct sockaddr *)(void *)p;
  154. len = SA_RLEN(sa);
  155. dcnt += len;
  156. p += len;
  157. }
  158. break;
  159. }
  160. }
  161. data = (char *)malloc(sizeof(struct _intl_ifmaddrs) * icnt + dcnt);
  162. if (data == NULL) {
  163. free(buf);
  164. return (-1);
  165. }
  166. ifa = (struct _intl_ifmaddrs *)(void *)data;
  167. data += sizeof(struct _intl_ifmaddrs) * icnt;
  168. memset(ifa, 0, sizeof(struct _intl_ifmaddrs) * icnt);
  169. ift = ifa;
  170. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  171. rtm = (struct rt_msghdr *)(void *)next;
  172. if (rtm->rtm_version != RTM_VERSION)
  173. continue;
  174. switch (rtm->rtm_type) {
  175. case GIM_RTM_ADDR:
  176. ifmam = (struct ifma_msghdr2 *)(void *)rtm;
  177. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  178. break;
  179. p = (char *)(ifmam + 1);
  180. for (i = 0; i < RTAX_MAX; i++) {
  181. if ((RTA_MASKS & ifmam->ifmam_addrs &
  182. (1 << i)) == 0)
  183. continue;
  184. sa = (struct sockaddr *)(void *)p;
  185. len = SA_RLEN(sa);
  186. switch (i) {
  187. case RTAX_GATEWAY:
  188. ift->ifma_lladdr =
  189. (struct sockaddr *)(void *)data;
  190. memcpy(data, p, len);
  191. data += len;
  192. break;
  193. case RTAX_IFP:
  194. ift->ifma_name =
  195. (struct sockaddr *)(void *)data;
  196. memcpy(data, p, len);
  197. data += len;
  198. break;
  199. case RTAX_IFA:
  200. ift->ifma_addr =
  201. (struct sockaddr *)(void *)data;
  202. memcpy(data, p, len);
  203. data += len;
  204. break;
  205. default:
  206. data += len;
  207. break;
  208. }
  209. p += len;
  210. }
  211. ift->ifma_next = ift + 1;
  212. ift = ift->ifma_next;
  213. break;
  214. }
  215. }
  216. free(buf);
  217. if (ift > ifa) {
  218. ift--;
  219. ift->ifma_next = NULL;
  220. *pif = ifa;
  221. } else {
  222. *pif = NULL;
  223. free(ifa);
  224. }
  225. return (0);
  226. }
  227. static inline void _intl_freeifmaddrs(struct _intl_ifmaddrs *ifmp)
  228. {
  229. free(ifmp);
  230. }
  231. // --------------------------------------------------------------------------
  232. // --------------------------------------------------------------------------
  233. #include <string>
  234. #include <map>
  235. #include <set>
  236. #include <algorithm>
  237. #include "../node/Constants.hpp"
  238. #include "../node/Utils.hpp"
  239. #include "../node/Mutex.hpp"
  240. #include "../node/Dictionary.hpp"
  241. #include "Arp.hpp"
  242. #include "OSUtils.hpp"
  243. #include "OSXEthernetTap.hpp"
  244. // ff:ff:ff:ff:ff:ff with no ADI
  245. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  246. static inline bool _setIpv6Stuff(const char *ifname,bool performNUD,bool acceptRouterAdverts)
  247. {
  248. struct in6_ndireq nd;
  249. struct in6_ifreq ifr;
  250. int s = socket(AF_INET6,SOCK_DGRAM,0);
  251. if (s <= 0)
  252. return false;
  253. memset(&nd,0,sizeof(nd));
  254. strncpy(nd.ifname,ifname,sizeof(nd.ifname));
  255. if (ioctl(s,SIOCGIFINFO_IN6,&nd)) {
  256. close(s);
  257. return false;
  258. }
  259. unsigned long oldFlags = (unsigned long)nd.ndi.flags;
  260. if (performNUD)
  261. nd.ndi.flags |= ND6_IFF_PERFORMNUD;
  262. else nd.ndi.flags &= ~ND6_IFF_PERFORMNUD;
  263. if (oldFlags != (unsigned long)nd.ndi.flags) {
  264. if (ioctl(s,SIOCSIFINFO_FLAGS,&nd)) {
  265. close(s);
  266. return false;
  267. }
  268. }
  269. memset(&ifr,0,sizeof(ifr));
  270. strncpy(ifr.ifr_name,ifname,sizeof(ifr.ifr_name));
  271. if (ioctl(s,acceptRouterAdverts ? SIOCAUTOCONF_START : SIOCAUTOCONF_STOP,&ifr)) {
  272. close(s);
  273. return false;
  274. }
  275. close(s);
  276. return true;
  277. }
  278. // Create an OSX-native utun device (utun# where # is desiredNumber)
  279. // Adapted from public domain utun example code by Jonathan Levin
  280. static int _make_utun(int desiredNumber)
  281. {
  282. struct sockaddr_ctl sc;
  283. struct ctl_info ctlInfo;
  284. struct ifreq ifr;
  285. memset(&ctlInfo, 0, sizeof(ctlInfo));
  286. if (strlcpy(ctlInfo.ctl_name, UTUN_CONTROL_NAME, sizeof(ctlInfo.ctl_name)) >= sizeof(ctlInfo.ctl_name)) {
  287. return -1;
  288. }
  289. int fd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
  290. if (fd == -1)
  291. return -1;
  292. if (ioctl(fd, CTLIOCGINFO, &ctlInfo) == -1) {
  293. close(fd);
  294. return -1;
  295. }
  296. sc.sc_id = ctlInfo.ctl_id;
  297. sc.sc_len = sizeof(sc);
  298. sc.sc_family = AF_SYSTEM;
  299. sc.ss_sysaddr = AF_SYS_CONTROL;
  300. sc.sc_unit = desiredNumber + 1;
  301. if (connect(fd, (struct sockaddr *)&sc, sizeof(sc)) == -1) {
  302. close(fd);
  303. return -1;
  304. }
  305. memset(&ifr,0,sizeof(ifr));
  306. sprintf(ifr.ifr_name,"utun%d",desiredNumber);
  307. if (ioctl(fd,SIOCGIFFLAGS,(void *)&ifr) < 0) {
  308. printf("SIOCGIFFLAGS failed\n");
  309. }
  310. ifr.ifr_flags &= ~IFF_POINTOPOINT;
  311. if (ioctl(fd,SIOCSIFFLAGS,(void *)&ifr) < 0) {
  312. printf("clear IFF_POINTOPOINT failed\n");
  313. }
  314. return fd;
  315. }
  316. namespace ZeroTier {
  317. static long globalTapsRunning = 0;
  318. static Mutex globalTapCreateLock;
  319. OSXEthernetTap::OSXEthernetTap(
  320. const char *homePath,
  321. const MAC &mac,
  322. unsigned int mtu,
  323. unsigned int metric,
  324. uint64_t nwid,
  325. const char *friendlyName,
  326. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *data,unsigned int len),
  327. void *arg) :
  328. _handler(handler),
  329. _arg(arg),
  330. _arp((Arp *)0),
  331. _nwid(nwid),
  332. _homePath(homePath),
  333. _mtu(mtu),
  334. _metric(metric),
  335. _fd(0),
  336. _utun(false),
  337. _enabled(true)
  338. {
  339. char devpath[64],ethaddr[64],mtustr[32],metstr[32],nwids[32];
  340. struct stat stattmp;
  341. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  342. if (mtu > 2800)
  343. throw std::runtime_error("max tap MTU is 2800");
  344. Mutex::Lock _gl(globalTapCreateLock);
  345. // Read remembered previous device name, if any -- we'll try to reuse
  346. Dictionary devmap;
  347. std::string desiredDevice;
  348. {
  349. std::string devmapbuf;
  350. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),devmapbuf)) {
  351. devmap.fromString(devmapbuf);
  352. desiredDevice = devmap.get(nwids,"");
  353. }
  354. }
  355. if (::stat((_homePath + ZT_PATH_SEPARATOR_S + "tap.kext").c_str(),&stattmp) == 0) {
  356. // Try to init kext if it's there, otherwise revert to utun mode
  357. if (::stat("/dev/zt0",&stattmp)) {
  358. long kextpid = (long)vfork();
  359. if (kextpid == 0) {
  360. ::chdir(homePath);
  361. OSUtils::redirectUnixOutputs("/dev/null",(const char *)0);
  362. ::execl("/sbin/kextload","/sbin/kextload","-q","-repository",homePath,"tap.kext",(const char *)0);
  363. ::_exit(-1);
  364. } else if (kextpid > 0) {
  365. int exitcode = -1;
  366. ::waitpid(kextpid,&exitcode,0);
  367. }
  368. ::usleep(500); // give tap device driver time to start up and try again
  369. if (::stat("/dev/zt0",&stattmp))
  370. _utun = true;
  371. }
  372. if (!_utun) {
  373. // See if we can re-use the last device we had.
  374. bool recalledDevice = false;
  375. if (desiredDevice.length() > 2) {
  376. Utils::snprintf(devpath,sizeof(devpath),"/dev/%s",desiredDevice.c_str());
  377. if (stat(devpath,&stattmp) == 0) {
  378. _fd = ::open(devpath,O_RDWR);
  379. if (_fd > 0) {
  380. _dev = desiredDevice;
  381. recalledDevice = true;
  382. }
  383. }
  384. }
  385. // Open the first unused tap device if we didn't recall a previous one.
  386. if (!recalledDevice) {
  387. for(int i=0;i<64;++i) {
  388. Utils::snprintf(devpath,sizeof(devpath),"/dev/zt%d",i);
  389. if (stat(devpath,&stattmp)) {
  390. _utun = true;
  391. break;
  392. }
  393. _fd = ::open(devpath,O_RDWR);
  394. if (_fd > 0) {
  395. char foo[16];
  396. Utils::snprintf(foo,sizeof(foo),"zt%d",i);
  397. _dev = foo;
  398. break;
  399. }
  400. }
  401. }
  402. if (_fd <= 0)
  403. _utun = true;
  404. }
  405. } else {
  406. _utun = true;
  407. }
  408. if (_utun) {
  409. // Use OSX built-in utun device if kext is not available or doesn't work
  410. int utunNo = 0;
  411. if ((desiredDevice.length() > 4)&&(desiredDevice.substr(0,4) == "utun")) {
  412. utunNo = Utils::strToInt(desiredDevice.substr(4).c_str());
  413. if (utunNo >= 0)
  414. _fd = _make_utun(utunNo);
  415. }
  416. if (_fd <= 0) {
  417. // Start at utun8 to leave lower utuns unused since other stuff might
  418. // want them -- OpenVPN, cjdns, etc. I'm not sure if those are smart
  419. // enough to scan upward like this.
  420. for(utunNo=8;utunNo<=256;++utunNo) {
  421. if ((_fd = _make_utun(utunNo)) > 0)
  422. break;
  423. }
  424. }
  425. if (_fd <= 0)
  426. throw std::runtime_error("unable to find/load ZeroTier tap driver OR use built-in utun driver in OSX; permission or system problem or too many open devices?");
  427. Utils::snprintf(devpath,sizeof(devpath),"utun%d",utunNo);
  428. _dev = devpath;
  429. // Configure address and bring it up
  430. Utils::snprintf(mtustr,sizeof(mtustr),"%u",_mtu);
  431. Utils::snprintf(metstr,sizeof(metstr),"%u",_metric);
  432. long cpid = (long)vfork();
  433. if (cpid == 0) {
  434. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"mtu",mtustr,"metric",metstr,"up",(const char *)0);
  435. ::_exit(-1);
  436. } else if (cpid > 0) {
  437. int exitcode = -1;
  438. ::waitpid(cpid,&exitcode,0);
  439. if (exitcode) {
  440. ::close(_fd);
  441. throw std::runtime_error("ifconfig failure activating utun interface");
  442. }
  443. }
  444. } else {
  445. // Use our ZeroTier OSX tun/tap driver for zt# Ethernet tap device
  446. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  447. ::close(_fd);
  448. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  449. }
  450. // Configure MAC address and MTU, bring interface up
  451. Utils::snprintf(ethaddr,sizeof(ethaddr),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(int)mac[0],(int)mac[1],(int)mac[2],(int)mac[3],(int)mac[4],(int)mac[5]);
  452. Utils::snprintf(mtustr,sizeof(mtustr),"%u",_mtu);
  453. Utils::snprintf(metstr,sizeof(metstr),"%u",_metric);
  454. long cpid = (long)vfork();
  455. if (cpid == 0) {
  456. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"lladdr",ethaddr,"mtu",mtustr,"metric",metstr,"up",(const char *)0);
  457. ::_exit(-1);
  458. } else if (cpid > 0) {
  459. int exitcode = -1;
  460. ::waitpid(cpid,&exitcode,0);
  461. if (exitcode) {
  462. ::close(_fd);
  463. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  464. }
  465. }
  466. _setIpv6Stuff(_dev.c_str(),true,false);
  467. }
  468. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  469. fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  470. ::pipe(_shutdownSignalPipe);
  471. ++globalTapsRunning;
  472. devmap[nwids] = _dev;
  473. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),devmap.toString());
  474. _thread = Thread::start(this);
  475. }
  476. OSXEthernetTap::~OSXEthernetTap()
  477. {
  478. Mutex::Lock _gl(globalTapCreateLock);
  479. ::write(_shutdownSignalPipe[1],(const void *)this,1); // writing a byte causes thread to exit
  480. Thread::join(_thread);
  481. ::close(_fd);
  482. ::close(_shutdownSignalPipe[0]);
  483. ::close(_shutdownSignalPipe[1]);
  484. if (_utun) {
  485. delete _arp;
  486. } else {
  487. if (--globalTapsRunning <= 0) {
  488. globalTapsRunning = 0; // sanity check -- should not be possible
  489. char tmp[16384];
  490. sprintf(tmp,"%s/%s",_homePath.c_str(),"tap.kext");
  491. long kextpid = (long)vfork();
  492. if (kextpid == 0) {
  493. OSUtils::redirectUnixOutputs("/dev/null",(const char *)0);
  494. ::execl("/sbin/kextunload","/sbin/kextunload",tmp,(const char *)0);
  495. ::_exit(-1);
  496. } else if (kextpid > 0) {
  497. int exitcode = -1;
  498. ::waitpid(kextpid,&exitcode,0);
  499. }
  500. }
  501. }
  502. }
  503. void OSXEthernetTap::setEnabled(bool en)
  504. {
  505. _enabled = en;
  506. // TODO: interface status change
  507. }
  508. bool OSXEthernetTap::enabled() const
  509. {
  510. return _enabled;
  511. }
  512. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  513. {
  514. long cpid = (long)vfork();
  515. if (cpid == 0) {
  516. execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  517. _exit(-1);
  518. } else if (cpid > 0) {
  519. int exitcode = -1;
  520. waitpid(cpid,&exitcode,0);
  521. return (exitcode == 0);
  522. }
  523. return false; // never reached, make compiler shut up about return value
  524. }
  525. bool OSXEthernetTap::addIp(const InetAddress &ip)
  526. {
  527. if (!ip)
  528. return false;
  529. std::vector<InetAddress> allIps(ips());
  530. if (std::binary_search(allIps.begin(),allIps.end(),ip))
  531. return true;
  532. // Remove and reconfigure if address is the same but netmask is different
  533. for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  534. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  535. if (___removeIp(_dev,*i))
  536. break;
  537. }
  538. }
  539. if (_utun) {
  540. long cpid = (long)vfork();
  541. if (cpid == 0) {
  542. if (ip.ss_family == AF_INET6) {
  543. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"inet6",ip.toString().c_str(),"alias",(const char *)0);
  544. } else {
  545. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.toString().c_str(),ip.toIpString().c_str(),"alias",(const char *)0);
  546. }
  547. ::_exit(-1);
  548. } else if (cpid > 0) {
  549. int exitcode = -1;
  550. ::waitpid(cpid,&exitcode,0);
  551. if (exitcode == 0) {
  552. if (ip.ss_family == AF_INET) {
  553. // Add route to network over tun for IPv4 -- otherwise it behaves
  554. // as a simple point to point tunnel instead of a true route.
  555. cpid = (long)vfork();
  556. if (cpid == 0) {
  557. ::close(STDERR_FILENO);
  558. ::close(STDOUT_FILENO);
  559. ::execl("/sbin/route","/sbin/route","add",ip.network().toString().c_str(),ip.toIpString().c_str(),(const char *)0);
  560. ::exit(-1);
  561. } else if (cpid > 0) {
  562. int exitcode = -1;
  563. ::waitpid(cpid,&exitcode,0);
  564. return (exitcode == 0);
  565. }
  566. } else return true;
  567. }
  568. }
  569. } else {
  570. long cpid = (long)vfork();
  571. if (cpid == 0) {
  572. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  573. ::_exit(-1);
  574. } else if (cpid > 0) {
  575. int exitcode = -1;
  576. ::waitpid(cpid,&exitcode,0);
  577. return (exitcode == 0);
  578. }
  579. }
  580. return false;
  581. }
  582. bool OSXEthernetTap::removeIp(const InetAddress &ip)
  583. {
  584. if (!ip)
  585. return true;
  586. std::vector<InetAddress> allIps(ips());
  587. if (!std::binary_search(allIps.begin(),allIps.end(),ip)) {
  588. if (___removeIp(_dev,ip))
  589. return true;
  590. }
  591. return false;
  592. }
  593. std::vector<InetAddress> OSXEthernetTap::ips() const
  594. {
  595. struct ifaddrs *ifa = (struct ifaddrs *)0;
  596. if (getifaddrs(&ifa))
  597. return std::vector<InetAddress>();
  598. std::vector<InetAddress> r;
  599. struct ifaddrs *p = ifa;
  600. while (p) {
  601. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  602. switch(p->ifa_addr->sa_family) {
  603. case AF_INET: {
  604. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  605. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  606. r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  607. } break;
  608. case AF_INET6: {
  609. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  610. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  611. uint32_t b[4];
  612. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  613. r.push_back(InetAddress(sin->sin6_addr.s6_addr,16,Utils::countBits(b[0]) + Utils::countBits(b[1]) + Utils::countBits(b[2]) + Utils::countBits(b[3])));
  614. } break;
  615. }
  616. }
  617. p = p->ifa_next;
  618. }
  619. if (ifa)
  620. freeifaddrs(ifa);
  621. std::sort(r.begin(),r.end());
  622. std::unique(r.begin(),r.end());
  623. return r;
  624. }
  625. void OSXEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  626. {
  627. char putBuf[4096];
  628. if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) {
  629. to.copyTo(putBuf,6);
  630. from.copyTo(putBuf + 6,6);
  631. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  632. memcpy(putBuf + 14,data,len);
  633. len += 14;
  634. ::write(_fd,putBuf,len);
  635. }
  636. }
  637. std::string OSXEthernetTap::deviceName() const
  638. {
  639. return _dev;
  640. }
  641. void OSXEthernetTap::setFriendlyName(const char *friendlyName)
  642. {
  643. }
  644. void OSXEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  645. {
  646. std::vector<MulticastGroup> newGroups;
  647. struct _intl_ifmaddrs *ifmap = (struct _intl_ifmaddrs *)0;
  648. if (!_intl_getifmaddrs(&ifmap)) {
  649. struct _intl_ifmaddrs *p = ifmap;
  650. while (p) {
  651. if (p->ifma_addr->sa_family == AF_LINK) {
  652. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  653. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  654. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  655. newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  656. }
  657. p = p->ifma_next;
  658. }
  659. _intl_freeifmaddrs(ifmap);
  660. }
  661. std::vector<InetAddress> allIps(ips());
  662. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  663. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  664. std::sort(newGroups.begin(),newGroups.end());
  665. std::unique(newGroups.begin(),newGroups.end());
  666. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  667. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  668. added.push_back(*m);
  669. }
  670. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  671. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  672. removed.push_back(*m);
  673. }
  674. _multicastGroups.swap(newGroups);
  675. }
  676. void OSXEthernetTap::threadMain()
  677. throw()
  678. {
  679. fd_set readfds,nullfds;
  680. MAC to,from;
  681. int n,nfds,r;
  682. char getBuf[8194];
  683. Thread::sleep(500);
  684. FD_ZERO(&readfds);
  685. FD_ZERO(&nullfds);
  686. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  687. r = 0;
  688. for(;;) {
  689. FD_SET(_shutdownSignalPipe[0],&readfds);
  690. FD_SET(_fd,&readfds);
  691. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  692. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  693. break;
  694. if (FD_ISSET(_fd,&readfds)) {
  695. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  696. if (n < 0) {
  697. if ((errno != EINTR)&&(errno != ETIMEDOUT))
  698. break;
  699. } else {
  700. // Some tap drivers like to send the ethernet frame and the
  701. // payload in two chunks, so handle that by accumulating
  702. // data until we have at least a frame.
  703. r += n;
  704. if (r > 14) {
  705. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  706. r = _mtu + 14;
  707. if (_enabled) {
  708. to.setTo(getBuf,6);
  709. from.setTo(getBuf + 6,6);
  710. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  711. // TODO: VLAN support
  712. _handler(_arg,_nwid,from,to,etherType,0,(const void *)(getBuf + 14),r - 14);
  713. }
  714. r = 0;
  715. }
  716. }
  717. }
  718. }
  719. }
  720. } // namespace ZeroTier