BSDRoutingTable.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 "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. unsigned int interfaceIndex = ((((unsigned int)sin6->sin6_addr.s6_addr[2]) << 8) & 0xff) | (((unsigned int)sin6->sin6_addr.s6_addr[3]) & 0xff);
  104. sin6->sin6_addr.s6_addr[2] = 0;
  105. sin6->sin6_addr.s6_addr[3] = 0;
  106. if (!sin6->sin6_scope_id)
  107. sin6->sin6_scope_id = interfaceIndex;
  108. }
  109. }
  110. e.destination.set(sa);
  111. break;
  112. case 1:
  113. //printf("RTA_GATEWAY\n");
  114. switch(sa->sa_family) {
  115. case AF_LINK:
  116. e.deviceIndex = (int)((const struct sockaddr_dl *)sa)->sdl_index;
  117. break;
  118. case AF_INET:
  119. case AF_INET6:
  120. e.gateway.set(sa);
  121. break;
  122. }
  123. break;
  124. case 2: {
  125. if (e.destination.isV6()) {
  126. salen = sizeof(struct sockaddr_in6); // Confess!
  127. unsigned int bits = 0;
  128. for(int i=0;i<16;++i) {
  129. unsigned char c = (unsigned char)((const struct sockaddr_in6 *)sa)->sin6_addr.s6_addr[i];
  130. if (c == 0xff)
  131. bits += 8;
  132. else break;
  133. /* must they be multiples of 8? Most of the BSD source I can find says yes..?
  134. else {
  135. while ((c & 0x80) == 0x80) {
  136. ++bits;
  137. c <<= 1;
  138. }
  139. break;
  140. }
  141. */
  142. }
  143. e.destination.setPort(bits);
  144. } else {
  145. salen = sizeof(struct sockaddr_in); // Confess!
  146. e.destination.setPort((unsigned int)Utils::countBits((uint32_t)((const struct sockaddr_in *)sa)->sin_addr.s_addr));
  147. }
  148. //printf("RTA_NETMASK\n");
  149. } break;
  150. /*
  151. case 3:
  152. //printf("RTA_GENMASK\n");
  153. break;
  154. case 4:
  155. //printf("RTA_IFP\n");
  156. break;
  157. case 5:
  158. //printf("RTA_IFA\n");
  159. break;
  160. case 6:
  161. //printf("RTA_AUTHOR\n");
  162. break;
  163. */
  164. }
  165. saptr += salen;
  166. }
  167. e.metric = (int)rtm->rtm_rmx.rmx_hopcount;
  168. if (e.metric < 0)
  169. e.metric = 0;
  170. if (((includeLinkLocal)||(!e.destination.isLinkLocal()))&&((includeLoopback)||((!e.destination.isLoopback())&&(!e.gateway.isLoopback()))))
  171. entries.push_back(e);
  172. }
  173. next = saend;
  174. }
  175. }
  176. ::free(buf);
  177. }
  178. }
  179. for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e1(entries.begin());e1!=entries.end();++e1) {
  180. if ((!e1->device[0])&&(e1->deviceIndex >= 0))
  181. if_indextoname(e1->deviceIndex,e1->device);
  182. }
  183. for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e1(entries.begin());e1!=entries.end();++e1) {
  184. if ((!e1->device[0])&&(e1->gateway)) {
  185. int bestMetric = 9999999;
  186. for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e2(entries.begin());e2!=entries.end();++e2) {
  187. if ((e1->gateway.within(e2->destination))&&(e2->metric <= bestMetric)) {
  188. bestMetric = e2->metric;
  189. Utils::scopy(e1->device,sizeof(e1->device),e2->device);
  190. }
  191. }
  192. }
  193. }
  194. std::sort(entries.begin(),entries.end());
  195. return entries;
  196. }
  197. RoutingTable::Entry BSDRoutingTable::set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric)
  198. {
  199. if ((!gateway)&&((!device)||(!device[0])))
  200. return RoutingTable::Entry();
  201. std::vector<RoutingTable::Entry> rtab(get(true,true));
  202. for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
  203. if (e->destination == destination) {
  204. if (((!device)||(!device[0]))||(!strcmp(device,e->device))) {
  205. long p = (long)fork();
  206. if (p > 0) {
  207. int exitcode = -1;
  208. ::waitpid(p,&exitcode,0);
  209. } else if (p == 0) {
  210. ::close(STDOUT_FILENO);
  211. ::close(STDERR_FILENO);
  212. ::execl(ZT_BSD_ROUTE_CMD,ZT_BSD_ROUTE_CMD,"delete",(destination.isV6() ? "-inet6" : "-inet"),destination.toString().c_str(),(const char *)0);
  213. ::_exit(-1);
  214. }
  215. }
  216. }
  217. }
  218. if (metric < 0)
  219. return RoutingTable::Entry();
  220. {
  221. char hcstr[64];
  222. Utils::snprintf(hcstr,sizeof(hcstr),"%d",metric);
  223. long p = (long)fork();
  224. if (p > 0) {
  225. int exitcode = -1;
  226. ::waitpid(p,&exitcode,0);
  227. } else if (p == 0) {
  228. ::close(STDOUT_FILENO);
  229. ::close(STDERR_FILENO);
  230. if (gateway) {
  231. ::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);
  232. } else if ((device)&&(device[0])) {
  233. ::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);
  234. }
  235. ::_exit(-1);
  236. }
  237. }
  238. rtab = get(true,true);
  239. std::vector<RoutingTable::Entry>::iterator bestEntry(rtab.end());
  240. for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
  241. if ((e->destination == destination)&&(e->gateway.ipsEqual(gateway))) {
  242. if ((device)&&(device[0])) {
  243. if (!strcmp(device,e->device)) {
  244. if (metric == e->metric)
  245. bestEntry = e;
  246. }
  247. }
  248. if (bestEntry == rtab.end())
  249. bestEntry = e;
  250. }
  251. }
  252. if (bestEntry != rtab.end())
  253. return *bestEntry;
  254. return RoutingTable::Entry();
  255. }
  256. } // namespace ZeroTier
  257. // Enable and build to test routing table interface
  258. #if 0
  259. using namespace ZeroTier;
  260. int main(int argc,char **argv)
  261. {
  262. BSDRoutingTable rt;
  263. printf("<destination> <gateway> <interface> <metric>\n");
  264. std::vector<RoutingTable::Entry> ents(rt.get());
  265. for(std::vector<RoutingTable::Entry>::iterator e(ents.begin());e!=ents.end();++e)
  266. printf("%s\n",e->toString().c_str());
  267. printf("\n");
  268. printf("adding 1.1.1.0 and 2.2.2.0...\n");
  269. rt.set(InetAddress("1.1.1.0",24),InetAddress("1.2.3.4",0),(const char *)0,1);
  270. rt.set(InetAddress("2.2.2.0",24),InetAddress(),"en0",1);
  271. printf("\n");
  272. printf("<destination> <gateway> <interface> <metric>\n");
  273. ents = rt.get();
  274. for(std::vector<RoutingTable::Entry>::iterator e(ents.begin());e!=ents.end();++e)
  275. printf("%s\n",e->toString().c_str());
  276. printf("\n");
  277. printf("deleting 1.1.1.0 and 2.2.2.0...\n");
  278. rt.set(InetAddress("1.1.1.0",24),InetAddress("1.2.3.4",0),(const char *)0,-1);
  279. rt.set(InetAddress("2.2.2.0",24),InetAddress(),"en0",-1);
  280. printf("\n");
  281. printf("<destination> <gateway> <interface> <metric>\n");
  282. ents = rt.get();
  283. for(std::vector<RoutingTable::Entry>::iterator e(ents.begin());e!=ents.end();++e)
  284. printf("%s\n",e->toString().c_str());
  285. printf("\n");
  286. return 0;
  287. }
  288. #endif