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