import Darwin import Dispatch import Foundation import OSLog public actor IPCServer { public let socketPath: String public var clientCount: Int { clients.count } public var subscriberCount: Int { subscribers.count } private let handler: any IPCHandler private let serverVersion: String private let onError: @Sendable (any Error) -> Void private var listener: Int32? private var lock: Int32? private var socketIdentity: SocketIdentity? private var source: (any DispatchSourceRead)? private var generation = UUID() private var stopping = false private var clients: [UUID: Client] = [:] private var subscribers: [UUID: Subscriber] = [:] public init( handler: any IPCHandler, socketPath: String? = nil, serverVersion: String = "0.1.0", onError: (@Sendable (any Error) -> Void)? = nil ) throws { self.handler = handler self.socketPath = try socketPath ?? IPCSocketPath.resolve() _ = try SocketAddress(self.socketPath) self.serverVersion = serverVersion self.onError = onError ?? { error in Logger(subsystem: "com.parcel.ipc", category: "server").error( "\(error.localizedDescription, privacy: .public)") } } deinit { source?.cancel() if let listener { Darwin.close(listener) } if let socketIdentity { socketIdentity.removeIfOwned(path: socketPath) } if let lock { Darwin.close(lock) } } public func start() throws { guard listener == nil, !stopping else { throw IPCTransportError.alreadyRunning(socketPath) } let lock = try acquireLock() var descriptor: Int32? var boundIdentity: SocketIdentity? do { try removeStaleSocket() let fd = try makeSocket() descriptor = fd var address = try SocketAddress(socketPath) guard address.withPointer({ Darwin.bind(fd, $0, $1) }) == 0 else { throw IPCTransportError.system(operation: "bind", code: errno) } boundIdentity = try SocketIdentity.read(path: socketPath) guard chmod(socketPath, S_IRUSR | S_IWUSR) == 0 else { throw IPCTransportError.system(operation: "chmod", code: errno) } guard Darwin.listen(fd, 128) == 0 else { throw IPCTransportError.system(operation: "listen", code: errno) } listener = fd self.lock = lock socketIdentity = boundIdentity generation = UUID() let generation = generation let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: .global()) self.source = source source.setEventHandler { @Sendable [weak self] in Task { [weak self] in await self?.acceptClients(generation: generation) } } source.resume() } catch { if let descriptor { Darwin.close(descriptor) } boundIdentity?.removeIfOwned(path: socketPath) Darwin.close(lock) throw error } } public func stop() async throws { guard !stopping else { throw IPCTransportError.operationInProgress } stopping = true defer { stopping = false } generation = UUID() source?.cancel() source = nil if let listener { Darwin.close(listener) } listener = nil let clients = Array(clients.values) self.clients.removeAll() for subscriber in subscribers.values { subscriber.continuation.finish() } subscribers.removeAll() for client in clients { client.task.cancel() await client.channel.close() } for client in clients { await client.task.value } var cleanupError: (any Error)? do { try socketIdentity?.remove(path: socketPath) } catch { cleanupError = error } socketIdentity = nil if let lock { Darwin.close(lock) } lock = nil if let cleanupError { throw cleanupError } } public func publish(_ event: IPCEvent) throws { guard event.v == IPCProtocol.version else { throw unsupportedVersion(event.v) } _ = try IPCCodec.encode(event) var finished: [UUID] = [] for (id, subscriber) in subscribers where subscriber.topics.contains(event.topic) { switch subscriber.continuation.yield(event) { case .enqueued: break case .dropped: subscriber.continuation.finish( throwing: IPCError( code: "slow_subscriber", message: String( localized: "The event consumer fell behind. Reconnect and query the current state.", bundle: .module) )) finished.append(id) case .terminated: finished.append(id) @unknown default: preconditionFailure("Unknown stream yield result") } } for id in finished { subscribers.removeValue(forKey: id) } } private func acquireLock() throws -> Int32 { let path = socketPath + ".lock" let fd = Darwin.open(path, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK, S_IRUSR | S_IWUSR) guard fd >= 0 else { throw IPCTransportError.system(operation: "open lock", code: errno) } do { var info = stat() guard fstat(fd, &info) == 0 else { throw IPCTransportError.system(operation: "fstat lock", code: errno) } guard info.st_uid == getuid(), info.st_mode & S_IFMT == S_IFREG, info.st_nlink == 1 else { throw IPCTransportError.unsafeExistingPath(path) } guard flock(fd, LOCK_EX | LOCK_NB) == 0 else { if errno == EWOULDBLOCK { throw IPCTransportError.alreadyRunning(socketPath) } throw IPCTransportError.system(operation: "flock", code: errno) } guard fchmod(fd, S_IRUSR | S_IWUSR) == 0 else { throw IPCTransportError.system(operation: "chmod lock", code: errno) } return fd } catch { Darwin.close(fd) throw error } } private func removeStaleSocket() throws { guard let identity = try SocketIdentity.read(path: socketPath) else { return } let probe = try makeSocket() defer { Darwin.close(probe) } var address = try SocketAddress(socketPath) let result = address.withPointer { Darwin.connect(probe, $0, $1) } if result == 0 || errno == EINPROGRESS || errno == EAGAIN { throw IPCTransportError.alreadyRunning(socketPath) } guard errno == ECONNREFUSED || errno == ENOENT else { throw IPCTransportError.system(operation: "probe", code: errno) } try identity.remove(path: socketPath) } private func acceptClients(generation: UUID) async { guard self.generation == generation, let listener else { return } while self.generation == generation { let fd = Darwin.accept(listener, nil, nil) if fd < 0 { if errno == EINTR { continue } if errno != EAGAIN && errno != EWOULDBLOCK { onError(IPCTransportError.system(operation: "accept", code: errno)) } return } do { try configureSocket(fd) var uid: uid_t = 0 var gid: gid_t = 0 guard getpeereid(fd, &uid, &gid) == 0 else { throw IPCTransportError.system(operation: "getpeereid", code: errno) } guard uid == getuid() else { throw IPCTransportError.unsafeExistingPath(socketPath) } let id = UUID() let channel = SocketChannel(descriptor: fd) let task = Task { await serve(id: id, channel: channel) } clients[id] = Client(channel: channel, task: task) } catch { Darwin.close(fd) onError(error) } } } private func serve(id: UUID, channel: SocketChannel) async { do { while let line = try await channel.readLine() { let request: IPCRequest do { request = try IPCCodec.decode(IPCRequest.self, from: line) } catch { let envelope: RequestEnvelope? do { envelope = try JSONDecoder().decode(RequestEnvelope.self, from: line) } catch { envelope = nil } let failure: IPCError if let version = envelope?.v, version != IPCProtocol.version { failure = unsupportedVersion(version) } else { failure = IPCError( code: "invalid_request", message: String( localized: "Expected a JSON request with v, id, command, and string args.", bundle: .module) ) } let response = IPCResponse(id: envelope?.id, error: failure) try await channel.write(IPCCodec.encode(response)) continue } guard request.v == IPCProtocol.version else { try await channel.write( IPCCodec.encode(IPCResponse(id: request.id, error: unsupportedVersion(request.v)))) continue } if request.command == "subscribe" { do { try await stream(request: request, id: id, channel: channel) } catch let error as IPCError { try await channel.write(IPCCodec.encode(IPCResponse(id: request.id, error: error))) } break } let response: IPCResponse do { response = IPCResponse(id: request.id, result: try await execute(request)) } catch { response = IPCResponse(id: request.id, error: handlerError(error)) } try await channel.write(IPCCodec.encode(response)) await handler.responseDidSend(request: request, response: response) } } catch { if !Task.isCancelled { onError(error) } } subscribers.removeValue(forKey: id)?.continuation.finish() clients.removeValue(forKey: id) await channel.close() } private func execute(_ request: IPCRequest) async throws -> JSONValue { switch request.command { case "ping": try requireNoArguments(request) return .string("pong") case "version": try requireNoArguments(request) return .object(["protocol": .integer(Int64(IPCProtocol.version)), "version": .string(serverVersion)]) case "query": guard request.args.count == 1, let argument = request.args.first, let query = IPCQuery(rawValue: argument) else { throw invalidArguments() } return try await handler.query(query) case "why": guard request.args.count == 1, let argument = request.args.first, let window = IPCProtocol.parseWindowID(argument) else { throw invalidArguments() } return try await handler.why(window: window) case "run": guard let command = request.args.first, !command.isEmpty else { throw invalidArguments() } return try await handler.run(command: command, args: Array(request.args.dropFirst())) case "setup-save", "setup-open", "setup-delete": guard request.args.count == 1 || (request.command == "setup-save" && request.args.count == 2 && request.args[1] == "no-hide"), let name = request.args.first, !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw invalidArguments() } return try await handler.run(command: request.command, args: request.args) case "reload-config": try requireNoArguments(request) return try await handler.reloadConfig() case "diagnostics": try requireNoArguments(request) return try IPCCodec.decode(JSONValue.self, from: IPCCodec.encode(await handler.diagnostics())) default: throw IPCError( code: "unknown_command", message: String(localized: "Unknown IPC command: \(request.command)", bundle: .module)) } } private func stream(request: IPCRequest, id: UUID, channel: SocketChannel) async throws { var topics = Set() for argument in request.args { guard let topic = IPCTopic(rawValue: argument) else { throw invalidArguments() } topics.insert(topic) } if topics.isEmpty { topics = Set(IPCTopic.allCases) } let (events, continuation) = AsyncThrowingStream.makeStream( bufferingPolicy: .bufferingOldest(128)) subscribers[id] = Subscriber(topics: topics, continuation: continuation) defer { subscribers.removeValue(forKey: id)?.continuation.finish() } try await channel.write( IPCCodec.encode( IPCResponse( id: request.id, result: .object(["topics": .array(topics.map(\.rawValue).sorted().map(JSONValue.string))]) ))) try await withThrowingTaskGroup(of: Void.self) { group in group.addTask { while (try await channel.readLine()) != nil { throw IPCError( code: "subscription_only", message: String(localized: "A subscribed connection only receives events.", bundle: .module)) } } group.addTask { do { for try await event in events { try await channel.write(IPCCodec.encode(event)) } } catch let error as IPCError { try await channel.write(IPCCodec.encode(IPCResponse(id: request.id, error: error))) } } defer { group.cancelAll() } _ = try await group.next() } } private func requireNoArguments(_ request: IPCRequest) throws { guard request.args.isEmpty else { throw invalidArguments() } } private func invalidArguments() -> IPCError { IPCError( code: "invalid_arguments", message: String(localized: "The command arguments are missing or invalid.", bundle: .module)) } private func unsupportedVersion(_ version: Int) -> IPCError { IPCError( code: "unsupported_version", message: String( localized: "Unsupported protocol version \(version). This server supports v=1.", bundle: .module)) } private func handlerError(_ error: any Error) -> IPCError { if let error = error as? IPCError { return error } return IPCError(code: "handler_error", message: error.localizedDescription) } private struct Client { let channel: SocketChannel let task: Task } private struct Subscriber { let topics: Set let continuation: AsyncThrowingStream.Continuation } private struct RequestEnvelope: Decodable { // pi-lens-ignore: identifier_name let v: Int? let id: IPCRequestID? } } private struct SocketIdentity { let device: dev_t let inode: ino_t static func read(path: String) throws -> Self? { var info = stat() guard lstat(path, &info) == 0 else { if errno == ENOENT { return nil } throw IPCTransportError.system(operation: "lstat", code: errno) } guard info.st_uid == getuid(), info.st_mode & S_IFMT == S_IFSOCK else { throw IPCTransportError.unsafeExistingPath(path) } return Self(device: info.st_dev, inode: info.st_ino) } func remove(path: String) throws { guard let current = try Self.read(path: path), current.device == device, current.inode == inode else { return } guard unlink(path) == 0 || errno == ENOENT else { throw IPCTransportError.system(operation: "unlink", code: errno) } } func removeIfOwned(path: String) { do { try remove(path: path) } catch { Logger(subsystem: "com.parcel.ipc", category: "cleanup").error( "\(error.localizedDescription, privacy: .public)") } } }