Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279public import Darwinimport Dispatchpublic import Foundation
public enum IPCTransportError: Error, Sendable, Equatable, LocalizedError { case invalidPath(String) case system(operation: String, code: Int32) case alreadyRunning(String) case unsafeExistingPath(String) case notRunning(String) case closed case truncatedMessage case messageTooLarge case operationInProgress case protocolViolation(String)
public var errorDescription: String? { switch self { case .invalidPath(let path): String(localized: "The socket path is empty, relative, or too long: \(path)", bundle: .module) case .system(let operation, let code): String( localized: "Socket operation \(operation) failed (\(code)): \(String(cString: strerror(code)))", bundle: .module) case .alreadyRunning(let path): String(localized: "Another Parcel server already owns \(path).", bundle: .module) case .unsafeExistingPath(let path): String( localized: "Refusing to replace a file, link, or socket owned by another user at \(path).", bundle: .module) case .notRunning(let path): String( localized: "Parcel isn't running. Open the Parcel app and try again. Socket: \(path)", bundle: .module ) case .closed: String(localized: "The Parcel connection closed.", bundle: .module) case .truncatedMessage: String(localized: "The connection ended before a complete JSON message arrived.", bundle: .module) case .messageTooLarge: String(localized: "The JSON message exceeds the 1 MiB limit.", bundle: .module) case .operationInProgress: String(localized: "Another operation is already using this connection.", bundle: .module) case .protocolViolation(let detail): String(localized: "Invalid Parcel response: \(detail)", bundle: .module) } }}
public enum IPCSocketPath { public static func resolve( environment: [String: String] = ProcessInfo.processInfo.environment, uid: UInt32 = getuid(), temporaryDirectory: String = NSTemporaryDirectory() ) throws -> String { let path: String if let override = environment["PARCEL_SOCKET"] { path = override } else { let directory = environment["TMPDIR"] ?? temporaryDirectory path = (directory as NSString).appendingPathComponent("parcel-\(uid).sock") } _ = try SocketAddress(path) return path }}
struct SocketAddress { var value: sockaddr_un let length: socklen_t
init(_ path: String) throws { var address = sockaddr_un() let bytes = Array(path.utf8) guard path.hasPrefix("/"), !bytes.contains(0), bytes.count < MemoryLayout.size(ofValue: address.sun_path) else { throw IPCTransportError.invalidPath(path) } address.sun_family = sa_family_t(AF_UNIX) length = socklen_t(MemoryLayout<sockaddr_un>.size) address.sun_len = UInt8(length) withUnsafeMutableBytes(of: &address.sun_path) { destination in destination.copyBytes(from: bytes) } value = address }
mutating func withPointer<Result>(_ body: (UnsafePointer<sockaddr>, socklen_t) throws -> Result) rethrows -> Result { try withUnsafePointer(to: &value) { pointer in try pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { try body($0, length) } } }}
func makeSocket() throws -> Int32 { let fd = Darwin.socket(AF_UNIX, SOCK_STREAM, 0) guard fd >= 0 else { throw IPCTransportError.system(operation: "socket", code: errno) } do { try configureSocket(fd) return fd } catch { Darwin.close(fd) throw error }}
func configureSocket(_ fd: Int32) throws { guard fcntl(fd, F_SETFL, O_NONBLOCK) == 0, fcntl(fd, F_SETFD, FD_CLOEXEC) == 0 else { throw IPCTransportError.system(operation: "fcntl", code: errno) } var enabled: Int32 = 1 guard setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &enabled, socklen_t(MemoryLayout<Int32>.size)) == 0 else { throw IPCTransportError.system(operation: "setsockopt", code: errno) }}
actor SocketChannel { private var descriptor: Int32? private var buffer = Data() private var reading = false private var writing = false private var readSource: (any DispatchSourceRead)? private var writeSource: (any DispatchSourceWrite)? private var readWaiter: CheckedContinuation<Void, any Error>? private var writeWaiter: CheckedContinuation<Void, any Error>? private var readToken: UUID? private var writeToken: UUID?
init(descriptor: Int32) { self.descriptor = descriptor }
deinit { readSource?.cancel() writeSource?.cancel() if let descriptor { Darwin.close(descriptor) } }
func connect(path: String) async throws { guard let descriptor else { throw IPCTransportError.closed } var address = try SocketAddress(path) let result = address.withPointer { Darwin.connect(descriptor, $0, $1) } if result == 0 { return } let code = errno if code == ENOENT || code == ECONNREFUSED { throw IPCTransportError.notRunning(path) } guard code == EINPROGRESS || code == EAGAIN else { throw IPCTransportError.system(operation: "connect", code: code) } try await wait(read: false) guard let descriptor = self.descriptor else { throw IPCTransportError.closed } var socketError: Int32 = 0 var length = socklen_t(MemoryLayout<Int32>.size) guard getsockopt(descriptor, SOL_SOCKET, SO_ERROR, &socketError, &length) == 0 else { throw IPCTransportError.system(operation: "getsockopt", code: errno) } if socketError == ENOENT || socketError == ECONNREFUSED { throw IPCTransportError.notRunning(path) } guard socketError == 0 else { throw IPCTransportError.system(operation: "connect", code: socketError) } }
func readLine() async throws -> Data? { guard !reading else { throw IPCTransportError.operationInProgress } reading = true defer { reading = false } while true { try Task.checkCancellation() if let newline = buffer.firstIndex(of: 0x0A) { let count = buffer.distance(from: buffer.startIndex, to: newline) guard count <= IPCProtocol.maximumMessageBytes else { throw IPCTransportError.messageTooLarge } let line = Data(buffer[..<newline]) buffer.removeSubrange(...newline) return line } guard buffer.count <= IPCProtocol.maximumMessageBytes else { throw IPCTransportError.messageTooLarge } guard let descriptor else { throw IPCTransportError.closed } var bytes = [UInt8](repeating: 0, count: 16_384) let count = Darwin.recv(descriptor, &bytes, bytes.count, 0) if count > 0 { buffer.append(contentsOf: bytes.prefix(count)) } else if count == 0 { guard buffer.isEmpty else { throw IPCTransportError.truncatedMessage } return nil } else if errno == EINTR { continue } else if errno == EAGAIN || errno == EWOULDBLOCK { try await wait(read: true) } else { throw IPCTransportError.system(operation: "recv", code: errno) } } }
func write(_ data: Data) async throws { guard !writing else { throw IPCTransportError.operationInProgress } writing = true defer { writing = false } var offset = 0 while offset < data.count { try Task.checkCancellation() guard let descriptor else { throw IPCTransportError.closed } let count = data.withUnsafeBytes { bytes in guard let base = bytes.baseAddress else { return 0 } return Darwin.send(descriptor, base.advanced(by: offset), data.count - offset, 0) } if count > 0 { offset += count } else if count < 0 && errno == EINTR { continue } else if count < 0 && (errno == EAGAIN || errno == EWOULDBLOCK) { try await wait(read: false) } else { throw IPCTransportError.system(operation: "send", code: count == 0 ? EPIPE : errno) } } }
func close() { readSource?.cancel() writeSource?.cancel() readSource = nil writeSource = nil if let descriptor { Darwin.shutdown(descriptor, SHUT_RDWR) Darwin.close(descriptor) self.descriptor = nil } readWaiter?.resume(throwing: IPCTransportError.closed) writeWaiter?.resume(throwing: IPCTransportError.closed) readWaiter = nil writeWaiter = nil }
private func wait(read: Bool) async throws { try await withTaskCancellationHandler { try Task.checkCancellation() try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in guard let descriptor else { continuation.resume(throwing: IPCTransportError.closed) return } let token = UUID() if read { let source = DispatchSource.makeReadSource(fileDescriptor: descriptor, queue: .global()) readWaiter = continuation readSource = source readToken = token source.setEventHandler { @Sendable in Task { await self.ready(read: true, token: token) } } source.resume() } else { let source = DispatchSource.makeWriteSource(fileDescriptor: descriptor, queue: .global()) writeWaiter = continuation writeSource = source writeToken = token source.setEventHandler { @Sendable in Task { await self.ready(read: false, token: token) } } source.resume() } } } onCancel: { Task { await self.close() } } }
private func ready(read: Bool, token: UUID) { if read { guard readToken == token else { return } readToken = nil readSource?.cancel() readSource = nil let waiter = readWaiter readWaiter = nil waiter?.resume() } else { guard writeToken == token else { return } writeToken = nil writeSource?.cancel() writeSource = nil let waiter = writeWaiter writeWaiter = nil waiter?.resume() } }}