// SPDX-License-Identifier: GPL-3.0-or-later import Foundation import Darwin /// One request per connection. Peers cannot hold the main thread or the emulator queue. final class MCPTransport { typealias Handler = @Sendable (Data) async -> Data let unixPath: String let port: UInt16 private let directory: URL private let queue = DispatchQueue(label: "vcc.mcp.accept") private let slots = DispatchSemaphore(value: 8) private var listeners: [DispatchSourceRead] = [] private static func checked(_ rc: Int32) throws -> Int32 { guard rc >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } return rc } init(handler: @escaping Handler) throws { directory = URL(fileURLWithPath: "/private/tmp/vcc-mcp-" + UUID().uuidString) unixPath = directory.appendingPathComponent("host.sock").path try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) var sockets: [Int32] = [] do { let uds = try Self.checked(socket(AF_UNIX, SOCK_STREAM, 0)) sockets.append(uds) var un = sockaddr_un() un.sun_family = sa_family_t(AF_UNIX) let path = Array(unixPath.utf8CString) guard path.count <= MemoryLayout.size(ofValue: un.sun_path) else { throw POSIXError(.ENAMETOOLONG) } withUnsafeMutableBytes(of: &un.sun_path) { dest in path.withUnsafeBytes { dest.copyBytes(from: $0) } } un.sun_len = UInt8(MemoryLayout.size) try Self.bindSocket(uds, &un) let tcp = try Self.checked(socket(AF_INET, SOCK_STREAM, 0)) sockets.append(tcp) var addr = sockaddr_in() addr.sin_family = sa_family_t(AF_INET) addr.sin_len = UInt8(MemoryLayout.size) addr.sin_addr.s_addr = inet_addr("127.0.0.1") try Self.bindSocket(tcp, &addr) var size = socklen_t(MemoryLayout.size) _ = try Self.checked(withUnsafeMutablePointer(to: &addr) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(tcp, $0, &size) } }) port = UInt16(bigEndian: addr.sin_port) for fd in sockets { _ = try Self.checked(fcntl(fd, F_SETFL, O_NONBLOCK)) _ = try Self.checked(fcntl(fd, F_SETFD, FD_CLOEXEC)) _ = try Self.checked(listen(fd, 8)) } for fd in sockets { let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: queue) source.setEventHandler { [slots] in let peer = accept(fd, nil, nil) guard peer >= 0 else { return } guard slots.wait(timeout: .now()) == .success else { close(peer); return } // Spawn a bounded worker; synchronous socket IO never runs on Swift's executor. DispatchQueue.global(qos: .utility).async { func finish() { close(peer); slots.signal() } if fd == uds { var uid: uid_t = 0, gid: gid_t = 0 guard getpeereid(peer, &uid, &gid) == 0, uid == geteuid() else { finish(); return } } var yes: Int32 = 1 var timeout = timeval(tv_sec: 3, tv_usec: 0) guard fcntl(peer, F_SETFD, FD_CLOEXEC) == 0, fcntl(peer, F_SETFL, 0) == 0, setsockopt(peer, SOL_SOCKET, SO_NOSIGPIPE, &yes, socklen_t(MemoryLayout.size(ofValue: yes))) == 0, setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) == 0, setsockopt(peer, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) == 0, let request = Self.readLine(peer) else { finish(); return } Task { let response = await handler(request) DispatchQueue.global(qos: .utility).async { Self.writeResponse(response, to: peer) finish() } } } } source.setCancelHandler { close(fd) } listeners.append(source) source.resume() } } catch { for fd in sockets { close(fd) } try? FileManager.default.removeItem(at: directory) throw error } } private static func bindSocket(_ fd: Int32, _ addr: inout T) throws { _ = try checked(withUnsafePointer(to: &addr) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, socklen_t(MemoryLayout.size)) } }) } private static func readLine(_ fd: Int32) -> Data? { let deadline = DispatchTime.now() + .seconds(5) let limit = 48 * 1024 var data = Data(), buffer = [UInt8](repeating: 0, count: 1024) while data.count < limit && DispatchTime.now() < deadline { let size = recv(fd, &buffer, min(limit - data.count, buffer.count), 0) guard size > 0 else { return nil } let bytes = buffer.prefix(size) if let lf = bytes.firstIndex(of: 10) { data.append(contentsOf: bytes[.. 0 else { return } offset += n } } } func stop() { for listener in listeners { listener.cancel() } listeners.removeAll() try? FileManager.default.removeItem(at: directory) } deinit { stop() } }