OSXEthernetTap.cpp.pcap-with-bridge-test 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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 <netinet/in.h>
  46. #include <arpa/inet.h>
  47. #include <net/route.h>
  48. #include <net/if.h>
  49. #include <net/if_arp.h>
  50. #include <net/if_dl.h>
  51. #include <net/if_media.h>
  52. #include <netinet6/in6_var.h>
  53. #include <netinet/in_var.h>
  54. #include <netinet/icmp6.h>
  55. #include <pcap/pcap.h>
  56. // OSX compile fix... in6_var defines this in a struct which namespaces it for C++ ... why?!?
  57. struct prf_ra {
  58. u_char onlink : 1;
  59. u_char autonomous : 1;
  60. u_char reserved : 6;
  61. } prf_ra;
  62. #include <netinet6/nd6.h>
  63. #include <ifaddrs.h>
  64. // These are KERNEL_PRIVATE... why?
  65. #ifndef SIOCAUTOCONF_START
  66. #define SIOCAUTOCONF_START _IOWR('i', 132, struct in6_ifreq) /* accept rtadvd on this interface */
  67. #endif
  68. #ifndef SIOCAUTOCONF_STOP
  69. #define SIOCAUTOCONF_STOP _IOWR('i', 133, struct in6_ifreq) /* stop accepting rtadv for this interface */
  70. #endif
  71. #ifndef ETH_ALEN
  72. #define ETH_ALEN 6
  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 "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. namespace ZeroTier {
  278. static std::set<std::string> globalDeviceNames;
  279. static Mutex globalTapCreateLock;
  280. OSXEthernetTap::OSXEthernetTap(
  281. const char *homePath,
  282. const MAC &mac,
  283. unsigned int mtu,
  284. unsigned int metric,
  285. uint64_t nwid,
  286. const char *friendlyName,
  287. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *data,unsigned int len),
  288. void *arg) :
  289. _handler(handler),
  290. _arg(arg),
  291. _pcap((void *)0),
  292. _nwid(nwid),
  293. _mac(mac),
  294. _homePath(homePath),
  295. _mtu(mtu),
  296. _metric(metric),
  297. _enabled(true)
  298. {
  299. char errbuf[PCAP_ERRBUF_SIZE];
  300. char devname[64],ethaddr[64],mtustr[32],metstr[32],nwids[32];
  301. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  302. if (mtu > 2800)
  303. throw std::runtime_error("max tap MTU is 2800");
  304. Mutex::Lock _gl(globalTapCreateLock);
  305. std::string desiredDevice;
  306. Dictionary devmap;
  307. {
  308. std::string devmapbuf;
  309. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),devmapbuf)) {
  310. devmap.fromString(devmapbuf);
  311. desiredDevice = devmap.get(nwids,"");
  312. }
  313. }
  314. if ((desiredDevice.length() >= 9)&&(desiredDevice.substr(0,6) == "bridge")) {
  315. // length() >= 9 matches bridge### or bridge####
  316. _dev = desiredDevice;
  317. } else {
  318. if (globalDeviceNames.size() >= (10000 - 128)) // sanity check... this would be nuts
  319. throw std::runtime_error("too many devices!");
  320. unsigned int pseudoBridgeNo = (unsigned int)((nwid ^ (nwid >> 32)) % (10000 - 128)) + 128; // range: bridge128 to bridge9999
  321. sprintf(devname,"bridge%u",pseudoBridgeNo);
  322. while (globalDeviceNames.count(std::string(devname)) > 0) {
  323. ++pseudoBridgeNo;
  324. if (pseudoBridgeNo > 9999)
  325. pseudoBridgeNo = 64;
  326. sprintf(devname,"bridge%u",pseudoBridgeNo);
  327. }
  328. _dev = devname;
  329. }
  330. // Configure MAC address and MTU, bring interface up
  331. long cpid = (long)vfork();
  332. if (cpid == 0) {
  333. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"create",(const char *)0);
  334. ::_exit(-1);
  335. } else if (cpid > 0) {
  336. int exitcode = -1;
  337. ::waitpid(cpid,&exitcode,0);
  338. if (exitcode != 0)
  339. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  340. } else throw std::runtime_error("unable to fork()");
  341. 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]);
  342. Utils::snprintf(mtustr,sizeof(mtustr),"%u",_mtu);
  343. Utils::snprintf(metstr,sizeof(metstr),"%u",_metric);
  344. cpid = (long)vfork();
  345. if (cpid == 0) {
  346. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"lladdr",ethaddr,"mtu",mtustr,"metric",metstr,"up",(const char *)0);
  347. ::_exit(-1);
  348. } else if (cpid > 0) {
  349. int exitcode = -1;
  350. ::waitpid(cpid,&exitcode,0);
  351. if (exitcode != 0)
  352. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  353. } else throw std::runtime_error("unable to fork()");
  354. _setIpv6Stuff(_dev.c_str(),true,false);
  355. _pcap = (void *)pcap_create(_dev.c_str(),errbuf);
  356. if (!_pcap) {
  357. cpid = (long)vfork();
  358. if (cpid == 0) {
  359. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"destroy",(const char *)0);
  360. ::_exit(-1);
  361. } else if (cpid > 0) {
  362. int exitcode = -1;
  363. ::waitpid(cpid,&exitcode,0);
  364. }
  365. throw std::runtime_error((std::string("pcap_create() on new bridge device failed: ") + errbuf).c_str());
  366. }
  367. pcap_set_promisc(reinterpret_cast<pcap_t *>(_pcap),1);
  368. pcap_set_timeout(reinterpret_cast<pcap_t *>(_pcap),120000);
  369. pcap_set_immediate_mode(reinterpret_cast<pcap_t *>(_pcap),1);
  370. if (pcap_set_buffer_size(reinterpret_cast<pcap_t *>(_pcap),1024 * 1024 * 16) != 0) // 16MB
  371. fprintf(stderr,"WARNING: pcap_set_buffer_size() failed!\n");
  372. if (pcap_set_snaplen(reinterpret_cast<pcap_t *>(_pcap),4096) != 0)
  373. fprintf(stderr,"WARNING: pcap_set_snaplen() failed!\n");
  374. if (pcap_activate(reinterpret_cast<pcap_t *>(_pcap)) != 0) {
  375. pcap_close(reinterpret_cast<pcap_t *>(_pcap));
  376. cpid = (long)vfork();
  377. if (cpid == 0) {
  378. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"destroy",(const char *)0);
  379. ::_exit(-1);
  380. } else if (cpid > 0) {
  381. int exitcode = -1;
  382. ::waitpid(cpid,&exitcode,0);
  383. }
  384. throw std::runtime_error("pcap_activate() on new bridge device failed.");
  385. }
  386. globalDeviceNames.insert(_dev);
  387. devmap[nwids] = _dev;
  388. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),devmap.toString());
  389. _thread = Thread::start(this);
  390. }
  391. OSXEthernetTap::~OSXEthernetTap()
  392. {
  393. _enabled = false;
  394. Mutex::Lock _gl(globalTapCreateLock);
  395. globalDeviceNames.erase(_dev);
  396. long cpid = (long)vfork();
  397. if (cpid == 0) {
  398. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"destroy",(const char *)0);
  399. ::_exit(-1);
  400. } else if (cpid > 0) {
  401. int exitcode = -1;
  402. ::waitpid(cpid,&exitcode,0);
  403. if (exitcode == 0) {
  404. // Destroying the interface nukes pcap and terminates the thread.
  405. Thread::join(_thread);
  406. }
  407. }
  408. pcap_close(reinterpret_cast<pcap_t *>(_pcap));
  409. }
  410. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  411. {
  412. long cpid = (long)vfork();
  413. if (cpid == 0) {
  414. execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  415. _exit(-1);
  416. } else if (cpid > 0) {
  417. int exitcode = -1;
  418. waitpid(cpid,&exitcode,0);
  419. return (exitcode == 0);
  420. }
  421. return false; // never reached, make compiler shut up about return value
  422. }
  423. bool OSXEthernetTap::addIp(const InetAddress &ip)
  424. {
  425. if (!ip)
  426. return false;
  427. std::vector<InetAddress> allIps(ips());
  428. if (std::binary_search(allIps.begin(),allIps.end(),ip))
  429. return true;
  430. // Remove and reconfigure if address is the same but netmask is different
  431. for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  432. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  433. if (___removeIp(_dev,*i))
  434. break;
  435. }
  436. }
  437. long cpid = (long)vfork();
  438. if (cpid == 0) {
  439. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  440. ::_exit(-1);
  441. } else if (cpid > 0) {
  442. int exitcode = -1;
  443. ::waitpid(cpid,&exitcode,0);
  444. return (exitcode == 0);
  445. } // else return false...
  446. return false;
  447. }
  448. bool OSXEthernetTap::removeIp(const InetAddress &ip)
  449. {
  450. if (!ip)
  451. return true;
  452. std::vector<InetAddress> allIps(ips());
  453. if (!std::binary_search(allIps.begin(),allIps.end(),ip)) {
  454. if (___removeIp(_dev,ip))
  455. return true;
  456. }
  457. return false;
  458. }
  459. std::vector<InetAddress> OSXEthernetTap::ips() const
  460. {
  461. struct ifaddrs *ifa = (struct ifaddrs *)0;
  462. if (getifaddrs(&ifa))
  463. return std::vector<InetAddress>();
  464. std::vector<InetAddress> r;
  465. struct ifaddrs *p = ifa;
  466. while (p) {
  467. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  468. switch(p->ifa_addr->sa_family) {
  469. case AF_INET: {
  470. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  471. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  472. r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  473. } break;
  474. case AF_INET6: {
  475. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  476. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  477. uint32_t b[4];
  478. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  479. 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])));
  480. } break;
  481. }
  482. }
  483. p = p->ifa_next;
  484. }
  485. if (ifa)
  486. freeifaddrs(ifa);
  487. std::sort(r.begin(),r.end());
  488. std::unique(r.begin(),r.end());
  489. return r;
  490. }
  491. void OSXEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  492. {
  493. char putBuf[4096];
  494. if ((len <= _mtu)&&(_enabled)) {
  495. to.copyTo(putBuf,6);
  496. from.copyTo(putBuf + 6,6);
  497. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  498. memcpy(putBuf + 14,data,len);
  499. len += 14;
  500. int r = pcap_inject(reinterpret_cast<pcap_t *>(_pcap),putBuf,len);
  501. if (r <= 0) {
  502. printf("%s: pcap_inject() failed\n",_dev.c_str());
  503. return;
  504. }
  505. printf("%s: inject %s -> %s etherType==%u len=%u r==%d\n",_dev.c_str(),from.toString().c_str(),to.toString().c_str(),etherType,len,r);
  506. }
  507. }
  508. std::string OSXEthernetTap::deviceName() const
  509. {
  510. return _dev;
  511. }
  512. void OSXEthernetTap::setFriendlyName(const char *friendlyName)
  513. {
  514. }
  515. void OSXEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  516. {
  517. std::vector<MulticastGroup> newGroups;
  518. struct _intl_ifmaddrs *ifmap = (struct _intl_ifmaddrs *)0;
  519. if (!_intl_getifmaddrs(&ifmap)) {
  520. struct _intl_ifmaddrs *p = ifmap;
  521. while (p) {
  522. if (p->ifma_addr->sa_family == AF_LINK) {
  523. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  524. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  525. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  526. newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  527. }
  528. p = p->ifma_next;
  529. }
  530. _intl_freeifmaddrs(ifmap);
  531. }
  532. std::vector<InetAddress> allIps(ips());
  533. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  534. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  535. std::sort(newGroups.begin(),newGroups.end());
  536. std::unique(newGroups.begin(),newGroups.end());
  537. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  538. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  539. added.push_back(*m);
  540. }
  541. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  542. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  543. removed.push_back(*m);
  544. }
  545. _multicastGroups.swap(newGroups);
  546. }
  547. static void _pcapHandler(u_char *ptr,const struct pcap_pkthdr *hdr,const u_char *data)
  548. {
  549. OSXEthernetTap *tap = reinterpret_cast<OSXEthernetTap *>(ptr);
  550. if (hdr->caplen > 14) {
  551. MAC to(data,6);
  552. MAC from(data + 6,6);
  553. if (from == tap->_mac) {
  554. unsigned int etherType = ntohs(((const uint16_t *)data)[6]);
  555. printf("%s: %s -> %s etherType==%u len==%u\n",tap->_dev.c_str(),from.toString().c_str(),to.toString().c_str(),etherType,(unsigned int)hdr->caplen);
  556. // TODO: VLAN support
  557. tap->_handler(tap->_arg,tap->_nwid,from,to,etherType,0,(const void *)(data + 14),hdr->len - 14);
  558. }
  559. }
  560. }
  561. void OSXEthernetTap::threadMain()
  562. throw()
  563. {
  564. pcap_loop(reinterpret_cast<pcap_t *>(_pcap),-1,&_pcapHandler,reinterpret_cast<u_char *>(this));
  565. }
  566. } // namespace ZeroTier