Files
Kymo/kymoTests/NetworkAddressChecks.swift
T

44 lines
2.3 KiB
Swift

import Foundation
import Darwin
@main struct NetworkAddressChecks {
static func main() {
var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
func check(_ address: UnsafePointer<sockaddr>) {
var original = [CChar](repeating: 0, count: Int(NI_MAXHOST))
let rc = getnameinfo(address, socklen_t(address.pointee.sa_len), &original, socklen_t(original.count), nil, 0, NI_NUMERICHOST)
let expected = rc == 0 ? String(cString: original) : nil
let value = NetworkMonitor.numericAddress(address, buffer: &buffer)
precondition(value == expected, "Canonical numeric address / scope changed")
}
let loop = if_nametoindex("lo0")
var v4 = sockaddr_in(); v4.sin_len = UInt8(MemoryLayout.size(ofValue: v4)); v4.sin_family = UInt8(AF_INET)
precondition(inet_pton(AF_INET, "192.0.2.1", &v4.sin_addr) == 1)
withUnsafePointer(to: &v4) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { check($0) } }
for text in ["::1", "2001:db8::1", "::ffff:192.0.2.1", "fe80::1"] {
var v6 = sockaddr_in6(); v6.sin6_len = UInt8(MemoryLayout.size(ofValue: v6)); v6.sin6_family = UInt8(AF_INET6)
precondition(inet_pton(AF_INET6, text, &v6.sin6_addr) == 1)
for scope in [UInt32(0), loop, UInt32.max] {
v6.sin6_scope_id = scope
withUnsafePointer(to: &v6) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
check($0)
var empty: [CChar] = []
precondition(NetworkMonitor.numericAddress($0, buffer: &empty) == nil)
} }
}
}
var head: UnsafeMutablePointer<ifaddrs>?
precondition(getifaddrs(&head) == 0)
defer { freeifaddrs(head) }
var cursor = head, count = 0
while let entry = cursor {
defer { cursor = entry.pointee.ifa_next }
guard let address = entry.pointee.ifa_addr, [UInt8(AF_INET), UInt8(AF_INET6)].contains(address.pointee.sa_family) else { continue }
check(UnsafePointer(address))
count += 1
}
precondition(count > 0)
print("PASS: sandbox IPv4/IPv6, known/unknown scopes, mapped addresses, empty buffer and canonical equivalence for", count, "live addresses (values omitted)")
}
}