BSDRoutingTable.cpp 9.9 KB

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