// Name → addresses, the way Windows does it: the user's `Name2IP` mappings // first, then DNS, with each group filtered on its own by the two optional // filters (reverse-lookup validation and the same-subnet check). There is no // discovery in this protocol (`docs/protocol.md` §7). // // Ported from App/Class/SocketStuff.cs StartNewTcpClient (904-1046), // CheckForSameSubNet (1065-1107) and GetMyIPv4Addresses (1109-1127). // // Every call here blocks: `getaddrinfo` talks to the network. The channel // calls it from a resolver queue, never from its own serial queue. import Foundation import MWBCore /// Turns a machine name into the addresses to dial. public enum Resolver { /// The addresses to try for `name`, in the order Windows tries them: /// the `Name2IP` mappings first, then whatever DNS returns, with /// duplicates removed (`SocketStuff.cs:904-1046`). /// /// The two groups are **filtered separately**, which is the control flow /// `StartNewTcpClient` has: the mapped addresses get their own same-subnet /// check and, when it fails, Windows `return`s before `Dns.GetHostEntry` is /// ever called, so that name is not dialled at all this round /// (`:928-944, 950`); the DNS group is filtered by the reverse lookup and /// then gets its own same-subnet check, which on failure drops only the DNS /// addresses (`:989-1044`). Reverse-lookup validation never applies to a /// user-supplied mapping. /// /// Returns an empty array when nothing resolves or when every group was /// rejected — Windows returning from `StartNewTcpClient` without starting a /// socket. public static func addresses(for name: String, config: ChannelConfig) -> [String] { let mapped = mappedAddresses(for: name, in: config.name2IP) if !mapped.isEmpty, config.sameSubnetOnly, !isSameSubnet(mapped) { return [] // `:934-937` — the early return that also skips DNS. } var resolved = lookup(name).filter { !mapped.contains($0) } if config.validateRemoteIP { resolved = resolved.filter { validates(address: $0, as: name) } } if !resolved.isEmpty, config.sameSubnetOnly, !isSameSubnet(resolved) { resolved = [] // `:1037-1040` — drops this group only. } return mapped + resolved } /// The `Name2IP` addresses mapped to `name`. /// /// The setting is CRLF-separated lines of `" "` split on blanks, /// matched case-insensitively, with anything past the second field ignored /// (`SocketStuff.cs:908-925, 1258-1259`). public static func mappedAddresses(for name: String, in name2IP: String) -> [String] { var out: [String] = [] for line in name2IP.components(separatedBy: .newlines) { let fields = line.split(separator: " ", omittingEmptySubsequences: true) guard fields.count >= 2 else { continue } guard fields[0].trimmingCharacters(in: .whitespaces) .caseInsensitiveCompare(name) == .orderedSame else { continue } let ip = fields[1].trimmingCharacters(in: .whitespaces) guard isNumericAddress(ip), !out.contains(ip) else { continue } out.append(ip) } return out } /// Every IPv4 and IPv6 address DNS has for `name` (`Dns.GetHostEntry`, /// `SocketStuff.cs:950, 976-988`). Empty when the name does not resolve. public static func lookup(_ name: String) -> [String] { var hints = addrinfo() hints.ai_family = AF_UNSPEC hints.ai_socktype = SOCK_STREAM hints.ai_protocol = IPPROTO_TCP var list: UnsafeMutablePointer? guard getaddrinfo(name, nil, &hints, &list) == 0, let head = list else { return [] } defer { freeaddrinfo(head) } var out: [String] = [] var node: UnsafeMutablePointer? = head while let current = node { let info = current.pointee if let text = presentation(of: info.ai_addr, length: info.ai_addrlen), !out.contains(text) { out.append(text) } node = info.ai_next } return out } /// The name reverse DNS gives `address`, with no domain part stripped. /// `nil` when there is no PTR record (`Dns.GetHostEntry(ip).HostName`, /// `SocketStuff.cs:1002`). public static func reverseName(for address: String) -> String? { withSockaddr(address) { pointer, length in var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST)) guard getnameinfo( pointer, length, &buffer, socklen_t(buffer.count), nil, 0, NI_NAMEREQD) == 0 else { return nil } return string(from: buffer) } } /// The short name for an address, for labelling an inbound connection /// before its `HandshakeAck` arrives: reverse DNS with the domain part /// removed, falling back to the address itself /// (`GetMachineNameFromSocket`, `SocketStuff.cs:733-762`). public static func shortName(for address: String) -> String { guard let full = reverseName(for: address), !full.isEmpty else { return address } guard let dot = full.firstIndex(of: "."), dot > full.startIndex else { return full } return String(full[full.startIndex.. Bool { guard let host = reverseName(for: address) else { return false } if host.caseInsensitiveCompare(address) == .orderedSame { return true } return host.lowercased().hasPrefix(name.lowercased()) } /// Whether any of `addresses` is on one of our own IPv4 networks. /// /// "Same network" is the first two octets only, and the check passes when /// either side has no IPv4 address at all — Windows only filters when it /// can compare (`SocketStuff.cs:1065-1107`). static func isSameSubnet(_ addresses: [String]) -> Bool { let remote = addresses.compactMap(ipv4Octets) guard !remote.isEmpty else { return true } let local = localIPv4Addresses().compactMap(ipv4Octets) guard !local.isEmpty else { return true } for mine in local where remote.contains(where: { $0[0] == mine[0] && $0[1] == mine[1] }) { return true } return false } /// This machine's IPv4 addresses on interfaces that are up and not /// loopback (`GetMyIPv4Addresses`, `SocketStuff.cs:1109-1127`). static func localIPv4Addresses() -> [String] { var list: UnsafeMutablePointer? guard getifaddrs(&list) == 0, let head = list else { return [] } defer { freeifaddrs(head) } var out: [String] = [] var node: UnsafeMutablePointer? = head while let current = node { let interface = current.pointee node = interface.ifa_next let flags = Int32(interface.ifa_flags) guard flags & IFF_UP != 0, flags & IFF_LOOPBACK == 0 else { continue } guard let address = interface.ifa_addr, address.pointee.sa_family == UInt8(AF_INET) else { continue } if let text = presentation( of: address, length: socklen_t(MemoryLayout.size)), !out.contains(text) { out.append(text) } } return out } // MARK: - Small C helpers, wrapped once /// The four octets of a dotted-quad address, or `nil` if it is not IPv4. static func ipv4Octets(_ text: String) -> [UInt8]? { let parts = text.split(separator: ".", omittingEmptySubsequences: false) guard parts.count == 4 else { return nil } var octets: [UInt8] = [] for part in parts { guard let value = UInt8(part) else { return nil } octets.append(value) } return octets } /// Whether `text` is already a numeric address, so it needs no lookup. static func isNumericAddress(_ text: String) -> Bool { withSockaddr(text) { _, _ in true } ?? false } /// Runs `body` with a `sockaddr` parsed from a numeric address string. /// Returns `nil` when the text is not an address. private static func withSockaddr( _ text: String, _ body: (UnsafeMutablePointer, socklen_t) -> T? ) -> T? { var hints = addrinfo() hints.ai_family = AF_UNSPEC hints.ai_socktype = SOCK_STREAM hints.ai_flags = AI_NUMERICHOST var list: UnsafeMutablePointer? guard getaddrinfo(text, nil, &hints, &list) == 0, let head = list else { return nil } defer { freeaddrinfo(head) } guard let address = head.pointee.ai_addr else { return nil } return body(address, head.pointee.ai_addrlen) } /// The numeric text of a `sockaddr` (`NI_NUMERICHOST`), including the /// `%interface` suffix IPv6 link-local addresses need. private static func presentation( of address: UnsafeMutablePointer?, length: socklen_t ) -> String? { guard let address else { return nil } var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST)) guard getnameinfo(address, length, &buffer, socklen_t(buffer.count), nil, 0, NI_NUMERICHOST) == 0 else { return nil } return string(from: buffer) } private static func string(from buffer: [CChar]) -> String? { buffer.withUnsafeBufferPointer { pointer in guard let base = pointer.baseAddress else { return nil } return String(validatingCString: base) } } }