MacEthernetTap.cpp 11 KB

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