LinuxEthernetTap.cpp 15 KB

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