NetPlatform_darwin.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "exception/Except.h"
  16. #include "util/platform/netdev/NetPlatform.h"
  17. #include "util/AddrTools.h"
  18. #include "util/platform/Sockaddr.h"
  19. #include "util/Assert.h"
  20. #include "util/Bits.h"
  21. #include "util/CString.h"
  22. #include "wire/Message.h"
  23. #include <stdbool.h>
  24. #include <errno.h>
  25. #include <stdio.h>
  26. #include <sys/ioctl.h>
  27. #include <unistd.h>
  28. #include <sys/socket.h>
  29. #include <sys/types.h>
  30. #include <stdlib.h>
  31. #include <stddef.h>
  32. #include <net/if.h>
  33. #include <net/if_dl.h>
  34. #include <net/if_types.h>
  35. #include <string.h>
  36. #include <netdb.h>
  37. #include <net/if_var.h>
  38. #include <netinet/in_var.h>
  39. #include <netinet6/nd6.h>
  40. #include <netinet/in.h>
  41. #include <sys/kern_control.h>
  42. #include <sys/sys_domain.h>
  43. #include <sys/kern_event.h>
  44. #include <net/route.h>
  45. #include <sys/sysctl.h>
  46. struct Prefix {
  47. struct sockaddr_storage ss;
  48. int prefix;
  49. };
  50. #define ArrayList_TYPE struct Prefix
  51. #define ArrayList_NAME OfPrefix
  52. #include "util/ArrayList.h"
  53. Assert_compileTime(sizeof(struct in_addr) == 4);
  54. struct RouteMessage4 {
  55. struct rt_msghdr header;
  56. struct sockaddr_in dest;
  57. struct sockaddr_dl link;
  58. struct sockaddr_in netmask;
  59. };
  60. Assert_compileTime(sizeof(struct rt_msghdr) == 92);
  61. Assert_compileTime(sizeof(struct sockaddr_in) == 16);
  62. Assert_compileTime(sizeof(struct sockaddr_dl) == 20);
  63. Assert_compileTime(sizeof(struct RouteMessage4) == 144);
  64. static Er_DEFUN(void mkRouteMsg(Message_t* msg,
  65. struct Prefix* addRoute,
  66. int ifIndex,
  67. const char* ifName,
  68. int seq,
  69. bool delete))
  70. {
  71. if (CString_strlen(ifName) >= 12) {
  72. Er_raise(Message_getAlloc(msg), "ifName [%s] too long, limit 11 chars", ifName);
  73. }
  74. int lengthBegin = Message_getLength(msg);
  75. bool ipv6 = addRoute->ss.ss_family == AF_INET6;
  76. if (ipv6) {
  77. struct sockaddr_in6 mask = {
  78. .sin6_family = AF_INET6,
  79. .sin6_len = sizeof(struct sockaddr_in6)
  80. };
  81. Bits_memset((void *)&mask.sin6_addr, 0xff, addRoute->prefix >> 3);
  82. ((uint8_t*)&mask.sin6_addr)[addRoute->prefix >> 3] = 0xff << (8 - (addRoute->prefix % 8));
  83. Er(Message_epush(msg, &mask, sizeof(struct sockaddr_in6)));
  84. } else {
  85. struct sockaddr_in mask = {
  86. .sin_family = AF_INET,
  87. .sin_len = sizeof(struct sockaddr_in)
  88. };
  89. mask.sin_addr.s_addr = Endian_hostToBigEndian32(~0u << (32 - addRoute->prefix));
  90. Er(Message_epush(msg, &mask, sizeof(struct sockaddr_in)));
  91. }
  92. if (!delete) {
  93. struct sockaddr_dl link = {
  94. .sdl_family = AF_LINK,
  95. .sdl_len = sizeof(struct sockaddr_dl),
  96. .sdl_type = IFT_OTHER,
  97. .sdl_index = ifIndex,
  98. .sdl_nlen = CString_strlen(ifName)
  99. };
  100. CString_safeStrncpy(link.sdl_data, ifName, 12);
  101. Er(Message_epush(msg, &link, sizeof(struct sockaddr_dl)));
  102. }
  103. int len = (ipv6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
  104. Assert_true(addRoute->ss.ss_len == len);
  105. Er(Message_epush(msg, &addRoute->ss, len));
  106. struct rt_msghdr hdr = {
  107. .rtm_type = (delete) ? RTM_DELETE : RTM_ADD,
  108. .rtm_flags = RTF_UP | RTF_STATIC,
  109. .rtm_version = RTM_VERSION,
  110. .rtm_seq = seq,
  111. .rtm_pid = getpid(),
  112. .rtm_addrs = RTA_DST | RTA_NETMASK | ((delete) ? 0 : RTA_GATEWAY),
  113. .rtm_msglen = sizeof(struct rt_msghdr) + (Message_getLength(msg) - lengthBegin)
  114. };
  115. Er(Message_epush(msg, &hdr, sizeof(struct rt_msghdr)));
  116. Er_ret();
  117. }
  118. static Er_DEFUN(void setRoutes(uint32_t ifIndex,
  119. const char* ifName,
  120. struct ArrayList_OfPrefix* toRemove,
  121. struct ArrayList_OfPrefix* toAdd,
  122. struct Log* logger,
  123. struct Allocator* alloc))
  124. {
  125. int seq = 0;
  126. int sock = socket(PF_ROUTE, SOCK_RAW, 0);
  127. if (sock == -1) {
  128. int err = errno;
  129. close(sock);
  130. Er_raise(alloc, "open route socket [%s]", strerror(err));
  131. }
  132. bool err = false;
  133. ssize_t returnLen = 0;
  134. for (int i = 0; !err && i < toRemove->length; i++) {
  135. struct Prefix* pfx = ArrayList_OfPrefix_get(toRemove, i);
  136. Message_t* msg = Message_new(0, 1024, alloc);
  137. Er(mkRouteMsg(msg, pfx, ifIndex, ifName, seq++, true));
  138. //printf("DELETE ROUTE %s\n", Hex_print(msg->bytes, Message_getLength(msg), alloc));
  139. returnLen = write(sock, Message_bytes(msg), Message_getLength(msg));
  140. if (returnLen < Message_getLength(msg)) { err = true; break; }
  141. }
  142. for (int i = 0; !err && i < toAdd->length; i++) {
  143. struct Prefix* pfx = ArrayList_OfPrefix_get(toAdd, i);
  144. Message_t* msg = Message_new(0, 1024, alloc);
  145. Er(mkRouteMsg(msg, pfx, ifIndex, ifName, seq++, false));
  146. //printf("ADD ROUTE %s\n", Hex_print(msg->bytes, Message_getLength(msg), alloc));
  147. returnLen = write(sock, Message_bytes(msg), Message_getLength(msg));
  148. if (returnLen < Message_getLength(msg)) { err = true; break; }
  149. }
  150. if (returnLen < 0) {
  151. int error = errno;
  152. close(sock);
  153. Er_raise(alloc, "setRoutes() [%s]", strerror(error));
  154. } else if (err) {
  155. close(sock);
  156. Er_raise(alloc, "setRoutes() returned short");
  157. }
  158. close(sock);
  159. Er_ret();
  160. }
  161. static int prefixFromWeirdBSDMask(uint8_t* weirdBsdMask, bool ipv6)
  162. {
  163. uint8_t len = weirdBsdMask[0];
  164. int out;
  165. if (ipv6) {
  166. Assert_true(len >= 8);
  167. out = (len - 9) * 8;
  168. } else {
  169. Assert_true(len >= 4);
  170. out = (len - 5) * 8;
  171. }
  172. for (int i = 1; i < len - 1; i++) {
  173. Assert_true(weirdBsdMask[i] == 0xff);
  174. }
  175. return out + Bits_popCountx32(weirdBsdMask[len - 1]);
  176. }
  177. static Er_DEFUN(struct ArrayList_OfPrefix* getRoutes(uint32_t ifIndex,
  178. struct Log* logger,
  179. struct Allocator* allocator))
  180. {
  181. size_t needed;
  182. int mib[] = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_DUMP, 0 };
  183. if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
  184. Er_raise(allocator, "sysctl(net.route.0.0.dump) estimate");
  185. }
  186. struct Allocator* tempAlloc = Allocator_child(allocator);
  187. uint8_t* buf = Allocator_malloc(tempAlloc, needed);
  188. if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
  189. Er_raise(allocator, "sysctl(net.route.0.0.dump)");
  190. }
  191. struct ArrayList_OfPrefix* addrList = ArrayList_OfPrefix_new(allocator);
  192. for (int i = 0; i < (int)needed;) {
  193. struct rt_msghdr* rtm = (struct rt_msghdr*) (&buf[i]);
  194. i += rtm->rtm_msglen;
  195. struct sockaddr* sa1 = (struct sockaddr*)(rtm + 1);
  196. struct sockaddr* sa2 = (struct sockaddr*)(sa1->sa_len + (char *)sa1);
  197. uint8_t* mask = (uint8_t*) (sa2->sa_len + (char*)sa2);
  198. Assert_true(&buf[i] >= mask);
  199. if (sa2->sa_family != AF_LINK) { continue; }
  200. if (rtm->rtm_flags & RTF_LOCAL) { continue; }
  201. if (!(rtm->rtm_flags & RTF_STATIC)) { continue; }
  202. if (((struct sockaddr_dl*) sa2)->sdl_index != ifIndex) { continue; }
  203. bool ipv6 = (sa1->sa_family == AF_INET6);
  204. if (!ipv6 && (sa1->sa_family != AF_INET)) { continue; }
  205. // printf("GOT ROUTE %s\n", Hex_print(rtm, rtm->rtm_msglen, tempAlloc));
  206. int prefix;
  207. if (&buf[i] < &mask[mask[0]] || mask[0] == 0) {
  208. //Assert_true(rtm->rtm_flags & RTF_HOST);
  209. prefix = (ipv6) ? 128 : 32;
  210. } else {
  211. prefix = prefixFromWeirdBSDMask(mask, ipv6);
  212. }
  213. struct Prefix* pfx = Allocator_calloc(allocator, sizeof(struct Prefix), 1);
  214. Assert_true(sizeof(pfx->ss) >= sa1->sa_len);
  215. Bits_memcpy(&pfx->ss, sa1, sa1->sa_len);
  216. pfx->prefix = prefix;
  217. ArrayList_OfPrefix_add(addrList, pfx);
  218. }
  219. Allocator_free(tempAlloc);
  220. Er_ret(addrList);
  221. }
  222. static Er_DEFUN(void addIp4Address(const char* interfaceName,
  223. const uint8_t address[4],
  224. int prefixLen,
  225. struct Log* logger,
  226. struct Allocator* tempAlloc))
  227. {
  228. struct ifaliasreq ifarted;
  229. Bits_memset(&ifarted, 0, sizeof(struct ifaliasreq));
  230. CString_safeStrncpy(ifarted.ifra_name, interfaceName, IFNAMSIZ);
  231. struct sockaddr_in sin = { .sin_family = AF_INET, .sin_len = sizeof(struct sockaddr_in) };
  232. Bits_memcpy(&sin.sin_addr.s_addr, address, 4);
  233. Bits_memcpy(&ifarted.ifra_addr, &sin, sizeof(struct sockaddr_in));
  234. sin.sin_addr.s_addr = Endian_hostToBigEndian32(~0u << (32 - prefixLen));
  235. Bits_memcpy(&ifarted.ifra_mask, &sin, sizeof(struct sockaddr_in));
  236. int s = socket(AF_INET, SOCK_DGRAM, 0);
  237. if (s < 0) {
  238. Er_raise(tempAlloc, "socket() [%s]", strerror(errno));
  239. }
  240. // will probably fail, ignore result.
  241. struct ifreq ifr = { .ifr_flags = 0 };
  242. CString_safeStrncpy(ifr.ifr_name, interfaceName, IFNAMSIZ);
  243. ioctl(s, SIOCDIFADDR, &ifr);
  244. if (ioctl(s, SIOCSIFADDR, &ifarted) < 0) {
  245. int err = errno;
  246. close(s);
  247. Er_raise(tempAlloc, "ioctl(SIOCSIFADDR) [%s]", strerror(err));
  248. }
  249. //setupRoute4(address, prefixLen, interfaceName, logger, tempAlloc, eh);
  250. Log_info(logger, "Configured IPv4 [%u.%u.%u.%u/%i] for [%s]",
  251. address[0], address[1], address[2], address[3], prefixLen, interfaceName);
  252. close(s);
  253. Er_ret();
  254. }
  255. static Er_DEFUN(void addIp6Address(const char* interfaceName,
  256. const uint8_t address[16],
  257. int prefixLen,
  258. struct Log* logger,
  259. struct Allocator* errAlloc))
  260. {
  261. /* stringify our IP address */
  262. char myIp[40];
  263. AddrTools_printIp((uint8_t*)myIp, address);
  264. /* set up the interface ip assignment request */
  265. struct in6_aliasreq in6_addreq;
  266. memset(&in6_addreq, 0, sizeof(in6_addreq));
  267. in6_addreq.ifra_lifetime.ia6t_vltime = ND6_INFINITE_LIFETIME;
  268. in6_addreq.ifra_lifetime.ia6t_pltime = ND6_INFINITE_LIFETIME;
  269. /* parse the IPv6 address and add it to the request */
  270. struct addrinfo hints, *result;
  271. bzero(&hints, sizeof(struct addrinfo));
  272. hints.ai_family = AF_INET6;
  273. int err = getaddrinfo((const char *)myIp, NULL, &hints, &result);
  274. if (err) {
  275. // Should never happen since the address is specified as binary.
  276. Er_raise(errAlloc, "bad IPv6 address [%s]", gai_strerror(err));
  277. }
  278. bcopy(result->ai_addr, &in6_addreq.ifra_addr, result->ai_addrlen);
  279. /* turn the prefixlen into a mask, and add it to the request */
  280. struct sockaddr_in6* mask = &in6_addreq.ifra_prefixmask;
  281. mask->sin6_len = sizeof(*mask);
  282. if (prefixLen >= 128 || prefixLen <= 0) {
  283. memset(&mask->sin6_addr, 0xff, sizeof(struct in6_addr));
  284. } else {
  285. memset((void *)&mask->sin6_addr, 0x00, sizeof(mask->sin6_addr));
  286. memset((void *)&mask->sin6_addr, 0xff, prefixLen>>3);
  287. ((uint8_t*)&mask->sin6_addr)[prefixLen>>3] = 0xff << (8 - (prefixLen%8));
  288. }
  289. CString_safeStrncpy(in6_addreq.ifra_name, interfaceName, sizeof(in6_addreq.ifra_name));
  290. /* do the actual assignment ioctl */
  291. int s = socket(AF_INET6, SOCK_DGRAM, 0);
  292. if (s < 0) {
  293. Er_raise(errAlloc, "socket() [%s]", strerror(errno));
  294. }
  295. if (ioctl(s, SIOCAIFADDR_IN6, &in6_addreq) < 0) {
  296. int err = errno;
  297. close(s);
  298. Er_raise(errAlloc, "ioctl(SIOCAIFADDR) [%s] for [%s]", strerror(err), interfaceName);
  299. }
  300. Log_info(logger, "Configured IPv6 [%s/%i] for [%s]", myIp, prefixLen, interfaceName);
  301. close(s);
  302. Er_ret();
  303. }
  304. Er_DEFUN(void NetPlatform_addAddress(const char* interfaceName,
  305. const uint8_t* address,
  306. int prefixLen,
  307. int addrFam,
  308. struct Log* logger,
  309. struct Allocator* tempAlloc))
  310. {
  311. if (addrFam == Sockaddr_AF_INET6) {
  312. Er(addIp6Address(interfaceName, address, prefixLen, logger, tempAlloc));
  313. } else if (addrFam == Sockaddr_AF_INET) {
  314. Er(addIp4Address(interfaceName, address, prefixLen, logger, tempAlloc));
  315. } else {
  316. Assert_true(0);
  317. }
  318. Er_ret();
  319. }
  320. Er_DEFUN(void NetPlatform_setMTU(const char* interfaceName,
  321. uint32_t mtu,
  322. struct Log* logger,
  323. struct Allocator* errAlloc))
  324. {
  325. int s = socket(AF_INET6, SOCK_DGRAM, 0);
  326. if (s < 0) {
  327. Er_raise(errAlloc, "socket() [%s]", strerror(errno));
  328. }
  329. struct ifreq ifRequest;
  330. CString_safeStrncpy(ifRequest.ifr_name, interfaceName, IFNAMSIZ);
  331. ifRequest.ifr_mtu = mtu;
  332. Log_info(logger, "Setting MTU for device [%s] to [%u] bytes.", interfaceName, mtu);
  333. if (ioctl(s, SIOCSIFMTU, &ifRequest) < 0) {
  334. int err = errno;
  335. close(s);
  336. Er_raise(errAlloc, "ioctl(SIOCSIFMTU) [%s]", strerror(err));
  337. }
  338. close(s);
  339. Er_ret();
  340. }
  341. Er_DEFUN(void NetPlatform_setRoutes(const char* ifName,
  342. struct Sockaddr** prefixSet,
  343. int prefixCount,
  344. struct Log* logger,
  345. struct Allocator* tempAlloc))
  346. {
  347. struct ArrayList_OfPrefix* newRoutes = ArrayList_OfPrefix_new(tempAlloc);
  348. for (int i = 0; i < prefixCount; i++) {
  349. struct Prefix* pfx = Allocator_calloc(tempAlloc, sizeof(struct Prefix), 1);
  350. //Sockaddr_getAddress
  351. int addrFam = Sockaddr_getFamily(prefixSet[i]);
  352. if (addrFam == Sockaddr_AF_INET) {
  353. // OK
  354. struct sockaddr_in* in = (struct sockaddr_in*) &pfx->ss;
  355. in->sin_family = AF_INET;
  356. Assert_compileTime(sizeof(in->sin_addr) == 4);
  357. Assert_true(Sockaddr_getAddress(prefixSet[i], &in->sin_addr) == AF_INET);
  358. } else if (addrFam == Sockaddr_AF_INET6) {
  359. // OK
  360. struct sockaddr_in6* in6 = (struct sockaddr_in6*) &pfx->ss;
  361. in6->sin6_family = AF_INET6;
  362. Assert_compileTime(sizeof(in6->sin6_addr) == 16);
  363. Assert_true(Sockaddr_getAddress(prefixSet[i], &in6->sin6_addr) == AF_INET6);
  364. } else {
  365. Er_raise(tempAlloc, "Unrecognized address type %d", addrFam);
  366. }
  367. ArrayList_OfPrefix_add(newRoutes, prefixSet[i]);
  368. }
  369. uint32_t ifIndex = if_nametoindex(ifName);
  370. if (!ifIndex) {
  371. Er_raise(tempAlloc, "tunName not recognized");
  372. }
  373. struct ArrayList_OfPrefix* oldRoutes = Er(getRoutes(ifIndex, logger, tempAlloc));
  374. Er(setRoutes(ifIndex, ifName, oldRoutes, newRoutes, logger, tempAlloc));
  375. Er_ret();
  376. }