Run a virtual iPhone on an Apple Silicon Mac.
Swift
Harden vphoned API transport and preserve file browser behavior
Lakrc8d155ea0f08
diff --git a/research/vphoned_http_api.md b/research/vphoned_http_api.mdindex b8d441aa..8fe95761 100644--- a/research/vphoned_http_api.md+++ b/research/vphoned_http_api.md@@ -36,6 +36,10 @@ directory then renames it after all chunks have been written. JSON bodieshave a 1 MiB limit. Binary transfers stream without loading the entire fileinto memory.+Upload accepts an optional octal `mode` query parameter (default `644`) and+creates missing parent directories. Download follows file symlinks, matching+the previous file browser behavior.+`POST /v1/rpc` accepts `{ "id": "...", "method": "device.snapshot","params": {} }`. JSON operations return`{ "type": "response", "id": "...", "result": { ... } }` or@@ -62,10 +66,21 @@ This intentionally breaks compatibility with guests that still have the olddaemon: install a guest image carrying this vphoned build before using the newhost control client.+## Connection failure behavior++A dropped HTTP or WebSocket connection closes only that request channel. The+guest launchd plist keeps vphoned alive and restarts it if the daemon itself+exits. Host socket writes use `F_SETNOSIGPIPE`, so a guest disconnect becomes+an ordinary error instead of terminating `vphone-vm`. The host HTTP client+also times out stalled reads and writes. Camera frames use a duplicated+descriptor for each in-flight send; the original descriptor remains owned by+`VZVirtioSocketConnection` and is never manually closed. The optional TCP+proxy uses NIO channels and closes the paired channel when either side ends.+## Usage```sh-vphone-cli boot --config /path/to/config.plist --api-listen 127.0.0.1:8765+vphone-cli vm launch <name> --api-listen 127.0.0.1:8765curl http://127.0.0.1:8765/v1/healthcurl http://127.0.0.1:8765/openapi.json```diff --git a/scripts/vphoned/Swift/GuestAPI.swift b/scripts/vphoned/Swift/GuestAPI.swiftindex 0bf214cb..0f227a60 100644--- a/scripts/vphoned/Swift/GuestAPI.swift+++ b/scripts/vphoned/Swift/GuestAPI.swift@@ -1,5 +1,6 @@import Foundationimport CryptoKit+import Darwinimport IcliKitimport VphonedNative@@ -36,7 +37,7 @@ enum GuestAPI {let version = ProcessInfo.processInfo.operatingSystemVersionreturn ["name": "vphoned", "api_version": 1, "status": "ok", "binary_hash": binaryHash,"ios": "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)", "ip": ip ?? "",- "capabilities": ["touch", "hid", "apps", "url", "files", "clipboard", "location", "keychain", "ipa_install", "camera"]]+ "capabilities": ["touch", "hid", "apps", "url", "files", "clipboard", "location", "keychain", "ipa_install", "camera", "icli"]]}static func execute(method: String, params: [String: Any]) throws -> [String: Any] {@@ -138,7 +139,7 @@ enum GuestAPI {case "clipboard.set":return try setClipboard(try string(params, "text"))case "files.list":- return try listDirectory(try string(params, "path"))+ return try fileList(try string(params, "path"))case "files.mkdir":return try makeDirectory(try string(params, "path"), mode: nil)case "files.remove":@@ -192,6 +193,29 @@ enum GuestAPI {return payload}+ private static func fileList(_ path: String) throws -> [String: Any] {+ var result = try listDirectory(path)+ let entries = result["entries"] as? [[String: Any]] ?? []+ result["entries"] = entries.compactMap { entry -> [String: Any]? in+ guard let fullPath = entry["path"] as? String else { return nil }+ var metadata = stat()+ guard lstat(fullPath, &metadata) == 0 else { return nil }+ let kind = metadata.st_mode & mode_t(S_IFMT)+ let isLink = kind == mode_t(S_IFLNK)+ var target = stat()+ let targetsDirectory = isLink && stat(fullPath, &target) == 0+ && target.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR)+ var enriched = entry+ enriched["type"] = isLink ? "link" : kind == mode_t(S_IFDIR) ? "dir" : "file"+ enriched["link_target_dir"] = targetsDirectory+ enriched["size"] = metadata.st_size+ enriched["perm"] = String(metadata.st_mode & 0o777, radix: 8)+ enriched["mtime"] = Double(metadata.st_mtimespec.tv_sec)+ return enriched+ }+ return result+ }+private static func string(_ params: [String: Any], _ key: String) throws -> String {guard let value = params[key] as? String, !value.isEmpty else {throw GuestAPIError.invalidRequest("\(key) is required")diff --git a/scripts/vphoned/Swift/GuestFileTransfer.swift b/scripts/vphoned/Swift/GuestFileTransfer.swiftindex deedf6a5..bf209f31 100644--- a/scripts/vphoned/Swift/GuestFileTransfer.swift+++ b/scripts/vphoned/Swift/GuestFileTransfer.swift@@ -14,7 +14,7 @@ enum GuestFileTransfer {}static func download(path: String, fileIO: NonBlockingFileIO, channel: Channel) {- let fd = open(path, O_RDONLY | O_NOFOLLOW)+ let fd = open(path, O_RDONLY)guard fd >= 0 else {GuestHTTPHandler.send(APIWire.error("File could not be opened", status: 404), on: channel)return@@ -60,9 +60,13 @@ final class GuestFileUpload: @unchecked Sendable {private var offset: Int64 = 0private var writes: EventLoopFuture<Void>private let onCommit: ((String) throws -> Void)?+ private let mode: mode_tinit(destination: String, fileIO: NonBlockingFileIO, channel: Channel,+ mode: mode_t = 0o644,onCommit: ((String) throws -> Void)? = nil) throws {+ let parent = (destination as NSString).deletingLastPathComponent+ try FileManager.default.createDirectory(atPath: parent, withIntermediateDirectories: true)let temporary = destination + ".vphoned-" + UUID().uuidString + ".tmp"let fd = open(temporary, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600)guard fd >= 0 else { throw GuestAPIError.operationFailed("Could not create upload file") }@@ -72,6 +76,7 @@ final class GuestFileUpload: @unchecked Sendable {self.fileIO = fileIOself.writes = channel.eventLoop.makeSucceededFuture(())self.onCommit = onCommit+ self.mode = mode}func append(_ buffer: ByteBuffer, channel: Channel) {@@ -95,10 +100,12 @@ final class GuestFileUpload: @unchecked Sendable {case .failure(let error): throw errorcase .success: break}+ guard chmod(temporary, mode) == 0 else {+ throw GuestAPIError.operationFailed("Could not set upload permissions")+ }guard rename(temporary, destination) == 0 else {throw GuestAPIError.operationFailed("Could not replace destination file")}- chmod(destination, 0o644)try onCommit?(destination)GuestHTTPHandler.send(.json(["result": ["path": destination, "size": offset]]), on: channel)} catch {diff --git a/scripts/vphoned/Swift/GuestHTTPHandler.swift b/scripts/vphoned/Swift/GuestHTTPHandler.swiftindex bf55cadb..49b93706 100644--- a/scripts/vphoned/Swift/GuestHTTPHandler.swift+++ b/scripts/vphoned/Swift/GuestHTTPHandler.swift@@ -40,6 +40,7 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u? "/var/root/Library/Caches/vphoned-clipboard-image" : GuestFileTransfer.path(from: request.uri),fileIO: fileIO,channel: context.channel,+ mode: try Self.uploadMode(from: request.uri),onCommit: requestPath == "/v1/clipboard/image" ? { path in_ = try setClipboardImage(Data(contentsOf: URL(fileURLWithPath: path)))unlink(path)@@ -143,6 +144,18 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @ureturn object}+ private static func uploadMode(from uri: String) throws -> mode_t {+ let components = URLComponents(string: "http://vphoned\(uri)")+ guard let value = components?.queryItems?.first(where: { $0.name == "mode" })?.value else {+ return 0o644+ }+ guard !value.isEmpty, value.count <= 4,+ value.utf8.allSatisfy({ (48...55).contains($0) }),+ let mode = UInt16(value, radix: 8), mode <= 0o777+ else { throw GuestAPIError.invalidRequest("mode must be an octal permission, up to 0777") }+ return mode_t(mode)+ }+private static func route(_ verb: HTTPMethod, path: String) throws -> String {switch (verb, path) {case (.GET, "/v1/device"): "device.snapshot"@@ -177,6 +190,7 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @ustatic func send(_ reply: APIReply, on channel: Channel, contentType: String = "application/json; charset=utf-8") {let write: @Sendable () -> Void = {+ guard channel.isActive else { return }var headers = HTTPHeaders()headers.add(name: "Content-Type", value: contentType)headers.add(name: "Content-Length", value: String(reply.data.count))@@ -193,6 +207,11 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @uif channel.eventLoop.inEventLoop { write() } else { channel.eventLoop.execute(write) }}+ func channelInactive(context: ChannelHandlerContext) {+ upload = nil+ context.fireChannelInactive()+ }+func errorCaught(context: ChannelHandlerContext, error: Error) {context.close(promise: nil)}diff --git a/scripts/vphoned/Swift/IcliCommand.swift b/scripts/vphoned/Swift/IcliCommand.swiftindex 745f662a..1cba2948 100644--- a/scripts/vphoned/Swift/IcliCommand.swift+++ b/scripts/vphoned/Swift/IcliCommand.swift@@ -46,7 +46,7 @@ enum IcliCommand {}defer { close(stdinFD); close(stdoutFD); close(stderrFD) }- var actions = posix_spawn_file_actions_t()+ var actions: posix_spawn_file_actions_t? = nilposix_spawn_file_actions_init(&actions)defer { posix_spawn_file_actions_destroy(&actions) }posix_spawn_file_actions_adddup2(&actions, stdinFD, STDIN_FILENO)@@ -68,7 +68,12 @@ enum IcliCommand {while true {let waited = waitpid(pid, &status, WNOHANG)if waited == pid { break }- if waited < 0 { throw GuestAPIError.operationFailed("Could not wait for icli") }+ if waited < 0 {+ if errno == EINTR { continue }+ kill(pid, SIGKILL)+ _ = waitpid(pid, &status, 0)+ throw GuestAPIError.operationFailed("Could not wait for icli")+ }if ProcessInfo.processInfo.systemUptime >= deadline {kill(pid, SIGKILL)_ = waitpid(pid, &status, 0)@@ -76,11 +81,14 @@ enum IcliCommand {}Thread.sleep(forTimeInterval: 0.05)}- let stdout = try Data(contentsOf: outputURL, options: .mappedIfSafe)- let stderr = try Data(contentsOf: errorURL, options: .mappedIfSafe)- guard stdout.count <= 64 << 20, stderr.count <= 1 << 20 else {+ let stdoutSize = try FileManager.default.attributesOfItem(atPath: outputURL.path)[.size] as? NSNumber+ let stderrSize = try FileManager.default.attributesOfItem(atPath: errorURL.path)[.size] as? NSNumber+ guard (stdoutSize?.int64Value ?? 0) <= 64 << 20,+ (stderrSize?.int64Value ?? 0) <= 1 << 20 else {throw GuestAPIError.operationFailed("icli output exceeded the API limit")}+ let stdout = try Data(contentsOf: outputURL, options: .mappedIfSafe)+ let stderr = try Data(contentsOf: errorURL, options: .mappedIfSafe)let parsed = try? JSONSerialization.jsonObject(with: stdout, options: [.fragmentsAllowed])let code = (status & 0x7f) == 0 ? Int((status >> 8) & 0xff) : -Int(status & 0x7f)return [diff --git a/scripts/vphoned/Swift/OpenAPISpec.swift b/scripts/vphoned/Swift/OpenAPISpec.swiftindex 30ca5cb0..31080a5b 100644--- a/scripts/vphoned/Swift/OpenAPISpec.swift+++ b/scripts/vphoned/Swift/OpenAPISpec.swift@@ -14,7 +14,7 @@ enum OpenAPISpec {"servers": [{"url": "/"}],"paths": {"/v1/health": {"get": {"operationId": "health", "responses": {"200": {"description": "Daemon is running"}}}},- "/v1/icli/execute": {"post": {"operationId": "icli.execute", "description": "Run any icli command inside the guest with an argv array. The result includes exit_code, output and stderr.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["argv"], "properties": {"argv": {"type": "array", "items": {"type": "string"}}, "stdin": {"type": "string"}, "stdin_base64": {"type": "string", "contentEncoding": "base64"}}}}}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/icli/execute": {"post": {"operationId": "icli.execute", "description": "Run icli inside the guest with argv, optional stdin or stdin_base64. Returns exit_code, output and stderr.", "requestBody": {"$ref": "#/components/requestBodies/IcliCommand"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},"/v1/device": {"get": {"operationId": "device.snapshot", "responses": {"200": {"$ref": "#/components/responses/Result"}}}},"/v1/device/screen": {"get": {"operationId": "device.screen", "responses": {"200": {"$ref": "#/components/responses/Result"}}}},"/v1/apps": {"get": {"operationId": "apps.list", "responses": {"200": {"$ref": "#/components/responses/Result"}}}},@@ -47,7 +47,7 @@ enum OpenAPISpec {"/v1/files": {"get": {"operationId": "files.list", "parameters": [{"name": "path", "in": "query", "required": true, "schema": {"type": "string"}}], "responses": {"200": {"$ref": "#/components/responses/Result"}}}},"/v1/files/content": {"get": {"operationId": "files.download", "parameters": [{"$ref": "#/components/parameters/FilePath"}], "responses": {"200": {"description": "File bytes", "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}}},- "put": {"operationId": "files.upload", "parameters": [{"$ref": "#/components/parameters/FilePath"}], "requestBody": {"required": true, "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}, "responses": {"200": {"description": "File stored"}}}+ "put": {"operationId": "files.upload", "parameters": [{"$ref": "#/components/parameters/FilePath"}, {"name": "mode", "in": "query", "schema": {"type": "string", "default": "644", "pattern": "^0?[0-7]{1,3}$"}}], "requestBody": {"required": true, "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}, "responses": {"200": {"description": "File stored"}}}},"/v1/files/mkdir": {"post": {"operationId": "files.mkdir", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},"/v1/files/remove": {"post": {"operationId": "files.remove", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},@@ -69,7 +69,10 @@ enum OpenAPISpec {"Event": {"type": "object", "required": ["type", "event", "data"], "properties": {"type": {"const": "event"}, "event": {"type": "string"}, "data": {"type": "object", "additionalProperties": true}}},"Error": {"type": "object", "required": ["code", "message"], "properties": {"code": {"type": "string"}, "message": {"type": "string"}}}},- "requestBodies": {"Parameters": {"content": {"application/json": {"schema": {"type": "object", "additionalProperties": true}}}}},+ "requestBodies": {+ "Parameters": {"content": {"application/json": {"schema": {"type": "object", "additionalProperties": true}}}},+ "IcliCommand": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["argv"], "properties": {"argv": {"type": "array", "minItems": 1, "maxItems": 64, "items": {"type": "string"}}, "stdin": {"type": "string"}, "stdin_base64": {"type": "string", "contentEncoding": "base64"}}}}}}+ },"responses": {"Result": {"description": "A Response envelope with result or error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Response"}}}}}},"x-websocket": {"path": "/v1/events", "request": {"$ref": "#/components/schemas/Request"}, "messages": [{"$ref": "#/components/schemas/Response"}, {"$ref": "#/components/schemas/Event"}]}diff --git a/sources/VPhoneKit/VPhoneAPIClient.swift b/sources/VPhoneKit/VPhoneAPIClient.swiftindex 9c800791..32b751c8 100644--- a/sources/VPhoneKit/VPhoneAPIClient.swift+++ b/sources/VPhoneKit/VPhoneAPIClient.swift@@ -75,6 +75,7 @@ public struct VPhoneAPIClient: Sendable {let request = Request(id: id, method: method, params: params)var http = URLRequest(url: baseURL.appending(path: "v1/rpc"))http.httpMethod = "POST"+ http.timeoutInterval = 130http.setValue("application/json", forHTTPHeaderField: "Content-Type")http.httpBody = try JSONEncoder().encode(request)let (data, response) = try await session.data(for: http)@@ -110,9 +111,14 @@ public struct VPhoneAPIClient: Sendable {/// Runs any icli subcommand inside the guest. Arguments are passed as an/// array to the pinned icli executable, without a shell. The result holds/// its exit code, decoded JSON output (or text), and stderr.- public func runIcli(_ arguments: [String], stdin: String? = nil) async throws -> VPhoneJSONValue {+ public func runIcli(_ arguments: [String], stdin: String? = nil,+ stdinData: Data? = nil) async throws -> VPhoneJSONValue {+ guard stdin == nil || stdinData == nil else {+ throw VPhoneAPIError(code: "input", message: "Pass either stdin or stdinData")+ }var params: [String: VPhoneJSONValue] = ["argv": .array(arguments.map(VPhoneJSONValue.string))]if let stdin { params["stdin"] = .string(stdin) }+ if let stdinData { params["stdin_base64"] = .string(stdinData.base64EncodedString()) }return try await call("icli.execute", params: params)}@@ -132,8 +138,9 @@ public struct VPhoneAPIClient: Sendable {/// Sends a host file to an absolute guest path without loading it into/// memory. The guest stages it beside the destination and renames it.- public func uploadFile(from localURL: URL, toGuestPath guestPath: String) async throws -> VPhoneJSONValue {- var request = URLRequest(url: try fileURL(guestPath))+ public func uploadFile(from localURL: URL, toGuestPath guestPath: String,+ permissions: String = "644") async throws -> VPhoneJSONValue {+ var request = URLRequest(url: try fileURL(guestPath, mode: permissions))request.httpMethod = "PUT"request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")let (data, response) = try await session.upload(for: request, fromFile: localURL)@@ -148,12 +155,13 @@ public struct VPhoneAPIClient: Sendable {return result}- private func fileURL(_ guestPath: String) throws -> URL {+ private func fileURL(_ guestPath: String, mode: String? = nil) throws -> URL {guard guestPath.hasPrefix("/"), !guestPath.contains("\0"),var components = URLComponents(url: baseURL.appending(path: "v1/files/content"),resolvingAgainstBaseURL: false)else { throw VPhoneAPIError(code: "path", message: "Guest path must be absolute") }components.queryItems = [URLQueryItem(name: "path", value: guestPath)]+ if let mode { components.queryItems?.append(URLQueryItem(name: "mode", value: mode)) }guard let url = components.url else { throw VPhoneAPIError(code: "url", message: "Invalid file URL") }return url}diff --git a/sources/VPhoneVMKit/Devices/VPhoneCameraServer.swift b/sources/VPhoneVMKit/Devices/VPhoneCameraServer.swiftindex 2a28761a..ee540971 100644--- a/sources/VPhoneVMKit/Devices/VPhoneCameraServer.swift+++ b/sources/VPhoneVMKit/Devices/VPhoneCameraServer.swift@@ -41,6 +41,7 @@ final class VPhoneCameraServer {private var producer: VPhoneFrameProducer?private var timer: DispatchSourceTimer?private var connectionAttemptToken: UInt64 = 0+ private var framePending = falseprivate let sendQueue = DispatchQueue(label: "com.vphone.camera.send",@@ -61,11 +62,11 @@ final class VPhoneCameraServer {}func disconnect() {+ connectionAttemptToken &+= 1stopStreaming()- if connectionFD >= 0 {- close(connectionFD)- connectionFD = -1- }+ connectionFD = -1+ // Virtualization.framework owns this descriptor and closes it with+ // the connection. Pending frame sends use their own dup.connection = nilif isConnected {isConnected = false@@ -129,20 +130,27 @@ final class VPhoneCameraServer {t.setEventHandler { [weak self] inguard let self else { return }guard let producer = self.producer else { return }- let fd = self.connectionFD- guard fd >= 0 else { return }+ guard !self.framePending, self.connectionFD >= 0 else { return }+ let sourceFD = self.connectionFD+ let fd = dup(sourceFD)+ guard fd >= 0 else { self.handleDisconnect(); return }+ guard fcntl(fd, F_SETNOSIGPIPE, 1) != -1 else {+ close(fd)+ self.handleDisconnect()+ return+ }+ self.framePending = true+ let connectionToken = self.connectionAttemptTokenlet q = self.producerQueue- q.async {- guard let frame = producer.nextFrame() else { return }- let ok = Self.send(fd: fd, frame: frame)- if !ok {- Task { @MainActor [weak self] in- guard let self else { return }- // Avoid double-handling if a parallel write already- // dropped the connection.- if self.connectionFD == fd {- self.handleDisconnect()- }+ q.async { [weak self] in+ let frame = producer.nextFrame()+ let ok = frame.map { Self.send(fd: fd, frame: $0) } ?? true+ close(fd)+ Task { @MainActor [weak self] in+ guard let self else { return }+ self.framePending = false+ if !ok && self.connectionAttemptToken == connectionToken && self.connectionFD == sourceFD {+ self.handleDisconnect()}}}@@ -164,14 +172,12 @@ final class VPhoneCameraServer {/// killing its server-side socket while the host is streaming.private func handleDisconnect() {print("[camera] disconnect detected, will reconnect")- let oldFD = connectionFDconnectionFD = -1connection = nilif isConnected {isConnected = falseonConnectionStateChange?(false)}- if oldFD >= 0 { close(oldFD) }// Note: streaming timer continues running but ticks no-op until// connectionFD becomes valid again.attemptConnect()diff --git a/sources/VPhoneVMKit/Guest/VPhoneAPIProxy.swift b/sources/VPhoneVMKit/Guest/VPhoneAPIProxy.swiftindex 31f9a630..d6e3c0b4 100644--- a/sources/VPhoneVMKit/Guest/VPhoneAPIProxy.swift+++ b/sources/VPhoneVMKit/Guest/VPhoneAPIProxy.swift@@ -123,7 +123,21 @@ private final class ByteRelay: ChannelInboundHandler, @unchecked Sendable {// Keeping this object alive also keeps Virtualization.framework's original// socket descriptor alive while NIO owns its duplicated descriptor.private let connection: VZVirtioSocketConnection- var peer: Channel?+ private let lock = NSLock()+ private var _peer: Channel?++ var peer: Channel? {+ get {+ lock.lock()+ defer { lock.unlock() }+ return _peer+ }+ set {+ lock.lock()+ _peer = newValue+ lock.unlock()+ }+ }init(connection: VZVirtioSocketConnection) { self.connection = connection }@@ -138,8 +152,10 @@ private final class ByteRelay: ChannelInboundHandler, @unchecked Sendable {}func channelInactive(context: ChannelHandlerContext) {- let other = peer- peer = nil+ lock.lock()+ let other = _peer+ _peer = nil+ lock.unlock()other?.close(promise: nil)context.fireChannelInactive()}diff --git a/sources/VPhoneVMKit/Guest/VPhoneControl.swift b/sources/VPhoneVMKit/Guest/VPhoneControl.swiftindex 239d1dc8..40b04130 100644--- a/sources/VPhoneVMKit/Guest/VPhoneControl.swift+++ b/sources/VPhoneVMKit/Guest/VPhoneControl.swift@@ -222,7 +222,7 @@ final class VPhoneControl {}func uploadFile(path: String, data: Data, permissions: String = "644") async throws {- let response = try await http(method: "PUT", path: try filePath(path), body: data,+ let response = try await http(method: "PUT", path: try filePath(path, mode: permissions), body: data,contentType: "application/octet-stream")guard response.status == 200 else { throw try httpError(response) }}@@ -283,13 +283,14 @@ final class VPhoneControl {catch { print("[control] location clear: \(error)") } }}- private func filePath(_ guestPath: String) throws -> String {+ private func filePath(_ guestPath: String, mode: String? = nil) throws -> String {guard guestPath.hasPrefix("/"), !guestPath.contains("\0") else {throw ControlError.protocolError("guest path must be absolute")}var components = URLComponents()components.path = "/v1/files/content"components.queryItems = [URLQueryItem(name: "path", value: guestPath)]+ if let mode { components.queryItems?.append(URLQueryItem(name: "mode", value: mode)) }return components.string ?? ""}@@ -346,9 +347,15 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {func run() throws -> VPhoneHTTPResponse {let fd = connection.fileDescriptor- var noSigPipe: Int32 = 1- _ = withUnsafePointer(to: &noSigPipe) {- setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, $0, socklen_t(MemoryLayout<Int32>.size))+ guard fcntl(fd, F_SETNOSIGPIPE, 1) != -1 else {+ throw VPhoneControl.ControlError.notConnected+ }+ var timeout = timeval(tv_sec: 120, tv_usec: 0)+ guard setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout,+ socklen_t(MemoryLayout<timeval>.size)) == 0,+ setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout,+ socklen_t(MemoryLayout<timeval>.size)) == 0 else {+ throw VPhoneControl.ControlError.notConnected}let headers = "\(method) \(path) HTTP/1.1\r\nHost: vphoned\r\nConnection: close\r\nContent-Type: \(contentType)\r\nContent-Length: \(body.count)\r\n\r\n"try write(fd, data: Data(headers.utf8))@@ -385,6 +392,7 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {var offset = 0while offset < bytes.count {let sent = Darwin.write(fd, base + offset, bytes.count - offset)+ if sent < 0 && errno == EINTR { continue }if sent <= 0 { throw VPhoneControl.ControlError.notConnected }offset += sent}@@ -393,7 +401,8 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {private func readMore(_ fd: Int32, into data: inout Data) throws {var bytes = [UInt8](repeating: 0, count: 32 * 1024)- let count = Darwin.read(fd, &bytes, bytes.count)+ var count = 0+ repeat { count = Darwin.read(fd, &bytes, bytes.count) } while count < 0 && errno == EINTRguard count > 0 else { throw VPhoneControl.ControlError.notConnected }data.append(contentsOf: bytes[..<count])}diff --git a/sources/VPhoneVMKit/VPhoneHostControl.swift b/sources/VPhoneVMKit/VPhoneHostControl.swiftindex a6b1ba73..8d739e6d 100644--- a/sources/VPhoneVMKit/VPhoneHostControl.swift+++ b/sources/VPhoneVMKit/VPhoneHostControl.swift@@ -177,6 +177,10 @@ class VPhoneHostControl {while true {let clientFD = accept(listenFD, nil, nil)guard clientFD >= 0 else { break }+ guard fcntl(clientFD, F_SETNOSIGPIPE, 1) != -1 else {+ close(clientFD)+ continue+ }handleClient(clientFD, controller: controller)}}@@ -433,6 +437,7 @@ class VPhoneHostControl {var offset = 0while remaining > 0 {let written = write(fd, ptr.advanced(by: offset), remaining)+ if written < 0 && errno == EINTR { continue }if written <= 0 { break }offset += writtenremaining -= written