NetPlatform_darwin.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. static Er_DEFUN(void setRoutes(uint32_t ifIndex,
  116. const char* ifName,
  117. struct ArrayList_OfSockaddr* toRemove,
  118. struct ArrayList_OfSockaddr* toAdd,
  119. struct Log* logger,
  120. struct Allocator* alloc))
  121. {
  122. int seq = 0;
  123. int sock = socket(PF_ROUTE, SOCK_RAW, 0);
  124. if (sock == -1) {
  125. int err = errno;
  126. close(sock);
  127. Er_raise(alloc, "open route socket [%s]", strerror(err));
  128. }
  129. bool err = false;
  130. ssize_t returnLen = 0;
  131. for (int i = 0; !err && i < toRemove->length; i++) {
  132. struct Sockaddr* pfx = ArrayList_OfSockaddr_get(toRemove, i);
  133. Log_debug(logger, "DELETE ROUTE %s", Sockaddr_print(pfx, alloc));
  134. struct Message* msg = Message_new(0, 1024, alloc);
  135. Er(mkRouteMsg(msg, pfx, ifIndex, ifName, seq++, true));
  136. //printf("DELETE ROUTE %s\n", Hex_print(msg->bytes, msg->length, alloc));
  137. returnLen = write(sock, msg->bytes, msg->length);
  138. if (returnLen < msg->length) { err = true; break; }
  139. }
  140. for (int i = 0; !err && i < toAdd->length; i++) {
  141. struct Sockaddr* pfx = ArrayList_OfSockaddr_get(toAdd, i);
  142. Log_debug(logger, "ADD ROUTE %s", Sockaddr_print(pfx, alloc));
  143. struct Message* msg = Message_new(0, 1024, alloc);
  144. Er(mkRouteMsg(msg, pfx, ifIndex, ifName, seq++, false));
  145. //printf("ADD ROUTE %s\n", Hex_print(msg->bytes, msg->length, alloc));
  146. returnLen = write(sock, msg->bytes, msg->length);
  147. if (returnLen < msg->length) { err = true; break; }
  148. }
  149. if (returnLen < 0) {
  150. int error = errno;
  151. close(sock);
  152. Er_raise(alloc, "setRoutes() [%s]", strerror(error));
  153. } else if (err) {
  154. close(sock);
  155. Er_raise(alloc, "setRoutes() returned short");
  156. }
  157. close(sock);
  158. Er_ret();
  159. }
  160. static int prefixFromWeirdBSDMask(uint8_t* weirdBsdMask, bool ipv6)
  161. {
  162. uint8_t len = weirdBsdMask[0];
  163. int out;
  164. if (ipv6) {
  165. Assert_true(len >= 8);
  166. out = (len - 9) * 8;
  167. } else {
  168. Assert_true(len >= 4);
  169. out = (len - 5) * 8;
  170. }
  171. for (int i = 1; i < len - 1; i++) {
  172. Assert_true(weirdBsdMask[i] == 0xff);
  173. }
  174. return out + Bits_popCountx32(weirdBsdMask[len - 1]);
  175. }
  176. static Er_DEFUN(struct ArrayList_OfSockaddr* getRoutes(uint32_t ifIndex,
  177. struct Log* logger,
  178. struct Allocator* allocator))
  179. {
  180. size_t needed;
  181. int mib[] = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_DUMP, 0 };
  182. if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
  183. Er_raise(allocator, "sysctl(net.route.0.0.dump) estimate");
  184. }
  185. struct Allocator* tempAlloc = Allocator_child(allocator);
  186. uint8_t* buf = Allocator_malloc(tempAlloc, needed);
  187. if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
  188. Er_raise(allocator, "sysctl(net.route.0.0.dump)");
  189. }
  190. struct ArrayList_OfSockaddr* addrList = ArrayList_OfSockaddr_new(allocator);
  191. for (int i = 0; i < (int)needed;) {
  192. struct rt_msghdr* rtm = (struct rt_msghdr*) (&buf[i]);
  193. i += rtm->rtm_msglen;
  194. struct sockaddr* sa1 = (struct sockaddr*)(rtm + 1);
  195. struct sockaddr* sa2 = (struct sockaddr*)(sa1->sa_len + (char *)sa1);
  196. uint8_t* mask = (uint8_t*) (sa2->sa_len + (char*)sa2);
  197. Assert_true(&buf[i] >= mask);
  198. if (sa2->sa_family != AF_LINK) { continue; }
  199. if (rtm->rtm_flags & RTF_LOCAL) { continue; }
  200. if (!(rtm->rtm_flags & RTF_STATIC)) { continue; }
  201. if (((struct sockaddr_dl*) sa2)->sdl_index != ifIndex) { continue; }
  202. bool ipv6 = (sa1->sa_family == AF_INET6);
  203. if (!ipv6 && (sa1->sa_family != AF_INET)) { continue; }
  204. // printf("GOT ROUTE %s\n", Hex_print(rtm, rtm->rtm_msglen, tempAlloc));
  205. int prefix;
  206. if (&buf[i] < &mask[mask[0]] || mask[0] == 0) {
  207. //Assert_true(rtm->rtm_flags & RTF_HOST);
  208. prefix = (ipv6) ? 128 : 32;
  209. } else {
  210. prefix = prefixFromWeirdBSDMask(mask, ipv6);
  211. }
  212. struct Sockaddr* addr = Sockaddr_fromNative(sa1, sa1->sa_len, allocator);
  213. addr->flags |= Sockaddr_flags_PREFIX;
  214. addr->prefix = prefix;
  215. ArrayList_OfSockaddr_add(addrList, addr);
  216. }
  217. Allocator_free(tempAlloc);
  218. Er_ret(addrList);
  219. }
  220. static Er_DEFUN(void addIp4Address(const char* interfaceName,
  221. const uint8_t address[4],
  222. int prefixLen,
  223. struct Log* logger,
  224. struct Allocator* tempAlloc))
  225. {
  226. struct ifaliasreq ifarted;
  227. Bits_memset(&ifarted, 0, sizeof(struct ifaliasreq));
  228. CString_safeStrncpy(ifarted.ifra_name, interfaceName, IFNAMSIZ);
  229. struct sockaddr_in sin = { .sin_family = AF_INET, .sin_len = sizeof(struct sockaddr_in) };
  230. Bits_memcpy(&sin.sin_addr.s_addr, address, 4);
  231. Bits_memcpy(&ifarted.ifra_addr, &sin, sizeof(struct sockaddr_in));
  232. sin.sin_addr.s_addr = Endian_hostToBigEndian32(~0u << (32 - prefixLen));
  233. Bits_memcpy(&ifarted.ifra_mask, &sin, sizeof(struct sockaddr_in));
  234. int s = socket(AF_INET, SOCK_DGRAM, 0);
  235. if (s < 0) {
  236. Er_raise(tempAlloc, "socket() [%s]", strerror(errno));
  237. }
  238. // will probably fail, ignore result.
  239. struct ifreq ifr = { .ifr_flags = 0 };
  240. CString_safeStrncpy(ifr.ifr_name, interfaceName, IFNAMSIZ);
  241. ioctl(s, SIOCDIFADDR, &ifr);
  242. if (ioctl(s, SIOCSIFADDR, &ifarted) < 0) {
  243. int err = errno;
  244. close(s);
  245. Er_raise(tempAlloc, "ioctl(SIOCSIFADDR) [%s]", strerror(err));
  246. }
  247. //setupRoute4(address, prefixLen, interfaceName, logger, tempAlloc, eh);
  248. Log_info(logger, "Configured IPv4 [%u.%u.%u.%u/%i] for [%s]",
  249. address[0], address[1], address[2], address[3], prefixLen, interfaceName);
  250. close(s);
  251. Er_ret();
  252. }
  253. static Er_DEFUN(void addIp6Address(const char* interfaceName,
  254. const uint8_t address[16],
  255. int prefixLen,
  256. struct Log* logger,
  257. struct Allocator* errAlloc))
  258. {
  259. /* stringify our IP address */
  260. char myIp[40];
  261. AddrTools_printIp((uint8_t*)myIp, address);
  262. /* set up the interface ip assignment request */
  263. struct in6_aliasreq in6_addreq;
  264. memset(&in6_addreq, 0, sizeof(in6_addreq));
  265. in6_addreq.ifra_lifetime.ia6t_vltime = ND6_INFINITE_LIFETIME;
  266. in6_addreq.ifra_lifetime.ia6t_pltime = ND6_INFINITE_LIFETIME;
  267. /* parse the IPv6 address and add it to the request */
  268. struct addrinfo hints, *result;
  269. bzero(&hints, sizeof(struct addrinfo));
  270. hints.ai_family = AF_INET6;
  271. int err = getaddrinfo((const char *)myIp, NULL, &hints, &result);
  272. if (err) {
  273. // Should never happen since the address is specified as binary.
  274. Er_raise(errAlloc, "bad IPv6 address [%s]", gai_strerror(err));
  275. }
  276. bcopy(result->ai_addr, &in6_addreq.ifra_addr, result->ai_addrlen);
  277. /* turn the prefixlen into a mask, and add it to the request */
  278. struct sockaddr_in6* mask = &in6_addreq.ifra_prefixmask;
  279. mask->sin6_len = sizeof(*mask);
  280. if (prefixLen >= 128 || prefixLen <= 0) {
  281. memset(&mask->sin6_addr, 0xff, sizeof(struct in6_addr));
  282. } else {
  283. memset((void *)&mask->sin6_addr, 0x00, sizeof(mask->sin6_addr));
  284. memset((void *)&mask->sin6_addr, 0xff, prefixLen>>3);
  285. ((uint8_t*)&mask->sin6_addr)[prefixLen>>3] = 0xff << (8 - (prefixLen%8));
  286. }
  287. CString_safeStrncpy(in6_addreq.ifra_name, interfaceName, sizeof(in6_addreq.ifra_name));
  288. /* do the actual assignment ioctl */
  289. int s = socket(AF_INET6, SOCK_DGRAM, 0);
  290. if (s < 0) {
  291. Er_raise(errAlloc, "socket() [%s]", strerror(errno));
  292. }
  293. if (ioctl(s, SIOCAIFADDR_IN6, &in6_addreq) < 0) {
  294. int err = errno;
  295. close(s);
  296. Er_raise(errAlloc, "ioctl(SIOCAIFADDR) [%s] for [%s]", strerror(err), interfaceName);
  297. }
  298. Log_info(logger, "Configured IPv6 [%s/%i] for [%s]", myIp, prefixLen, interfaceName);
  299. close(s);
  300. Er_ret();
  301. }
  302. Er_DEFUN(void NetPlatform_addAddress(const char* interfaceName,
  303. const uint8_t* address,
  304. int prefixLen,
  305. int addrFam,
  306. struct Log* logger,
  307. struct Allocator* tempAlloc))
  308. {
  309. if (addrFam == Sockaddr_AF_INET6) {
  310. Er(addIp6Address(interfaceName, address, prefixLen, logger, tempAlloc));
  311. } else if (addrFam == Sockaddr_AF_INET) {
  312. Er(addIp4Address(interfaceName, address, prefixLen, logger, tempAlloc));
  313. } else {
  314. Assert_true(0);
  315. }
  316. Er_ret();
  317. }
  318. Er_DEFUN(void NetPlatform_setMTU(const char* interfaceName,
  319. uint32_t mtu,
  320. struct Log* logger,
  321. struct Allocator* errAlloc))
  322. {
  323. int s = socket(AF_INET6, SOCK_DGRAM, 0);
  324. if (s < 0) {
  325. Er_raise(errAlloc, "socket() [%s]", strerror(errno));
  326. }
  327. struct ifreq ifRequest;
  328. CString_safeStrncpy(ifRequest.ifr_name, interfaceName, IFNAMSIZ);
  329. ifRequest.ifr_mtu = mtu;
  330. Log_info(logger, "Setting MTU for device [%s] to [%u] bytes.", interfaceName, mtu);
  331. if (ioctl(s, SIOCSIFMTU, &ifRequest) < 0) {
  332. int err = errno;
  333. close(s);
  334. Er_raise(errAlloc, "ioctl(SIOCSIFMTU) [%s]", strerror(err));
  335. }
  336. close(s);
  337. Er_ret();
  338. }
  339. Er_DEFUN(void NetPlatform_setRoutes(const char* ifName,
  340. struct Sockaddr** prefixSet,
  341. int prefixCount,
  342. struct Log* logger,
  343. struct Allocator* tempAlloc))
  344. {
  345. struct ArrayList_OfSockaddr* newRoutes = ArrayList_OfSockaddr_new(tempAlloc);
  346. for (int i = 0; i < prefixCount; i++) {
  347. int addrFam = Sockaddr_getFamily(prefixSet[i]);
  348. if (addrFam == Sockaddr_AF_INET) {
  349. // OK
  350. } else if (addrFam == Sockaddr_AF_INET6) {
  351. // OK
  352. } else {
  353. Er_raise(tempAlloc, "Unrecognized address type %d", addrFam);
  354. }
  355. ArrayList_OfSockaddr_add(newRoutes, prefixSet[i]);
  356. }
  357. uint32_t ifIndex = if_nametoindex(ifName);
  358. if (!ifIndex) {
  359. Er_raise(tempAlloc, "tunName not recognized");
  360. }
  361. struct ArrayList_OfSockaddr* oldRoutes = Er(getRoutes(ifIndex, logger, tempAlloc));
  362. Er(setRoutes(ifIndex, ifName, oldRoutes, newRoutes, logger, tempAlloc));
  363. Er_ret();
  364. }