NetBSDEthernetTap.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  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. #include <stdint.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <errno.h>
  23. #include <unistd.h>
  24. #include <signal.h>
  25. #include <fcntl.h>
  26. #include <sys/types.h>
  27. #include <sys/stat.h>
  28. #include <sys/ioctl.h>
  29. #include <sys/wait.h>
  30. #include <sys/select.h>
  31. #include <sys/cdefs.h>
  32. #include <sys/uio.h>
  33. #include <sys/param.h>
  34. #include <sys/ioctl.h>
  35. #include <sys/socket.h>
  36. #include <netinet/in.h>
  37. #include <arpa/inet.h>
  38. #include <net/if.h>
  39. #include <ifaddrs.h>
  40. #include <net/if_arp.h>
  41. #include <net/if_dl.h>
  42. #include <net/if_media.h>
  43. #include <net/route.h>
  44. #include <sys/sysctl.h>
  45. #include "freebsd_getifmaddrs.h"
  46. #include <string>
  47. #include <map>
  48. #include <set>
  49. #include <algorithm>
  50. #include <utility>
  51. #include "../node/Constants.hpp"
  52. #include "../node/Utils.hpp"
  53. #include "../node/Mutex.hpp"
  54. #include "OSUtils.hpp"
  55. #include "NetBSDEthernetTap.hpp"
  56. #include <iostream>
  57. using namespace std;
  58. #define ZT_BASE32_CHARS "0123456789abcdefghijklmnopqrstuv"
  59. // ff:ff:ff:ff:ff:ff with no ADI
  60. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  61. namespace ZeroTier {
  62. NetBSDEthernetTap::NetBSDEthernetTap(
  63. const char *homePath,
  64. const MAC &mac,
  65. unsigned int mtu,
  66. unsigned int metric,
  67. uint64_t nwid,
  68. const char *friendlyName,
  69. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  70. void *arg) :
  71. _handler(handler),
  72. _arg(arg),
  73. _nwid(nwid),
  74. _mtu(mtu),
  75. _metric(metric),
  76. _fd(0),
  77. _enabled(true)
  78. {
  79. static Mutex globalTapCreateLock;
  80. char devpath[64],ethaddr[64],mtustr[32],metstr[32],tmpdevname[32];
  81. struct stat stattmp;
  82. // On FreeBSD at least we can rename, so use nwid to generate a deterministic unique zt#### name using base32
  83. // As a result we don't use desiredDevice
  84. _dev = "zt";
  85. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 60) & 0x1f)]);
  86. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 55) & 0x1f)]);
  87. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 50) & 0x1f)]);
  88. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 45) & 0x1f)]);
  89. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 40) & 0x1f)]);
  90. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 35) & 0x1f)]);
  91. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 30) & 0x1f)]);
  92. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 25) & 0x1f)]);
  93. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 20) & 0x1f)]);
  94. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 15) & 0x1f)]);
  95. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 10) & 0x1f)]);
  96. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 5) & 0x1f)]);
  97. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)(nwid & 0x1f)]);
  98. Mutex::Lock _gl(globalTapCreateLock);
  99. if (mtu > 2800)
  100. throw std::runtime_error("max tap MTU is 2800");
  101. // On NetBSD there are /dev/tap{0..3} pre-created and for a moment I will stick with only them
  102. std::vector<std::string> devFiles(OSUtils::listDirectory("/dev"));
  103. for(int i=0;i<4;++i) {
  104. Utils::snprintf(tmpdevname,sizeof(tmpdevname),"tap%d",i);
  105. Utils::snprintf(devpath,sizeof(devpath),"/dev/%s",tmpdevname);
  106. //if (std::find(devFiles.begin(),devFiles.end(),std::string(tmpdevname)) == devFiles.end()) {
  107. long cpid = (long)vfork();
  108. if (cpid == 0) {
  109. ::execl("/sbin/ifconfig","/sbin/ifconfig",tmpdevname,"create",(const char *)0);
  110. ::_exit(-1);
  111. } else if (cpid > 0) {
  112. int exitcode = -1;
  113. ::waitpid(cpid,&exitcode,0);
  114. } else throw std::runtime_error("fork() failed");
  115. _dev = tmpdevname;
  116. _fd = ::open( devpath,O_RDWR);
  117. if (!stat(devpath,&stattmp)) {
  118. /*cpid = (long)vfork();
  119. if (cpid == 0) {
  120. ::execl("/sbin/ifconfig","/sbin/ifconfig",tmpdevname,"name",_dev.c_str(),(const char *)0);
  121. ::_exit(-1);
  122. } else if (cpid > 0) {
  123. int exitcode = -1;
  124. ::waitpid(cpid,&exitcode,0);
  125. if (exitcode)
  126. throw std::runtime_error("ifconfig rename operation failed");
  127. } else throw std::runtime_error("fork() failed");*/
  128. if (_fd > 0)
  129. break;
  130. //else throw std::runtime_error("unable to open created tap device ");
  131. } else {
  132. throw std::runtime_error("cannot find /dev node for newly created tap device");
  133. }
  134. //}
  135. }
  136. if (_fd <= 0)
  137. throw std::runtime_error("unable to open TAP device or no more devices available");
  138. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  139. ::close(_fd);
  140. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  141. }
  142. // Configure MAC address and MTU, bring interface up
  143. 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]);
  144. Utils::snprintf(mtustr,sizeof(mtustr),"%u",_mtu);
  145. Utils::snprintf(metstr,sizeof(metstr),"%u",_metric);
  146. long cpid = (long)vfork();
  147. if (cpid == 0) {
  148. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"link",ethaddr,"mtu",mtustr,"metric",metstr,"up",(const char *)0);
  149. ::_exit(-1);
  150. } else if (cpid > 0) {
  151. int exitcode = -1;
  152. ::waitpid(cpid,&exitcode,0);
  153. if (exitcode) {
  154. ::close(_fd);
  155. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  156. }
  157. }
  158. // ifconfig link seems to be different from address
  159. // https://wiki.netbsd.org/tutorials/faking_a_mac_address/
  160. cpid = (long)vfork();
  161. if (cpid == 0) {
  162. string cmdline = "net.link.tap."+string(_dev);
  163. cmdline += "="+string(ethaddr);
  164. ::execl("/sbin/sysctl","/sbin/sysctl","-w",cmdline.c_str(),(const char *)0);
  165. ::_exit(-1);
  166. } else if (cpid > 0) {
  167. int exitcode = -1;
  168. ::waitpid(cpid,&exitcode,0);
  169. if (exitcode) {
  170. ::close(_fd);
  171. throw std::runtime_error("sysctl failure setting link-layer address and activating tap interface");
  172. }
  173. }
  174. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  175. fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  176. ::pipe(_shutdownSignalPipe);
  177. _thread = Thread::start(this);
  178. }
  179. NetBSDEthernetTap::~NetBSDEthernetTap()
  180. {
  181. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  182. Thread::join(_thread);
  183. ::close(_fd);
  184. ::close(_shutdownSignalPipe[0]);
  185. ::close(_shutdownSignalPipe[1]);
  186. long cpid = (long)vfork();
  187. if (cpid == 0) {
  188. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"destroy",(const char *)0);
  189. ::_exit(-1);
  190. } else if (cpid > 0) {
  191. int exitcode = -1;
  192. ::waitpid(cpid,&exitcode,0);
  193. }
  194. }
  195. void NetBSDEthernetTap::setEnabled(bool en)
  196. {
  197. _enabled = en;
  198. }
  199. bool NetBSDEthernetTap::enabled() const
  200. {
  201. return _enabled;
  202. }
  203. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  204. {
  205. long cpid = (long)vfork();
  206. if (cpid == 0) {
  207. execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  208. _exit(-1);
  209. } else if (cpid > 0) {
  210. int exitcode = -1;
  211. waitpid(cpid,&exitcode,0);
  212. return (exitcode == 0);
  213. }
  214. return false; // never reached, make compiler shut up about return value
  215. }
  216. bool NetBSDEthernetTap::addIp(const InetAddress &ip)
  217. {
  218. if (!ip)
  219. return false;
  220. std::vector<InetAddress> allIps(ips());
  221. if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end())
  222. return true; // IP/netmask already assigned
  223. // Remove and reconfigure if address is the same but netmask is different
  224. for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  225. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  226. if (___removeIp(_dev,*i))
  227. break;
  228. }
  229. }
  230. long cpid = (long)vfork();
  231. if (cpid == 0) {
  232. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  233. ::_exit(-1);
  234. } else if (cpid > 0) {
  235. int exitcode = -1;
  236. ::waitpid(cpid,&exitcode,0);
  237. return (exitcode == 0);
  238. }
  239. return false;
  240. }
  241. bool NetBSDEthernetTap::removeIp(const InetAddress &ip)
  242. {
  243. if (!ip)
  244. return false;
  245. std::vector<InetAddress> allIps(ips());
  246. if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end()) {
  247. if (___removeIp(_dev,ip))
  248. return true;
  249. }
  250. return false;
  251. }
  252. std::vector<InetAddress> NetBSDEthernetTap::ips() const
  253. {
  254. struct ifaddrs *ifa = (struct ifaddrs *)0;
  255. if (getifaddrs(&ifa))
  256. return std::vector<InetAddress>();
  257. std::vector<InetAddress> r;
  258. struct ifaddrs *p = ifa;
  259. while (p) {
  260. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  261. switch(p->ifa_addr->sa_family) {
  262. case AF_INET: {
  263. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  264. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  265. r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  266. } break;
  267. case AF_INET6: {
  268. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  269. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  270. uint32_t b[4];
  271. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  272. 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])));
  273. } break;
  274. }
  275. }
  276. p = p->ifa_next;
  277. }
  278. if (ifa)
  279. freeifaddrs(ifa);
  280. std::sort(r.begin(),r.end());
  281. std::unique(r.begin(),r.end());
  282. return r;
  283. }
  284. void NetBSDEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  285. {
  286. char putBuf[4096];
  287. if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) {
  288. to.copyTo(putBuf,6);
  289. from.copyTo(putBuf + 6,6);
  290. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  291. memcpy(putBuf + 14,data,len);
  292. len += 14;
  293. ::write(_fd,putBuf,len);
  294. }
  295. }
  296. std::string NetBSDEthernetTap::deviceName() const
  297. {
  298. return _dev;
  299. }
  300. void NetBSDEthernetTap::setFriendlyName(const char *friendlyName)
  301. {
  302. }
  303. void NetBSDEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  304. {
  305. std::vector<MulticastGroup> newGroups;
  306. struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
  307. if (!getifmaddrs(&ifmap)) {
  308. struct ifmaddrs *p = ifmap;
  309. while (p) {
  310. if (p->ifma_addr->sa_family == AF_LINK) {
  311. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  312. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  313. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  314. newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  315. }
  316. p = p->ifma_next;
  317. }
  318. freeifmaddrs(ifmap);
  319. }
  320. std::vector<InetAddress> allIps(ips());
  321. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  322. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  323. std::sort(newGroups.begin(),newGroups.end());
  324. std::unique(newGroups.begin(),newGroups.end());
  325. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  326. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  327. added.push_back(*m);
  328. }
  329. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  330. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  331. removed.push_back(*m);
  332. }
  333. _multicastGroups.swap(newGroups);
  334. }
  335. /*
  336. bool NetBSDEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  337. {
  338. std::set<MulticastGroup> newGroups;
  339. struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
  340. if (!getifmaddrs(&ifmap)) {
  341. struct ifmaddrs *p = ifmap;
  342. while (p) {
  343. if (p->ifma_addr->sa_family == AF_LINK) {
  344. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  345. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  346. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  347. newGroups.insert(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  348. }
  349. p = p->ifma_next;
  350. }
  351. freeifmaddrs(ifmap);
  352. }
  353. {
  354. std::set<InetAddress> allIps(ips());
  355. for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
  356. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  357. }
  358. bool changed = false;
  359. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  360. if (!groups.count(*mg)) {
  361. groups.insert(*mg);
  362. changed = true;
  363. }
  364. }
  365. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  366. if ((!newGroups.count(*mg))&&(*mg != _blindWildcardMulticastGroup)) {
  367. groups.erase(mg++);
  368. changed = true;
  369. } else ++mg;
  370. }
  371. return changed;
  372. }
  373. */
  374. void NetBSDEthernetTap::threadMain()
  375. throw()
  376. {
  377. fd_set readfds,nullfds;
  378. MAC to,from;
  379. int n,nfds,r;
  380. char getBuf[8194];
  381. // Wait for a moment after startup -- wait for Network to finish
  382. // constructing itself.
  383. Thread::sleep(500);
  384. FD_ZERO(&readfds);
  385. FD_ZERO(&nullfds);
  386. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  387. r = 0;
  388. for(;;) {
  389. FD_SET(_shutdownSignalPipe[0],&readfds);
  390. FD_SET(_fd,&readfds);
  391. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  392. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  393. break;
  394. if (FD_ISSET(_fd,&readfds)) {
  395. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  396. if (n < 0) {
  397. if ((errno != EINTR)&&(errno != ETIMEDOUT))
  398. break;
  399. } else {
  400. // Some tap drivers like to send the ethernet frame and the
  401. // payload in two chunks, so handle that by accumulating
  402. // data until we have at least a frame.
  403. r += n;
  404. if (r > 14) {
  405. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  406. r = _mtu + 14;
  407. if (_enabled) {
  408. to.setTo(getBuf,6);
  409. from.setTo(getBuf + 6,6);
  410. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  411. // TODO: VLAN support
  412. _handler(_arg,_nwid,from,to,etherType,0,(const void *)(getBuf + 14),r - 14);
  413. }
  414. r = 0;
  415. }
  416. }
  417. }
  418. }
  419. }
  420. } // namespace ZeroTier