LinuxEthernetTap.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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: 2023-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 "../node/Constants.hpp"
  14. #ifdef __LINUX__
  15. #include "../node/Utils.hpp"
  16. #include "../node/Mutex.hpp"
  17. #include "../node/Dictionary.hpp"
  18. #include "OSUtils.hpp"
  19. #include "LinuxEthernetTap.hpp"
  20. #include "LinuxNetLink.hpp"
  21. #include <stdint.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <unistd.h>
  26. #include <signal.h>
  27. #include <fcntl.h>
  28. #include <errno.h>
  29. #include <sys/types.h>
  30. #include <sys/stat.h>
  31. #include <sys/ioctl.h>
  32. #include <sys/wait.h>
  33. #include <sys/select.h>
  34. #include <netinet/in.h>
  35. #include <net/if_arp.h>
  36. #include <arpa/inet.h>
  37. #include <linux/if.h>
  38. #include <linux/if_tun.h>
  39. #include <linux/if_addr.h>
  40. #include <linux/if_ether.h>
  41. #include <ifaddrs.h>
  42. #include <algorithm>
  43. #include <utility>
  44. #include <string>
  45. // ff:ff:ff:ff:ff:ff with no ADI
  46. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  47. namespace ZeroTier {
  48. static Mutex __tapCreateLock;
  49. static const char _base32_chars[32] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','2','3','4','5','6','7' };
  50. static void _base32_5_to_8(const uint8_t *in,char *out)
  51. {
  52. out[0] = _base32_chars[(in[0]) >> 3];
  53. out[1] = _base32_chars[(in[0] & 0x07) << 2 | (in[1] & 0xc0) >> 6];
  54. out[2] = _base32_chars[(in[1] & 0x3e) >> 1];
  55. out[3] = _base32_chars[(in[1] & 0x01) << 4 | (in[2] & 0xf0) >> 4];
  56. out[4] = _base32_chars[(in[2] & 0x0f) << 1 | (in[3] & 0x80) >> 7];
  57. out[5] = _base32_chars[(in[3] & 0x7c) >> 2];
  58. out[6] = _base32_chars[(in[3] & 0x03) << 3 | (in[4] & 0xe0) >> 5];
  59. out[7] = _base32_chars[(in[4] & 0x1f)];
  60. }
  61. LinuxEthernetTap::LinuxEthernetTap(
  62. const char *homePath,
  63. const MAC &mac,
  64. unsigned int mtu,
  65. unsigned int metric,
  66. uint64_t nwid,
  67. const char *friendlyName,
  68. void (*handler)(void *,void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  69. void *arg) :
  70. _handler(handler),
  71. _arg(arg),
  72. _nwid(nwid),
  73. _homePath(homePath),
  74. _mtu(mtu),
  75. _fd(0),
  76. _enabled(true)
  77. {
  78. char procpath[128],nwids[32];
  79. struct stat sbuf;
  80. // ensure netlink connection is started
  81. (void)LinuxNetLink::getInstance();
  82. OSUtils::ztsnprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  83. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  84. _fd = ::open("/dev/net/tun",O_RDWR);
  85. if (_fd <= 0) {
  86. _fd = ::open("/dev/tun",O_RDWR);
  87. if (_fd <= 0)
  88. throw std::runtime_error(std::string("could not open TUN/TAP device: ") + strerror(errno));
  89. }
  90. struct ifreq ifr;
  91. memset(&ifr,0,sizeof(ifr));
  92. // Restore device names from legacy devicemap, but for new devices we use a base32-based canonical naming
  93. std::map<std::string,std::string> globalDeviceMap;
  94. FILE *devmapf = fopen((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),"r");
  95. if (devmapf) {
  96. char buf[256];
  97. while (fgets(buf,sizeof(buf),devmapf)) {
  98. char *x = (char *)0;
  99. char *y = (char *)0;
  100. char *saveptr = (char *)0;
  101. for(char *f=Utils::stok(buf,"\r\n=",&saveptr);(f);f=Utils::stok((char *)0,"\r\n=",&saveptr)) {
  102. if (!x) x = f;
  103. else if (!y) y = f;
  104. else break;
  105. }
  106. if ((x)&&(y)&&(x[0])&&(y[0]))
  107. globalDeviceMap[x] = y;
  108. }
  109. fclose(devmapf);
  110. }
  111. bool recalledDevice = false;
  112. std::map<std::string,std::string>::const_iterator gdmEntry = globalDeviceMap.find(nwids);
  113. if (gdmEntry != globalDeviceMap.end()) {
  114. Utils::scopy(ifr.ifr_name,sizeof(ifr.ifr_name),gdmEntry->second.c_str());
  115. OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  116. recalledDevice = (stat(procpath,&sbuf) != 0);
  117. }
  118. if (!recalledDevice) {
  119. #ifdef __SYNOLOGY__
  120. int devno = 50;
  121. do {
  122. OSUtils::ztsnprintf(ifr.ifr_name,sizeof(ifr.ifr_name),"eth%d",devno++);
  123. OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  124. } while (stat(procpath,&sbuf) == 0); // try zt#++ until we find one that does not exist
  125. #else
  126. uint64_t trial = 0; // incremented in the very unlikely event of a name collision with another network
  127. do {
  128. const uint64_t nwid40 = (nwid ^ (nwid >> 24)) + trial++;
  129. uint8_t tmp2[5];
  130. char tmp3[11];
  131. tmp2[0] = (uint8_t)((nwid40 >> 32) & 0xff);
  132. tmp2[1] = (uint8_t)((nwid40 >> 24) & 0xff);
  133. tmp2[2] = (uint8_t)((nwid40 >> 16) & 0xff);
  134. tmp2[3] = (uint8_t)((nwid40 >> 8) & 0xff);
  135. tmp2[4] = (uint8_t)(nwid40 & 0xff);
  136. tmp3[0] = 'z';
  137. tmp3[1] = 't';
  138. _base32_5_to_8(tmp2,tmp3 + 2);
  139. tmp3[10] = (char)0;
  140. memcpy(ifr.ifr_name,tmp3,11);
  141. OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  142. } while (stat(procpath,&sbuf) == 0);
  143. #endif
  144. }
  145. ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
  146. if (ioctl(_fd,TUNSETIFF,(void *)&ifr) < 0) {
  147. ::close(_fd);
  148. throw std::runtime_error("unable to configure TUN/TAP device for TAP operation");
  149. }
  150. _dev = ifr.ifr_name;
  151. ::ioctl(_fd,TUNSETPERSIST,0); // valgrind may generate a false alarm here
  152. // Open an arbitrary socket to talk to netlink
  153. int sock = socket(AF_INET,SOCK_DGRAM,0);
  154. if (sock <= 0) {
  155. ::close(_fd);
  156. throw std::runtime_error("unable to open netlink socket");
  157. }
  158. // Set MAC address
  159. ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER;
  160. mac.copyTo(ifr.ifr_ifru.ifru_hwaddr.sa_data,6);
  161. if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) {
  162. ::close(_fd);
  163. ::close(sock);
  164. throw std::runtime_error("unable to configure TAP hardware (MAC) address");
  165. return;
  166. }
  167. // Set MTU
  168. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  169. if (ioctl(sock,SIOCSIFMTU,(void *)&ifr) < 0) {
  170. ::close(_fd);
  171. ::close(sock);
  172. throw std::runtime_error("unable to configure TAP MTU");
  173. }
  174. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  175. ::close(_fd);
  176. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  177. }
  178. /* Bring interface up */
  179. if (ioctl(sock,SIOCGIFFLAGS,(void *)&ifr) < 0) {
  180. ::close(_fd);
  181. ::close(sock);
  182. throw std::runtime_error("unable to get TAP interface flags");
  183. }
  184. ifr.ifr_flags |= IFF_UP;
  185. if (ioctl(sock,SIOCSIFFLAGS,(void *)&ifr) < 0) {
  186. ::close(_fd);
  187. ::close(sock);
  188. throw std::runtime_error("unable to set TAP interface flags");
  189. }
  190. ::close(sock);
  191. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  192. ::fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  193. (void)::pipe(_shutdownSignalPipe);
  194. /*
  195. globalDeviceMap[nwids] = _dev;
  196. devmapf = fopen((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),"w");
  197. if (devmapf) {
  198. gdmEntry = globalDeviceMap.begin();
  199. while (gdmEntry != globalDeviceMap.end()) {
  200. fprintf(devmapf,"%s=%s\n",gdmEntry->first.c_str(),gdmEntry->second.c_str());
  201. ++gdmEntry;
  202. }
  203. fclose(devmapf);
  204. }
  205. */
  206. _thread = Thread::start(this);
  207. }
  208. LinuxEthernetTap::~LinuxEthernetTap()
  209. {
  210. (void)::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  211. Thread::join(_thread);
  212. ::close(_fd);
  213. ::close(_shutdownSignalPipe[0]);
  214. ::close(_shutdownSignalPipe[1]);
  215. }
  216. void LinuxEthernetTap::setEnabled(bool en)
  217. {
  218. _enabled = en;
  219. }
  220. bool LinuxEthernetTap::enabled() const
  221. {
  222. return _enabled;
  223. }
  224. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  225. {
  226. LinuxNetLink::getInstance().removeAddress(ip, _dev.c_str());
  227. return true;
  228. }
  229. bool LinuxEthernetTap::addIps(std::vector<InetAddress> ips)
  230. {
  231. #ifdef __SYNOLOGY__
  232. std::string filepath = "/etc/sysconfig/network-scripts/ifcfg-"+_dev;
  233. std::string cfg_contents = "DEVICE="+_dev+"\nBOOTPROTO=static";
  234. int ip4=0,ip6=0,ip4_tot=0,ip6_tot=0;
  235. for(int i=0; i<(int)ips.size(); i++) {
  236. if (ips[i].isV4())
  237. ip4_tot++;
  238. else
  239. ip6_tot++;
  240. }
  241. // Assemble and write contents of ifcfg-dev file
  242. for(int i=0; i<(int)ips.size(); i++) {
  243. if (ips[i].isV4()) {
  244. char iptmp[64],iptmp2[64];
  245. std::string numstr4 = ip4_tot > 1 ? std::to_string(ip4) : "";
  246. cfg_contents += "\nIPADDR"+numstr4+"="+ips[i].toIpString(iptmp)
  247. + "\nNETMASK"+numstr4+"="+ips[i].netmask().toIpString(iptmp2)+"\n";
  248. ip4++;
  249. } else {
  250. char iptmp[64],iptmp2[64];
  251. std::string numstr6 = ip6_tot > 1 ? std::to_string(ip6) : "";
  252. cfg_contents += "\nIPV6ADDR"+numstr6+"="+ips[i].toIpString(iptmp)
  253. + "\nNETMASK"+numstr6+"="+ips[i].netmask().toIpString(iptmp2)+"\n";
  254. ip6++;
  255. }
  256. }
  257. OSUtils::writeFile(filepath.c_str(), cfg_contents.c_str(), cfg_contents.length());
  258. // Finally, add IPs
  259. for(int i=0; i<(int)ips.size(); i++){
  260. LinuxNetLink::getInstance().addAddress(ips[i], _dev.c_str());
  261. }
  262. return true;
  263. #endif // __SYNOLOGY__
  264. return false;
  265. }
  266. bool LinuxEthernetTap::addIp(const InetAddress &ip)
  267. {
  268. if (!ip)
  269. return false;
  270. std::vector<InetAddress> allIps(ips());
  271. if (std::binary_search(allIps.begin(),allIps.end(),ip))
  272. return true;
  273. // Remove and reconfigure if address is the same but netmask is different
  274. for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  275. if (i->ipsEqual(ip))
  276. ___removeIp(_dev,*i);
  277. }
  278. LinuxNetLink::getInstance().addAddress(ip, _dev.c_str());
  279. return true;
  280. }
  281. bool LinuxEthernetTap::removeIp(const InetAddress &ip)
  282. {
  283. if (!ip)
  284. return true;
  285. std::vector<InetAddress> allIps(ips());
  286. if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end()) {
  287. if (___removeIp(_dev,ip))
  288. return true;
  289. }
  290. return false;
  291. }
  292. std::vector<InetAddress> LinuxEthernetTap::ips() const
  293. {
  294. struct ifaddrs *ifa = (struct ifaddrs *)0;
  295. if (getifaddrs(&ifa))
  296. return std::vector<InetAddress>();
  297. std::vector<InetAddress> r;
  298. struct ifaddrs *p = ifa;
  299. while (p) {
  300. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  301. switch(p->ifa_addr->sa_family) {
  302. case AF_INET: {
  303. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  304. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  305. r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  306. } break;
  307. case AF_INET6: {
  308. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  309. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  310. uint32_t b[4];
  311. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  312. 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])));
  313. } break;
  314. }
  315. }
  316. p = p->ifa_next;
  317. }
  318. if (ifa)
  319. freeifaddrs(ifa);
  320. std::sort(r.begin(),r.end());
  321. r.erase(std::unique(r.begin(),r.end()),r.end());
  322. return r;
  323. }
  324. void LinuxEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  325. {
  326. char putBuf[ZT_MAX_MTU + 64];
  327. if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) {
  328. to.copyTo(putBuf,6);
  329. from.copyTo(putBuf + 6,6);
  330. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  331. memcpy(putBuf + 14,data,len);
  332. len += 14;
  333. (void)::write(_fd,putBuf,len);
  334. }
  335. }
  336. std::string LinuxEthernetTap::deviceName() const
  337. {
  338. return _dev;
  339. }
  340. void LinuxEthernetTap::setFriendlyName(const char *friendlyName)
  341. {
  342. }
  343. void LinuxEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  344. {
  345. char *ptr,*ptr2;
  346. unsigned char mac[6];
  347. std::vector<MulticastGroup> newGroups;
  348. int fd = ::open("/proc/net/dev_mcast",O_RDONLY);
  349. if (fd > 0) {
  350. char buf[131072];
  351. int n = (int)::read(fd,buf,sizeof(buf));
  352. if ((n > 0)&&(n < (int)sizeof(buf))) {
  353. buf[n] = (char)0;
  354. for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) {
  355. int fno = 0;
  356. char *devname = (char *)0;
  357. char *mcastmac = (char *)0;
  358. for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) {
  359. if (fno == 1)
  360. devname = f;
  361. else if (fno == 4)
  362. mcastmac = f;
  363. ++fno;
  364. }
  365. if ((devname)&&(!strcmp(devname,_dev.c_str()))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6))
  366. newGroups.push_back(MulticastGroup(MAC(mac,6),0));
  367. }
  368. }
  369. ::close(fd);
  370. }
  371. std::vector<InetAddress> allIps(ips());
  372. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  373. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  374. std::sort(newGroups.begin(),newGroups.end());
  375. newGroups.erase(std::unique(newGroups.begin(),newGroups.end()),newGroups.end());
  376. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  377. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  378. added.push_back(*m);
  379. }
  380. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  381. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  382. removed.push_back(*m);
  383. }
  384. _multicastGroups.swap(newGroups);
  385. }
  386. void LinuxEthernetTap::setMtu(unsigned int mtu)
  387. {
  388. if (_mtu != mtu) {
  389. _mtu = mtu;
  390. int sock = socket(AF_INET,SOCK_DGRAM,0);
  391. if (sock > 0) {
  392. struct ifreq ifr;
  393. memset(&ifr,0,sizeof(ifr));
  394. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  395. ioctl(sock,SIOCSIFMTU,(void *)&ifr);
  396. close(sock);
  397. }
  398. }
  399. }
  400. void LinuxEthernetTap::threadMain()
  401. throw()
  402. {
  403. fd_set readfds,nullfds;
  404. MAC to,from;
  405. int n,nfds,r;
  406. char getBuf[ZT_MAX_MTU + 64];
  407. Thread::sleep(500);
  408. FD_ZERO(&readfds);
  409. FD_ZERO(&nullfds);
  410. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  411. r = 0;
  412. for(;;) {
  413. FD_SET(_shutdownSignalPipe[0],&readfds);
  414. FD_SET(_fd,&readfds);
  415. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  416. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  417. break;
  418. if (FD_ISSET(_fd,&readfds)) {
  419. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  420. if (n < 0) {
  421. if ((errno != EINTR)&&(errno != ETIMEDOUT))
  422. break;
  423. } else {
  424. // Some tap drivers like to send the ethernet frame and the
  425. // payload in two chunks, so handle that by accumulating
  426. // data until we have at least a frame.
  427. r += n;
  428. if (r > 14) {
  429. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  430. r = _mtu + 14;
  431. if (_enabled) {
  432. to.setTo(getBuf,6);
  433. from.setTo(getBuf + 6,6);
  434. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  435. // TODO: VLAN support
  436. _handler(_arg,(void *)0,_nwid,from,to,etherType,0,(const void *)(getBuf + 14),r - 14);
  437. }
  438. r = 0;
  439. }
  440. }
  441. }
  442. }
  443. }
  444. } // namespace ZeroTier
  445. #endif // __LINUX__