UnixEthernetTap.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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. ::pipe(_shutdownSignalPipe);
  274. TRACE("tap %s created",_dev.c_str());
  275. _thread = Thread::start(this);
  276. }
  277. #endif // __LINUX__
  278. #ifdef __APPLE__
  279. UnixEthernetTap::UnixEthernetTap(
  280. const RuntimeEnvironment *renv,
  281. const char *tryToGetDevice,
  282. const MAC &mac,
  283. unsigned int mtu,
  284. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  285. void *arg)
  286. throw(std::runtime_error) :
  287. EthernetTap("UnixEthernetTap",mac,mtu),
  288. _r(renv),
  289. _handler(handler),
  290. _arg(arg),
  291. _fd(0),
  292. _enabled(true)
  293. {
  294. char devpath[64],ethaddr[64],mtustr[16],tmp[4096];
  295. struct stat stattmp;
  296. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  297. if (mtu > 4096)
  298. throw std::runtime_error("max tap MTU is 4096");
  299. // Check for existence of ZT tap devices, try to load module if not there
  300. const char *kextload = UNIX_COMMANDS[ZT_MAC_KEXTLOAD_COMMAND];
  301. if ((stat("/dev/zt0",&stattmp))&&(kextload)) {
  302. strcpy(tmp,_r->homePath.c_str());
  303. long kextpid = (long)vfork();
  304. if (kextpid == 0) {
  305. chdir(tmp);
  306. execl(kextload,kextload,"-q","-repository",tmp,"tap.kext",(const char *)0);
  307. _exit(-1);
  308. } else if (kextpid > 0) {
  309. int exitcode = -1;
  310. waitpid(kextpid,&exitcode,0);
  311. usleep(500);
  312. } else throw std::runtime_error("unable to create subprocess with fork()");
  313. }
  314. if (stat("/dev/zt0",&stattmp))
  315. throw std::runtime_error("/dev/zt# tap devices do not exist and unable to load kernel extension");
  316. // Try to reopen the last device we had, if we had one and it's still unused.
  317. bool recalledDevice = false;
  318. if ((tryToGetDevice)&&(tryToGetDevice[0])) {
  319. Utils::snprintf(devpath,sizeof(devpath),"/dev/%s",tryToGetDevice);
  320. if (stat(devpath,&stattmp) == 0) {
  321. _fd = ::open(devpath,O_RDWR);
  322. if (_fd > 0) {
  323. _dev = tryToGetDevice;
  324. recalledDevice = true;
  325. }
  326. }
  327. }
  328. // Open the first unused tap device if we didn't recall a previous one.
  329. if (!recalledDevice) {
  330. for(int i=0;i<256;++i) {
  331. Utils::snprintf(devpath,sizeof(devpath),"/dev/zt%d",i);
  332. if (stat(devpath,&stattmp))
  333. throw std::runtime_error("no more TAP devices available");
  334. _fd = ::open(devpath,O_RDWR);
  335. if (_fd > 0) {
  336. char foo[16];
  337. Utils::snprintf(foo,sizeof(foo),"zt%d",i);
  338. _dev = foo;
  339. break;
  340. }
  341. }
  342. }
  343. if (_fd <= 0)
  344. throw std::runtime_error("unable to open TAP device or no more devices available");
  345. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  346. ::close(_fd);
  347. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  348. }
  349. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  350. if (!ifconfig) {
  351. ::close(_fd);
  352. throw std::runtime_error("unable to find 'ifconfig' command on system");
  353. }
  354. // Configure MAC address and MTU, bring interface up
  355. 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]);
  356. Utils::snprintf(mtustr,sizeof(mtustr),"%u",mtu);
  357. long cpid;
  358. if ((cpid = (long)vfork()) == 0) {
  359. execl(ifconfig,ifconfig,_dev.c_str(),"lladdr",ethaddr,"mtu",mtustr,"up",(const char *)0);
  360. _exit(-1);
  361. } else {
  362. int exitcode = -1;
  363. waitpid(cpid,&exitcode,0);
  364. if (exitcode) {
  365. ::close(_fd);
  366. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  367. }
  368. }
  369. _setIpv6Stuff(_dev.c_str(),true,false);
  370. ::pipe(_shutdownSignalPipe);
  371. _thread = Thread::start(this);
  372. EthernetTap_instances_m.lock();
  373. ++EthernetTap_instances;
  374. EthernetTap_instances_m.unlock();
  375. }
  376. #endif // __APPLE__
  377. UnixEthernetTap::~UnixEthernetTap()
  378. {
  379. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  380. Thread::join(_thread);
  381. ::close(_fd);
  382. #ifdef __APPLE__
  383. EthernetTap_instances_m.lock();
  384. int instances = --EthernetTap_instances;
  385. EthernetTap_instances_m.unlock();
  386. if (instances <= 0) {
  387. // Unload OSX kernel extension on the deletion of the last EthernetTap
  388. // instance.
  389. const char *kextunload = UNIX_COMMANDS[ZT_MAC_KEXTUNLOAD_COMMAND];
  390. if (kextunload) {
  391. char tmp[4096];
  392. sprintf(tmp,"%s/tap.kext",_r->homePath.c_str());
  393. long kextpid = (long)vfork();
  394. if (kextpid == 0) {
  395. execl(kextunload,kextunload,tmp,(const char *)0);
  396. _exit(-1);
  397. } else if (kextpid > 0) {
  398. int exitcode = -1;
  399. waitpid(kextpid,&exitcode,0);
  400. }
  401. }
  402. }
  403. #endif // __APPLE__
  404. }
  405. void UnixEthernetTap::setEnabled(bool en)
  406. {
  407. _enabled = en;
  408. // TODO: interface status change
  409. }
  410. bool UnixEthernetTap::enabled() const
  411. {
  412. return _enabled;
  413. }
  414. void UnixEthernetTap::setDisplayName(const char *dn)
  415. {
  416. }
  417. #ifdef __LINUX__
  418. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  419. {
  420. const char *ipcmd = UNIX_COMMANDS[ZT_UNIX_IP_COMMAND];
  421. if (!ipcmd)
  422. return false;
  423. long cpid = (long)vfork();
  424. if (cpid == 0) {
  425. execl(ipcmd,ipcmd,"addr","del",ip.toString().c_str(),"dev",_dev.c_str(),(const char *)0);
  426. _exit(-1);
  427. } else {
  428. int exitcode = -1;
  429. waitpid(cpid,&exitcode,0);
  430. return (exitcode == 0);
  431. }
  432. }
  433. bool UnixEthernetTap::addIP(const InetAddress &ip)
  434. {
  435. const char *ipcmd = UNIX_COMMANDS[ZT_UNIX_IP_COMMAND];
  436. if (!ipcmd) {
  437. 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());
  438. return false;
  439. }
  440. if (!ip)
  441. return false;
  442. std::set<InetAddress> allIps(ips());
  443. if (allIps.count(ip) > 0)
  444. return true;
  445. // Remove and reconfigure if address is the same but netmask is different
  446. for(std::set<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  447. if (i->ipsEqual(ip)) {
  448. if (___removeIp(_dev,*i)) {
  449. break;
  450. } else {
  451. LOG("WARNING: failed to remove old IP/netmask %s to replace with %s",i->toString().c_str(),ip.toString().c_str());
  452. }
  453. }
  454. }
  455. long cpid;
  456. if ((cpid = (long)vfork()) == 0) {
  457. execl(ipcmd,ipcmd,"addr","add",ip.toString().c_str(),"dev",_dev.c_str(),(const char *)0);
  458. _exit(-1);
  459. } else if (cpid > 0) {
  460. int exitcode = -1;
  461. waitpid(cpid,&exitcode,0);
  462. return (exitcode == 0);
  463. }
  464. return false;
  465. }
  466. #endif // __LINUX__
  467. #ifdef __APPLE__
  468. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  469. {
  470. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  471. if (!ifconfig)
  472. return false;
  473. long cpid;
  474. if ((cpid = (long)vfork()) == 0) {
  475. execl(ifconfig,ifconfig,_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  476. _exit(-1);
  477. } else {
  478. int exitcode = -1;
  479. waitpid(cpid,&exitcode,0);
  480. return (exitcode == 0);
  481. }
  482. return false; // never reached, make compiler shut up about return value
  483. }
  484. bool UnixEthernetTap::addIP(const InetAddress &ip)
  485. {
  486. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  487. if (!ifconfig) {
  488. 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());
  489. return false;
  490. }
  491. if (!ip)
  492. return false;
  493. std::set<InetAddress> allIps(ips());
  494. if (allIps.count(ip) > 0)
  495. return true; // IP/netmask already assigned
  496. // Remove and reconfigure if address is the same but netmask is different
  497. for(std::set<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  498. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  499. if (___removeIp(_dev,*i)) {
  500. break;
  501. } else {
  502. LOG("WARNING: failed to remove old IP/netmask %s to replace with %s",i->toString().c_str(),ip.toString().c_str());
  503. }
  504. }
  505. }
  506. long cpid;
  507. if ((cpid = (long)vfork()) == 0) {
  508. execl(ifconfig,ifconfig,_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  509. _exit(-1);
  510. } else {
  511. int exitcode = -1;
  512. waitpid(cpid,&exitcode,0);
  513. return (exitcode == 0);
  514. }
  515. return false;
  516. }
  517. #endif // __APPLE__
  518. bool UnixEthernetTap::removeIP(const InetAddress &ip)
  519. {
  520. if (ips().count(ip) > 0) {
  521. if (___removeIp(_dev,ip))
  522. return true;
  523. }
  524. return false;
  525. }
  526. std::set<InetAddress> UnixEthernetTap::ips() const
  527. {
  528. struct ifaddrs *ifa = (struct ifaddrs *)0;
  529. if (getifaddrs(&ifa))
  530. return std::set<InetAddress>();
  531. std::set<InetAddress> r;
  532. struct ifaddrs *p = ifa;
  533. while (p) {
  534. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  535. switch(p->ifa_addr->sa_family) {
  536. case AF_INET: {
  537. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  538. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  539. r.insert(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  540. } break;
  541. case AF_INET6: {
  542. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  543. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  544. uint32_t b[4];
  545. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  546. 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])));
  547. } break;
  548. }
  549. }
  550. p = p->ifa_next;
  551. }
  552. if (ifa)
  553. freeifaddrs(ifa);
  554. return r;
  555. }
  556. void UnixEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  557. {
  558. char putBuf[4096 + 14];
  559. if ((_fd > 0)&&(len <= _mtu)) {
  560. for(int i=0;i<6;++i)
  561. putBuf[i] = to.data[i];
  562. for(int i=0;i<6;++i)
  563. putBuf[i+6] = from.data[i];
  564. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  565. memcpy(putBuf + 14,data,len);
  566. len += 14;
  567. int n = ::write(_fd,putBuf,len);
  568. if (n <= 0) {
  569. LOG("error writing packet to Ethernet tap device: %s",strerror(errno));
  570. } else if (n != (int)len) {
  571. // Saw this gremlin once, so log it if we see it again... OSX tap
  572. // or something seems to have goofy issues with certain MTUs.
  573. LOG("ERROR: write underrun: %s tap write() wrote %d of %u bytes of frame",_dev.c_str(),n,len);
  574. }
  575. }
  576. }
  577. std::string UnixEthernetTap::deviceName() const
  578. {
  579. return _dev;
  580. }
  581. std::string UnixEthernetTap::persistentId() const
  582. {
  583. return std::string();
  584. }
  585. #ifdef __LINUX__
  586. bool UnixEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  587. {
  588. char *ptr,*ptr2;
  589. unsigned char mac[6];
  590. std::set<MulticastGroup> newGroups;
  591. int fd = ::open("/proc/net/dev_mcast",O_RDONLY);
  592. if (fd > 0) {
  593. char buf[131072];
  594. int n = (int)::read(fd,buf,sizeof(buf));
  595. if ((n > 0)&&(n < (int)sizeof(buf))) {
  596. buf[n] = (char)0;
  597. for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) {
  598. int fno = 0;
  599. char *devname = (char *)0;
  600. char *mcastmac = (char *)0;
  601. for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) {
  602. if (fno == 1)
  603. devname = f;
  604. else if (fno == 4)
  605. mcastmac = f;
  606. ++fno;
  607. }
  608. if ((devname)&&(!strcmp(devname,_dev.c_str()))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6))
  609. newGroups.insert(MulticastGroup(MAC(mac),0));
  610. }
  611. }
  612. ::close(fd);
  613. }
  614. {
  615. std::set<InetAddress> allIps(ips());
  616. for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
  617. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  618. }
  619. bool changed = false;
  620. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  621. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  622. if (!groups.count(*mg)) {
  623. groups.insert(*mg);
  624. changed = true;
  625. }
  626. }
  627. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  628. if (!newGroups.count(*mg)) {
  629. groups.erase(mg++);
  630. changed = true;
  631. } else ++mg;
  632. }
  633. return changed;
  634. }
  635. #endif // __LINUX__
  636. #ifdef __APPLE__
  637. // --------------------------------------------------------------------------
  638. // This source is from:
  639. // http://www.opensource.apple.com/source/Libinfo/Libinfo-406.17/gen.subproj/getifmaddrs.c?txt
  640. // It's here because OSX 10.6 does not have this convenience function.
  641. #define SALIGN (sizeof(uint32_t) - 1)
  642. #define SA_RLEN(sa) ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : \
  643. (SALIGN + 1))
  644. #define MAX_SYSCTL_TRY 5
  645. #define RTA_MASKS (RTA_GATEWAY | RTA_IFP | RTA_IFA)
  646. /* FreeBSD uses NET_RT_IFMALIST and RTM_NEWMADDR from <sys/socket.h> */
  647. /* We can use NET_RT_IFLIST2 and RTM_NEWMADDR2 on Darwin */
  648. //#define DARWIN_COMPAT
  649. //#ifdef DARWIN_COMPAT
  650. #define GIM_SYSCTL_MIB NET_RT_IFLIST2
  651. #define GIM_RTM_ADDR RTM_NEWMADDR2
  652. //#else
  653. //#define GIM_SYSCTL_MIB NET_RT_IFMALIST
  654. //#define GIM_RTM_ADDR RTM_NEWMADDR
  655. //#endif
  656. // Not in 10.6 includes so use our own
  657. struct _intl_ifmaddrs {
  658. struct _intl_ifmaddrs *ifma_next;
  659. struct sockaddr *ifma_name;
  660. struct sockaddr *ifma_addr;
  661. struct sockaddr *ifma_lladdr;
  662. };
  663. static inline int _intl_getifmaddrs(struct _intl_ifmaddrs **pif)
  664. {
  665. int icnt = 1;
  666. int dcnt = 0;
  667. int ntry = 0;
  668. size_t len;
  669. size_t needed;
  670. int mib[6];
  671. int i;
  672. char *buf;
  673. char *data;
  674. char *next;
  675. char *p;
  676. struct ifma_msghdr2 *ifmam;
  677. struct _intl_ifmaddrs *ifa, *ift;
  678. struct rt_msghdr *rtm;
  679. struct sockaddr *sa;
  680. mib[0] = CTL_NET;
  681. mib[1] = PF_ROUTE;
  682. mib[2] = 0; /* protocol */
  683. mib[3] = 0; /* wildcard address family */
  684. mib[4] = GIM_SYSCTL_MIB;
  685. mib[5] = 0; /* no flags */
  686. do {
  687. if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
  688. return (-1);
  689. if ((buf = (char *)malloc(needed)) == NULL)
  690. return (-1);
  691. if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
  692. if (errno != ENOMEM || ++ntry >= MAX_SYSCTL_TRY) {
  693. free(buf);
  694. return (-1);
  695. }
  696. free(buf);
  697. buf = NULL;
  698. }
  699. } while (buf == NULL);
  700. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  701. rtm = (struct rt_msghdr *)(void *)next;
  702. if (rtm->rtm_version != RTM_VERSION)
  703. continue;
  704. switch (rtm->rtm_type) {
  705. case GIM_RTM_ADDR:
  706. ifmam = (struct ifma_msghdr2 *)(void *)rtm;
  707. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  708. break;
  709. icnt++;
  710. p = (char *)(ifmam + 1);
  711. for (i = 0; i < RTAX_MAX; i++) {
  712. if ((RTA_MASKS & ifmam->ifmam_addrs &
  713. (1 << i)) == 0)
  714. continue;
  715. sa = (struct sockaddr *)(void *)p;
  716. len = SA_RLEN(sa);
  717. dcnt += len;
  718. p += len;
  719. }
  720. break;
  721. }
  722. }
  723. data = (char *)malloc(sizeof(struct _intl_ifmaddrs) * icnt + dcnt);
  724. if (data == NULL) {
  725. free(buf);
  726. return (-1);
  727. }
  728. ifa = (struct _intl_ifmaddrs *)(void *)data;
  729. data += sizeof(struct _intl_ifmaddrs) * icnt;
  730. memset(ifa, 0, sizeof(struct _intl_ifmaddrs) * icnt);
  731. ift = ifa;
  732. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  733. rtm = (struct rt_msghdr *)(void *)next;
  734. if (rtm->rtm_version != RTM_VERSION)
  735. continue;
  736. switch (rtm->rtm_type) {
  737. case GIM_RTM_ADDR:
  738. ifmam = (struct ifma_msghdr2 *)(void *)rtm;
  739. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  740. break;
  741. p = (char *)(ifmam + 1);
  742. for (i = 0; i < RTAX_MAX; i++) {
  743. if ((RTA_MASKS & ifmam->ifmam_addrs &
  744. (1 << i)) == 0)
  745. continue;
  746. sa = (struct sockaddr *)(void *)p;
  747. len = SA_RLEN(sa);
  748. switch (i) {
  749. case RTAX_GATEWAY:
  750. ift->ifma_lladdr =
  751. (struct sockaddr *)(void *)data;
  752. memcpy(data, p, len);
  753. data += len;
  754. break;
  755. case RTAX_IFP:
  756. ift->ifma_name =
  757. (struct sockaddr *)(void *)data;
  758. memcpy(data, p, len);
  759. data += len;
  760. break;
  761. case RTAX_IFA:
  762. ift->ifma_addr =
  763. (struct sockaddr *)(void *)data;
  764. memcpy(data, p, len);
  765. data += len;
  766. break;
  767. default:
  768. data += len;
  769. break;
  770. }
  771. p += len;
  772. }
  773. ift->ifma_next = ift + 1;
  774. ift = ift->ifma_next;
  775. break;
  776. }
  777. }
  778. free(buf);
  779. if (ift > ifa) {
  780. ift--;
  781. ift->ifma_next = NULL;
  782. *pif = ifa;
  783. } else {
  784. *pif = NULL;
  785. free(ifa);
  786. }
  787. return (0);
  788. }
  789. static inline void _intl_freeifmaddrs(struct _intl_ifmaddrs *ifmp)
  790. {
  791. free(ifmp);
  792. }
  793. // --------------------------------------------------------------------------
  794. bool UnixEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  795. {
  796. std::set<MulticastGroup> newGroups;
  797. struct _intl_ifmaddrs *ifmap = (struct _intl_ifmaddrs *)0;
  798. if (!_intl_getifmaddrs(&ifmap)) {
  799. struct _intl_ifmaddrs *p = ifmap;
  800. while (p) {
  801. if (p->ifma_addr->sa_family == AF_LINK) {
  802. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  803. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  804. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  805. newGroups.insert(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen),0));
  806. }
  807. p = p->ifma_next;
  808. }
  809. _intl_freeifmaddrs(ifmap);
  810. }
  811. {
  812. std::set<InetAddress> allIps(ips());
  813. for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
  814. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  815. }
  816. bool changed = false;
  817. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  818. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  819. if (!groups.count(*mg)) {
  820. groups.insert(*mg);
  821. changed = true;
  822. }
  823. }
  824. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  825. if (!newGroups.count(*mg)) {
  826. groups.erase(mg++);
  827. changed = true;
  828. } else ++mg;
  829. }
  830. return changed;
  831. }
  832. #endif // __APPLE__
  833. void UnixEthernetTap::threadMain()
  834. throw()
  835. {
  836. fd_set readfds,nullfds;
  837. MAC to,from;
  838. int n,nfds,r;
  839. char getBuf[8194];
  840. Buffer<4096> data;
  841. // Wait for a moment after startup -- wait for Network to finish
  842. // constructing itself.
  843. Thread::sleep(500);
  844. FD_ZERO(&readfds);
  845. FD_ZERO(&nullfds);
  846. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  847. r = 0;
  848. for(;;) {
  849. FD_SET(_shutdownSignalPipe[0],&readfds);
  850. FD_SET(_fd,&readfds);
  851. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  852. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  853. break;
  854. if (FD_ISSET(_fd,&readfds)) {
  855. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  856. if (n < 0) {
  857. if ((errno != EINTR)&&(errno != ETIMEDOUT)) {
  858. TRACE("unexpected error reading from tap: %s",strerror(errno));
  859. break;
  860. }
  861. } else {
  862. // Some tap drivers like to send the ethernet frame and the
  863. // payload in two chunks, so handle that by accumulating
  864. // data until we have at least a frame.
  865. r += n;
  866. if (r > 14) {
  867. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  868. r = _mtu + 14;
  869. for(int i=0;i<6;++i)
  870. to.data[i] = (unsigned char)getBuf[i];
  871. for(int i=0;i<6;++i)
  872. from.data[i] = (unsigned char)getBuf[i + 6];
  873. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  874. if (etherType != 0x8100) { // VLAN tagged frames are not supported!
  875. data.copyFrom(getBuf + 14,(unsigned int)r - 14);
  876. _handler(_arg,from,to,etherType,data);
  877. }
  878. r = 0;
  879. }
  880. }
  881. }
  882. }
  883. }
  884. } // namespace ZeroTier