Files
ucvl-zonghengjia-open-source/ios/App/InternalIPProbe.swift
T

76 lines
3.1 KiB
Swift

import Darwin
import Foundation
enum InternalIPProbe {
static func isReachable(_ address: String, port: Int) async -> Bool {
guard NetworkAddress.isAuthorizedInternalIPv4(address), (1...65535).contains(port), !Task.isCancelled else { return false }
let attempt = EndpointAttempt()
return await withTaskCancellationHandler(operation: {
await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .utility).async {
continuation.resume(returning: attempt.run(address, port: UInt16(port)))
}
}
}, onCancel: { attempt.cancel() })
}
}
private final class EndpointAttempt: @unchecked Sendable {
private let lock = NSLock()
private var cancelled = false
func cancel() {
lock.lock()
cancelled = true
lock.unlock()
}
private var isCancelled: Bool {
lock.lock()
defer { lock.unlock() }
return cancelled
}
func run(_ address: String, port: UInt16) -> Bool {
let deadline = DispatchTime.now().uptimeNanoseconds + 5_000_000_000
guard !isCancelled else { return false }
// Connect to the exact authorized endpoint using the system route.
let descriptor = Darwin.socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
guard descriptor >= 0 else { return false }
defer { Darwin.close(descriptor) }
let flags = fcntl(descriptor, F_GETFL, 0)
guard flags >= 0, fcntl(descriptor, F_SETFL, flags | O_NONBLOCK) == 0 else { return false }
var destination = sockaddr_in()
destination.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
destination.sin_family = sa_family_t(AF_INET)
destination.sin_port = port.bigEndian
guard address.withCString({ inet_pton(AF_INET, $0, &destination.sin_addr) }) == 1 else { return false }
let connected = withUnsafePointer(to: &destination) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
Darwin.connect(descriptor, $0, socklen_t(MemoryLayout<sockaddr_in>.size))
}
}
if connected == 0 { return !isCancelled }
guard errno == EINPROGRESS || errno == EINTR else { return false }
var descriptorState = pollfd(fd: descriptor, events: Int16(POLLOUT), revents: 0)
while !isCancelled {
let now = DispatchTime.now().uptimeNanoseconds
guard now < deadline else { return false }
let waitMS = Int32(min(50, max(1, (deadline - now) / 1_000_000)))
let ready = Darwin.poll(&descriptorState, 1, waitMS)
if ready < 0 {
if errno == EINTR { continue }
return false
}
guard ready > 0 else { continue }
var socketError: Int32 = 0
var size = socklen_t(MemoryLayout<Int32>.size)
return descriptorState.revents & Int16(POLLOUT) != 0
&& getsockopt(descriptor, SOL_SOCKET, SO_ERROR, &socketError, &size) == 0
&& socketError == 0 && !isCancelled && DispatchTime.now().uptimeNanoseconds < deadline
}
return false
}
}