MacEthernetTap.cpp 12 KB

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