MacEthernetTap.cpp 13 KB

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