UnixEthernetTap.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdint.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <unistd.h>
  32. #include <signal.h>
  33. #include <fcntl.h>
  34. #include <errno.h>
  35. #include <sys/types.h>
  36. #include <sys/stat.h>
  37. #include <sys/ioctl.h>
  38. #include <sys/wait.h>
  39. #include <sys/select.h>
  40. #include <netinet/in.h>
  41. #include <net/if_arp.h>
  42. #include <arpa/inet.h>
  43. #include <string>
  44. #include <map>
  45. #include <set>
  46. #include <algorithm>
  47. #include "Constants.hpp"
  48. #include "UnixEthernetTap.hpp"
  49. #include "Logger.hpp"
  50. #include "RuntimeEnvironment.hpp"
  51. #include "Utils.hpp"
  52. #include "Mutex.hpp"
  53. // ff:ff:ff:ff:ff:ff with no ADI
  54. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  55. // Command identifiers used with command finder static (on various *nixes)
  56. #define ZT_UNIX_IP_COMMAND 1
  57. #define ZT_UNIX_IFCONFIG_COMMAND 2
  58. #define ZT_MAC_KEXTLOAD_COMMAND 3
  59. #define ZT_MAC_KEXTUNLOAD_COMMAND 4
  60. // Finds external commands on startup ----------------------------------------
  61. class _CommandFinder
  62. {
  63. public:
  64. _CommandFinder()
  65. {
  66. _findCmd(ZT_UNIX_IFCONFIG_COMMAND,"ifconfig");
  67. #ifdef __LINUX__
  68. _findCmd(ZT_UNIX_IP_COMMAND,"ip");
  69. #endif
  70. #ifdef __APPLE__
  71. _findCmd(ZT_MAC_KEXTLOAD_COMMAND,"kextload");
  72. _findCmd(ZT_MAC_KEXTUNLOAD_COMMAND,"kextunload");
  73. #endif
  74. }
  75. inline const char *operator[](int id) const
  76. throw()
  77. {
  78. std::map<int,std::string>::const_iterator c(_paths.find(id));
  79. if (c == _paths.end())
  80. return (const char *)0;
  81. return c->second.c_str();
  82. }
  83. private:
  84. inline void _findCmd(int id,const char *name)
  85. {
  86. char tmp[4096];
  87. ZeroTier::Utils::snprintf(tmp,sizeof(tmp),"/sbin/%s",name);
  88. if (ZeroTier::Utils::fileExists(tmp)) {
  89. _paths[id] = tmp;
  90. return;
  91. }
  92. ZeroTier::Utils::snprintf(tmp,sizeof(tmp),"/usr/sbin/%s",name);
  93. if (ZeroTier::Utils::fileExists(tmp)) {
  94. _paths[id] = tmp;
  95. return;
  96. }
  97. ZeroTier::Utils::snprintf(tmp,sizeof(tmp),"/bin/%s",name);
  98. if (ZeroTier::Utils::fileExists(tmp)) {
  99. _paths[id] = tmp;
  100. return;
  101. }
  102. ZeroTier::Utils::snprintf(tmp,sizeof(tmp),"/usr/bin/%s",name);
  103. if (ZeroTier::Utils::fileExists(tmp)) {
  104. _paths[id] = tmp;
  105. return;
  106. }
  107. }
  108. std::map<int,std::string> _paths;
  109. };
  110. static const _CommandFinder UNIX_COMMANDS;
  111. // ---------------------------------------------------------------------------
  112. #ifdef __LINUX__
  113. #include <linux/if.h>
  114. #include <linux/if_tun.h>
  115. #include <linux/if_addr.h>
  116. #include <linux/if_ether.h>
  117. #include <ifaddrs.h>
  118. #endif // __LINUX__
  119. #ifdef __APPLE__
  120. #include <sys/cdefs.h>
  121. #include <sys/uio.h>
  122. #include <sys/param.h>
  123. #include <sys/sysctl.h>
  124. #include <sys/ioctl.h>
  125. #include <sys/types.h>
  126. #include <sys/socket.h>
  127. #include <net/route.h>
  128. #include <net/if.h>
  129. #include <net/if_dl.h>
  130. #include <net/if_media.h>
  131. struct prf_ra { // stupid OSX compile fix... in6_var defines this in a struct which namespaces it for C++
  132. u_char onlink : 1;
  133. u_char autonomous : 1;
  134. u_char reserved : 6;
  135. } prf_ra;
  136. #include <netinet6/in6_var.h>
  137. #include <netinet/in.h>
  138. #include <netinet/in_var.h>
  139. #include <netinet/icmp6.h>
  140. #include <netinet6/nd6.h>
  141. #include <ifaddrs.h>
  142. // These are KERNEL_PRIVATE... why?
  143. #ifndef SIOCAUTOCONF_START
  144. #define SIOCAUTOCONF_START _IOWR('i', 132, struct in6_ifreq) /* accept rtadvd on this interface */
  145. #endif
  146. #ifndef SIOCAUTOCONF_STOP
  147. #define SIOCAUTOCONF_STOP _IOWR('i', 133, struct in6_ifreq) /* stop accepting rtadv for this interface */
  148. #endif
  149. static volatile int EthernetTap_instances = 0;
  150. static ZeroTier::Mutex EthernetTap_instances_m;
  151. static inline bool _setIpv6Stuff(const char *ifname,bool performNUD,bool acceptRouterAdverts)
  152. {
  153. struct in6_ndireq nd;
  154. struct in6_ifreq ifr;
  155. int s = socket(AF_INET6,SOCK_DGRAM,0);
  156. if (s <= 0)
  157. return false;
  158. memset(&nd,0,sizeof(nd));
  159. strncpy(nd.ifname,ifname,sizeof(nd.ifname));
  160. if (ioctl(s,SIOCGIFINFO_IN6,&nd)) {
  161. close(s);
  162. return false;
  163. }
  164. unsigned long oldFlags = (unsigned long)nd.ndi.flags;
  165. if (performNUD)
  166. nd.ndi.flags |= ND6_IFF_PERFORMNUD;
  167. else nd.ndi.flags &= ~ND6_IFF_PERFORMNUD;
  168. if (oldFlags != (unsigned long)nd.ndi.flags) {
  169. if (ioctl(s,SIOCSIFINFO_FLAGS,&nd)) {
  170. close(s);
  171. return false;
  172. }
  173. }
  174. memset(&ifr,0,sizeof(ifr));
  175. strncpy(ifr.ifr_name,ifname,sizeof(ifr.ifr_name));
  176. if (ioctl(s,acceptRouterAdverts ? SIOCAUTOCONF_START : SIOCAUTOCONF_STOP,&ifr)) {
  177. close(s);
  178. return false;
  179. }
  180. close(s);
  181. return true;
  182. }
  183. #endif // __APPLE__
  184. namespace ZeroTier {
  185. // Only permit one tap to be opened concurrently across the entire process
  186. static Mutex __tapCreateLock;
  187. #ifdef __LINUX__
  188. UnixEthernetTap::UnixEthernetTap(
  189. const RuntimeEnvironment *renv,
  190. const char *tryToGetDevice,
  191. const MAC &mac,
  192. unsigned int mtu,
  193. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  194. void *arg)
  195. throw(std::runtime_error) :
  196. EthernetTap("UnixEthernetTap",mac,mtu),
  197. _r(renv),
  198. _handler(handler),
  199. _arg(arg),
  200. _fd(0),
  201. _enabled(true)
  202. {
  203. char procpath[128];
  204. struct stat sbuf;
  205. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  206. if (mtu > 4096)
  207. throw std::runtime_error("max tap MTU is 4096");
  208. _fd = ::open("/dev/net/tun",O_RDWR);
  209. if (_fd <= 0)
  210. throw std::runtime_error(std::string("could not open TUN/TAP device: ") + strerror(errno));
  211. struct ifreq ifr;
  212. memset(&ifr,0,sizeof(ifr));
  213. // Try to recall our last device name, or pick an unused one if that fails.
  214. bool recalledDevice = false;
  215. if ((tryToGetDevice)&&(tryToGetDevice[0])) {
  216. Utils::scopy(ifr.ifr_name,sizeof(ifr.ifr_name),tryToGetDevice);
  217. Utils::snprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  218. recalledDevice = (stat(procpath,&sbuf) != 0);
  219. }
  220. if (!recalledDevice) {
  221. int devno = 0;
  222. do {
  223. Utils::snprintf(ifr.ifr_name,sizeof(ifr.ifr_name),"zt%d",devno++);
  224. Utils::snprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  225. } while (stat(procpath,&sbuf) == 0); // try zt#++ until we find one that does not exist
  226. }
  227. ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
  228. if (ioctl(_fd,TUNSETIFF,(void *)&ifr) < 0) {
  229. ::close(_fd);
  230. throw std::runtime_error("unable to configure TUN/TAP device for TAP operation");
  231. }
  232. _dev = ifr.ifr_name;
  233. ioctl(_fd,TUNSETPERSIST,0); // valgrind may generate a false alarm here
  234. // Open an arbitrary socket to talk to netlink
  235. int sock = socket(AF_INET,SOCK_DGRAM,0);
  236. if (sock <= 0) {
  237. ::close(_fd);
  238. throw std::runtime_error("unable to open netlink socket");
  239. }
  240. // Set MAC address
  241. ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER;
  242. mac.copyTo(ifr.ifr_ifru.ifru_hwaddr.sa_data,6);
  243. if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) {
  244. ::close(_fd);
  245. ::close(sock);
  246. throw std::runtime_error("unable to configure TAP hardware (MAC) address");
  247. return;
  248. }
  249. // Set MTU
  250. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  251. if (ioctl(sock,SIOCSIFMTU,(void *)&ifr) < 0) {
  252. ::close(_fd);
  253. ::close(sock);
  254. throw std::runtime_error("unable to configure TAP MTU");
  255. }
  256. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  257. ::close(_fd);
  258. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  259. }
  260. /* Bring interface up */
  261. if (ioctl(sock,SIOCGIFFLAGS,(void *)&ifr) < 0) {
  262. ::close(_fd);
  263. ::close(sock);
  264. throw std::runtime_error("unable to get TAP interface flags");
  265. }
  266. ifr.ifr_flags |= IFF_UP;
  267. if (ioctl(sock,SIOCSIFFLAGS,(void *)&ifr) < 0) {
  268. ::close(_fd);
  269. ::close(sock);
  270. throw std::runtime_error("unable to set TAP interface flags");
  271. }
  272. ::close(sock);
  273. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  274. fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  275. ::pipe(_shutdownSignalPipe);
  276. TRACE("tap %s created",_dev.c_str());
  277. _thread = Thread::start(this);
  278. }
  279. #endif // __LINUX__
  280. #ifdef __APPLE__
  281. UnixEthernetTap::UnixEthernetTap(
  282. const RuntimeEnvironment *renv,
  283. const char *tryToGetDevice,
  284. const MAC &mac,
  285. unsigned int mtu,
  286. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  287. void *arg)
  288. throw(std::runtime_error) :
  289. EthernetTap("UnixEthernetTap",mac,mtu),
  290. _r(renv),
  291. _handler(handler),
  292. _arg(arg),
  293. _fd(0),
  294. _enabled(true)
  295. {
  296. char devpath[64],ethaddr[64],mtustr[16],tmp[4096];
  297. struct stat stattmp;
  298. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  299. if (mtu > 4096)
  300. throw std::runtime_error("max tap MTU is 4096");
  301. // Check for existence of ZT tap devices, try to load module if not there
  302. const char *kextload = UNIX_COMMANDS[ZT_MAC_KEXTLOAD_COMMAND];
  303. if ((stat("/dev/zt0",&stattmp))&&(kextload)) {
  304. strcpy(tmp,_r->homePath.c_str());
  305. long kextpid = (long)vfork();
  306. if (kextpid == 0) {
  307. chdir(tmp);
  308. execl(kextload,kextload,"-q","-repository",tmp,"tap.kext",(const char *)0);
  309. _exit(-1);
  310. } else if (kextpid > 0) {
  311. int exitcode = -1;
  312. waitpid(kextpid,&exitcode,0);
  313. usleep(500);
  314. } else throw std::runtime_error("unable to create subprocess with fork()");
  315. }
  316. if (stat("/dev/zt0",&stattmp))
  317. throw std::runtime_error("/dev/zt# tap devices do not exist and unable to load kernel extension");
  318. // Try to reopen the last device we had, if we had one and it's still unused.
  319. bool recalledDevice = false;
  320. if ((tryToGetDevice)&&(tryToGetDevice[0])) {
  321. Utils::snprintf(devpath,sizeof(devpath),"/dev/%s",tryToGetDevice);
  322. if (stat(devpath,&stattmp) == 0) {
  323. _fd = ::open(devpath,O_RDWR);
  324. if (_fd > 0) {
  325. _dev = tryToGetDevice;
  326. recalledDevice = true;
  327. }
  328. }
  329. }
  330. // Open the first unused tap device if we didn't recall a previous one.
  331. if (!recalledDevice) {
  332. for(int i=0;i<256;++i) {
  333. Utils::snprintf(devpath,sizeof(devpath),"/dev/zt%d",i);
  334. if (stat(devpath,&stattmp))
  335. throw std::runtime_error("no more TAP devices available");
  336. _fd = ::open(devpath,O_RDWR);
  337. if (_fd > 0) {
  338. char foo[16];
  339. Utils::snprintf(foo,sizeof(foo),"zt%d",i);
  340. _dev = foo;
  341. break;
  342. }
  343. }
  344. }
  345. if (_fd <= 0)
  346. throw std::runtime_error("unable to open TAP device or no more devices available");
  347. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  348. ::close(_fd);
  349. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  350. }
  351. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  352. if (!ifconfig) {
  353. ::close(_fd);
  354. throw std::runtime_error("unable to find 'ifconfig' command on system");
  355. }
  356. // Configure MAC address and MTU, bring interface up
  357. Utils::snprintf(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]);
  358. Utils::snprintf(mtustr,sizeof(mtustr),"%u",mtu);
  359. long cpid;
  360. if ((cpid = (long)vfork()) == 0) {
  361. execl(ifconfig,ifconfig,_dev.c_str(),"lladdr",ethaddr,"mtu",mtustr,"up",(const char *)0);
  362. _exit(-1);
  363. } else {
  364. int exitcode = -1;
  365. waitpid(cpid,&exitcode,0);
  366. if (exitcode) {
  367. ::close(_fd);
  368. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  369. }
  370. }
  371. _setIpv6Stuff(_dev.c_str(),true,false);
  372. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  373. fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  374. ::pipe(_shutdownSignalPipe);
  375. _thread = Thread::start(this);
  376. EthernetTap_instances_m.lock();
  377. ++EthernetTap_instances;
  378. EthernetTap_instances_m.unlock();
  379. }
  380. #endif // __APPLE__
  381. UnixEthernetTap::~UnixEthernetTap()
  382. {
  383. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  384. Thread::join(_thread);
  385. ::close(_fd);
  386. ::close(_shutdownSignalPipe[0]);
  387. ::close(_shutdownSignalPipe[1]);
  388. #ifdef __APPLE__
  389. EthernetTap_instances_m.lock();
  390. int instances = --EthernetTap_instances;
  391. EthernetTap_instances_m.unlock();
  392. if (instances <= 0) {
  393. // Unload OSX kernel extension on the deletion of the last EthernetTap
  394. // instance.
  395. const char *kextunload = UNIX_COMMANDS[ZT_MAC_KEXTUNLOAD_COMMAND];
  396. if (kextunload) {
  397. char tmp[4096];
  398. sprintf(tmp,"%s/tap.kext",_r->homePath.c_str());
  399. long kextpid = (long)vfork();
  400. if (kextpid == 0) {
  401. execl(kextunload,kextunload,tmp,(const char *)0);
  402. _exit(-1);
  403. } else if (kextpid > 0) {
  404. int exitcode = -1;
  405. waitpid(kextpid,&exitcode,0);
  406. }
  407. }
  408. }
  409. #endif // __APPLE__
  410. }
  411. void UnixEthernetTap::setEnabled(bool en)
  412. {
  413. _enabled = en;
  414. // TODO: interface status change
  415. }
  416. bool UnixEthernetTap::enabled() const
  417. {
  418. return _enabled;
  419. }
  420. void UnixEthernetTap::setDisplayName(const char *dn)
  421. {
  422. }
  423. #ifdef __LINUX__
  424. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  425. {
  426. const char *ipcmd = UNIX_COMMANDS[ZT_UNIX_IP_COMMAND];
  427. if (!ipcmd)
  428. return false;
  429. long cpid = (long)vfork();
  430. if (cpid == 0) {
  431. execl(ipcmd,ipcmd,"addr","del",ip.toString().c_str(),"dev",_dev.c_str(),(const char *)0);
  432. _exit(-1);
  433. } else {
  434. int exitcode = -1;
  435. waitpid(cpid,&exitcode,0);
  436. return (exitcode == 0);
  437. }
  438. }
  439. bool UnixEthernetTap::addIP(const InetAddress &ip)
  440. {
  441. const char *ipcmd = UNIX_COMMANDS[ZT_UNIX_IP_COMMAND];
  442. if (!ipcmd) {
  443. LOG("ERROR: could not configure IP address for %s: unable to find 'ip' command on system (checked /sbin, /bin, /usr/sbin, /usr/bin)",_dev.c_str());
  444. return false;
  445. }
  446. if (!ip)
  447. return false;
  448. std::set<InetAddress> allIps(ips());
  449. if (allIps.count(ip) > 0)
  450. return true;
  451. // Remove and reconfigure if address is the same but netmask is different
  452. for(std::set<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  453. if (i->ipsEqual(ip)) {
  454. if (___removeIp(_dev,*i)) {
  455. break;
  456. } else {
  457. LOG("WARNING: failed to remove old IP/netmask %s to replace with %s",i->toString().c_str(),ip.toString().c_str());
  458. }
  459. }
  460. }
  461. long cpid;
  462. if ((cpid = (long)vfork()) == 0) {
  463. execl(ipcmd,ipcmd,"addr","add",ip.toString().c_str(),"dev",_dev.c_str(),(const char *)0);
  464. _exit(-1);
  465. } else if (cpid > 0) {
  466. int exitcode = -1;
  467. waitpid(cpid,&exitcode,0);
  468. return (exitcode == 0);
  469. }
  470. return false;
  471. }
  472. #endif // __LINUX__
  473. #ifdef __APPLE__
  474. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  475. {
  476. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  477. if (!ifconfig)
  478. return false;
  479. long cpid;
  480. if ((cpid = (long)vfork()) == 0) {
  481. execl(ifconfig,ifconfig,_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  482. _exit(-1);
  483. } else {
  484. int exitcode = -1;
  485. waitpid(cpid,&exitcode,0);
  486. return (exitcode == 0);
  487. }
  488. return false; // never reached, make compiler shut up about return value
  489. }
  490. bool UnixEthernetTap::addIP(const InetAddress &ip)
  491. {
  492. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  493. if (!ifconfig) {
  494. LOG("ERROR: could not configure IP address for %s: unable to find 'ifconfig' command on system (checked /sbin, /bin, /usr/sbin, /usr/bin)",_dev.c_str());
  495. return false;
  496. }
  497. if (!ip)
  498. return false;
  499. std::set<InetAddress> allIps(ips());
  500. if (allIps.count(ip) > 0)
  501. return true; // IP/netmask already assigned
  502. // Remove and reconfigure if address is the same but netmask is different
  503. for(std::set<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  504. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  505. if (___removeIp(_dev,*i)) {
  506. break;
  507. } else {
  508. LOG("WARNING: failed to remove old IP/netmask %s to replace with %s",i->toString().c_str(),ip.toString().c_str());
  509. }
  510. }
  511. }
  512. long cpid;
  513. if ((cpid = (long)vfork()) == 0) {
  514. execl(ifconfig,ifconfig,_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  515. _exit(-1);
  516. } else {
  517. int exitcode = -1;
  518. waitpid(cpid,&exitcode,0);
  519. return (exitcode == 0);
  520. }
  521. return false;
  522. }
  523. #endif // __APPLE__
  524. bool UnixEthernetTap::removeIP(const InetAddress &ip)
  525. {
  526. if (ips().count(ip) > 0) {
  527. if (___removeIp(_dev,ip))
  528. return true;
  529. }
  530. return false;
  531. }
  532. std::set<InetAddress> UnixEthernetTap::ips() const
  533. {
  534. struct ifaddrs *ifa = (struct ifaddrs *)0;
  535. if (getifaddrs(&ifa))
  536. return std::set<InetAddress>();
  537. std::set<InetAddress> r;
  538. struct ifaddrs *p = ifa;
  539. while (p) {
  540. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  541. switch(p->ifa_addr->sa_family) {
  542. case AF_INET: {
  543. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  544. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  545. r.insert(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  546. } break;
  547. case AF_INET6: {
  548. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  549. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  550. uint32_t b[4];
  551. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  552. r.insert(InetAddress(sin->sin6_addr.s6_addr,16,Utils::countBits(b[0]) + Utils::countBits(b[1]) + Utils::countBits(b[2]) + Utils::countBits(b[3])));
  553. } break;
  554. }
  555. }
  556. p = p->ifa_next;
  557. }
  558. if (ifa)
  559. freeifaddrs(ifa);
  560. return r;
  561. }
  562. void UnixEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  563. {
  564. char putBuf[4096 + 14];
  565. if ((_fd > 0)&&(len <= _mtu)) {
  566. to.copyTo(putBuf,6);
  567. from.copyTo(putBuf + 6,6);
  568. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  569. memcpy(putBuf + 14,data,len);
  570. len += 14;
  571. int n = ::write(_fd,putBuf,len);
  572. if (n <= 0) {
  573. LOG("error writing packet to Ethernet tap device: %s",strerror(errno));
  574. } else if (n != (int)len) {
  575. // Saw this gremlin once, so log it if we see it again... OSX tap
  576. // or something seems to have goofy issues with certain MTUs.
  577. LOG("ERROR: write underrun: %s tap write() wrote %d of %u bytes of frame",_dev.c_str(),n,len);
  578. }
  579. }
  580. }
  581. std::string UnixEthernetTap::deviceName() const
  582. {
  583. return _dev;
  584. }
  585. std::string UnixEthernetTap::persistentId() const
  586. {
  587. return std::string();
  588. }
  589. #ifdef __LINUX__
  590. bool UnixEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  591. {
  592. char *ptr,*ptr2;
  593. unsigned char mac[6];
  594. std::set<MulticastGroup> newGroups;
  595. int fd = ::open("/proc/net/dev_mcast",O_RDONLY);
  596. if (fd > 0) {
  597. char buf[131072];
  598. int n = (int)::read(fd,buf,sizeof(buf));
  599. if ((n > 0)&&(n < (int)sizeof(buf))) {
  600. buf[n] = (char)0;
  601. for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) {
  602. int fno = 0;
  603. char *devname = (char *)0;
  604. char *mcastmac = (char *)0;
  605. for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) {
  606. if (fno == 1)
  607. devname = f;
  608. else if (fno == 4)
  609. mcastmac = f;
  610. ++fno;
  611. }
  612. if ((devname)&&(!strcmp(devname,_dev.c_str()))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6))
  613. newGroups.insert(MulticastGroup(MAC(mac,6),0));
  614. }
  615. }
  616. ::close(fd);
  617. }
  618. {
  619. std::set<InetAddress> allIps(ips());
  620. for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
  621. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  622. }
  623. bool changed = false;
  624. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  625. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  626. if (!groups.count(*mg)) {
  627. groups.insert(*mg);
  628. changed = true;
  629. }
  630. }
  631. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  632. if (!newGroups.count(*mg)) {
  633. groups.erase(mg++);
  634. changed = true;
  635. } else ++mg;
  636. }
  637. return changed;
  638. }
  639. #endif // __LINUX__
  640. #ifdef __APPLE__
  641. // --------------------------------------------------------------------------
  642. // This source is from:
  643. // http://www.opensource.apple.com/source/Libinfo/Libinfo-406.17/gen.subproj/getifmaddrs.c?txt
  644. // It's here because OSX 10.6 does not have this convenience function.
  645. #define SALIGN (sizeof(uint32_t) - 1)
  646. #define SA_RLEN(sa) ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : \
  647. (SALIGN + 1))
  648. #define MAX_SYSCTL_TRY 5
  649. #define RTA_MASKS (RTA_GATEWAY | RTA_IFP | RTA_IFA)
  650. /* FreeBSD uses NET_RT_IFMALIST and RTM_NEWMADDR from <sys/socket.h> */
  651. /* We can use NET_RT_IFLIST2 and RTM_NEWMADDR2 on Darwin */
  652. //#define DARWIN_COMPAT
  653. //#ifdef DARWIN_COMPAT
  654. #define GIM_SYSCTL_MIB NET_RT_IFLIST2
  655. #define GIM_RTM_ADDR RTM_NEWMADDR2
  656. //#else
  657. //#define GIM_SYSCTL_MIB NET_RT_IFMALIST
  658. //#define GIM_RTM_ADDR RTM_NEWMADDR
  659. //#endif
  660. // Not in 10.6 includes so use our own
  661. struct _intl_ifmaddrs {
  662. struct _intl_ifmaddrs *ifma_next;
  663. struct sockaddr *ifma_name;
  664. struct sockaddr *ifma_addr;
  665. struct sockaddr *ifma_lladdr;
  666. };
  667. static inline int _intl_getifmaddrs(struct _intl_ifmaddrs **pif)
  668. {
  669. int icnt = 1;
  670. int dcnt = 0;
  671. int ntry = 0;
  672. size_t len;
  673. size_t needed;
  674. int mib[6];
  675. int i;
  676. char *buf;
  677. char *data;
  678. char *next;
  679. char *p;
  680. struct ifma_msghdr2 *ifmam;
  681. struct _intl_ifmaddrs *ifa, *ift;
  682. struct rt_msghdr *rtm;
  683. struct sockaddr *sa;
  684. mib[0] = CTL_NET;
  685. mib[1] = PF_ROUTE;
  686. mib[2] = 0; /* protocol */
  687. mib[3] = 0; /* wildcard address family */
  688. mib[4] = GIM_SYSCTL_MIB;
  689. mib[5] = 0; /* no flags */
  690. do {
  691. if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
  692. return (-1);
  693. if ((buf = (char *)malloc(needed)) == NULL)
  694. return (-1);
  695. if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
  696. if (errno != ENOMEM || ++ntry >= MAX_SYSCTL_TRY) {
  697. free(buf);
  698. return (-1);
  699. }
  700. free(buf);
  701. buf = NULL;
  702. }
  703. } while (buf == NULL);
  704. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  705. rtm = (struct rt_msghdr *)(void *)next;
  706. if (rtm->rtm_version != RTM_VERSION)
  707. continue;
  708. switch (rtm->rtm_type) {
  709. case GIM_RTM_ADDR:
  710. ifmam = (struct ifma_msghdr2 *)(void *)rtm;
  711. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  712. break;
  713. icnt++;
  714. p = (char *)(ifmam + 1);
  715. for (i = 0; i < RTAX_MAX; i++) {
  716. if ((RTA_MASKS & ifmam->ifmam_addrs &
  717. (1 << i)) == 0)
  718. continue;
  719. sa = (struct sockaddr *)(void *)p;
  720. len = SA_RLEN(sa);
  721. dcnt += len;
  722. p += len;
  723. }
  724. break;
  725. }
  726. }
  727. data = (char *)malloc(sizeof(struct _intl_ifmaddrs) * icnt + dcnt);
  728. if (data == NULL) {
  729. free(buf);
  730. return (-1);
  731. }
  732. ifa = (struct _intl_ifmaddrs *)(void *)data;
  733. data += sizeof(struct _intl_ifmaddrs) * icnt;
  734. memset(ifa, 0, sizeof(struct _intl_ifmaddrs) * icnt);
  735. ift = ifa;
  736. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  737. rtm = (struct rt_msghdr *)(void *)next;
  738. if (rtm->rtm_version != RTM_VERSION)
  739. continue;
  740. switch (rtm->rtm_type) {
  741. case GIM_RTM_ADDR:
  742. ifmam = (struct ifma_msghdr2 *)(void *)rtm;
  743. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  744. break;
  745. p = (char *)(ifmam + 1);
  746. for (i = 0; i < RTAX_MAX; i++) {
  747. if ((RTA_MASKS & ifmam->ifmam_addrs &
  748. (1 << i)) == 0)
  749. continue;
  750. sa = (struct sockaddr *)(void *)p;
  751. len = SA_RLEN(sa);
  752. switch (i) {
  753. case RTAX_GATEWAY:
  754. ift->ifma_lladdr =
  755. (struct sockaddr *)(void *)data;
  756. memcpy(data, p, len);
  757. data += len;
  758. break;
  759. case RTAX_IFP:
  760. ift->ifma_name =
  761. (struct sockaddr *)(void *)data;
  762. memcpy(data, p, len);
  763. data += len;
  764. break;
  765. case RTAX_IFA:
  766. ift->ifma_addr =
  767. (struct sockaddr *)(void *)data;
  768. memcpy(data, p, len);
  769. data += len;
  770. break;
  771. default:
  772. data += len;
  773. break;
  774. }
  775. p += len;
  776. }
  777. ift->ifma_next = ift + 1;
  778. ift = ift->ifma_next;
  779. break;
  780. }
  781. }
  782. free(buf);
  783. if (ift > ifa) {
  784. ift--;
  785. ift->ifma_next = NULL;
  786. *pif = ifa;
  787. } else {
  788. *pif = NULL;
  789. free(ifa);
  790. }
  791. return (0);
  792. }
  793. static inline void _intl_freeifmaddrs(struct _intl_ifmaddrs *ifmp)
  794. {
  795. free(ifmp);
  796. }
  797. // --------------------------------------------------------------------------
  798. bool UnixEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  799. {
  800. std::set<MulticastGroup> newGroups;
  801. struct _intl_ifmaddrs *ifmap = (struct _intl_ifmaddrs *)0;
  802. if (!_intl_getifmaddrs(&ifmap)) {
  803. struct _intl_ifmaddrs *p = ifmap;
  804. while (p) {
  805. if (p->ifma_addr->sa_family == AF_LINK) {
  806. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  807. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  808. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  809. newGroups.insert(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  810. }
  811. p = p->ifma_next;
  812. }
  813. _intl_freeifmaddrs(ifmap);
  814. }
  815. {
  816. std::set<InetAddress> allIps(ips());
  817. for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
  818. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  819. }
  820. bool changed = false;
  821. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  822. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  823. if (!groups.count(*mg)) {
  824. groups.insert(*mg);
  825. changed = true;
  826. }
  827. }
  828. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  829. if (!newGroups.count(*mg)) {
  830. groups.erase(mg++);
  831. changed = true;
  832. } else ++mg;
  833. }
  834. return changed;
  835. }
  836. #endif // __APPLE__
  837. void UnixEthernetTap::threadMain()
  838. throw()
  839. {
  840. fd_set readfds,nullfds;
  841. MAC to,from;
  842. int n,nfds,r;
  843. char getBuf[8194];
  844. Buffer<4096> data;
  845. // Wait for a moment after startup -- wait for Network to finish
  846. // constructing itself.
  847. Thread::sleep(500);
  848. FD_ZERO(&readfds);
  849. FD_ZERO(&nullfds);
  850. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  851. r = 0;
  852. for(;;) {
  853. FD_SET(_shutdownSignalPipe[0],&readfds);
  854. FD_SET(_fd,&readfds);
  855. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  856. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  857. break;
  858. if (FD_ISSET(_fd,&readfds)) {
  859. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  860. if (n < 0) {
  861. if ((errno != EINTR)&&(errno != ETIMEDOUT)) {
  862. TRACE("unexpected error reading from tap: %s",strerror(errno));
  863. break;
  864. }
  865. } else {
  866. // Some tap drivers like to send the ethernet frame and the
  867. // payload in two chunks, so handle that by accumulating
  868. // data until we have at least a frame.
  869. r += n;
  870. if (r > 14) {
  871. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  872. r = _mtu + 14;
  873. to.setTo(getBuf,6);
  874. from.setTo(getBuf + 6,6);
  875. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  876. if (etherType != 0x8100) { // VLAN tagged frames are not supported!
  877. data.copyFrom(getBuf + 14,(unsigned int)r - 14);
  878. _handler(_arg,from,to,etherType,data);
  879. }
  880. r = 0;
  881. }
  882. }
  883. }
  884. }
  885. }
  886. } // namespace ZeroTier