NetBSDEthernetTap.cpp 14 KB

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