RoutingTable.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include "../node/Constants.hpp"
  19. #ifdef __WINDOWS__
  20. #include <WinSock2.h>
  21. #include <Windows.h>
  22. #include <netioapi.h>
  23. #include <IPHlpApi.h>
  24. #endif
  25. #include <stdint.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #ifdef __UNIX_LIKE__
  30. #include <unistd.h>
  31. #include <sys/param.h>
  32. #include <sys/sysctl.h>
  33. #include <sys/socket.h>
  34. #include <sys/types.h>
  35. #include <sys/wait.h>
  36. #include <netinet/in.h>
  37. #include <arpa/inet.h>
  38. #include <net/route.h>
  39. #include <net/if.h>
  40. #include <net/if_dl.h>
  41. #include <ifaddrs.h>
  42. #endif
  43. #include <vector>
  44. #include <algorithm>
  45. #include <utility>
  46. #include "RoutingTable.hpp"
  47. #define ZT_BSD_ROUTE_CMD "/sbin/route"
  48. #define ZT_LINUX_IP_COMMAND "/sbin/ip"
  49. namespace ZeroTier {
  50. // ---------------------------------------------------------------------------
  51. #ifdef __LINUX__
  52. std::vector<RoutingTable::Entry> RoutingTable::get(bool includeLinkLocal,bool includeLoopback)
  53. {
  54. char buf[131072];
  55. char *stmp,*stmp2;
  56. std::vector<RoutingTable::Entry> entries;
  57. {
  58. int fd = ::open("/proc/net/route",O_RDONLY);
  59. if (fd <= 0)
  60. buf[0] = (char)0;
  61. else {
  62. int n = (int)::read(fd,buf,sizeof(buf) - 1);
  63. ::close(fd);
  64. if (n < 0) n = 0;
  65. buf[n] = (char)0;
  66. }
  67. }
  68. int lineno = 0;
  69. for(char *line=Utils::stok(buf,"\r\n",&stmp);(line);line=Utils::stok((char *)0,"\r\n",&stmp)) {
  70. if (lineno == 0) {
  71. ++lineno;
  72. continue; // skip header
  73. }
  74. char *iface = (char *)0;
  75. uint32_t destination = 0;
  76. uint32_t gateway = 0;
  77. int metric = 0;
  78. uint32_t mask = 0;
  79. int fno = 0;
  80. for(char *f=Utils::stok(line,"\t \r\n",&stmp2);(f);f=Utils::stok((char *)0,"\t \r\n",&stmp2)) {
  81. switch(fno) {
  82. case 0: iface = f; break;
  83. case 1: destination = (uint32_t)Utils::hexStrToULong(f); break;
  84. case 2: gateway = (uint32_t)Utils::hexStrToULong(f); break;
  85. case 6: metric = (int)Utils::strToInt(f); break;
  86. case 7: mask = (uint32_t)Utils::hexStrToULong(f); break;
  87. }
  88. ++fno;
  89. }
  90. if ((iface)&&(destination)) {
  91. RoutingTable::Entry e;
  92. if (destination)
  93. e.destination.set(&destination,4,Utils::countBits(mask));
  94. e.gateway.set(&gateway,4,0);
  95. e.deviceIndex = 0; // not used on Linux
  96. e.metric = metric;
  97. Utils::scopy(e.device,sizeof(e.device),iface);
  98. if ((e.destination)&&((includeLinkLocal)||(!e.destination.isLinkLocal()))&&((includeLoopback)||((!e.destination.isLoopback())&&(!e.gateway.isLoopback())&&(strcmp(iface,"lo")))))
  99. entries.push_back(e);
  100. }
  101. ++lineno;
  102. }
  103. {
  104. int fd = ::open("/proc/net/ipv6_route",O_RDONLY);
  105. if (fd <= 0)
  106. buf[0] = (char)0;
  107. else {
  108. int n = (int)::read(fd,buf,sizeof(buf) - 1);
  109. ::close(fd);
  110. if (n < 0) n = 0;
  111. buf[n] = (char)0;
  112. }
  113. }
  114. for(char *line=Utils::stok(buf,"\r\n",&stmp);(line);line=Utils::stok((char *)0,"\r\n",&stmp)) {
  115. char *destination = (char *)0;
  116. unsigned int destPrefixLen = 0;
  117. char *gateway = (char *)0; // next hop in ipv6 terminology
  118. int metric = 0;
  119. char *device = (char *)0;
  120. int fno = 0;
  121. for(char *f=Utils::stok(line,"\t \r\n",&stmp2);(f);f=Utils::stok((char *)0,"\t \r\n",&stmp2)) {
  122. switch(fno) {
  123. case 0: destination = f; break;
  124. case 1: destPrefixLen = (unsigned int)Utils::hexStrToULong(f); break;
  125. case 4: gateway = f; break;
  126. case 5: metric = (int)Utils::hexStrToLong(f); break;
  127. case 9: device = f; break;
  128. }
  129. ++fno;
  130. }
  131. if ((device)&&(destination)) {
  132. unsigned char tmp[16];
  133. RoutingTable::Entry e;
  134. Utils::unhex(destination,tmp,16);
  135. if ((!Utils::isZero(tmp,16))&&(tmp[0] != 0xff))
  136. e.destination.set(tmp,16,destPrefixLen);
  137. Utils::unhex(gateway,tmp,16);
  138. e.gateway.set(tmp,16,0);
  139. e.deviceIndex = 0; // not used on Linux
  140. e.metric = metric;
  141. Utils::scopy(e.device,sizeof(e.device),device);
  142. if ((e.destination)&&((includeLinkLocal)||(!e.destination.isLinkLocal()))&&((includeLoopback)||((!e.destination.isLoopback())&&(!e.gateway.isLoopback())&&(strcmp(device,"lo")))))
  143. entries.push_back(e);
  144. }
  145. }
  146. std::sort(entries.begin(),entries.end());
  147. return entries;
  148. }
  149. RoutingTable::Entry RoutingTable::set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric,bool ifscope)
  150. {
  151. char metstr[128];
  152. if ((!gateway)&&((!device)||(!device[0])))
  153. return RoutingTable::Entry();
  154. Utils::snprintf(metstr,sizeof(metstr),"%d",metric);
  155. if (metric < 0) {
  156. long pid = (long)vfork();
  157. if (pid == 0) {
  158. if (gateway) {
  159. if ((device)&&(device[0])) {
  160. ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","del",destination.toString().c_str(),"via",gateway.toIpString().c_str(),"dev",device,(const char *)0);
  161. } else {
  162. ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","del",destination.toString().c_str(),"via",gateway.toIpString().c_str(),(const char *)0);
  163. }
  164. } else {
  165. ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","del",destination.toString().c_str(),"dev",device,(const char *)0);
  166. }
  167. ::_exit(-1);
  168. } else if (pid > 0) {
  169. int exitcode = -1;
  170. ::waitpid(pid,&exitcode,0);
  171. }
  172. } else {
  173. long pid = (long)vfork();
  174. if (pid == 0) {
  175. if (gateway) {
  176. if ((device)&&(device[0])) {
  177. ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","replace",destination.toString().c_str(),"metric",metstr,"via",gateway.toIpString().c_str(),"dev",device,(const char *)0);
  178. } else {
  179. ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","replace",destination.toString().c_str(),"metric",metstr,"via",gateway.toIpString().c_str(),(const char *)0);
  180. }
  181. } else {
  182. ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","replace",destination.toString().c_str(),"metric",metstr,"dev",device,(const char *)0);
  183. }
  184. ::_exit(-1);
  185. } else if (pid > 0) {
  186. int exitcode = -1;
  187. ::waitpid(pid,&exitcode,0);
  188. }
  189. }
  190. std::vector<RoutingTable::Entry> rtab(get(true,true));
  191. std::vector<RoutingTable::Entry>::iterator bestEntry(rtab.end());
  192. for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
  193. if ((e->destination == destination)&&(e->gateway.ipsEqual(gateway))) {
  194. if ((device)&&(device[0])) {
  195. if (!strcmp(device,e->device)) {
  196. if (metric == e->metric)
  197. bestEntry = e;
  198. }
  199. }
  200. if (bestEntry == rtab.end())
  201. bestEntry = e;
  202. }
  203. }
  204. if (bestEntry != rtab.end())
  205. return *bestEntry;
  206. return RoutingTable::Entry();
  207. }
  208. #endif // __LINUX__
  209. // ---------------------------------------------------------------------------
  210. #ifdef __BSD__
  211. std::vector<RoutingTable::Entry> RoutingTable::get(bool includeLinkLocal,bool includeLoopback)
  212. {
  213. std::vector<RoutingTable::Entry> entries;
  214. int mib[6];
  215. size_t needed;
  216. mib[0] = CTL_NET;
  217. mib[1] = PF_ROUTE;
  218. mib[2] = 0;
  219. mib[3] = 0;
  220. mib[4] = NET_RT_DUMP;
  221. mib[5] = 0;
  222. if (!sysctl(mib,6,NULL,&needed,NULL,0)) {
  223. if (needed <= 0)
  224. return entries;
  225. char *buf = (char *)::malloc(needed);
  226. if (buf) {
  227. if (!sysctl(mib,6,buf,&needed,NULL,0)) {
  228. struct rt_msghdr *rtm;
  229. for(char *next=buf,*end=buf+needed;next<end;) {
  230. rtm = (struct rt_msghdr *)next;
  231. char *saptr = (char *)(rtm + 1);
  232. char *saend = next + rtm->rtm_msglen;
  233. if (((rtm->rtm_flags & RTF_LLINFO) == 0)&&((rtm->rtm_flags & RTF_HOST) == 0)&&((rtm->rtm_flags & RTF_UP) != 0)&&((rtm->rtm_flags & RTF_MULTICAST) == 0)) {
  234. RoutingTable::Entry e;
  235. e.deviceIndex = -9999; // unset
  236. int which = 0;
  237. while (saptr < saend) {
  238. struct sockaddr *sa = (struct sockaddr *)saptr;
  239. unsigned int salen = sa->sa_len;
  240. if (!salen)
  241. break;
  242. // Skip missing fields in rtm_addrs bit field
  243. while ((rtm->rtm_addrs & 1) == 0) {
  244. rtm->rtm_addrs >>= 1;
  245. ++which;
  246. if (which > 6)
  247. break;
  248. }
  249. if (which > 6)
  250. break;
  251. rtm->rtm_addrs >>= 1;
  252. switch(which++) {
  253. case 0:
  254. //printf("RTA_DST\n");
  255. if (sa->sa_family == AF_INET6) {
  256. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
  257. // Nobody expects the Spanish inquisition!
  258. if ((sin6->sin6_addr.s6_addr[0] == 0xfe)&&((sin6->sin6_addr.s6_addr[1] & 0xc0) == 0x80)) {
  259. // Our chief weapon is... in-band signaling!
  260. // Seriously who in the living fuck thought this was a good idea and
  261. // then had the sadistic idea to not document it anywhere? Of course it's
  262. // not like there is any documentation on BSD sysctls anyway.
  263. unsigned int interfaceIndex = ((((unsigned int)sin6->sin6_addr.s6_addr[2]) << 8) & 0xff) | (((unsigned int)sin6->sin6_addr.s6_addr[3]) & 0xff);
  264. sin6->sin6_addr.s6_addr[2] = 0;
  265. sin6->sin6_addr.s6_addr[3] = 0;
  266. if (!sin6->sin6_scope_id)
  267. sin6->sin6_scope_id = interfaceIndex;
  268. }
  269. }
  270. e.destination = *sa;
  271. break;
  272. case 1:
  273. //printf("RTA_GATEWAY\n");
  274. switch(sa->sa_family) {
  275. case AF_LINK:
  276. e.deviceIndex = (int)((const struct sockaddr_dl *)sa)->sdl_index;
  277. break;
  278. case AF_INET:
  279. case AF_INET6:
  280. e.gateway = *sa;
  281. break;
  282. }
  283. break;
  284. case 2: {
  285. if (e.destination.isV6()) {
  286. salen = sizeof(struct sockaddr_in6); // Confess!
  287. unsigned int bits = 0;
  288. for(int i=0;i<16;++i) {
  289. unsigned char c = (unsigned char)((const struct sockaddr_in6 *)sa)->sin6_addr.s6_addr[i];
  290. if (c == 0xff)
  291. bits += 8;
  292. else break;
  293. /* must they be multiples of 8? Most of the BSD source I can find says yes..?
  294. else {
  295. while ((c & 0x80) == 0x80) {
  296. ++bits;
  297. c <<= 1;
  298. }
  299. break;
  300. }
  301. */
  302. }
  303. e.destination.setPort(bits);
  304. } else {
  305. salen = sizeof(struct sockaddr_in); // Confess!
  306. e.destination.setPort((unsigned int)Utils::countBits((uint32_t)((const struct sockaddr_in *)sa)->sin_addr.s_addr));
  307. }
  308. //printf("RTA_NETMASK\n");
  309. } break;
  310. /*
  311. case 3:
  312. //printf("RTA_GENMASK\n");
  313. break;
  314. case 4:
  315. //printf("RTA_IFP\n");
  316. break;
  317. case 5:
  318. //printf("RTA_IFA\n");
  319. break;
  320. case 6:
  321. //printf("RTA_AUTHOR\n");
  322. break;
  323. */
  324. }
  325. saptr += salen;
  326. }
  327. e.metric = (int)rtm->rtm_rmx.rmx_hopcount;
  328. if (e.metric < 0)
  329. e.metric = 0;
  330. InetAddress::IpScope dscope = e.destination.ipScope();
  331. if ( ((includeLinkLocal)||(dscope != InetAddress::IP_SCOPE_LINK_LOCAL)) && ((includeLoopback)||((dscope != InetAddress::IP_SCOPE_LOOPBACK) && (e.gateway.ipScope() != InetAddress::IP_SCOPE_LOOPBACK) )))
  332. entries.push_back(e);
  333. }
  334. next = saend;
  335. }
  336. }
  337. ::free(buf);
  338. }
  339. }
  340. for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e1(entries.begin());e1!=entries.end();++e1) {
  341. if ((!e1->device[0])&&(e1->deviceIndex >= 0))
  342. if_indextoname(e1->deviceIndex,e1->device);
  343. }
  344. for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e1(entries.begin());e1!=entries.end();++e1) {
  345. if ((!e1->device[0])&&(e1->gateway)) {
  346. int bestMetric = 9999999;
  347. for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e2(entries.begin());e2!=entries.end();++e2) {
  348. if ((e2->destination.containsAddress(e1->gateway))&&(e2->metric <= bestMetric)) {
  349. bestMetric = e2->metric;
  350. Utils::scopy(e1->device,sizeof(e1->device),e2->device);
  351. }
  352. }
  353. }
  354. }
  355. std::sort(entries.begin(),entries.end());
  356. return entries;
  357. }
  358. RoutingTable::Entry RoutingTable::set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric,bool ifscope)
  359. {
  360. if ((!gateway)&&((!device)||(!device[0])))
  361. return RoutingTable::Entry();
  362. std::vector<RoutingTable::Entry> rtab(get(true,true));
  363. for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
  364. if (e->destination == destination) {
  365. if (((!device)||(!device[0]))||(!strcmp(device,e->device))) {
  366. long p = (long)fork();
  367. if (p > 0) {
  368. int exitcode = -1;
  369. ::waitpid(p,&exitcode,0);
  370. } else if (p == 0) {
  371. ::close(STDOUT_FILENO);
  372. ::close(STDERR_FILENO);
  373. ::execl(ZT_BSD_ROUTE_CMD,ZT_BSD_ROUTE_CMD,"delete",(destination.isV6() ? "-inet6" : "-inet"),destination.toString().c_str(),(const char *)0);
  374. ::_exit(-1);
  375. }
  376. }
  377. }
  378. }
  379. if (metric < 0)
  380. return RoutingTable::Entry();
  381. {
  382. char hcstr[64];
  383. Utils::snprintf(hcstr,sizeof(hcstr),"%d",metric);
  384. long p = (long)fork();
  385. if (p > 0) {
  386. int exitcode = -1;
  387. ::waitpid(p,&exitcode,0);
  388. } else if (p == 0) {
  389. ::close(STDOUT_FILENO);
  390. ::close(STDERR_FILENO);
  391. if (gateway) {
  392. ::execl(ZT_BSD_ROUTE_CMD,ZT_BSD_ROUTE_CMD,"add",(destination.isV6() ? "-inet6" : "-inet"),destination.toString().c_str(),gateway.toIpString().c_str(),"-hopcount",hcstr,(const char *)0);
  393. } else if ((device)&&(device[0])) {
  394. ::execl(ZT_BSD_ROUTE_CMD,ZT_BSD_ROUTE_CMD,"add",(destination.isV6() ? "-inet6" : "-inet"),destination.toString().c_str(),"-interface",device,"-hopcount",hcstr,(const char *)0);
  395. }
  396. ::_exit(-1);
  397. }
  398. }
  399. rtab = get(true,true);
  400. std::vector<RoutingTable::Entry>::iterator bestEntry(rtab.end());
  401. for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
  402. if ((e->destination == destination)&&(e->gateway.ipsEqual(gateway))) {
  403. if ((device)&&(device[0])) {
  404. if (!strcmp(device,e->device)) {
  405. if (metric == e->metric)
  406. bestEntry = e;
  407. }
  408. }
  409. if (bestEntry == rtab.end())
  410. bestEntry = e;
  411. }
  412. }
  413. if (bestEntry != rtab.end())
  414. return *bestEntry;
  415. return RoutingTable::Entry();
  416. }
  417. #endif // __BSD__
  418. // ---------------------------------------------------------------------------
  419. #ifdef __WINDOWS__
  420. static void _copyInetAddressToSockaddrInet(const InetAddress &a,SOCKADDR_INET &sinet)
  421. {
  422. memset(&sinet,0,sizeof(sinet));
  423. if (a.isV4()) {
  424. sinet.Ipv4.sin_addr.S_un.S_addr = *((const uint32_t *)a.rawIpData());
  425. sinet.Ipv4.sin_family = AF_INET;
  426. sinet.Ipv4.sin_port = htons(a.port());
  427. } else if (a.isV6()) {
  428. memcpy(sinet.Ipv6.sin6_addr.u.Byte,a.rawIpData(),16);
  429. sinet.Ipv6.sin6_family = AF_INET6;
  430. sinet.Ipv6.sin6_port = htons(a.port());
  431. }
  432. }
  433. std::vector<RoutingTable::Entry> RoutingTable::get(bool includeLinkLocal,bool includeLoopback) const
  434. {
  435. std::vector<RoutingTable::Entry> entries;
  436. PMIB_IPFORWARD_TABLE2 rtbl = NULL;
  437. if (GetIpForwardTable2(AF_UNSPEC,&rtbl) != NO_ERROR)
  438. return entries;
  439. if (!rtbl)
  440. return entries;
  441. for(ULONG r=0;r<rtbl->NumEntries;++r) {
  442. RoutingTable::Entry e;
  443. switch(rtbl->Table[r].DestinationPrefix.Prefix.si_family) {
  444. case AF_INET:
  445. e.destination.set(&(rtbl->Table[r].DestinationPrefix.Prefix.Ipv4.sin_addr.S_un.S_addr),4,rtbl->Table[r].DestinationPrefix.PrefixLength);
  446. break;
  447. case AF_INET6:
  448. e.destination.set(rtbl->Table[r].DestinationPrefix.Prefix.Ipv6.sin6_addr.u.Byte,16,rtbl->Table[r].DestinationPrefix.PrefixLength);
  449. break;
  450. }
  451. switch(rtbl->Table[r].NextHop.si_family) {
  452. case AF_INET:
  453. e.gateway.set(&(rtbl->Table[r].NextHop.Ipv4.sin_addr.S_un.S_addr),4,0);
  454. break;
  455. case AF_INET6:
  456. e.gateway.set(rtbl->Table[r].NextHop.Ipv6.sin6_addr.u.Byte,16,0);
  457. break;
  458. }
  459. e.deviceIndex = (int)rtbl->Table[r].InterfaceIndex;
  460. e.metric = (int)rtbl->Table[r].Metric;
  461. ConvertInterfaceLuidToNameA(&(rtbl->Table[r].InterfaceLuid),e.device,sizeof(e.device));
  462. if ((e.destination)&&((includeLinkLocal)||(!e.destination.isLinkLocal()))&&((includeLoopback)||((!e.destination.isLoopback())&&(!e.gateway.isLoopback()))))
  463. entries.push_back(e);
  464. }
  465. FreeMibTable(rtbl);
  466. std::sort(entries.begin(),entries.end());
  467. return entries;
  468. }
  469. RoutingTable::Entry RoutingTable::set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric,bool ifscope)
  470. {
  471. NET_LUID luid;
  472. luid.Value = 0;
  473. if (ConvertInterfaceNameToLuidA(device,&luid) != NO_ERROR)
  474. return RoutingTable::Entry();
  475. bool needCreate = true;
  476. PMIB_IPFORWARD_TABLE2 rtbl = NULL;
  477. if (GetIpForwardTable2(AF_UNSPEC,&rtbl) != NO_ERROR)
  478. return RoutingTable::Entry();
  479. if (!rtbl)
  480. return RoutingTable::Entry();
  481. for(ULONG r=0;r<rtbl->NumEntries;++r) {
  482. if (rtbl->Table[r].InterfaceLuid.Value == luid.Value) {
  483. InetAddress rdest;
  484. switch(rtbl->Table[r].DestinationPrefix.Prefix.si_family) {
  485. case AF_INET:
  486. rdest.set(&(rtbl->Table[r].DestinationPrefix.Prefix.Ipv4.sin_addr.S_un.S_addr),4,rtbl->Table[r].DestinationPrefix.PrefixLength);
  487. break;
  488. case AF_INET6:
  489. rdest.set(rtbl->Table[r].DestinationPrefix.Prefix.Ipv6.sin6_addr.u.Byte,16,rtbl->Table[r].DestinationPrefix.PrefixLength);
  490. break;
  491. }
  492. if (rdest == destination) {
  493. if (metric >= 0) {
  494. _copyInetAddressToSockaddrInet(gateway,rtbl->Table[r].NextHop);
  495. rtbl->Table[r].Metric = metric;
  496. SetIpForwardEntry2(&(rtbl->Table[r]));
  497. needCreate = false;
  498. } else {
  499. DeleteIpForwardEntry2(&(rtbl->Table[r]));
  500. FreeMibTable(rtbl);
  501. return RoutingTable::Entry();
  502. }
  503. }
  504. }
  505. }
  506. FreeMibTable(rtbl);
  507. if ((metric >= 0)&&(needCreate)) {
  508. MIB_IPFORWARD_ROW2 nr;
  509. InitializeIpForwardEntry(&nr);
  510. nr.InterfaceLuid.Value = luid.Value;
  511. _copyInetAddressToSockaddrInet(destination,nr.DestinationPrefix.Prefix);
  512. nr.DestinationPrefix.PrefixLength = destination.netmaskBits();
  513. _copyInetAddressToSockaddrInet(gateway,nr.NextHop);
  514. nr.Metric = metric;
  515. nr.Protocol = MIB_IPPROTO_NETMGMT;
  516. DWORD result = CreateIpForwardEntry2(&nr);
  517. if (result != NO_ERROR)
  518. return RoutingTable::Entry();
  519. }
  520. std::vector<RoutingTable::Entry> rtab(get(true,true));
  521. std::vector<RoutingTable::Entry>::iterator bestEntry(rtab.end());
  522. for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
  523. if ((e->destination == destination)&&(e->gateway.ipsEqual(gateway))) {
  524. if ((device)&&(device[0])) {
  525. if (!strcmp(device,e->device)) {
  526. if (metric == e->metric)
  527. bestEntry = e;
  528. }
  529. }
  530. if (bestEntry == rtab.end())
  531. bestEntry = e;
  532. }
  533. }
  534. if (bestEntry != rtab.end())
  535. return *bestEntry;
  536. return RoutingTable::Entry();
  537. }
  538. #endif // __WINDOWS__
  539. // ---------------------------------------------------------------------------
  540. } // namespace ZeroTier