NetBSDEthernetTap.cpp 14 KB

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