diff --git a/Sources/CTunnelKitCore/RoutingTable.m b/Sources/CTunnelKitCore/RoutingTable.m deleted file mode 100644 index 9696d29..0000000 --- a/Sources/CTunnelKitCore/RoutingTable.m +++ /dev/null @@ -1,162 +0,0 @@ -// -// RoutingTable.m -// TunnelKit -// -// Created by Davide De Rosa on 4/30/19. -// Copyright (c) 2023 Davide De Rosa. All rights reserved. -// -// https://github.com/passepartoutvpn -// -// This file is part of TunnelKit. -// -// TunnelKit is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// TunnelKit is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with TunnelKit. If not, see . -// - -#import -#import "route.h" - -#import "RoutingTable.h" -#import "Allocation.h" - -// adapted from: https://github.com/jianpx/ios-cabin - -@interface RoutingTableEntry () - -- (instancetype)initWithRTM:(const struct rt_msghdr2 *)rtm; - -@end - -#pragma mark - - -@interface RoutingTable () - -@property (nonatomic, strong) NSArray *ipv4; -@property (nonatomic, strong) NSArray *ipv6; - -@end - -@implementation RoutingTable - -- (instancetype)init -{ - if (!(self = [super init])) { - return nil; - } - - int mib[] = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_DUMP2, 0 }; - const int mibLen = sizeof(mib) / sizeof(int); - size_t len; - if (sysctl(mib, mibLen, NULL, &len, NULL, 0) || (len <= 0)) { - return nil; - } - - char *buf = allocate_safely(len); - if (!buf) { - return nil; - } - if (sysctl(mib, mibLen, buf, &len, NULL, 0)) { - free(buf); - return nil; - } - - NSMutableArray *entries4 = [[NSMutableArray alloc] init]; - NSMutableArray *entries6 = [[NSMutableArray alloc] init]; - - for (const char *ptr = buf; ptr < buf + len;) { - const struct rt_msghdr2 *rtm = (struct rt_msghdr2 *)ptr; - - if (rtm->rtm_addrs & RTA_DST) { - struct sockaddr *dst_sa = (struct sockaddr *)(rtm + 1); // XXX: why +1 ?!? - - if (((dst_sa->sa_family == AF_INET) || (dst_sa->sa_family == AF_INET6)) && !((rtm->rtm_flags & RTF_WASCLONED) && (rtm->rtm_parentflags & RTF_PRCLONING))) { - RoutingTableEntry *entry = [[RoutingTableEntry alloc] initWithRTM:rtm]; - if (!entry) { - continue; - } - if (dst_sa->sa_family == AF_INET) { - [entries4 addObject:entry]; - } else if (dst_sa->sa_family == AF_INET6) { - [entries6 addObject:entry]; - } - } - } - - ptr += rtm->rtm_msglen; - } - - free(buf); - - self.ipv4 = entries4; - self.ipv6 = entries6; - - return self; -} - -- (RoutingTableEntry *)defaultGateway4 -{ - for (RoutingTableEntry *entry in self.ipv4) { - if ([entry isDefault]) { - return entry; - } - } - return nil; -} - -- (RoutingTableEntry *)defaultGateway6 -{ - for (RoutingTableEntry *entry in self.ipv6) { - if ([entry isDefault]) { - return entry; - } - } - return nil; -} - -- (RoutingTableEntry *)broadestRoute4MatchingDestination:(NSString *)destination -{ - RoutingTableEntry *defaultRoute; - RoutingTableEntry *minRoute; - NSInteger minPrefix = 32 + 1; - for (RoutingTableEntry *route in self.ipv4) { - if ([route isDefault]) { // leave last - defaultRoute = route; - continue; - } - if ([route matchesDestination:destination] && route.prefix < minPrefix) { - minRoute = route; - minPrefix = route.prefix; - } - } - return minRoute ?: defaultRoute; -} - -- (RoutingTableEntry *)broadestRoute6MatchingDestination:(NSString *)destination -{ - RoutingTableEntry *defaultRoute; - RoutingTableEntry *minRoute; - NSInteger minPrefix = 128 + 1; - for (RoutingTableEntry *route in self.ipv6) { - if ([route isDefault]) { // leave last - defaultRoute = route; - continue; - } - if ([route matchesDestination:destination] && route.prefix < minPrefix) { - minRoute = route; - minPrefix = route.prefix; - } - } - return minRoute ?: defaultRoute; -} - -@end diff --git a/Sources/CTunnelKitCore/RoutingTableEntry.m b/Sources/CTunnelKitCore/RoutingTableEntry.m deleted file mode 100644 index 6841591..0000000 --- a/Sources/CTunnelKitCore/RoutingTableEntry.m +++ /dev/null @@ -1,614 +0,0 @@ -// -// RoutingTableEntry.m -// TunnelKit -// -// Created by Davide De Rosa on 4/30/19. -// Copyright (c) 2023 Davide De Rosa. All rights reserved. -// -// https://github.com/passepartoutvpn -// -// This file is part of TunnelKit. -// -// TunnelKit is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// TunnelKit is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with TunnelKit. If not, see . -// - -#import -#import -#import -#import "route.h" - -#import "RoutingTableEntry.h" - -#define ASSERT_PRINTF(r) NSCAssert(r >= 0, @"*printf() failed") -#define ASSERT_GETNAMEINFO(r) NSCAssert(r == 0, @"getnameinfo() failed") - -// adapted from: https://github.com/jianpx/ios-cabin - -#define ROUNDUP(a) ((a) > 0 ? (1 + (((a) - 1) | (sizeof(uint32_t) - 1))) : sizeof(uint32_t)) - -typedef union { - uint32_t dummy; - struct sockaddr u_sa; - u_short u_data[128]; -} sa_u; - -static uint32_t RoutingTableEntryAddress4(NSString *string); -static NSData *RoutingTableEntryAddress6(NSString *string); -static NSString *RoutingTableEntryName(struct sockaddr *sa, struct sockaddr *mask, int flags); - -#pragma mark - - -@interface RoutingTableEntry () - -@property (nonatomic, assign) BOOL isIPv6; -@property (nonatomic, copy) NSString *network; -@property (nonatomic, assign) NSInteger prefix; -@property (nonatomic, copy) NSString *gateway; -@property (nonatomic, copy) NSString *networkInterface; - -@end - -@implementation RoutingTableEntry - -- (instancetype)initWithNetwork:(NSString *)network prefix:(NSInteger)prefix gateway:(NSString *)gateway networkInterface:(NSString *)networkInterface -{ - if (!(self = [super init])) { - return nil; - } - - self.network = network; - self.prefix = prefix; - self.gateway = gateway; - self.networkInterface = networkInterface; - - return self; -} - -- (instancetype)initWithIPv4Network:(NSString *)network gateway:(NSString *)gateway networkInterface:(NSString *)networkInterface -{ - NSInteger prefix = 0; - - NSArray *networkComps = [network componentsSeparatedByString:@"/"]; - network = networkComps.firstObject; - if (networkComps.count == 2) { - prefix = [networkComps.lastObject integerValue]; - NSAssert(prefix >= 0 && prefix <= 32, @"IPv4 prefix must lie in [0..32]"); - } else { - prefix = 32; - } - - NSMutableArray *groups = [[network componentsSeparatedByString:@"."] mutableCopy]; - if (![network isEqualToString:@"default"]) { - if (prefix == 32) { - prefix = 8 * groups.count; - } - for (NSInteger i = groups.count; i < 4; ++i) { - [groups addObject:@"0"]; - } - network = [groups componentsJoinedByString:@"."]; - } - - if (!(self = [self initWithNetwork:network prefix:prefix gateway:gateway networkInterface:networkInterface])) { - return nil; - } - self.isIPv6 = NO; - return self; -} - -- (instancetype)initWithIPv6Network:(NSString *)network gateway:(NSString *)gateway networkInterface:(NSString *)networkInterface -{ - NSInteger prefix = 0; - - NSArray *networkComps = [network componentsSeparatedByString:@"/"]; - network = networkComps.firstObject; - if (networkComps.count == 2) { - prefix = [networkComps.lastObject integerValue]; - NSAssert(prefix >= 0 && prefix <= 128, @"IPv6 prefix must lie in [0..128]"); - } else { - prefix = 128; - } - network = [[network componentsSeparatedByString:@"%"] firstObject]; - gateway = [[gateway componentsSeparatedByString:@"%"] firstObject]; - - if (!(self = [self initWithNetwork:network prefix:prefix gateway:gateway networkInterface:networkInterface])) { - return nil; - } - self.isIPv6 = YES; - return self; -} - -- (instancetype)initWithRTM:(const struct rt_msghdr2 *)rtm -{ - NSParameterAssert(rtm); - - NSString *network; - NSString *gateway; - NSString *networkInterface; - - struct sockaddr *rti_info[RTAX_MAX]; - struct sockaddr *sa = (struct sockaddr *)(rtm + 1); - for (int i = 0; i < RTAX_MAX; ++i) { - if (rtm->rtm_addrs & (1 << i)) { - rti_info[i] = sa; - sa = (struct sockaddr *)(ROUNDUP(sa->sa_len) + (char *)sa); - } else { - rti_info[i] = NULL; - } - } - - // network - sa_u destinationStruct, destinationNetmask; - bzero(&destinationStruct, sizeof(destinationStruct)); - if (rtm->rtm_addrs & RTA_DST) { - bcopy(rti_info[RTAX_DST], &destinationStruct, rti_info[RTAX_DST]->sa_len); - } - bzero(&destinationNetmask, sizeof(destinationNetmask)); - if (rtm->rtm_addrs & RTA_NETMASK) { - bcopy(rti_info[RTAX_NETMASK], &destinationNetmask, rti_info[RTAX_NETMASK]->sa_len); - } - network = RoutingTableEntryName(&destinationStruct.u_sa, &destinationNetmask.u_sa, rtm->rtm_flags); - - // gateway - sa_u gatewayStruct; - bzero(&gatewayStruct, sizeof(gatewayStruct)); - if (rtm->rtm_addrs & RTA_GATEWAY) { - bcopy(rti_info[RTAX_GATEWAY], &gatewayStruct, rti_info[RTAX_GATEWAY]->sa_len); - } - gateway = RoutingTableEntryName(rti_info[RTAX_GATEWAY], NULL, RTF_HOST); - - // network interface - char networkInterfaceStr[IF_NAMESIZE]; - const char *networkInterfaceName = if_indextoname(rtm->rtm_index, networkInterfaceStr); - if (networkInterfaceName) { - networkInterface = [NSString stringWithCString:networkInterfaceName encoding:NSASCIIStringEncoding]; - } - - if (rti_info[RTAX_DST]->sa_family == AF_INET6) { - return [self initWithIPv6Network:network gateway:gateway networkInterface:networkInterface]; - } else { - return [self initWithIPv4Network:network gateway:gateway networkInterface:networkInterface]; - } -} - -- (NSString *)networkMask -{ - struct in_addr mask; - mask.s_addr = htonl(~((1 << (32 - self.prefix)) - 1)); - const char *address = inet_ntoa(mask); - return [NSString stringWithCString:address encoding:NSASCIIStringEncoding]; -} - -- (BOOL)isDefault -{ - return [self.network isEqualToString:@"default"]; -} - -- (BOOL)matchesDestination:(NSString *)destination -{ - NSParameterAssert(destination); - - if ([self isDefault]) { - return YES; - } - - if (self.isIPv6) { - NSData *networkAddress = RoutingTableEntryAddress6(self.network); - NSData *destinationAddress = RoutingTableEntryAddress6(destination); - if (!networkAddress || !destinationAddress) { - return NO; - } - -// NSLog(@"network: %@ = %@", networkAddress, self.network); -// NSLog(@"destination: %@ = %@", destinationAddress, destination); - - const uint8_t *networkPtr = networkAddress.bytes; - const uint8_t *destinationPtr = destinationAddress.bytes; - - NSInteger leftBits = self.prefix; -// NSLog(@"\tprefix = %u", (int)self.prefix); - for (NSInteger i = 0; leftBits > 0; ++i) { - uint8_t networkMask; - if (leftBits >= 8) { - networkMask = 0xff; - } else { - networkMask = ~((1 << (8 - leftBits)) - 1); - } -// NSLog(@"\tnetworkMask[%u] = %x", (int)i, networkMask); - if (((networkPtr[i] ^ destinationPtr[i]) & networkMask) != 0) { - return NO; - } - leftBits -= 8; - } -// NSLog(@"\tMATCH"); - return YES; - } - else { - const uint32_t networkAddress = RoutingTableEntryAddress4(self.network); - const uint32_t destinationAddress = RoutingTableEntryAddress4(destination); - if ((networkAddress == UINT32_MAX) || (destinationAddress == UINT32_MAX)) { - return NO; - } - const uint32_t networkMask = ~((1 << (32 - self.prefix)) - 1); - -// NSLog(@"network: %x = %@", networkAddress, self.network); -// NSLog(@"destination: %x = %@", destinationAddress, destination); -// NSLog(@"mask: %x", networkMask); - - return ((networkAddress ^ destinationAddress) & networkMask) == 0; - } -} - -- (nullable NSArray *)partitioned -{ - NSMutableArray *segments = [[NSMutableArray alloc] init]; - const int halfPrefix = (int)(self.prefix + 1); - if (self.isIPv6) { - if (self.prefix == 128) { - NSLog(@"Can't partition single IPv6"); - return @[self, self]; - } - - struct in6_addr saddr1, saddr2; - char addr[INET6_ADDRSTRLEN]; - NSData *addressData = RoutingTableEntryAddress6(self.network); - if (!addressData) { - return nil; - } - memcpy(&saddr1, addressData.bytes, addressData.length); - NSMutableData *addressData2 = [addressData mutableCopy]; - - uint8_t *addressBytes2 = (uint8_t *)addressData2.bytes; - const uint8_t mask2 = 1 << ((8 - halfPrefix % 8) % 8); - addressBytes2[(halfPrefix - 1) / 8] |= mask2; - - memcpy(&saddr2, addressData2.bytes, addressData2.length); - - inet_ntop(AF_INET6, &saddr1, addr, INET6_ADDRSTRLEN); - NSString *network1 = [NSString stringWithFormat:@"%s/%d", addr, halfPrefix]; - inet_ntop(AF_INET6, &saddr2, addr, INET6_ADDRSTRLEN); - NSString *network2 = [NSString stringWithFormat:@"%s/%d", addr, halfPrefix]; - - [segments addObject:[[RoutingTableEntry alloc] initWithIPv6Network:network1 gateway:self.gateway networkInterface:self.networkInterface]]; - [segments addObject:[[RoutingTableEntry alloc] initWithIPv6Network:network2 gateway:self.gateway networkInterface:self.networkInterface]]; - } else { - if (self.prefix == 32) { - NSLog(@"Can't partition single IPv4"); - return @[self, self]; - } - - struct in_addr saddr1, saddr2; - const uint32_t address = RoutingTableEntryAddress4(self.network); - if (address == UINT32_MAX) { - return nil; - } - saddr1.s_addr = htonl(address); - saddr2.s_addr = htonl(address | (1 << (32 - halfPrefix))); - - // XXX: inet_ntoa returns pointer to static variable, copy before next call - const char *address1 = inet_ntoa(saddr1); - NSString *network1 = [NSString stringWithFormat:@"%s/%d", address1, halfPrefix]; - const char *address2 = inet_ntoa(saddr2); - NSString *network2 = [NSString stringWithFormat:@"%s/%d", address2, halfPrefix]; - - [segments addObject:[[RoutingTableEntry alloc] initWithIPv4Network:network1 gateway:self.gateway networkInterface:self.networkInterface]]; - [segments addObject:[[RoutingTableEntry alloc] initWithIPv4Network:network2 gateway:self.gateway networkInterface:self.networkInterface]]; - } - return segments; -} - -- (NSString *)description -{ - return [NSString stringWithFormat:@"{%@/%ld -> %@ via %@}", self.network, self.prefix, self.gateway ?: @"nil", self.networkInterface]; -} - -@end - -#pragma mark - - -static char *netname(uint32_t in, uint32_t mask); -static char *netname6(struct sockaddr_in6 *sa6, struct sockaddr *sam); -static char *routename(uint32_t in); -static char *routename6(struct sockaddr_in6 *sa6); -static uint32_t forgemask(uint32_t a); -static void domask(char *dst, size_t dstsize, uint32_t addr, uint32_t mask); -static void trimdomain(char *cp); - -static inline uint32_t RoutingTableEntryAddress4(NSString *string) -{ - struct in_addr addr; - if (inet_pton(AF_INET, [string cStringUsingEncoding:NSASCIIStringEncoding], &addr) <= 0) { - return UINT32_MAX; - } - return CFSwapInt32BigToHost(addr.s_addr); -} - -static inline NSData *RoutingTableEntryAddress6(NSString *string) -{ - struct in6_addr addr; - if (inet_pton(AF_INET6, [string cStringUsingEncoding:NSASCIIStringEncoding], &addr) <= 0) { - return nil; - } - NSMutableData *data = [[NSMutableData alloc] initWithLength:16]; - memcpy(data.mutableBytes, (void *)&addr, data.length); - return data; -} - -static NSString *RoutingTableEntryName(struct sockaddr *sa, struct sockaddr *mask, int flags) -{ - char *cp = NULL; - switch (sa->sa_family) { - case AF_INET: { - struct sockaddr_in *sin = (struct sockaddr_in *)sa; - - if ((sin->sin_addr.s_addr == INADDR_ANY) && mask && (ntohl(((struct sockaddr_in *)mask)->sin_addr.s_addr) == 0L || mask->sa_len == 0)) { - cp = "default"; - } else if (flags & RTF_HOST) { - cp = routename(sin->sin_addr.s_addr); - } else if (mask) { - cp = netname(sin->sin_addr.s_addr, ntohl(((struct sockaddr_in *)mask)->sin_addr.s_addr)); - } else { - cp = netname(sin->sin_addr.s_addr, 0L); - } - break; - } - case AF_INET6: { - struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa; - struct in6_addr *in6 = &sa6->sin6_addr; - - /* - * XXX: This is a special workaround for KAME kernels. - * sin6_scope_id field of SA should be set in the future. - */ - if (IN6_IS_ADDR_LINKLOCAL(in6) || - IN6_IS_ADDR_MC_NODELOCAL(in6) || - IN6_IS_ADDR_MC_LINKLOCAL(in6)) { - - /* XXX: override is ok? */ - sa6->sin6_scope_id = (u_int32_t)ntohs(*(u_short *)&in6->s6_addr[2]); - *(u_short *)&in6->s6_addr[2] = 0; - } - - if (flags & RTF_HOST) { - cp = routename6(sa6); - } else if (mask) { - cp = netname6(sa6, mask); - } else { - cp = netname6(sa6, NULL); - } - break; - } - default: - break; - } - if (!cp) { - return nil; - } - return [NSString stringWithCString:cp encoding:NSASCIIStringEncoding]; -} - -char *routename(uint32_t in) -{ - static char line[MAXHOSTNAMELEN]; - -#define C(x) ((x) & 0xff) - in = ntohl(in); - ASSERT_PRINTF(snprintf(line, sizeof(line), "%u.%u.%u.%u", C(in >> 24), C(in >> 16), C(in >> 8), C(in))); - - return (line); -} - -char *routename6(struct sockaddr_in6 *sa6) -{ - static char line[MAXHOSTNAMELEN]; - int flag = NI_NUMERICHOST; - /* use local variable for safety */ - struct sockaddr_in6 sa6_local = {sizeof(sa6_local), AF_INET6, }; - - sa6_local.sin6_addr = sa6->sin6_addr; - sa6_local.sin6_scope_id = sa6->sin6_scope_id; - - ASSERT_GETNAMEINFO(getnameinfo((struct sockaddr *)&sa6_local, sa6_local.sin6_len, line, sizeof(line), NULL, 0, flag)); - - return line; -} -/* - * Return the name of the network whose address is given. - * The address is assumed to be that of a net or subnet, not a host. - */ -char *netname(uint32_t in, uint32_t mask) -{ - char *cp = 0; - static char line[MAXHOSTNAMELEN]; - struct netent *np = 0; - uint32_t net, omask, dmask; - uint32_t i; - - i = ntohl(in); - dmask = forgemask(i); - omask = mask; - // if (!nflag && i) { - if (i) { - net = i & dmask; - if (!(np = getnetbyaddr(i, AF_INET)) && net != i) - np = getnetbyaddr(net, AF_INET); - if (np) { - cp = np->n_name; - trimdomain(cp); - } - } - if (cp) { - strncpy(line, cp, sizeof(line) - 1); - } else { - switch (dmask) { - case IN_CLASSA_NET: - if ((i & IN_CLASSA_HOST) == 0) { - ASSERT_PRINTF(snprintf(line, sizeof(line), "%u", C(i >> 24))); - break; - } - /* FALLTHROUGH */ - case IN_CLASSB_NET: - if ((i & IN_CLASSB_HOST) == 0) { - ASSERT_PRINTF(snprintf(line, sizeof(line), "%u.%u", C(i >> 24), C(i >> 16))); - break; - } - /* FALLTHROUGH */ - case IN_CLASSC_NET: - if ((i & IN_CLASSC_HOST) == 0) { - ASSERT_PRINTF(snprintf(line, sizeof(line), "%u.%u.%u", C(i >> 24), C(i >> 16), C(i >> 8))); - break; - } - /* FALLTHROUGH */ - default: - ASSERT_PRINTF(snprintf(line, sizeof(line), "%u.%u.%u.%u", C(i >> 24), C(i >> 16), C(i >> 8), C(i))); - break; - } - } - domask(line + strlen(line), sizeof(line) - strlen(line), i, omask); - return (line); -} - - -char *netname6(struct sockaddr_in6 *sa6, struct sockaddr *sam) -{ - char host[MAXHOSTNAMELEN]; - static char line[MAXHOSTNAMELEN + 10]; - u_char *lim; - int masklen, illegal = 0, flag = NI_NUMERICHOST; - struct in6_addr *mask = sam ? &((struct sockaddr_in6 *)sam)->sin6_addr : 0; - - if (sam && sam->sa_len == 0) { - masklen = 0; - } else if (mask) { - u_char *p = (u_char *)mask; - for (masklen = 0, lim = p + 16; p < lim; p++) { - switch (*p) { - case 0xff: - masklen += 8; - break; - case 0xfe: - masklen += 7; - break; - case 0xfc: - masklen += 6; - break; - case 0xf8: - masklen += 5; - break; - case 0xf0: - masklen += 4; - break; - case 0xe0: - masklen += 3; - break; - case 0xc0: - masklen += 2; - break; - case 0x80: - masklen += 1; - break; - case 0x00: - break; - default: - illegal ++; - break; - } - } - if (illegal) - fprintf(stderr, "illegal prefixlen\n"); - } else { - masklen = 128; - } - if (masklen == 0 && IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr)) { - return("default"); - } - - ASSERT_GETNAMEINFO(getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, host, sizeof(host), NULL, 0, flag)); - - if (masklen > 0) { - ASSERT_PRINTF(sprintf(line, "%s/%u", host, masklen)); - } else { - ASSERT_PRINTF(sprintf(line, "%s", host)); - } - - return line; -} - -uint32_t forgemask(uint32_t a) -{ - uint32_t m; - - if (IN_CLASSA(a)) - m = IN_CLASSA_NET; - else if (IN_CLASSB(a)) - m = IN_CLASSB_NET; - else - m = IN_CLASSC_NET; - return (m); -} - -void domask(char *dst, size_t dstsize, uint32_t addr, uint32_t mask) -{ - int b, i; - - if (!mask || (forgemask(addr) == mask)) { - *dst = '\0'; - return; - } - i = 0; - for (b = 0; b < 32; b++) { - if (mask & (1 << b)) { - int bb; - - i = b; - for (bb = b+1; bb < 32; bb++) - if (!(mask & (1 << bb))) { - i = -1; /* noncontig */ - break; - } - break; - } - } - if (i == -1) { - ASSERT_PRINTF(snprintf(dst, dstsize, "&0x%x", mask)); - } else { - ASSERT_PRINTF(snprintf(dst, dstsize, "/%d", 32-i)); - } -} - -void trimdomain(char *cp) -{ - static char domain[MAXHOSTNAMELEN + 1]; - static int first = 1; - char *s; - - if (first) { - first = 0; - if (gethostname(domain, MAXHOSTNAMELEN) == 0 && - (s = strchr(domain, '.'))) - (void) strcpy(domain, s + 1); - else - domain[0] = 0; - } - - if (domain[0]) { - while ((cp = strchr(cp, '.'))) { - if (!strcasecmp(cp + 1, domain)) { - *cp = 0; /* hit it */ - break; - } else { - cp++; - } - } - } -} diff --git a/Sources/CTunnelKitCore/include/RoutingTable.h b/Sources/CTunnelKitCore/include/RoutingTable.h deleted file mode 100644 index 8509b8b..0000000 --- a/Sources/CTunnelKitCore/include/RoutingTable.h +++ /dev/null @@ -1,43 +0,0 @@ -// -// RoutingTable.h -// TunnelKit -// -// Created by Davide De Rosa on 4/30/19. -// Copyright (c) 2023 Davide De Rosa. All rights reserved. -// -// https://github.com/passepartoutvpn -// -// This file is part of TunnelKit. -// -// TunnelKit is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// TunnelKit is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with TunnelKit. If not, see . -// - -#import - -#import "RoutingTableEntry.h" - -NS_ASSUME_NONNULL_BEGIN - -@interface RoutingTable : NSObject - -- (NSArray *)ipv4; -- (NSArray *)ipv6; -- (nullable RoutingTableEntry *)defaultGateway4; -- (nullable RoutingTableEntry *)defaultGateway6; -- (nullable RoutingTableEntry *)broadestRoute4MatchingDestination:(NSString *)destination; -- (nullable RoutingTableEntry *)broadestRoute6MatchingDestination:(NSString *)destination; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Sources/CTunnelKitCore/include/RoutingTableEntry.h b/Sources/CTunnelKitCore/include/RoutingTableEntry.h deleted file mode 100644 index a55490e..0000000 --- a/Sources/CTunnelKitCore/include/RoutingTableEntry.h +++ /dev/null @@ -1,48 +0,0 @@ -// -// RoutingTableEntry.h -// TunnelKit -// -// Created by Davide De Rosa on 4/30/19. -// Copyright (c) 2023 Davide De Rosa. All rights reserved. -// -// https://github.com/passepartoutvpn -// -// This file is part of TunnelKit. -// -// TunnelKit is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// TunnelKit is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with TunnelKit. If not, see . -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface RoutingTableEntry : NSObject - -- (instancetype)initWithIPv4Network:(NSString *)network gateway:(nullable NSString *)gateway networkInterface:(NSString *)networkInterface; -- (instancetype)initWithIPv6Network:(NSString *)network gateway:(nullable NSString *)gateway networkInterface:(NSString *)networkInterface; - -- (BOOL)isIPv6; -- (NSString *)network; -- (NSInteger)prefix; -- (nullable NSString *)networkMask; // nil if IPv6 -- (nullable NSString *)gateway; -- (NSString *)networkInterface; - -- (BOOL)isDefault; -- (BOOL)matchesDestination:(NSString *)destination; -- (nullable NSArray *)partitioned; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Sources/CTunnelKitCore/include/route.h b/Sources/CTunnelKitCore/include/route.h deleted file mode 100644 index 49a4d46..0000000 --- a/Sources/CTunnelKitCore/include/route.h +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright (c) 2000-2017 Apple Inc. All rights reserved. - * - * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. The rights granted to you under the License - * may not be used to create, or enable the creation or redistribution of, - * unlawful or unlicensed copies of an Apple operating system, or to - * circumvent, violate, or enable the circumvention or violation of, any - * terms of an Apple operating system software license agreement. - * - * Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ - */ -/* - * Copyright (c) 1980, 1986, 1993 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)route.h 8.3 (Berkeley) 4/19/94 - * $FreeBSD: src/sys/net/route.h,v 1.36.2.1 2000/08/16 06:14:23 jayanth Exp $ - */ - -#ifndef _NET_ROUTE_H_ -#define _NET_ROUTE_H_ -#include -#include -#include -#include - -/* - * These numbers are used by reliable protocols for determining - * retransmission behavior and are included in the routing structure. - */ -struct rt_metrics { - u_int32_t rmx_locks; /* Kernel leaves these values alone */ - u_int32_t rmx_mtu; /* MTU for this path */ - u_int32_t rmx_hopcount; /* max hops expected */ - int32_t rmx_expire; /* lifetime for route, e.g. redirect */ - u_int32_t rmx_recvpipe; /* inbound delay-bandwidth product */ - u_int32_t rmx_sendpipe; /* outbound delay-bandwidth product */ - u_int32_t rmx_ssthresh; /* outbound gateway buffer limit */ - u_int32_t rmx_rtt; /* estimated round trip time */ - u_int32_t rmx_rttvar; /* estimated rtt variance */ - u_int32_t rmx_pksent; /* packets sent using this route */ - u_int32_t rmx_state; /* route state */ - u_int32_t rmx_filler[3]; /* will be used for T/TCP later */ -}; - -/* - * rmx_rtt and rmx_rttvar are stored as microseconds; - */ -#define RTM_RTTUNIT 1000000 /* units for rtt, rttvar, as units per sec */ - - - -#define RTF_UP 0x1 /* route usable */ -#define RTF_GATEWAY 0x2 /* destination is a gateway */ -#define RTF_HOST 0x4 /* host entry (net otherwise) */ -#define RTF_REJECT 0x8 /* host or net unreachable */ -#define RTF_DYNAMIC 0x10 /* created dynamically (by redirect) */ -#define RTF_MODIFIED 0x20 /* modified dynamically (by redirect) */ -#define RTF_DONE 0x40 /* message confirmed */ -#define RTF_DELCLONE 0x80 /* delete cloned route */ -#define RTF_CLONING 0x100 /* generate new routes on use */ -#define RTF_XRESOLVE 0x200 /* external daemon resolves name */ -#define RTF_LLINFO 0x400 /* DEPRECATED - exists ONLY for backward - * compatibility */ -#define RTF_LLDATA 0x400 /* used by apps to add/del L2 entries */ -#define RTF_STATIC 0x800 /* manually added */ -#define RTF_BLACKHOLE 0x1000 /* just discard pkts (during updates) */ -#define RTF_NOIFREF 0x2000 /* not eligible for RTF_IFREF */ -#define RTF_PROTO2 0x4000 /* protocol specific routing flag */ -#define RTF_PROTO1 0x8000 /* protocol specific routing flag */ - -#define RTF_PRCLONING 0x10000 /* protocol requires cloning */ -#define RTF_WASCLONED 0x20000 /* route generated through cloning */ -#define RTF_PROTO3 0x40000 /* protocol specific routing flag */ - /* 0x80000 unused */ -#define RTF_PINNED 0x100000 /* future use */ -#define RTF_LOCAL 0x200000 /* route represents a local address */ -#define RTF_BROADCAST 0x400000 /* route represents a bcast address */ -#define RTF_MULTICAST 0x800000 /* route represents a mcast address */ -#define RTF_IFSCOPE 0x1000000 /* has valid interface scope */ -#define RTF_CONDEMNED 0x2000000 /* defunct; no longer modifiable */ -#define RTF_IFREF 0x4000000 /* route holds a ref to interface */ -#define RTF_PROXY 0x8000000 /* proxying, no interface scope */ -#define RTF_ROUTER 0x10000000 /* host is a router */ -#define RTF_DEAD 0x20000000 /* Route entry is being freed */ - /* 0x40000000 and up unassigned */ - -#define RTPRF_OURS RTF_PROTO3 /* set on routes we manage */ -#define RTF_BITS \ - "\020\1UP\2GATEWAY\3HOST\4REJECT\5DYNAMIC\6MODIFIED\7DONE" \ - "\10DELCLONE\11CLONING\12XRESOLVE\13LLINFO\14STATIC\15BLACKHOLE" \ - "\16NOIFREF\17PROTO2\20PROTO1\21PRCLONING\22WASCLONED\23PROTO3" \ - "\25PINNED\26LOCAL\27BROADCAST\30MULTICAST\31IFSCOPE\32CONDEMNED" \ - "\33IFREF\34PROXY\35ROUTER" - -#define IS_DIRECT_HOSTROUTE(rt) \ - (((rt)->rt_flags & (RTF_HOST | RTF_GATEWAY)) == RTF_HOST) -/* - * Routing statistics. - */ -struct rtstat { - short rts_badredirect; /* bogus redirect calls */ - short rts_dynamic; /* routes created by redirects */ - short rts_newgateway; /* routes modified by redirects */ - short rts_unreach; /* lookups which failed */ - short rts_wildcard; /* lookups satisfied by a wildcard */ - short rts_badrtgwroute; /* route to gateway is not direct */ -}; - -/* - * Structures for routing messages. - */ -struct rt_msghdr { - u_short rtm_msglen; /* to skip over non-understood messages */ - u_char rtm_version; /* future binary compatibility */ - u_char rtm_type; /* message type */ - u_short rtm_index; /* index for associated ifp */ - int rtm_flags; /* flags, incl. kern & message, e.g. DONE */ - int rtm_addrs; /* bitmask identifying sockaddrs in msg */ - pid_t rtm_pid; /* identify sender */ - int rtm_seq; /* for sender to identify action */ - int rtm_errno; /* why failed */ - int rtm_use; /* from rtentry */ - u_int32_t rtm_inits; /* which metrics we are initializing */ - struct rt_metrics rtm_rmx; /* metrics themselves */ -}; - -struct rt_msghdr2 { - u_short rtm_msglen; /* to skip over non-understood messages */ - u_char rtm_version; /* future binary compatibility */ - u_char rtm_type; /* message type */ - u_short rtm_index; /* index for associated ifp */ - int rtm_flags; /* flags, incl. kern & message, e.g. DONE */ - int rtm_addrs; /* bitmask identifying sockaddrs in msg */ - int32_t rtm_refcnt; /* reference count */ - int rtm_parentflags; /* flags of the parent route */ - int rtm_reserved; /* reserved field set to 0 */ - int rtm_use; /* from rtentry */ - u_int32_t rtm_inits; /* which metrics we are initializing */ - struct rt_metrics rtm_rmx; /* metrics themselves */ -}; - - -#define RTM_VERSION 5 /* Up the ante and ignore older versions */ - -/* - * Message types. - */ -#define RTM_ADD 0x1 /* Add Route */ -#define RTM_DELETE 0x2 /* Delete Route */ -#define RTM_CHANGE 0x3 /* Change Metrics or flags */ -#define RTM_GET 0x4 /* Report Metrics */ -#define RTM_LOSING 0x5 /* RTM_LOSING is no longer generated by xnu - * and is deprecated */ -#define RTM_REDIRECT 0x6 /* Told to use different route */ -#define RTM_MISS 0x7 /* Lookup failed on this address */ -#define RTM_LOCK 0x8 /* fix specified metrics */ -#define RTM_OLDADD 0x9 /* caused by SIOCADDRT */ -#define RTM_OLDDEL 0xa /* caused by SIOCDELRT */ -#define RTM_RESOLVE 0xb /* req to resolve dst to LL addr */ -#define RTM_NEWADDR 0xc /* address being added to iface */ -#define RTM_DELADDR 0xd /* address being removed from iface */ -#define RTM_IFINFO 0xe /* iface going up/down etc. */ -#define RTM_NEWMADDR 0xf /* mcast group membership being added to if */ -#define RTM_DELMADDR 0x10 /* mcast group membership being deleted */ -#define RTM_IFINFO2 0x12 /* */ -#define RTM_NEWMADDR2 0x13 /* */ -#define RTM_GET2 0x14 /* */ - -/* - * Bitmask values for rtm_inits and rmx_locks. - */ -#define RTV_MTU 0x1 /* init or lock _mtu */ -#define RTV_HOPCOUNT 0x2 /* init or lock _hopcount */ -#define RTV_EXPIRE 0x4 /* init or lock _expire */ -#define RTV_RPIPE 0x8 /* init or lock _recvpipe */ -#define RTV_SPIPE 0x10 /* init or lock _sendpipe */ -#define RTV_SSTHRESH 0x20 /* init or lock _ssthresh */ -#define RTV_RTT 0x40 /* init or lock _rtt */ -#define RTV_RTTVAR 0x80 /* init or lock _rttvar */ - -/* - * Bitmask values for rtm_addrs. - */ -#define RTA_DST 0x1 /* destination sockaddr present */ -#define RTA_GATEWAY 0x2 /* gateway sockaddr present */ -#define RTA_NETMASK 0x4 /* netmask sockaddr present */ -#define RTA_GENMASK 0x8 /* cloning mask sockaddr present */ -#define RTA_IFP 0x10 /* interface name sockaddr present */ -#define RTA_IFA 0x20 /* interface addr sockaddr present */ -#define RTA_AUTHOR 0x40 /* sockaddr for author of redirect */ -#define RTA_BRD 0x80 /* for NEWADDR, broadcast or p-p dest addr */ - -/* - * Index offsets for sockaddr array for alternate internal encoding. - */ -#define RTAX_DST 0 /* destination sockaddr present */ -#define RTAX_GATEWAY 1 /* gateway sockaddr present */ -#define RTAX_NETMASK 2 /* netmask sockaddr present */ -#define RTAX_GENMASK 3 /* cloning mask sockaddr present */ -#define RTAX_IFP 4 /* interface name sockaddr present */ -#define RTAX_IFA 5 /* interface addr sockaddr present */ -#define RTAX_AUTHOR 6 /* sockaddr for author of redirect */ -#define RTAX_BRD 7 /* for NEWADDR, broadcast or p-p dest addr */ -#define RTAX_MAX 8 /* size of array to allocate */ - -struct rt_addrinfo { - int rti_addrs; - struct sockaddr *rti_info[RTAX_MAX]; -}; - - -#endif /* _NET_ROUTE_H_ */