BSDRoutingTable.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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 <sys/param.h>
  33. #include <sys/sysctl.h>
  34. #include <sys/socket.h>
  35. #include <sys/types.h>
  36. #include <sys/wait.h>
  37. #include <netinet/in.h>
  38. #include <arpa/inet.h>
  39. #include <net/route.h>
  40. #include <net/if.h>
  41. #include <net/if_dl.h>
  42. #include <ifaddrs.h>
  43. #include <algorithm>
  44. #include <utility>
  45. #include "../node/Constants.hpp"
  46. #include "BSDRoutingTable.hpp"
  47. // All I wanted was the bloody rounting table. I didn't expect the Spanish inquisition.
  48. #define ZT_BSD_ROUTE_CMD "/sbin/route"
  49. namespace ZeroTier {
  50. BSDRoutingTable::BSDRoutingTable()
  51. {
  52. }
  53. BSDRoutingTable::~BSDRoutingTable()
  54. {
  55. }
  56. std::vector<RoutingTable::Entry> BSDRoutingTable::get(bool includeLinkLocal,bool includeLoopback) const
  57. {
  58. std::vector<RoutingTable::Entry> entries;
  59. int mib[6];
  60. size_t needed;
  61. mib[0] = CTL_NET;
  62. mib[1] = PF_ROUTE;
  63. mib[2] = 0;
  64. mib[3] = 0;
  65. mib[4] = NET_RT_DUMP;
  66. mib[5] = 0;
  67. if (!sysctl(mib,6,NULL,&needed,NULL,0)) {
  68. if (needed <= 0)
  69. return entries;
  70. char *buf = (char *)::malloc(needed);
  71. if (buf) {
  72. if (!sysctl(mib,6,buf,&needed,NULL,0)) {
  73. struct rt_msghdr *rtm;
  74. for(char *next=buf,*end=buf+needed;next<end;) {
  75. rtm = (struct rt_msghdr *)next;
  76. char *saptr = (char *)(rtm + 1);
  77. char *saend = next + rtm->rtm_msglen;
  78. 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)) {
  79. RoutingTable::Entry e;
  80. e.deviceIndex = -9999; // unset
  81. int which = 0;
  82. while (saptr < saend) {
  83. struct sockaddr *sa = (struct sockaddr *)saptr;
  84. unsigned int salen = sa->sa_len;
  85. if (!salen)
  86. break;
  87. // Skip missing fields in rtm_addrs bit field
  88. while ((rtm->rtm_addrs & 1) == 0) {
  89. rtm->rtm_addrs >>= 1;
  90. ++which;
  91. if (which > 6)
  92. break;
  93. }
  94. if (which > 6)
  95. break;
  96. rtm->rtm_addrs >>= 1;
  97. switch(which++) {
  98. case 0:
  99. //printf("RTA_DST\n");
  100. if (sa->sa_family == AF_INET6) {
  101. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
  102. // Nobody expects the Spanish inquisition!
  103. if ((sin6->sin6_addr.s6_addr[0] == 0xfe)&&((sin6->sin6_addr.s6_addr[1] & 0xc0) == 0x80)) {
  104. // Our chief weapon is... in-band signaling!
  105. // Seriously who in the living fuck thought this was a good idea and
  106. // then had the sadistic idea to not document it anywhere? Of course it's
  107. // not like there is any documentation on BSD sysctls anyway.
  108. unsigned int interfaceIndex = ((((unsigned int)sin6->sin6_addr.s6_addr[2]) << 8) & 0xff) | (((unsigned int)sin6->sin6_addr.s6_addr[3]) & 0xff);
  109. sin6->sin6_addr.s6_addr[2] = 0;
  110. sin6->sin6_addr.s6_addr[3] = 0;
  111. if (!sin6->sin6_scope_id)
  112. sin6->sin6_scope_id = interfaceIndex;
  113. }
  114. }
  115. e.destination.set(sa);
  116. break;
  117. case 1:
  118. //printf("RTA_GATEWAY\n");
  119. switch(sa->sa_family) {
  120. case AF_LINK:
  121. e.deviceIndex = (int)((const struct sockaddr_dl *)sa)->sdl_index;
  122. break;
  123. case AF_INET:
  124. case AF_INET6:
  125. e.gateway.set(sa);
  126. break;
  127. }
  128. break;
  129. case 2: {
  130. if (e.destination.isV6()) {
  131. salen = sizeof(struct sockaddr_in6); // Confess!
  132. unsigned int bits = 0;
  133. for(int i=0;i<16;++i) {
  134. unsigned char c = (unsigned char)((const struct sockaddr_in6 *)sa)->sin6_addr.s6_addr[i];
  135. if (c == 0xff)
  136. bits += 8;
  137. else break;
  138. /* must they be multiples of 8? Most of the BSD source I can find says yes..?
  139. else {
  140. while ((c & 0x80) == 0x80) {
  141. ++bits;
  142. c <<= 1;
  143. }
  144. break;
  145. }
  146. */
  147. }
  148. e.destination.setPort(bits);
  149. } else {
  150. salen = sizeof(struct sockaddr_in); // Confess!
  151. e.destination.setPort((unsigned int)Utils::countBits((uint32_t)((const struct sockaddr_in *)sa)->sin_addr.s_addr));
  152. }
  153. //printf("RTA_NETMASK\n");
  154. } break;
  155. /*
  156. case 3:
  157. //printf("RTA_GENMASK\n");
  158. break;
  159. case 4:
  160. //printf("RTA_IFP\n");
  161. break;
  162. case 5:
  163. //printf("RTA_IFA\n");
  164. break;
  165. case 6:
  166. //printf("RTA_AUTHOR\n");
  167. break;
  168. */
  169. }
  170. saptr += salen;
  171. }
  172. e.metric = (int)rtm->rtm_rmx.rmx_hopcount;
  173. if (e.metric < 0)
  174. e.metric = 0;
  175. if (((includeLinkLocal)||(!e.destination.isLinkLocal()))&&((includeLoopback)||((!e.destination.isLoopback())&&(!e.gateway.isLoopback()))))
  176. entries.push_back(e);
  177. }
  178. next = saend;
  179. }
  180. }
  181. ::free(buf);
  182. }
  183. }
  184. for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e1(entries.begin());e1!=entries.end();++e1) {
  185. if ((!e1->device[0])&&(e1->deviceIndex >= 0))
  186. if_indextoname(e1->deviceIndex,e1->device);
  187. }
  188. for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e1(entries.begin());e1!=entries.end();++e1) {
  189. if ((!e1->device[0])&&(e1->gateway)) {
  190. int bestMetric = 9999999;
  191. for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e2(entries.begin());e2!=entries.end();++e2) {
  192. if ((e1->gateway.within(e2->destination))&&(e2->metric <= bestMetric)) {
  193. bestMetric = e2->metric;
  194. Utils::scopy(e1->device,sizeof(e1->device),e2->device);
  195. }
  196. }
  197. }
  198. }
  199. std::sort(entries.begin(),entries.end());
  200. return entries;
  201. }
  202. RoutingTable::Entry BSDRoutingTable::set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric)
  203. {
  204. if ((!gateway)&&((!device)||(!device[0])))
  205. return RoutingTable::Entry();
  206. std::vector<RoutingTable::Entry> rtab(get(true,true));
  207. for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
  208. if (e->destination == destination) {
  209. if (((!device)||(!device[0]))||(!strcmp(device,e->device))) {
  210. long p = (long)fork();
  211. if (p > 0) {
  212. int exitcode = -1;
  213. ::waitpid(p,&exitcode,0);
  214. } else if (p == 0) {
  215. ::close(STDOUT_FILENO);
  216. ::close(STDERR_FILENO);
  217. ::execl(ZT_BSD_ROUTE_CMD,ZT_BSD_ROUTE_CMD,"delete",(destination.isV6() ? "-inet6" : "-inet"),destination.toString().c_str(),(const char *)0);
  218. ::_exit(-1);
  219. }
  220. }
  221. }
  222. }
  223. if (metric < 0)
  224. return RoutingTable::Entry();
  225. {
  226. char hcstr[64];
  227. Utils::snprintf(hcstr,sizeof(hcstr),"%d",metric);
  228. long p = (long)fork();
  229. if (p > 0) {
  230. int exitcode = -1;
  231. ::waitpid(p,&exitcode,0);
  232. } else if (p == 0) {
  233. ::close(STDOUT_FILENO);
  234. ::close(STDERR_FILENO);
  235. if (gateway) {
  236. ::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);
  237. } else if ((device)&&(device[0])) {
  238. ::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);
  239. }
  240. ::_exit(-1);
  241. }
  242. }
  243. rtab = get(true,true);
  244. std::vector<RoutingTable::Entry>::iterator bestEntry(rtab.end());
  245. for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
  246. if ((e->destination == destination)&&(e->gateway.ipsEqual(gateway))) {
  247. if ((device)&&(device[0])) {
  248. if (!strcmp(device,e->device)) {
  249. if (metric == e->metric)
  250. bestEntry = e;
  251. }
  252. }
  253. if (bestEntry == rtab.end())
  254. bestEntry = e;
  255. }
  256. }
  257. if (bestEntry != rtab.end())
  258. return *bestEntry;
  259. return RoutingTable::Entry();
  260. }
  261. } // namespace ZeroTier
  262. // Enable and build to test routing table interface
  263. #if 0
  264. using namespace ZeroTier;
  265. int main(int argc,char **argv)
  266. {
  267. BSDRoutingTable rt;
  268. printf("<destination> <gateway> <interface> <metric>\n");
  269. std::vector<RoutingTable::Entry> ents(rt.get());
  270. for(std::vector<RoutingTable::Entry>::iterator e(ents.begin());e!=ents.end();++e)
  271. printf("%s\n",e->toString().c_str());
  272. printf("\n");
  273. printf("adding 1.1.1.0 and 2.2.2.0...\n");
  274. rt.set(InetAddress("1.1.1.0",24),InetAddress("1.2.3.4",0),(const char *)0,1);
  275. rt.set(InetAddress("2.2.2.0",24),InetAddress(),"en0",1);
  276. printf("\n");
  277. printf("<destination> <gateway> <interface> <metric>\n");
  278. ents = rt.get();
  279. for(std::vector<RoutingTable::Entry>::iterator e(ents.begin());e!=ents.end();++e)
  280. printf("%s\n",e->toString().c_str());
  281. printf("\n");
  282. printf("deleting 1.1.1.0 and 2.2.2.0...\n");
  283. rt.set(InetAddress("1.1.1.0",24),InetAddress("1.2.3.4",0),(const char *)0,-1);
  284. rt.set(InetAddress("2.2.2.0",24),InetAddress(),"en0",-1);
  285. printf("\n");
  286. printf("<destination> <gateway> <interface> <metric>\n");
  287. ents = rt.get();
  288. for(std::vector<RoutingTable::Entry>::iterator e(ents.begin());e!=ents.end();++e)
  289. printf("%s\n",e->toString().c_str());
  290. printf("\n");
  291. return 0;
  292. }
  293. #endif