LinuxEthernetTap.cpp 14 KB

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