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

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