NetBSDEthernetTap.cpp 13 KB

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