MacEthernetTap.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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/route.h>
  47. #include <net/if.h>
  48. #include <net/if_dl.h>
  49. #include <sys/sysctl.h>
  50. #include <ifaddrs.h>
  51. #include <string>
  52. #include <map>
  53. #include <set>
  54. #include <algorithm>
  55. #include "../node/Constants.hpp"
  56. #include "../node/Utils.hpp"
  57. #include "../node/Mutex.hpp"
  58. #include "../node/Dictionary.hpp"
  59. #include "OSUtils.hpp"
  60. #include "MacEthernetTap.hpp"
  61. #include "MacEthernetTapAgent.h"
  62. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  63. namespace ZeroTier {
  64. static Mutex globalTapCreateLock;
  65. static bool globalTapInitialized = false;
  66. MacEthernetTap::MacEthernetTap(
  67. const char *homePath,
  68. const MAC &mac,
  69. unsigned int mtu,
  70. unsigned int metric,
  71. uint64_t nwid,
  72. const char *friendlyName,
  73. void (*handler)(void *,void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *data,unsigned int len),
  74. void *arg) :
  75. _handler(handler),
  76. _arg(arg),
  77. _nwid(nwid),
  78. _homePath(homePath),
  79. _mtu(mtu),
  80. _metric(metric),
  81. _agentStdin(-1),
  82. _agentStdout(-1),
  83. _agentStderr(-1),
  84. _agentStdin2(-1),
  85. _agentStdout2(-1),
  86. _agentStderr2(-1),
  87. _agentPid(-1),
  88. _enabled(true)
  89. {
  90. char ethaddr[64],mtustr[16],devnostr[16],devstr[16],metricstr[16];
  91. OSUtils::ztsnprintf(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]);
  92. OSUtils::ztsnprintf(mtustr,sizeof(mtustr),"%u",mtu);
  93. OSUtils::ztsnprintf(metricstr,sizeof(metricstr),"%u",metric);
  94. std::string agentPath(homePath);
  95. agentPath.push_back(ZT_PATH_SEPARATOR);
  96. agentPath.append("MacEthernetTapAgent");
  97. if (!OSUtils::fileExists(agentPath.c_str()))
  98. throw std::runtime_error("MacEthernetTapAgent not installed in ZeroTier home");
  99. Mutex::Lock _gl(globalTapCreateLock); // only make one at a time
  100. // Destroy all feth devices on first tap start in case ZeroTier did not exit cleanly last time.
  101. // We leave interfaces less than feth100 alone in case something else is messing with feth devices.
  102. if (!globalTapInitialized) {
  103. globalTapInitialized = true;
  104. struct ifaddrs *ifa = (struct ifaddrs *)0;
  105. std::set<std::string> deleted;
  106. if (!getifaddrs(&ifa)) {
  107. struct ifaddrs *p = ifa;
  108. while (p) {
  109. if ((!strncmp(p->ifa_name,"feth",4))&&(strlen(p->ifa_name) >= 7)&&(deleted.count(std::string(p->ifa_name)) == 0)) {
  110. deleted.insert(std::string(p->ifa_name));
  111. const char *args[4];
  112. args[0] = "/sbin/ifconfig";
  113. args[1] = p->ifa_name;
  114. args[2] = "destroy";
  115. args[3] = (char *)0;
  116. const pid_t pid = vfork();
  117. if (pid == 0) {
  118. execv(args[0],const_cast<char **>(args));
  119. _exit(-1);
  120. } else if (pid > 0) {
  121. int rv = 0;
  122. waitpid(pid,&rv,0);
  123. }
  124. }
  125. p = p->ifa_next;
  126. }
  127. freeifaddrs(ifa);
  128. }
  129. }
  130. unsigned int devNo = 100 + ((nwid ^ (nwid >> 32) ^ (nwid >> 48)) % 4900);
  131. for(;;) {
  132. OSUtils::ztsnprintf(devnostr,sizeof(devnostr),"%u",devNo);
  133. OSUtils::ztsnprintf(devstr,sizeof(devstr),"feth%u",devNo);
  134. bool duplicate = false;
  135. struct ifaddrs *ifa = (struct ifaddrs *)0;
  136. if (!getifaddrs(&ifa)) {
  137. struct ifaddrs *p = ifa;
  138. while (p) {
  139. if (!strcmp(p->ifa_name,devstr)) {
  140. duplicate = true;
  141. break;
  142. }
  143. p = p->ifa_next;
  144. }
  145. freeifaddrs(ifa);
  146. }
  147. if (duplicate) {
  148. devNo = (devNo + 1) % 5000;
  149. if (devNo < 100)
  150. devNo = 100;
  151. } else {
  152. break;
  153. }
  154. }
  155. _dev = devstr;
  156. if (::pipe(_shutdownSignalPipe))
  157. throw std::runtime_error("pipe creation failed");
  158. int agentStdin[2];
  159. int agentStdout[2];
  160. int agentStderr[2];
  161. if (::pipe(agentStdin))
  162. throw std::runtime_error("pipe creation failed");
  163. if (::pipe(agentStdout))
  164. throw std::runtime_error("pipe creation failed");
  165. if (::pipe(agentStderr))
  166. throw std::runtime_error("pipe creation failed");
  167. _agentStdin = agentStdin[1];
  168. _agentStdout = agentStdout[0];
  169. _agentStderr = agentStderr[0];
  170. _agentStdin2 = agentStdin[0];
  171. _agentStdout2 = agentStdout[1];
  172. _agentStderr2 = agentStderr[1];
  173. long apid = (long)fork();
  174. if (apid < 0) {
  175. throw std::runtime_error("fork failed");
  176. } else if (apid == 0) {
  177. ::dup2(agentStdin[0],STDIN_FILENO);
  178. ::dup2(agentStdout[1],STDOUT_FILENO);
  179. ::dup2(agentStderr[1],STDERR_FILENO);
  180. ::close(agentStdin[0]);
  181. ::close(agentStdin[1]);
  182. ::close(agentStdout[0]);
  183. ::close(agentStdout[1]);
  184. ::close(agentStderr[0]);
  185. ::close(agentStderr[1]);
  186. ::execl(agentPath.c_str(),agentPath.c_str(),devnostr,ethaddr,mtustr,metricstr,(char *)0);
  187. ::_exit(-1);
  188. } else {
  189. _agentPid = apid;
  190. }
  191. Thread::sleep(100); // this causes them to come up in a more user-friendly order on launch
  192. _thread = Thread::start(this);
  193. }
  194. MacEthernetTap::~MacEthernetTap()
  195. {
  196. Mutex::Lock _gl(globalTapCreateLock);
  197. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  198. Thread::join(_thread);
  199. ::close(_shutdownSignalPipe[0]);
  200. ::close(_shutdownSignalPipe[1]);
  201. int ec = 0;
  202. ::kill(_agentPid,SIGTERM);
  203. ::waitpid(_agentPid,&ec,0);
  204. ::close(_agentStdin);
  205. ::close(_agentStdout);
  206. ::close(_agentStderr);
  207. ::close(_agentStdin2);
  208. ::close(_agentStdout2);
  209. ::close(_agentStderr2);
  210. }
  211. void MacEthernetTap::setEnabled(bool en) { _enabled = en; }
  212. bool MacEthernetTap::enabled() const { return _enabled; }
  213. bool MacEthernetTap::addIp(const InetAddress &ip)
  214. {
  215. char tmp[128];
  216. if (!ip)
  217. return false;
  218. std::string cmd;
  219. cmd.push_back((char)ZT_MACETHERNETTAPAGENT_STDIN_CMD_IFCONFIG);
  220. cmd.append((ip.ss_family == AF_INET6) ? "inet6" : "inet");
  221. cmd.push_back(0);
  222. cmd.append(ip.toString(tmp));
  223. cmd.push_back(0);
  224. cmd.append("alias");
  225. cmd.push_back(0);
  226. uint16_t l = (uint16_t)cmd.length();
  227. _putLock.lock();
  228. write(_agentStdin,&l,2);
  229. write(_agentStdin,cmd.data(),cmd.length());
  230. _putLock.unlock();
  231. return true;
  232. }
  233. bool MacEthernetTap::removeIp(const InetAddress &ip)
  234. {
  235. char tmp[128];
  236. if (!ip)
  237. return false;
  238. std::string cmd;
  239. cmd.push_back((char)ZT_MACETHERNETTAPAGENT_STDIN_CMD_IFCONFIG);
  240. cmd.append((ip.ss_family == AF_INET6) ? "inet6" : "inet");
  241. cmd.push_back(0);
  242. cmd.append(ip.toString(tmp));
  243. cmd.push_back(0);
  244. cmd.append("-alias");
  245. cmd.push_back(0);
  246. uint16_t l = (uint16_t)cmd.length();
  247. _putLock.lock();
  248. write(_agentStdin,&l,2);
  249. write(_agentStdin,cmd.data(),cmd.length());
  250. _putLock.unlock();
  251. return true;
  252. }
  253. std::vector<InetAddress> MacEthernetTap::ips() const
  254. {
  255. struct ifaddrs *ifa = (struct ifaddrs *)0;
  256. std::vector<InetAddress> r;
  257. if (!getifaddrs(&ifa)) {
  258. struct ifaddrs *p = ifa;
  259. while (p) {
  260. if ((p->ifa_name)&&(!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)) {
  261. switch(p->ifa_addr->sa_family) {
  262. case AF_INET: {
  263. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  264. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  265. r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  266. } break;
  267. case AF_INET6: {
  268. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  269. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  270. uint32_t b[4];
  271. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  272. 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])));
  273. } break;
  274. }
  275. }
  276. p = p->ifa_next;
  277. }
  278. freeifaddrs(ifa);
  279. }
  280. std::sort(r.begin(),r.end());
  281. r.erase(std::unique(r.begin(),r.end()),r.end());
  282. return r;
  283. }
  284. void MacEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  285. {
  286. struct iovec iov[3];
  287. unsigned char hdr[15];
  288. uint16_t l;
  289. if ((_agentStdin > 0)&&(len <= _mtu)&&(_enabled)) {
  290. hdr[0] = ZT_MACETHERNETTAPAGENT_STDIN_CMD_PACKET;
  291. to.copyTo(hdr + 1,6);
  292. from.copyTo(hdr + 7,6);
  293. hdr[13] = (unsigned char)((etherType >> 8) & 0xff);
  294. hdr[14] = (unsigned char)(etherType & 0xff);
  295. l = (uint16_t)(len + 15);
  296. iov[0].iov_base = &l;
  297. iov[0].iov_len = 2;
  298. iov[1].iov_base = hdr;
  299. iov[1].iov_len = 15;
  300. iov[2].iov_base = const_cast<void *>(data);
  301. iov[2].iov_len = len;
  302. _putLock.lock();
  303. writev(_agentStdin,iov,3);
  304. _putLock.unlock();
  305. }
  306. }
  307. std::string MacEthernetTap::deviceName() const { return _dev; }
  308. void MacEthernetTap::setFriendlyName(const char *friendlyName) {}
  309. void MacEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  310. {
  311. std::vector<MulticastGroup> newGroups;
  312. struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
  313. if (!getifmaddrs(&ifmap)) {
  314. struct ifmaddrs *p = ifmap;
  315. while (p) {
  316. if (p->ifma_addr->sa_family == AF_LINK) {
  317. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  318. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  319. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  320. newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  321. }
  322. p = p->ifma_next;
  323. }
  324. freeifmaddrs(ifmap);
  325. }
  326. std::vector<InetAddress> allIps(ips());
  327. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  328. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  329. std::sort(newGroups.begin(),newGroups.end());
  330. newGroups.erase(std::unique(newGroups.begin(),newGroups.end()),newGroups.end());
  331. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  332. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  333. added.push_back(*m);
  334. }
  335. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  336. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  337. removed.push_back(*m);
  338. }
  339. _multicastGroups.swap(newGroups);
  340. }
  341. void MacEthernetTap::setMtu(unsigned int mtu)
  342. {
  343. if (_mtu != mtu) {
  344. char tmp[16];
  345. std::string cmd;
  346. cmd.push_back((char)ZT_MACETHERNETTAPAGENT_STDIN_CMD_IFCONFIG);
  347. cmd.append("mtu");
  348. cmd.push_back(0);
  349. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%u",mtu);
  350. cmd.append(tmp);
  351. cmd.push_back(0);
  352. uint16_t l = (uint16_t)cmd.length();
  353. _putLock.lock();
  354. write(_agentStdin,&l,2);
  355. write(_agentStdin,cmd.data(),cmd.length());
  356. _putLock.unlock();
  357. _mtu = mtu;
  358. }
  359. }
  360. #define ZT_MACETHERNETTAP_AGENT_READ_BUF_SIZE 131072
  361. void MacEthernetTap::threadMain()
  362. throw()
  363. {
  364. char agentReadBuf[ZT_MACETHERNETTAP_AGENT_READ_BUF_SIZE];
  365. char agentStderrBuf[256];
  366. fd_set readfds,nullfds;
  367. MAC to,from;
  368. Thread::sleep(250);
  369. const int nfds = std::max(std::max(_shutdownSignalPipe[0],_agentStdout),_agentStderr) + 1;
  370. long agentReadPtr = 0;
  371. fcntl(_agentStdout,F_SETFL,fcntl(_agentStdout,F_GETFL)|O_NONBLOCK);
  372. fcntl(_agentStderr,F_SETFL,fcntl(_agentStderr,F_GETFL)|O_NONBLOCK);
  373. FD_ZERO(&readfds);
  374. FD_ZERO(&nullfds);
  375. for(;;) {
  376. FD_SET(_shutdownSignalPipe[0],&readfds);
  377. FD_SET(_agentStdout,&readfds);
  378. FD_SET(_agentStderr,&readfds);
  379. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  380. if (FD_ISSET(_shutdownSignalPipe[0],&readfds))
  381. break;
  382. if (FD_ISSET(_agentStdout,&readfds)) {
  383. long n = (long)read(_agentStdout,agentReadBuf + agentReadPtr,ZT_MACETHERNETTAP_AGENT_READ_BUF_SIZE - agentReadPtr);
  384. if (n > 0) {
  385. agentReadPtr += n;
  386. while (agentReadPtr >= 2) {
  387. long len = *((uint16_t *)agentReadBuf);
  388. if (agentReadPtr >= (len + 2)) {
  389. char *msg = agentReadBuf + 2;
  390. if ((len > 14)&&(_enabled)) {
  391. to.setTo(msg,6);
  392. from.setTo(msg + 6,6);
  393. _handler(_arg,(void *)0,_nwid,from,to,ntohs(((const uint16_t *)msg)[6]),0,(const void *)(msg + 14),(unsigned int)len - 14);
  394. }
  395. if (agentReadPtr > (len + 2)) {
  396. memmove(agentReadBuf,agentReadBuf + len + 2,agentReadPtr -= (len + 2));
  397. } else {
  398. agentReadPtr = 0;
  399. }
  400. } else {
  401. break;
  402. }
  403. }
  404. }
  405. }
  406. if (FD_ISSET(_agentStderr,&readfds)) {
  407. read(_agentStderr,agentStderrBuf,sizeof(agentStderrBuf));
  408. /*
  409. const ssize_t n = read(_agentStderr,agentStderrBuf,sizeof(agentStderrBuf));
  410. if (n > 0)
  411. write(STDERR_FILENO,agentStderrBuf,(size_t)n);
  412. */
  413. }
  414. }
  415. }
  416. } // namespace ZeroTier