NetPlatform_darwin.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. #define ArrayList_TYPE struct Sockaddr
  47. #define ArrayList_NAME OfSockaddr
  48. #include "util/ArrayList.h"
  49. Assert_compileTime(sizeof(struct in_addr) == 4);
  50. struct RouteMessage4 {
  51. struct rt_msghdr header;
  52. struct sockaddr_in dest;
  53. struct sockaddr_dl link;
  54. struct sockaddr_in netmask;
  55. };
  56. Assert_compileTime(sizeof(struct rt_msghdr) == 92);
  57. Assert_compileTime(sizeof(struct sockaddr_in) == 16);
  58. Assert_compileTime(sizeof(struct sockaddr_dl) == 20);
  59. Assert_compileTime(sizeof(struct RouteMessage4) == 144);
  60. static Er_DEFUN(void mkRouteMsg(struct Message* msg,
  61. struct Sockaddr* addRoute,
  62. int ifIndex,
  63. const char* ifName,
  64. int seq,
  65. bool delete))
  66. {
  67. if (CString_strlen(ifName) >= 12) {
  68. Er_raise(msg->alloc, "ifName [%s] too long, limit 11 chars", ifName);
  69. }
  70. int lengthBegin = msg->length;
  71. bool ipv6 = Sockaddr_getFamily(addRoute) == Sockaddr_AF_INET6;
  72. if (ipv6) {
  73. struct sockaddr_in6 mask = {
  74. .sin6_family = AF_INET6,
  75. .sin6_len = sizeof(struct sockaddr_in6)
  76. };
  77. Bits_memset((void *)&mask.sin6_addr, 0xff, addRoute->prefix >> 3);
  78. ((uint8_t*)&mask.sin6_addr)[addRoute->prefix >> 3] = 0xff << (8 - (addRoute->prefix % 8));
  79. Er(Message_epush(msg, &mask, sizeof(struct sockaddr_in6)));
  80. } else {
  81. struct sockaddr_in mask = {
  82. .sin_family = AF_INET,
  83. .sin_len = sizeof(struct sockaddr_in)
  84. };
  85. mask.sin_addr.s_addr = Endian_hostToBigEndian32(~0u << (32 - addRoute->prefix));
  86. Er(Message_epush(msg, &mask, sizeof(struct sockaddr_in)));
  87. }
  88. if (!delete) {
  89. struct sockaddr_dl link = {
  90. .sdl_family = AF_LINK,
  91. .sdl_len = sizeof(struct sockaddr_dl),
  92. .sdl_type = IFT_OTHER,
  93. .sdl_index = ifIndex,
  94. .sdl_nlen = CString_strlen(ifName)
  95. };
  96. CString_safeStrncpy(link.sdl_data, ifName, 12);
  97. Er(Message_epush(msg, &link, sizeof(struct sockaddr_dl)));
  98. }
  99. void* dest = Sockaddr_asNative(addRoute);
  100. int len = (ipv6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
  101. ((struct sockaddr*)dest)->sa_len = len;
  102. Er(Message_epush(msg, dest, len));
  103. struct rt_msghdr hdr = {
  104. .rtm_type = (delete) ? RTM_DELETE : RTM_ADD,
  105. .rtm_flags = RTF_UP | RTF_STATIC,
  106. .rtm_version = RTM_VERSION,
  107. .rtm_seq = seq,
  108. .rtm_pid = getpid(),
  109. .rtm_addrs = RTA_DST | RTA_NETMASK | ((delete) ? 0 : RTA_GATEWAY),
  110. .rtm_msglen = sizeof(struct rt_msghdr) + (msg->length - lengthBegin)
  111. };
  112. Er(Message_epush(msg, &hdr, sizeof(struct rt_msghdr)));
  113. Er_ret();
  114. }
  115. // This is a hack because OSX as of 10.15.4 refuses to a route with prefix /0
  116. static struct ArrayList_OfSockaddr* ipv6DefaultRoute(
  117. struct ArrayList_OfSockaddr* list,
  118. struct Allocator* alloc)
  119. {
  120. struct Sockaddr* pfx0 =
  121. Sockaddr_fromBytes("\x00\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", Sockaddr_AF_INET6, alloc);
  122. struct Sockaddr* pfx1 =
  123. Sockaddr_fromBytes("\x80\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", Sockaddr_AF_INET6, alloc);
  124. pfx0->prefix = 1;
  125. pfx1->prefix = 1;
  126. struct ArrayList_OfSockaddr* arr = ArrayList_OfSockaddr_new(alloc);
  127. ArrayList_OfSockaddr_add(arr, pfx0);
  128. ArrayList_OfSockaddr_add(arr, pfx1);
  129. for (int i = 0; i < list->length; i++) {
  130. struct Sockaddr* pfx = ArrayList_OfSockaddr_get(list, i);
  131. if (Sockaddr_getFamily(pfx) == Sockaddr_AF_INET6) { continue; }
  132. ArrayList_OfSockaddr_add(arr, pfx);
  133. }
  134. return arr;
  135. }
  136. static bool isDefault6(struct ArrayList_OfSockaddr* prefixes)
  137. {
  138. // v4 and v6 routes can be mixed together in one request
  139. int sixCount = 0;
  140. for (int i = 0; i < prefixes->length; i++) {
  141. struct Sockaddr* pfx = ArrayList_OfSockaddr_get(prefixes, i);
  142. if (Sockaddr_getFamily(pfx) != Sockaddr_AF_INET6) { continue; }
  143. sixCount++;
  144. if (pfx->prefix) { return false; }
  145. }
  146. return sixCount == 1;
  147. }
  148. static Er_DEFUN(void setRoutes(uint32_t ifIndex,
  149. const char* ifName,
  150. struct ArrayList_OfSockaddr* toRemove,
  151. struct ArrayList_OfSockaddr* toAdd,
  152. struct Log* logger,
  153. struct Allocator* alloc))
  154. {
  155. int seq = 0;
  156. int sock = socket(PF_ROUTE, SOCK_RAW, 0);
  157. if (sock == -1) {
  158. int err = errno;
  159. close(sock);
  160. Er_raise(alloc, "open route socket [%s]", strerror(err));
  161. }
  162. bool err = false;
  163. ssize_t returnLen = 0;
  164. if (isDefault6(toRemove)) { toRemove = ipv6DefaultRoute(toRemove, alloc); }
  165. if (isDefault6(toAdd)) { toAdd = ipv6DefaultRoute(toAdd, alloc); }
  166. for (int i = 0; !err && i < toRemove->length; i++) {
  167. struct Sockaddr* pfx = ArrayList_OfSockaddr_get(toRemove, i);
  168. Log_debug(logger, "DELETE ROUTE %s", Sockaddr_print(pfx, alloc));
  169. struct Message* msg = Message_new(0, 1024, alloc);
  170. Er(mkRouteMsg(msg, pfx, ifIndex, ifName, seq++, true));
  171. //printf("DELETE ROUTE %s\n", Hex_print(msg->bytes, msg->length, alloc));
  172. returnLen = write(sock, msg->bytes, msg->length);
  173. if (returnLen < msg->length) { err = true; break; }
  174. }
  175. for (int i = 0; !err && i < toAdd->length; i++) {
  176. struct Sockaddr* pfx = ArrayList_OfSockaddr_get(toAdd, i);
  177. Log_debug(logger, "ADD ROUTE %s", Sockaddr_print(pfx, alloc));
  178. struct Message* msg = Message_new(0, 1024, alloc);
  179. Er(mkRouteMsg(msg, pfx, ifIndex, ifName, seq++, false));
  180. //printf("ADD ROUTE %s\n", Hex_print(msg->bytes, msg->length, alloc));
  181. returnLen = write(sock, msg->bytes, msg->length);
  182. if (returnLen < msg->length) { err = true; break; }
  183. }
  184. if (returnLen < 0) {
  185. int error = errno;
  186. close(sock);
  187. Er_raise(alloc, "setRoutes() [%s]", strerror(error));
  188. } else if (err) {
  189. close(sock);
  190. Er_raise(alloc, "setRoutes() returned short");
  191. }
  192. close(sock);
  193. Er_ret();
  194. }
  195. static int prefixFromWeirdBSDMask(uint8_t* weirdBsdMask, bool ipv6)
  196. {
  197. uint8_t len = weirdBsdMask[0];
  198. int out;
  199. if (ipv6) {
  200. Assert_true(len >= 8);
  201. out = (len - 9) * 8;
  202. } else {
  203. Assert_true(len >= 4);
  204. out = (len - 5) * 8;
  205. }
  206. for (int i = 1; i < len - 1; i++) {
  207. Assert_true(weirdBsdMask[i] == 0xff);
  208. }
  209. return out + Bits_popCountx32(weirdBsdMask[len - 1]);
  210. }
  211. static Er_DEFUN(struct ArrayList_OfSockaddr* getRoutes(uint32_t ifIndex,
  212. struct Log* logger,
  213. struct Allocator* allocator))
  214. {
  215. size_t needed;
  216. int mib[] = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_DUMP, 0 };
  217. if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
  218. Er_raise(allocator, "sysctl(net.route.0.0.dump) estimate");
  219. }
  220. struct Allocator* tempAlloc = Allocator_child(allocator);
  221. uint8_t* buf = Allocator_malloc(tempAlloc, needed);
  222. if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
  223. Er_raise(allocator, "sysctl(net.route.0.0.dump)");
  224. }
  225. struct ArrayList_OfSockaddr* addrList = ArrayList_OfSockaddr_new(allocator);
  226. for (int i = 0; i < (int)needed;) {
  227. struct rt_msghdr* rtm = (struct rt_msghdr*) (&buf[i]);
  228. i += rtm->rtm_msglen;
  229. struct sockaddr* sa1 = (struct sockaddr*)(rtm + 1);
  230. struct sockaddr* sa2 = (struct sockaddr*)(sa1->sa_len + (char *)sa1);
  231. uint8_t* mask = (uint8_t*) (sa2->sa_len + (char*)sa2);
  232. Assert_true(&buf[i] >= mask);
  233. if (sa2->sa_family != AF_LINK) { continue; }
  234. if (rtm->rtm_flags & RTF_LOCAL) { continue; }
  235. if (!(rtm->rtm_flags & RTF_STATIC)) { continue; }
  236. if (((struct sockaddr_dl*) sa2)->sdl_index != ifIndex) { continue; }
  237. bool ipv6 = (sa1->sa_family == AF_INET6);
  238. if (!ipv6 && (sa1->sa_family != AF_INET)) { continue; }
  239. // printf("GOT ROUTE %s\n", Hex_print(rtm, rtm->rtm_msglen, tempAlloc));
  240. int prefix;
  241. if (&buf[i] < &mask[mask[0]] || mask[0] == 0) {
  242. //Assert_true(rtm->rtm_flags & RTF_HOST);
  243. prefix = (ipv6) ? 128 : 32;
  244. } else {
  245. prefix = prefixFromWeirdBSDMask(mask, ipv6);
  246. }
  247. struct Sockaddr* addr = Sockaddr_fromNative(sa1, sa1->sa_len, allocator);
  248. addr->flags |= Sockaddr_flags_PREFIX;
  249. addr->prefix = prefix;
  250. ArrayList_OfSockaddr_add(addrList, addr);
  251. }
  252. Allocator_free(tempAlloc);
  253. Er_ret(addrList);
  254. }
  255. static Er_DEFUN(void addIp4Address(const char* interfaceName,
  256. const uint8_t address[4],
  257. int prefixLen,
  258. struct Log* logger,
  259. struct Allocator* tempAlloc))
  260. {
  261. struct ifaliasreq ifarted;
  262. Bits_memset(&ifarted, 0, sizeof(struct ifaliasreq));
  263. CString_safeStrncpy(ifarted.ifra_name, interfaceName, IFNAMSIZ);
  264. struct sockaddr_in sin = { .sin_family = AF_INET, .sin_len = sizeof(struct sockaddr_in) };
  265. Bits_memcpy(&sin.sin_addr.s_addr, address, 4);
  266. Bits_memcpy(&ifarted.ifra_addr, &sin, sizeof(struct sockaddr_in));
  267. sin.sin_addr.s_addr = Endian_hostToBigEndian32(~0u << (32 - prefixLen));
  268. Bits_memcpy(&ifarted.ifra_mask, &sin, sizeof(struct sockaddr_in));
  269. int s = socket(AF_INET, SOCK_DGRAM, 0);
  270. if (s < 0) {
  271. Er_raise(tempAlloc, "socket() [%s]", strerror(errno));
  272. }
  273. // will probably fail, ignore result.
  274. struct ifreq ifr = { .ifr_flags = 0 };
  275. CString_safeStrncpy(ifr.ifr_name, interfaceName, IFNAMSIZ);
  276. ioctl(s, SIOCDIFADDR, &ifr);
  277. if (ioctl(s, SIOCSIFADDR, &ifarted) < 0) {
  278. int err = errno;
  279. close(s);
  280. Er_raise(tempAlloc, "ioctl(SIOCSIFADDR) [%s]", strerror(err));
  281. }
  282. //setupRoute4(address, prefixLen, interfaceName, logger, tempAlloc, eh);
  283. Log_info(logger, "Configured IPv4 [%u.%u.%u.%u/%i] for [%s]",
  284. address[0], address[1], address[2], address[3], prefixLen, interfaceName);
  285. close(s);
  286. Er_ret();
  287. }
  288. static Er_DEFUN(void addIp6Address(const char* interfaceName,
  289. const uint8_t address[16],
  290. int prefixLen,
  291. struct Log* logger,
  292. struct Allocator* errAlloc))
  293. {
  294. /* stringify our IP address */
  295. char myIp[40];
  296. AddrTools_printIp((uint8_t*)myIp, address);
  297. /* set up the interface ip assignment request */
  298. struct in6_aliasreq in6_addreq;
  299. memset(&in6_addreq, 0, sizeof(in6_addreq));
  300. in6_addreq.ifra_lifetime.ia6t_vltime = ND6_INFINITE_LIFETIME;
  301. in6_addreq.ifra_lifetime.ia6t_pltime = ND6_INFINITE_LIFETIME;
  302. /* parse the IPv6 address and add it to the request */
  303. struct addrinfo hints, *result;
  304. bzero(&hints, sizeof(struct addrinfo));
  305. hints.ai_family = AF_INET6;
  306. int err = getaddrinfo((const char *)myIp, NULL, &hints, &result);
  307. if (err) {
  308. // Should never happen since the address is specified as binary.
  309. Er_raise(errAlloc, "bad IPv6 address [%s]", gai_strerror(err));
  310. }
  311. bcopy(result->ai_addr, &in6_addreq.ifra_addr, result->ai_addrlen);
  312. /* turn the prefixlen into a mask, and add it to the request */
  313. struct sockaddr_in6* mask = &in6_addreq.ifra_prefixmask;
  314. mask->sin6_len = sizeof(*mask);
  315. if (prefixLen >= 128 || prefixLen <= 0) {
  316. memset(&mask->sin6_addr, 0xff, sizeof(struct in6_addr));
  317. } else {
  318. memset((void *)&mask->sin6_addr, 0x00, sizeof(mask->sin6_addr));
  319. memset((void *)&mask->sin6_addr, 0xff, prefixLen>>3);
  320. ((uint8_t*)&mask->sin6_addr)[prefixLen>>3] = 0xff << (8 - (prefixLen%8));
  321. }
  322. CString_safeStrncpy(in6_addreq.ifra_name, interfaceName, sizeof(in6_addreq.ifra_name));
  323. /* do the actual assignment ioctl */
  324. int s = socket(AF_INET6, SOCK_DGRAM, 0);
  325. if (s < 0) {
  326. Er_raise(errAlloc, "socket() [%s]", strerror(errno));
  327. }
  328. if (ioctl(s, SIOCAIFADDR_IN6, &in6_addreq) < 0) {
  329. int err = errno;
  330. close(s);
  331. Er_raise(errAlloc, "ioctl(SIOCAIFADDR) [%s] for [%s]", strerror(err), interfaceName);
  332. }
  333. Log_info(logger, "Configured IPv6 [%s/%i] for [%s]", myIp, prefixLen, interfaceName);
  334. close(s);
  335. Er_ret();
  336. }
  337. Er_DEFUN(void NetPlatform_addAddress(const char* interfaceName,
  338. const uint8_t* address,
  339. int prefixLen,
  340. int addrFam,
  341. struct Log* logger,
  342. struct Allocator* tempAlloc))
  343. {
  344. if (addrFam == Sockaddr_AF_INET6) {
  345. Er(addIp6Address(interfaceName, address, prefixLen, logger, tempAlloc));
  346. } else if (addrFam == Sockaddr_AF_INET) {
  347. Er(addIp4Address(interfaceName, address, prefixLen, logger, tempAlloc));
  348. } else {
  349. Assert_true(0);
  350. }
  351. Er_ret();
  352. }
  353. Er_DEFUN(void NetPlatform_setMTU(const char* interfaceName,
  354. uint32_t mtu,
  355. struct Log* logger,
  356. struct Allocator* errAlloc))
  357. {
  358. int s = socket(AF_INET6, SOCK_DGRAM, 0);
  359. if (s < 0) {
  360. Er_raise(errAlloc, "socket() [%s]", strerror(errno));
  361. }
  362. struct ifreq ifRequest;
  363. CString_safeStrncpy(ifRequest.ifr_name, interfaceName, IFNAMSIZ);
  364. ifRequest.ifr_mtu = mtu;
  365. Log_info(logger, "Setting MTU for device [%s] to [%u] bytes.", interfaceName, mtu);
  366. if (ioctl(s, SIOCSIFMTU, &ifRequest) < 0) {
  367. int err = errno;
  368. close(s);
  369. Er_raise(errAlloc, "ioctl(SIOCSIFMTU) [%s]", strerror(err));
  370. }
  371. close(s);
  372. Er_ret();
  373. }
  374. Er_DEFUN(void NetPlatform_setRoutes(const char* ifName,
  375. struct Sockaddr** prefixSet,
  376. int prefixCount,
  377. struct Log* logger,
  378. struct Allocator* tempAlloc))
  379. {
  380. struct ArrayList_OfSockaddr* newRoutes = ArrayList_OfSockaddr_new(tempAlloc);
  381. for (int i = 0; i < prefixCount; i++) {
  382. int addrFam = Sockaddr_getFamily(prefixSet[i]);
  383. if (addrFam == Sockaddr_AF_INET) {
  384. // OK
  385. } else if (addrFam == Sockaddr_AF_INET6) {
  386. // OK
  387. } else {
  388. Er_raise(tempAlloc, "Unrecognized address type %d", addrFam);
  389. }
  390. ArrayList_OfSockaddr_add(newRoutes, prefixSet[i]);
  391. }
  392. uint32_t ifIndex = if_nametoindex(ifName);
  393. if (!ifIndex) {
  394. Er_raise(tempAlloc, "tunName not recognized");
  395. }
  396. struct ArrayList_OfSockaddr* oldRoutes = Er(getRoutes(ifIndex, logger, tempAlloc));
  397. Er(setRoutes(ifIndex, ifName, oldRoutes, newRoutes, logger, tempAlloc));
  398. Er_ret();
  399. }