UnixEthernetTap.cpp 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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. memcpy(ifr.ifr_ifru.ifru_hwaddr.sa_data,mac.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. for(int i=0;i<6;++i)
  567. putBuf[i] = to.data[i];
  568. for(int i=0;i<6;++i)
  569. putBuf[i+6] = from.data[i];
  570. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  571. memcpy(putBuf + 14,data,len);
  572. len += 14;
  573. int n = ::write(_fd,putBuf,len);
  574. if (n <= 0) {
  575. LOG("error writing packet to Ethernet tap device: %s",strerror(errno));
  576. } else if (n != (int)len) {
  577. // Saw this gremlin once, so log it if we see it again... OSX tap
  578. // or something seems to have goofy issues with certain MTUs.
  579. LOG("ERROR: write underrun: %s tap write() wrote %d of %u bytes of frame",_dev.c_str(),n,len);
  580. }
  581. }
  582. }
  583. std::string UnixEthernetTap::deviceName() const
  584. {
  585. return _dev;
  586. }
  587. std::string UnixEthernetTap::persistentId() const
  588. {
  589. return std::string();
  590. }
  591. #ifdef __LINUX__
  592. bool UnixEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  593. {
  594. char *ptr,*ptr2;
  595. unsigned char mac[6];
  596. std::set<MulticastGroup> newGroups;
  597. int fd = ::open("/proc/net/dev_mcast",O_RDONLY);
  598. if (fd > 0) {
  599. char buf[131072];
  600. int n = (int)::read(fd,buf,sizeof(buf));
  601. if ((n > 0)&&(n < (int)sizeof(buf))) {
  602. buf[n] = (char)0;
  603. for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) {
  604. int fno = 0;
  605. char *devname = (char *)0;
  606. char *mcastmac = (char *)0;
  607. for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) {
  608. if (fno == 1)
  609. devname = f;
  610. else if (fno == 4)
  611. mcastmac = f;
  612. ++fno;
  613. }
  614. if ((devname)&&(!strcmp(devname,_dev.c_str()))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6))
  615. newGroups.insert(MulticastGroup(MAC(mac),0));
  616. }
  617. }
  618. ::close(fd);
  619. }
  620. {
  621. std::set<InetAddress> allIps(ips());
  622. for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
  623. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  624. }
  625. bool changed = false;
  626. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  627. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  628. if (!groups.count(*mg)) {
  629. groups.insert(*mg);
  630. changed = true;
  631. }
  632. }
  633. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  634. if (!newGroups.count(*mg)) {
  635. groups.erase(mg++);
  636. changed = true;
  637. } else ++mg;
  638. }
  639. return changed;
  640. }
  641. #endif // __LINUX__
  642. #ifdef __APPLE__
  643. // --------------------------------------------------------------------------
  644. // This source is from:
  645. // http://www.opensource.apple.com/source/Libinfo/Libinfo-406.17/gen.subproj/getifmaddrs.c?txt
  646. // It's here because OSX 10.6 does not have this convenience function.
  647. #define SALIGN (sizeof(uint32_t) - 1)
  648. #define SA_RLEN(sa) ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : \
  649. (SALIGN + 1))
  650. #define MAX_SYSCTL_TRY 5
  651. #define RTA_MASKS (RTA_GATEWAY | RTA_IFP | RTA_IFA)
  652. /* FreeBSD uses NET_RT_IFMALIST and RTM_NEWMADDR from <sys/socket.h> */
  653. /* We can use NET_RT_IFLIST2 and RTM_NEWMADDR2 on Darwin */
  654. //#define DARWIN_COMPAT
  655. //#ifdef DARWIN_COMPAT
  656. #define GIM_SYSCTL_MIB NET_RT_IFLIST2
  657. #define GIM_RTM_ADDR RTM_NEWMADDR2
  658. //#else
  659. //#define GIM_SYSCTL_MIB NET_RT_IFMALIST
  660. //#define GIM_RTM_ADDR RTM_NEWMADDR
  661. //#endif
  662. // Not in 10.6 includes so use our own
  663. struct _intl_ifmaddrs {
  664. struct _intl_ifmaddrs *ifma_next;
  665. struct sockaddr *ifma_name;
  666. struct sockaddr *ifma_addr;
  667. struct sockaddr *ifma_lladdr;
  668. };
  669. static inline int _intl_getifmaddrs(struct _intl_ifmaddrs **pif)
  670. {
  671. int icnt = 1;
  672. int dcnt = 0;
  673. int ntry = 0;
  674. size_t len;
  675. size_t needed;
  676. int mib[6];
  677. int i;
  678. char *buf;
  679. char *data;
  680. char *next;
  681. char *p;
  682. struct ifma_msghdr2 *ifmam;
  683. struct _intl_ifmaddrs *ifa, *ift;
  684. struct rt_msghdr *rtm;
  685. struct sockaddr *sa;
  686. mib[0] = CTL_NET;
  687. mib[1] = PF_ROUTE;
  688. mib[2] = 0; /* protocol */
  689. mib[3] = 0; /* wildcard address family */
  690. mib[4] = GIM_SYSCTL_MIB;
  691. mib[5] = 0; /* no flags */
  692. do {
  693. if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
  694. return (-1);
  695. if ((buf = (char *)malloc(needed)) == NULL)
  696. return (-1);
  697. if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
  698. if (errno != ENOMEM || ++ntry >= MAX_SYSCTL_TRY) {
  699. free(buf);
  700. return (-1);
  701. }
  702. free(buf);
  703. buf = NULL;
  704. }
  705. } while (buf == NULL);
  706. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  707. rtm = (struct rt_msghdr *)(void *)next;
  708. if (rtm->rtm_version != RTM_VERSION)
  709. continue;
  710. switch (rtm->rtm_type) {
  711. case GIM_RTM_ADDR:
  712. ifmam = (struct ifma_msghdr2 *)(void *)rtm;
  713. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  714. break;
  715. icnt++;
  716. p = (char *)(ifmam + 1);
  717. for (i = 0; i < RTAX_MAX; i++) {
  718. if ((RTA_MASKS & ifmam->ifmam_addrs &
  719. (1 << i)) == 0)
  720. continue;
  721. sa = (struct sockaddr *)(void *)p;
  722. len = SA_RLEN(sa);
  723. dcnt += len;
  724. p += len;
  725. }
  726. break;
  727. }
  728. }
  729. data = (char *)malloc(sizeof(struct _intl_ifmaddrs) * icnt + dcnt);
  730. if (data == NULL) {
  731. free(buf);
  732. return (-1);
  733. }
  734. ifa = (struct _intl_ifmaddrs *)(void *)data;
  735. data += sizeof(struct _intl_ifmaddrs) * icnt;
  736. memset(ifa, 0, sizeof(struct _intl_ifmaddrs) * icnt);
  737. ift = ifa;
  738. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  739. rtm = (struct rt_msghdr *)(void *)next;
  740. if (rtm->rtm_version != RTM_VERSION)
  741. continue;
  742. switch (rtm->rtm_type) {
  743. case GIM_RTM_ADDR:
  744. ifmam = (struct ifma_msghdr2 *)(void *)rtm;
  745. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  746. break;
  747. p = (char *)(ifmam + 1);
  748. for (i = 0; i < RTAX_MAX; i++) {
  749. if ((RTA_MASKS & ifmam->ifmam_addrs &
  750. (1 << i)) == 0)
  751. continue;
  752. sa = (struct sockaddr *)(void *)p;
  753. len = SA_RLEN(sa);
  754. switch (i) {
  755. case RTAX_GATEWAY:
  756. ift->ifma_lladdr =
  757. (struct sockaddr *)(void *)data;
  758. memcpy(data, p, len);
  759. data += len;
  760. break;
  761. case RTAX_IFP:
  762. ift->ifma_name =
  763. (struct sockaddr *)(void *)data;
  764. memcpy(data, p, len);
  765. data += len;
  766. break;
  767. case RTAX_IFA:
  768. ift->ifma_addr =
  769. (struct sockaddr *)(void *)data;
  770. memcpy(data, p, len);
  771. data += len;
  772. break;
  773. default:
  774. data += len;
  775. break;
  776. }
  777. p += len;
  778. }
  779. ift->ifma_next = ift + 1;
  780. ift = ift->ifma_next;
  781. break;
  782. }
  783. }
  784. free(buf);
  785. if (ift > ifa) {
  786. ift--;
  787. ift->ifma_next = NULL;
  788. *pif = ifa;
  789. } else {
  790. *pif = NULL;
  791. free(ifa);
  792. }
  793. return (0);
  794. }
  795. static inline void _intl_freeifmaddrs(struct _intl_ifmaddrs *ifmp)
  796. {
  797. free(ifmp);
  798. }
  799. // --------------------------------------------------------------------------
  800. bool UnixEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  801. {
  802. std::set<MulticastGroup> newGroups;
  803. struct _intl_ifmaddrs *ifmap = (struct _intl_ifmaddrs *)0;
  804. if (!_intl_getifmaddrs(&ifmap)) {
  805. struct _intl_ifmaddrs *p = ifmap;
  806. while (p) {
  807. if (p->ifma_addr->sa_family == AF_LINK) {
  808. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  809. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  810. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  811. newGroups.insert(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen),0));
  812. }
  813. p = p->ifma_next;
  814. }
  815. _intl_freeifmaddrs(ifmap);
  816. }
  817. {
  818. std::set<InetAddress> allIps(ips());
  819. for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
  820. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  821. }
  822. bool changed = false;
  823. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  824. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  825. if (!groups.count(*mg)) {
  826. groups.insert(*mg);
  827. changed = true;
  828. }
  829. }
  830. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  831. if (!newGroups.count(*mg)) {
  832. groups.erase(mg++);
  833. changed = true;
  834. } else ++mg;
  835. }
  836. return changed;
  837. }
  838. #endif // __APPLE__
  839. void UnixEthernetTap::threadMain()
  840. throw()
  841. {
  842. fd_set readfds,nullfds;
  843. MAC to,from;
  844. int n,nfds,r;
  845. char getBuf[8194];
  846. Buffer<4096> data;
  847. // Wait for a moment after startup -- wait for Network to finish
  848. // constructing itself.
  849. Thread::sleep(500);
  850. FD_ZERO(&readfds);
  851. FD_ZERO(&nullfds);
  852. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  853. r = 0;
  854. for(;;) {
  855. FD_SET(_shutdownSignalPipe[0],&readfds);
  856. FD_SET(_fd,&readfds);
  857. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  858. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  859. break;
  860. if (FD_ISSET(_fd,&readfds)) {
  861. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  862. if (n < 0) {
  863. if ((errno != EINTR)&&(errno != ETIMEDOUT)) {
  864. TRACE("unexpected error reading from tap: %s",strerror(errno));
  865. break;
  866. }
  867. } else {
  868. // Some tap drivers like to send the ethernet frame and the
  869. // payload in two chunks, so handle that by accumulating
  870. // data until we have at least a frame.
  871. r += n;
  872. if (r > 14) {
  873. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  874. r = _mtu + 14;
  875. for(int i=0;i<6;++i)
  876. to.data[i] = (unsigned char)getBuf[i];
  877. for(int i=0;i<6;++i)
  878. from.data[i] = (unsigned char)getBuf[i + 6];
  879. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  880. if (etherType != 0x8100) { // VLAN tagged frames are not supported!
  881. data.copyFrom(getBuf + 14,(unsigned int)r - 14);
  882. _handler(_arg,from,to,etherType,data);
  883. }
  884. r = 0;
  885. }
  886. }
  887. }
  888. }
  889. }
  890. } // namespace ZeroTier