NetPlatform_darwin.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 void mkRouteMsg(struct Message* msg,
  61. struct Sockaddr* addRoute,
  62. int ifIndex,
  63. const char* ifName,
  64. int seq,
  65. bool delete,
  66. struct Except* eh)
  67. {
  68. if (CString_strlen(ifName) >= 12) {
  69. Except_throw(eh, "ifName [%s] too long, limit 11 chars", ifName);
  70. }
  71. int lengthBegin = msg->length;
  72. bool ipv6 = Sockaddr_getFamily(addRoute) == Sockaddr_AF_INET6;
  73. if (ipv6) {
  74. struct sockaddr_in6 mask = {
  75. .sin6_family = AF_INET6,
  76. .sin6_len = sizeof(struct sockaddr_in6)
  77. };
  78. Bits_memset((void *)&mask.sin6_addr, 0xff, addRoute->prefix >> 3);
  79. ((uint8_t*)&mask.sin6_addr)[addRoute->prefix >> 3] = 0xff << (8 - (addRoute->prefix % 8));
  80. Message_push(msg, &mask, sizeof(struct sockaddr_in6), eh);
  81. } else {
  82. struct sockaddr_in mask = {
  83. .sin_family = AF_INET,
  84. .sin_len = sizeof(struct sockaddr_in)
  85. };
  86. mask.sin_addr.s_addr = Endian_hostToBigEndian32(~0 << (32 - addRoute->prefix));
  87. Message_push(msg, &mask, sizeof(struct sockaddr_in), eh);
  88. }
  89. if (!delete) {
  90. struct sockaddr_dl link = {
  91. .sdl_family = AF_LINK,
  92. .sdl_len = sizeof(struct sockaddr_dl),
  93. .sdl_type = IFT_OTHER,
  94. .sdl_index = ifIndex,
  95. .sdl_nlen = CString_strlen(ifName)
  96. };
  97. CString_strncpy(link.sdl_data, ifName, 12);
  98. Message_push(msg, &link, sizeof(struct sockaddr_dl), eh);
  99. }
  100. void* dest = Sockaddr_asNative(addRoute);
  101. int len = (ipv6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
  102. ((struct sockaddr*)dest)->sa_len = len;
  103. Message_push(msg, dest, len, eh);
  104. struct rt_msghdr hdr = {
  105. .rtm_type = (delete) ? RTM_DELETE : RTM_ADD,
  106. .rtm_flags = RTF_UP | RTF_STATIC,
  107. .rtm_version = RTM_VERSION,
  108. .rtm_seq = seq,
  109. .rtm_pid = getpid(),
  110. .rtm_addrs = RTA_DST | RTA_NETMASK | ((delete) ? 0 : RTA_GATEWAY),
  111. .rtm_msglen = sizeof(struct rt_msghdr) + (msg->length - lengthBegin)
  112. };
  113. Message_push(msg, &hdr, sizeof(struct rt_msghdr), eh);
  114. }
  115. static 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. struct Except* eh)
  122. {
  123. int seq = 0;
  124. int sock = socket(PF_ROUTE, SOCK_RAW, 0);
  125. if (sock == -1) {
  126. int err = errno;
  127. close(sock);
  128. Except_throw(eh, "open route socket [%s]", strerror(err));
  129. }
  130. bool err = false;
  131. ssize_t returnLen = 0;
  132. for (int i = 0; !err && i < toRemove->length; i++) {
  133. struct Sockaddr* pfx = ArrayList_OfSockaddr_get(toRemove, i);
  134. Log_debug(logger, "DELETE ROUTE %s", Sockaddr_print(pfx, alloc));
  135. struct Message* msg = Message_new(0, 1024, alloc);
  136. mkRouteMsg(msg, pfx, ifIndex, ifName, seq++, true, eh);
  137. //printf("DELETE ROUTE %s\n", Hex_print(msg->bytes, msg->length, alloc));
  138. returnLen = write(sock, msg->bytes, msg->length);
  139. if (returnLen < msg->length) { err = true; break; }
  140. }
  141. for (int i = 0; !err && i < toAdd->length; i++) {
  142. struct Sockaddr* pfx = ArrayList_OfSockaddr_get(toAdd, i);
  143. Log_debug(logger, "ADD ROUTE %s", Sockaddr_print(pfx, alloc));
  144. struct Message* msg = Message_new(0, 1024, alloc);
  145. mkRouteMsg(msg, pfx, ifIndex, ifName, seq++, false, eh);
  146. //printf("ADD ROUTE %s\n", Hex_print(msg->bytes, msg->length, alloc));
  147. returnLen = write(sock, msg->bytes, msg->length);
  148. if (returnLen < msg->length) { err = true; break; }
  149. }
  150. if (returnLen < 0) {
  151. int error = errno;
  152. close(sock);
  153. Except_throw(eh, "setRoutes() [%s]", strerror(error));
  154. } else if (err) {
  155. close(sock);
  156. Except_throw(eh, "setRoutes() returned short");
  157. }
  158. close(sock);
  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 struct ArrayList_OfSockaddr* getRoutes(uint32_t ifIndex,
  177. struct Log* logger,
  178. struct Allocator* allocator,
  179. struct Except* eh)
  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. Except_throw(eh, "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. Except_throw(eh, "sysctl(net.route.0.0.dump)");
  190. }
  191. struct ArrayList_OfSockaddr* addrList = ArrayList_OfSockaddr_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 Sockaddr* addr = Sockaddr_fromNative(sa1, sa1->sa_len, allocator);
  214. addr->flags |= Sockaddr_flags_PREFIX;
  215. addr->prefix = prefix;
  216. ArrayList_OfSockaddr_add(addrList, addr);
  217. }
  218. Allocator_free(tempAlloc);
  219. return addrList;
  220. }
  221. static void addIp4Address(const char* interfaceName,
  222. const uint8_t address[4],
  223. int prefixLen,
  224. struct Log* logger,
  225. struct Allocator* tempAlloc,
  226. struct Except* eh)
  227. {
  228. struct ifaliasreq ifarted;
  229. Bits_memset(&ifarted, 0, sizeof(struct ifaliasreq));
  230. CString_strncpy(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(~0 << (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. Except_throw(eh, "socket() [%s]", strerror(errno));
  239. }
  240. // will probably fail, ignore result.
  241. struct ifreq ifr = { .ifr_flags = 0 };
  242. CString_strncpy(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. Except_throw(eh, "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. }
  254. static void addIp6Address(const char* interfaceName,
  255. const uint8_t address[16],
  256. int prefixLen,
  257. struct Log* logger,
  258. struct Except* eh)
  259. {
  260. /* stringify our IP address */
  261. char myIp[40];
  262. AddrTools_printIp((uint8_t*)myIp, address);
  263. /* set up the interface ip assignment request */
  264. struct in6_aliasreq in6_addreq;
  265. memset(&in6_addreq, 0, sizeof(in6_addreq));
  266. in6_addreq.ifra_lifetime.ia6t_vltime = ND6_INFINITE_LIFETIME;
  267. in6_addreq.ifra_lifetime.ia6t_pltime = ND6_INFINITE_LIFETIME;
  268. /* parse the IPv6 address and add it to the request */
  269. struct addrinfo hints, *result;
  270. bzero(&hints, sizeof(struct addrinfo));
  271. hints.ai_family = AF_INET6;
  272. int err = getaddrinfo((const char *)myIp, NULL, &hints, &result);
  273. if (err) {
  274. // Should never happen since the address is specified as binary.
  275. Except_throw(eh, "bad IPv6 address [%s]", gai_strerror(err));
  276. }
  277. bcopy(result->ai_addr, &in6_addreq.ifra_addr, result->ai_addrlen);
  278. /* turn the prefixlen into a mask, and add it to the request */
  279. struct sockaddr_in6* mask = &in6_addreq.ifra_prefixmask;
  280. mask->sin6_len = sizeof(*mask);
  281. if (prefixLen >= 128 || prefixLen <= 0) {
  282. memset(&mask->sin6_addr, 0xff, sizeof(struct in6_addr));
  283. } else {
  284. memset((void *)&mask->sin6_addr, 0x00, sizeof(mask->sin6_addr));
  285. memset((void *)&mask->sin6_addr, 0xff, prefixLen>>3);
  286. ((uint8_t*)&mask->sin6_addr)[prefixLen>>3] = 0xff << (8 - (prefixLen%8));
  287. }
  288. strncpy(in6_addreq.ifra_name, interfaceName, sizeof(in6_addreq.ifra_name));
  289. /* do the actual assignment ioctl */
  290. int s = socket(AF_INET6, SOCK_DGRAM, 0);
  291. if (s < 0) {
  292. Except_throw(eh, "socket() [%s]", strerror(errno));
  293. }
  294. if (ioctl(s, SIOCAIFADDR_IN6, &in6_addreq) < 0) {
  295. int err = errno;
  296. close(s);
  297. Except_throw(eh, "ioctl(SIOCAIFADDR) [%s] for [%s]", strerror(err), interfaceName);
  298. }
  299. Log_info(logger, "Configured IPv6 [%s/%i] for [%s]", myIp, prefixLen, interfaceName);
  300. close(s);
  301. }
  302. 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. struct Except* eh)
  309. {
  310. if (addrFam == Sockaddr_AF_INET6) {
  311. addIp6Address(interfaceName, address, prefixLen, logger, eh);
  312. } else if (addrFam == Sockaddr_AF_INET) {
  313. addIp4Address(interfaceName, address, prefixLen, logger, tempAlloc, eh);
  314. } else {
  315. Assert_true(0);
  316. }
  317. }
  318. void NetPlatform_setMTU(const char* interfaceName,
  319. uint32_t mtu,
  320. struct Log* logger,
  321. struct Except* eh)
  322. {
  323. int s = socket(AF_INET6, SOCK_DGRAM, 0);
  324. if (s < 0) {
  325. Except_throw(eh, "socket() [%s]", strerror(errno));
  326. }
  327. struct ifreq ifRequest;
  328. strncpy(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. Except_throw(eh, "ioctl(SIOCSIFMTU) [%s]", strerror(err));
  335. }
  336. close(s);
  337. }
  338. void NetPlatform_setRoutes(const char* ifName,
  339. struct Sockaddr** prefixSet,
  340. int prefixCount,
  341. struct Log* logger,
  342. struct Allocator* tempAlloc,
  343. struct Except* eh)
  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. Except_throw(eh, "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. Except_throw(eh, "tunName not recognized");
  360. }
  361. struct ArrayList_OfSockaddr* oldRoutes = getRoutes(ifIndex, logger, tempAlloc, eh);
  362. setRoutes(ifIndex, ifName, oldRoutes, newRoutes, logger, tempAlloc, eh);
  363. }