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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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 <netinet/in.h>
  47. #include <arpa/inet.h>
  48. #include <net/route.h>
  49. #include <net/if.h>
  50. #include <net/if_arp.h>
  51. #include <net/if_dl.h>
  52. #include <net/if_media.h>
  53. #include <netinet6/in6_var.h>
  54. #include <netinet/in_var.h>
  55. #include <netinet/icmp6.h>
  56. #include <pcap/pcap.h>
  57. // OSX compile fix... in6_var defines this in a struct which namespaces it for C++ ... why?!?
  58. struct prf_ra {
  59. u_char onlink : 1;
  60. u_char autonomous : 1;
  61. u_char reserved : 6;
  62. } prf_ra;
  63. #include <netinet6/nd6.h>
  64. #include <ifaddrs.h>
  65. // These are KERNEL_PRIVATE... why?
  66. #ifndef SIOCAUTOCONF_START
  67. #define SIOCAUTOCONF_START _IOWR('i', 132, struct in6_ifreq) /* accept rtadvd on this interface */
  68. #endif
  69. #ifndef SIOCAUTOCONF_STOP
  70. #define SIOCAUTOCONF_STOP _IOWR('i', 133, struct in6_ifreq) /* stop accepting rtadv for this interface */
  71. #endif
  72. #ifndef ETH_ALEN
  73. #define ETH_ALEN 6
  74. #endif
  75. // --------------------------------------------------------------------------
  76. // --------------------------------------------------------------------------
  77. // This source is from:
  78. // http://www.opensource.apple.com/source/Libinfo/Libinfo-406.17/gen.subproj/getifmaddrs.c?txt
  79. // It's here because OSX 10.6 does not have this convenience function.
  80. #define SALIGN (sizeof(uint32_t) - 1)
  81. #define SA_RLEN(sa) ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : \
  82. (SALIGN + 1))
  83. #define MAX_SYSCTL_TRY 5
  84. #define RTA_MASKS (RTA_GATEWAY | RTA_IFP | RTA_IFA)
  85. /* FreeBSD uses NET_RT_IFMALIST and RTM_NEWMADDR from <sys/socket.h> */
  86. /* We can use NET_RT_IFLIST2 and RTM_NEWMADDR2 on Darwin */
  87. //#define DARWIN_COMPAT
  88. //#ifdef DARWIN_COMPAT
  89. #define GIM_SYSCTL_MIB NET_RT_IFLIST2
  90. #define GIM_RTM_ADDR RTM_NEWMADDR2
  91. //#else
  92. //#define GIM_SYSCTL_MIB NET_RT_IFMALIST
  93. //#define GIM_RTM_ADDR RTM_NEWMADDR
  94. //#endif
  95. // Not in 10.6 includes so use our own
  96. struct _intl_ifmaddrs {
  97. struct _intl_ifmaddrs *ifma_next;
  98. struct sockaddr *ifma_name;
  99. struct sockaddr *ifma_addr;
  100. struct sockaddr *ifma_lladdr;
  101. };
  102. static inline int _intl_getifmaddrs(struct _intl_ifmaddrs **pif)
  103. {
  104. int icnt = 1;
  105. int dcnt = 0;
  106. int ntry = 0;
  107. size_t len;
  108. size_t needed;
  109. int mib[6];
  110. int i;
  111. char *buf;
  112. char *data;
  113. char *next;
  114. char *p;
  115. struct ifma_msghdr2 *ifmam;
  116. struct _intl_ifmaddrs *ifa, *ift;
  117. struct rt_msghdr *rtm;
  118. struct sockaddr *sa;
  119. mib[0] = CTL_NET;
  120. mib[1] = PF_ROUTE;
  121. mib[2] = 0; /* protocol */
  122. mib[3] = 0; /* wildcard address family */
  123. mib[4] = GIM_SYSCTL_MIB;
  124. mib[5] = 0; /* no flags */
  125. do {
  126. if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
  127. return (-1);
  128. if ((buf = (char *)malloc(needed)) == NULL)
  129. return (-1);
  130. if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
  131. if (errno != ENOMEM || ++ntry >= MAX_SYSCTL_TRY) {
  132. free(buf);
  133. return (-1);
  134. }
  135. free(buf);
  136. buf = NULL;
  137. }
  138. } while (buf == NULL);
  139. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  140. rtm = (struct rt_msghdr *)(void *)next;
  141. if (rtm->rtm_version != RTM_VERSION)
  142. continue;
  143. switch (rtm->rtm_type) {
  144. case GIM_RTM_ADDR:
  145. ifmam = (struct ifma_msghdr2 *)(void *)rtm;
  146. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  147. break;
  148. icnt++;
  149. p = (char *)(ifmam + 1);
  150. for (i = 0; i < RTAX_MAX; i++) {
  151. if ((RTA_MASKS & ifmam->ifmam_addrs &
  152. (1 << i)) == 0)
  153. continue;
  154. sa = (struct sockaddr *)(void *)p;
  155. len = SA_RLEN(sa);
  156. dcnt += len;
  157. p += len;
  158. }
  159. break;
  160. }
  161. }
  162. data = (char *)malloc(sizeof(struct _intl_ifmaddrs) * icnt + dcnt);
  163. if (data == NULL) {
  164. free(buf);
  165. return (-1);
  166. }
  167. ifa = (struct _intl_ifmaddrs *)(void *)data;
  168. data += sizeof(struct _intl_ifmaddrs) * icnt;
  169. memset(ifa, 0, sizeof(struct _intl_ifmaddrs) * icnt);
  170. ift = ifa;
  171. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  172. rtm = (struct rt_msghdr *)(void *)next;
  173. if (rtm->rtm_version != RTM_VERSION)
  174. continue;
  175. switch (rtm->rtm_type) {
  176. case GIM_RTM_ADDR:
  177. ifmam = (struct ifma_msghdr2 *)(void *)rtm;
  178. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  179. break;
  180. p = (char *)(ifmam + 1);
  181. for (i = 0; i < RTAX_MAX; i++) {
  182. if ((RTA_MASKS & ifmam->ifmam_addrs &
  183. (1 << i)) == 0)
  184. continue;
  185. sa = (struct sockaddr *)(void *)p;
  186. len = SA_RLEN(sa);
  187. switch (i) {
  188. case RTAX_GATEWAY:
  189. ift->ifma_lladdr =
  190. (struct sockaddr *)(void *)data;
  191. memcpy(data, p, len);
  192. data += len;
  193. break;
  194. case RTAX_IFP:
  195. ift->ifma_name =
  196. (struct sockaddr *)(void *)data;
  197. memcpy(data, p, len);
  198. data += len;
  199. break;
  200. case RTAX_IFA:
  201. ift->ifma_addr =
  202. (struct sockaddr *)(void *)data;
  203. memcpy(data, p, len);
  204. data += len;
  205. break;
  206. default:
  207. data += len;
  208. break;
  209. }
  210. p += len;
  211. }
  212. ift->ifma_next = ift + 1;
  213. ift = ift->ifma_next;
  214. break;
  215. }
  216. }
  217. free(buf);
  218. if (ift > ifa) {
  219. ift--;
  220. ift->ifma_next = NULL;
  221. *pif = ifa;
  222. } else {
  223. *pif = NULL;
  224. free(ifa);
  225. }
  226. return (0);
  227. }
  228. static inline void _intl_freeifmaddrs(struct _intl_ifmaddrs *ifmp)
  229. {
  230. free(ifmp);
  231. }
  232. // --------------------------------------------------------------------------
  233. // --------------------------------------------------------------------------
  234. #include <string>
  235. #include <map>
  236. #include <set>
  237. #include <algorithm>
  238. #include "../node/Constants.hpp"
  239. #include "../node/Utils.hpp"
  240. #include "../node/Mutex.hpp"
  241. #include "../node/Dictionary.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. namespace ZeroTier {
  279. static std::set<std::string> globalDeviceNames;
  280. static Mutex globalTapCreateLock;
  281. OSXEthernetTap::OSXEthernetTap(
  282. const char *homePath,
  283. const MAC &mac,
  284. unsigned int mtu,
  285. unsigned int metric,
  286. uint64_t nwid,
  287. const char *friendlyName,
  288. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *data,unsigned int len),
  289. void *arg) :
  290. _handler(handler),
  291. _arg(arg),
  292. _pcap((void *)0),
  293. _nwid(nwid),
  294. _mac(mac),
  295. _homePath(homePath),
  296. _mtu(mtu),
  297. _metric(metric),
  298. _enabled(true)
  299. {
  300. char errbuf[PCAP_ERRBUF_SIZE];
  301. char devname[64],ethaddr[64],mtustr[32],metstr[32],nwids[32];
  302. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  303. if (mtu > 2800)
  304. throw std::runtime_error("max tap MTU is 2800");
  305. Mutex::Lock _gl(globalTapCreateLock);
  306. std::string desiredDevice;
  307. Dictionary devmap;
  308. {
  309. std::string devmapbuf;
  310. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),devmapbuf)) {
  311. devmap.fromString(devmapbuf);
  312. desiredDevice = devmap.get(nwids,"");
  313. }
  314. }
  315. if ((desiredDevice.length() >= 9)&&(desiredDevice.substr(0,6) == "bridge")) {
  316. // length() >= 9 matches bridge### or bridge####
  317. _dev = desiredDevice;
  318. } else {
  319. if (globalDeviceNames.size() >= (10000 - 128)) // sanity check... this would be nuts
  320. throw std::runtime_error("too many devices!");
  321. unsigned int pseudoBridgeNo = (unsigned int)((nwid ^ (nwid >> 32)) % (10000 - 128)) + 128; // range: bridge128 to bridge9999
  322. sprintf(devname,"bridge%u",pseudoBridgeNo);
  323. while (globalDeviceNames.count(std::string(devname)) > 0) {
  324. ++pseudoBridgeNo;
  325. if (pseudoBridgeNo > 9999)
  326. pseudoBridgeNo = 64;
  327. sprintf(devname,"bridge%u",pseudoBridgeNo);
  328. }
  329. _dev = devname;
  330. }
  331. // Configure MAC address and MTU, bring interface up
  332. long cpid = (long)vfork();
  333. if (cpid == 0) {
  334. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"create",(const char *)0);
  335. ::_exit(-1);
  336. } else if (cpid > 0) {
  337. int exitcode = -1;
  338. ::waitpid(cpid,&exitcode,0);
  339. if (exitcode != 0)
  340. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  341. } else throw std::runtime_error("unable to fork()");
  342. 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]);
  343. Utils::snprintf(mtustr,sizeof(mtustr),"%u",_mtu);
  344. Utils::snprintf(metstr,sizeof(metstr),"%u",_metric);
  345. cpid = (long)vfork();
  346. if (cpid == 0) {
  347. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"lladdr",ethaddr,"mtu",mtustr,"metric",metstr,"up",(const char *)0);
  348. ::_exit(-1);
  349. } else if (cpid > 0) {
  350. int exitcode = -1;
  351. ::waitpid(cpid,&exitcode,0);
  352. if (exitcode != 0)
  353. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  354. } else throw std::runtime_error("unable to fork()");
  355. _setIpv6Stuff(_dev.c_str(),true,false);
  356. _pcap = (void *)pcap_create(_dev.c_str(),errbuf);
  357. if (!_pcap) {
  358. cpid = (long)vfork();
  359. if (cpid == 0) {
  360. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"destroy",(const char *)0);
  361. ::_exit(-1);
  362. } else if (cpid > 0) {
  363. int exitcode = -1;
  364. ::waitpid(cpid,&exitcode,0);
  365. }
  366. throw std::runtime_error((std::string("pcap_create() on new bridge device failed: ") + errbuf).c_str());
  367. }
  368. pcap_set_promisc(reinterpret_cast<pcap_t *>(_pcap),1);
  369. pcap_set_timeout(reinterpret_cast<pcap_t *>(_pcap),120000);
  370. pcap_set_immediate_mode(reinterpret_cast<pcap_t *>(_pcap),1);
  371. if (pcap_set_buffer_size(reinterpret_cast<pcap_t *>(_pcap),1024 * 1024 * 16) != 0) // 16MB
  372. fprintf(stderr,"WARNING: pcap_set_buffer_size() failed!\n");
  373. if (pcap_set_snaplen(reinterpret_cast<pcap_t *>(_pcap),4096) != 0)
  374. fprintf(stderr,"WARNING: pcap_set_snaplen() failed!\n");
  375. if (pcap_activate(reinterpret_cast<pcap_t *>(_pcap)) != 0) {
  376. pcap_close(reinterpret_cast<pcap_t *>(_pcap));
  377. cpid = (long)vfork();
  378. if (cpid == 0) {
  379. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"destroy",(const char *)0);
  380. ::_exit(-1);
  381. } else if (cpid > 0) {
  382. int exitcode = -1;
  383. ::waitpid(cpid,&exitcode,0);
  384. }
  385. throw std::runtime_error("pcap_activate() on new bridge device failed.");
  386. }
  387. globalDeviceNames.insert(_dev);
  388. devmap[nwids] = _dev;
  389. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),devmap.toString());
  390. _thread = Thread::start(this);
  391. }
  392. OSXEthernetTap::~OSXEthernetTap()
  393. {
  394. _enabled = false;
  395. Mutex::Lock _gl(globalTapCreateLock);
  396. globalDeviceNames.erase(_dev);
  397. long cpid = (long)vfork();
  398. if (cpid == 0) {
  399. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"destroy",(const char *)0);
  400. ::_exit(-1);
  401. } else if (cpid > 0) {
  402. int exitcode = -1;
  403. ::waitpid(cpid,&exitcode,0);
  404. if (exitcode == 0) {
  405. // Destroying the interface nukes pcap and terminates the thread.
  406. Thread::join(_thread);
  407. }
  408. }
  409. pcap_close(reinterpret_cast<pcap_t *>(_pcap));
  410. }
  411. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  412. {
  413. long cpid = (long)vfork();
  414. if (cpid == 0) {
  415. execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  416. _exit(-1);
  417. } else if (cpid > 0) {
  418. int exitcode = -1;
  419. waitpid(cpid,&exitcode,0);
  420. return (exitcode == 0);
  421. }
  422. return false; // never reached, make compiler shut up about return value
  423. }
  424. bool OSXEthernetTap::addIp(const InetAddress &ip)
  425. {
  426. if (!ip)
  427. return false;
  428. std::vector<InetAddress> allIps(ips());
  429. if (std::binary_search(allIps.begin(),allIps.end(),ip))
  430. return true;
  431. // Remove and reconfigure if address is the same but netmask is different
  432. for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  433. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  434. if (___removeIp(_dev,*i))
  435. break;
  436. }
  437. }
  438. long cpid = (long)vfork();
  439. if (cpid == 0) {
  440. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  441. ::_exit(-1);
  442. } else if (cpid > 0) {
  443. int exitcode = -1;
  444. ::waitpid(cpid,&exitcode,0);
  445. return (exitcode == 0);
  446. } // else return false...
  447. return false;
  448. }
  449. bool OSXEthernetTap::removeIp(const InetAddress &ip)
  450. {
  451. if (!ip)
  452. return true;
  453. std::vector<InetAddress> allIps(ips());
  454. if (!std::binary_search(allIps.begin(),allIps.end(),ip)) {
  455. if (___removeIp(_dev,ip))
  456. return true;
  457. }
  458. return false;
  459. }
  460. std::vector<InetAddress> OSXEthernetTap::ips() const
  461. {
  462. struct ifaddrs *ifa = (struct ifaddrs *)0;
  463. if (getifaddrs(&ifa))
  464. return std::vector<InetAddress>();
  465. std::vector<InetAddress> r;
  466. struct ifaddrs *p = ifa;
  467. while (p) {
  468. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  469. switch(p->ifa_addr->sa_family) {
  470. case AF_INET: {
  471. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  472. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  473. r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  474. } break;
  475. case AF_INET6: {
  476. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  477. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  478. uint32_t b[4];
  479. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  480. 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])));
  481. } break;
  482. }
  483. }
  484. p = p->ifa_next;
  485. }
  486. if (ifa)
  487. freeifaddrs(ifa);
  488. std::sort(r.begin(),r.end());
  489. std::unique(r.begin(),r.end());
  490. return r;
  491. }
  492. void OSXEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  493. {
  494. char putBuf[4096];
  495. if ((len <= _mtu)&&(_enabled)) {
  496. to.copyTo(putBuf,6);
  497. from.copyTo(putBuf + 6,6);
  498. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  499. memcpy(putBuf + 14,data,len);
  500. len += 14;
  501. int r = pcap_inject(reinterpret_cast<pcap_t *>(_pcap),putBuf,len);
  502. if (r <= 0) {
  503. printf("%s: pcap_inject() failed\n",_dev.c_str());
  504. return;
  505. }
  506. 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);
  507. }
  508. }
  509. std::string OSXEthernetTap::deviceName() const
  510. {
  511. return _dev;
  512. }
  513. void OSXEthernetTap::setFriendlyName(const char *friendlyName)
  514. {
  515. }
  516. void OSXEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  517. {
  518. std::vector<MulticastGroup> newGroups;
  519. struct _intl_ifmaddrs *ifmap = (struct _intl_ifmaddrs *)0;
  520. if (!_intl_getifmaddrs(&ifmap)) {
  521. struct _intl_ifmaddrs *p = ifmap;
  522. while (p) {
  523. if (p->ifma_addr->sa_family == AF_LINK) {
  524. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  525. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  526. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  527. newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  528. }
  529. p = p->ifma_next;
  530. }
  531. _intl_freeifmaddrs(ifmap);
  532. }
  533. std::vector<InetAddress> allIps(ips());
  534. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  535. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  536. std::sort(newGroups.begin(),newGroups.end());
  537. std::unique(newGroups.begin(),newGroups.end());
  538. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  539. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  540. added.push_back(*m);
  541. }
  542. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  543. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  544. removed.push_back(*m);
  545. }
  546. _multicastGroups.swap(newGroups);
  547. }
  548. static void _pcapHandler(u_char *ptr,const struct pcap_pkthdr *hdr,const u_char *data)
  549. {
  550. OSXEthernetTap *tap = reinterpret_cast<OSXEthernetTap *>(ptr);
  551. if (hdr->caplen > 14) {
  552. MAC to(data,6);
  553. MAC from(data + 6,6);
  554. if (from == tap->_mac) {
  555. unsigned int etherType = ntohs(((const uint16_t *)data)[6]);
  556. 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);
  557. // TODO: VLAN support
  558. tap->_handler(tap->_arg,tap->_nwid,from,to,etherType,0,(const void *)(data + 14),hdr->len - 14);
  559. }
  560. }
  561. }
  562. void OSXEthernetTap::threadMain()
  563. throw()
  564. {
  565. pcap_loop(reinterpret_cast<pcap_t *>(_pcap),-1,&_pcapHandler,reinterpret_cast<u_char *>(this));
  566. }
  567. } // namespace ZeroTier