Cotton code
83 lines · 4.2 KB · SwiftRaw
// Where a link may make this phone knock (FEEDBACK-4 B4, chat CONTRACT.md "Link previews"): http or https, to a host// whose every address is public; never this phone, its network or a private address. ChatLinkFetch asks it of the// first hop and of every redirect; the core refuses such links before the phone is offered them.#if os(iOS)import Darwinimport Foundationenum ChatLinkAddress {    /// Whether `url` may be asked: http or https, to a host whose every address is public.    static func mayAsk(_ url: URL?) -> Bool {        guard let url, let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https",              let host = url.host(percentEncoded: false), !host.isEmpty else { return false }        return isPublic(host: host)    }    /// Whether `host` (a name or an address) is somewhere a link may make this phone knock: never this phone, its    /// network or a private address (localhost, 10/8, 172.16/12, 192.168/16, 169.254/16, 100.64/10, ::1, fc00::/7,    /// fe80::/10), by every address a name has. A name that has none is not asked.    static func isPublic(host: String) -> Bool {        let name = host.trimmingCharacters(in: CharacterSet(charactersIn: "[]")).lowercased()        if let address = literal(name) { return !isPrivate(address) }        let bare = name.hasSuffix(".") ? String(name.dropLast()) : name        if bare.isEmpty || bare == "localhost" || bare.hasSuffix(".localhost") || bare.hasSuffix(".local") || bare.hasSuffix(".internal")            || !bare.contains(".") {            return false        }        guard let all = addresses(bare), !all.isEmpty else { return false }        return !all.contains(where: isPrivate)    }    /// An address's bytes: 4 for IPv4, 16 for IPv6.    static func isPrivate(_ bytes: [UInt8]) -> Bool {        if bytes.count == 4 {            let (a, b) = (bytes[0], bytes[1])            return a == 0 || a == 10 || a == 127 || (a == 169 && b == 254) || (a == 172 && (b & 0xF0) == 16) || (a == 192 && b == 168)                || (a == 100 && (b & 0xC0) == 64) || a >= 224        }        guard bytes.count == 16 else { return true }        if bytes[0..<10].allSatisfy({ $0 == 0 }) && bytes[10] == 0xFF && bytes[11] == 0xFF { return isPrivate(Array(bytes[12..<16])) }        if bytes[0..<15].allSatisfy({ $0 == 0 }) { return true }        return (bytes[0] & 0xFE) == 0xFC || (bytes[0] == 0xFE && (bytes[1] & 0xC0) == 0x80) || bytes[0] == 0xFF    }    /// `text` read as an address, when it is one.    static func literal(_ text: String) -> [UInt8]? {        var four = in_addr()        if inet_pton(AF_INET, text, &four) == 1 { return withUnsafeBytes(of: &four) { Array($0) } }        var six = in6_addr()        if inet_pton(AF_INET6, text, &six) == 1 { return withUnsafeBytes(of: &six) { Array($0) } }        return nil    }    /// Every address `name` has, or nil when it has none.    private static func addresses(_ name: String) -> [[UInt8]]? {        #if COTTON_DEV        // Chat Dev's seed: its invented pages' names have invented addresses, never asked of the network.        if ChatWarmSeed.asked, let seeded = ChatWarmLinks.addresses(name) { return seeded.compactMap(literal) }        #endif        var hints = addrinfo()        hints.ai_family = AF_UNSPEC        hints.ai_socktype = SOCK_STREAM        var found: UnsafeMutablePointer<addrinfo>?        guard getaddrinfo(name, nil, &hints, &found) == 0, let first = found else { return nil }        defer { freeaddrinfo(first) }        var out: [[UInt8]] = []        var at: UnsafeMutablePointer<addrinfo>? = first        while let one = at {            if let address = one.pointee.ai_addr {                switch Int32(address.pointee.sa_family) {                case AF_INET:                    out.append(address.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { p in withUnsafeBytes(of: p.pointee.sin_addr) { Array($0) } })                case AF_INET6:                    out.append(address.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { p in withUnsafeBytes(of: p.pointee.sin6_addr) { Array($0) } })                default: break                }            }            at = one.pointee.ai_next        }        return out    }}#endif