Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Drain tunnel writes and bound interrupted uploads

Lakrdeb80046498c
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index 7bf03c5c..6ba4bb5f 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -56,6 +56,9 @@ TCP connection and closes it when the WebSocket closes. For example, with
`--api-listen 127.0.0.1:8765`, `ws://127.0.0.1:8765/v1/ports/22` carries
the guest SSH byte stream. An SSH client still needs a local TCP-to-WebSocket
bridge; SSH cannot use a WebSocket URL directly.
+WebSocket fragmentation is reassembled before forwarding. On disconnect, the
+guest tunnel and the host TCP-to-VSOCK proxy let their final queued write
+finish before closing the opposite socket, with a five-second drain limit.
`apps.launch` returns a PID and `frontmost_verified`. IcliKit 0.6.7 checks
RunningBoard's live focal assertion and accepts it only when one real app owns
@@ -69,7 +72,10 @@ confirmation remains an error.
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.
+the previous file browser behavior. Uploads write to a temporary file and
+replace the destination only after the complete request body is written. The
+daemon pauses socket reads while disk writes are pending and removes an
+unfinished temporary file after a disconnect.
`POST /v1/rpc` accepts `{ "id": "...", "method": "device.snapshot",
"params": {} }`. JSON operations return
diff --git a/VPhoneDaemon/Daemon/GuestFileTransfer.swift b/VPhoneDaemon/Daemon/GuestFileTransfer.swift
index 18d1e226..885ba480 100644
--- a/VPhoneDaemon/Daemon/GuestFileTransfer.swift
+++ b/VPhoneDaemon/Daemon/GuestFileTransfer.swift
@@ -66,6 +66,7 @@ final class GuestFileUpload: @unchecked Sendable {
private let fileIO: NonBlockingFileIO
private var offset: Int64 = 0
private var writes: EventLoopFuture<Void>
+ private var pendingWrites = 0
private let onCommit: ((String) throws -> Void)?
private let mode: mode_t
@@ -93,13 +94,18 @@ final class GuestFileUpload: @unchecked Sendable {
func append(_ buffer: ByteBuffer, channel: Channel) {
let start = offset
offset += Int64(buffer.readableBytes)
+ pendingWrites += 1
_ = channel.setOption(ChannelOptions.autoRead, value: false)
writes = writes.flatMap { [fileIO, handle] in
fileIO.write(fileHandle: handle, toOffset: start, buffer: buffer, eventLoop: channel.eventLoop)
}
- writes.whenComplete { [self] _ in
- _ = self
- _ = channel.setOption(ChannelOptions.autoRead, value: true)
+ writes.whenComplete { [self] result in
+ pendingWrites -= 1
+ if case .failure = result {
+ channel.close(promise: nil)
+ } else if pendingWrites == 0, channel.isActive {
+ _ = channel.setOption(ChannelOptions.autoRead, value: true)
+ }
}
}
diff --git a/VPhoneDaemon/Daemon/GuestPortForwardHandler.swift b/VPhoneDaemon/Daemon/GuestPortForwardHandler.swift
index d2e1b9de..986ef67c 100644
--- a/VPhoneDaemon/Daemon/GuestPortForwardHandler.swift
+++ b/VPhoneDaemon/Daemon/GuestPortForwardHandler.swift
@@ -13,6 +13,8 @@ final class GuestPortForwardHandler: ChannelInboundHandler, @unchecked Sendable
private var pending: [ByteBuffer] = []
private var pendingBytes = 0
private let maximumPendingBytes = 1 << 20
+ private var lastBackendWrite: EventLoopFuture<Void>?
+ private var closing = false
init(port: Int) {
self.port = port
@@ -33,23 +35,28 @@ final class GuestPortForwardHandler: ChannelInboundHandler, @unchecked Sendable
_ = webSocket.setOption(ChannelOptions.autoRead, value: false)
ClientBootstrap(group: context.eventLoop)
.connectTimeout(.seconds(5))
- .channelInitializer { backend in
- backend.pipeline.addHandler(GuestPortBackendHandler(webSocket: webSocket))
+ .channelInitializer { [weak self] backend in
+ backend.pipeline.addHandler(GuestPortBackendHandler(webSocket: webSocket) { [weak self] in
+ self?.closing == false
+ })
}
.connect(host: "127.0.0.1", port: port)
.whenComplete { result in
- guard webSocket.isActive else {
+ guard webSocket.isActive, !self.closing else {
if case let .success(backend) = result { backend.close(promise: nil) }
return
}
switch result {
case let .success(backend):
self.backend = backend
- for chunk in self.pending { backend.write(chunk, promise: nil) }
- backend.flush()
+ for chunk in self.pending.dropLast() { backend.write(chunk, promise: nil) }
+ if let chunk = self.pending.last {
+ self.lastBackendWrite = backend.writeAndFlush(chunk)
+ self.lastBackendWrite?.whenFailure { _ in self.closeWithError(on: webSocket) }
+ }
self.pending.removeAll()
self.pendingBytes = 0
- _ = webSocket.setOption(ChannelOptions.autoRead, value: true)
+ _ = webSocket.setOption(ChannelOptions.autoRead, value: backend.isWritable)
case .failure:
self.closeWithError(on: webSocket)
}
@@ -58,11 +65,14 @@ final class GuestPortForwardHandler: ChannelInboundHandler, @unchecked Sendable
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let frame = unwrapInboundIn(data)
+ guard !closing else { return }
switch frame.opcode {
case .binary:
let chunk = frame.unmaskedData
if let backend {
- backend.writeAndFlush(chunk, promise: nil)
+ lastBackendWrite = backend.writeAndFlush(chunk)
+ let webSocket = context.channel
+ lastBackendWrite?.whenFailure { _ in self.closeWithError(on: webSocket) }
} else {
pendingBytes += chunk.readableBytes
guard pendingBytes <= maximumPendingBytes else {
@@ -75,6 +85,7 @@ final class GuestPortForwardHandler: ChannelInboundHandler, @unchecked Sendable
context.writeAndFlush(wrapOutboundOut(WebSocketFrame(fin: true, opcode: .pong,
data: frame.unmaskedData)), promise: nil)
case .connectionClose:
+ closing = true
let webSocket = context.channel
context.writeAndFlush(wrapOutboundOut(WebSocketFrame(fin: true, opcode: .connectionClose,
data: frame.unmaskedData))).whenComplete { _ in
@@ -91,8 +102,24 @@ final class GuestPortForwardHandler: ChannelInboundHandler, @unchecked Sendable
}
func channelInactive(context: ChannelHandlerContext) {
- backend?.close(promise: nil)
+ closing = true
+ if let backend {
+ if let lastBackendWrite {
+ // A WebSocket close can arrive in the same read as the final data
+ // frame. Let NIO flush those bytes before closing the TCP socket.
+ let timeout = context.eventLoop.scheduleTask(in: .seconds(5)) {
+ backend.close(promise: nil)
+ }
+ lastBackendWrite.whenComplete { _ in
+ timeout.cancel()
+ backend.close(promise: nil)
+ }
+ } else {
+ backend.close(promise: nil)
+ }
+ }
backend = nil
+ lastBackendWrite = nil
pending.removeAll()
context.fireChannelInactive()
}
@@ -102,6 +129,8 @@ final class GuestPortForwardHandler: ChannelInboundHandler, @unchecked Sendable
}
private func closeWithError(on channel: Channel) {
+ guard !closing, channel.isActive else { return }
+ closing = true
var data = channel.allocator.buffer(capacity: 2)
data.writeInteger(UInt16(1011), endianness: .big)
channel.writeAndFlush(WebSocketFrame(fin: true, opcode: .connectionClose,
@@ -115,14 +144,16 @@ private final class GuestPortBackendHandler: ChannelInboundHandler, @unchecked S
typealias InboundIn = ByteBuffer
let webSocket: Channel
+ let shouldForward: @Sendable () -> Bool
private var lastWrite: EventLoopFuture<Void>?
- init(webSocket: Channel) {
+ init(webSocket: Channel, shouldForward: @escaping @Sendable () -> Bool) {
self.webSocket = webSocket
+ self.shouldForward = shouldForward
}
func channelRead(context _: ChannelHandlerContext, data: NIOAny) {
- guard webSocket.isActive else { return }
+ guard webSocket.isActive, shouldForward() else { return }
let frame = WebSocketFrame(fin: true, opcode: .binary, data: unwrapInboundIn(data))
lastWrite = webSocket.writeAndFlush(frame)
}
@@ -146,7 +177,7 @@ private final class GuestPortBackendHandler: ChannelInboundHandler, @unchecked S
}
private func closeWebSocket() {
- guard webSocket.isActive else { return }
+ guard webSocket.isActive, shouldForward() else { return }
var data = webSocket.allocator.buffer(capacity: 2)
data.writeInteger(UInt16(1000), endianness: .big)
webSocket.writeAndFlush(WebSocketFrame(fin: true, opcode: .connectionClose,
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneAPIProxy.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneAPIProxy.swift
index 51d5c3b3..59344eac 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneAPIProxy.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneAPIProxy.swift
@@ -96,17 +96,28 @@ private final class GuestSocketProvider: @unchecked Sendable {
let guestRelay = ByteRelay(connection: connection)
let hostRelay = ByteRelay(connection: connection)
ClientBootstrap(group: self.group)
+ .channelOption(ChannelOptions.autoRead, value: false)
.channelInitializer { guest in guest.pipeline.addHandler(guestRelay) }
.withConnectedSocket(fd)
.flatMap { guest in
guestRelay.peer = host
hostRelay.peer = guest
return host.pipeline.addHandler(hostRelay)
+ .flatMap {
+ host.setOption(ChannelOptions.autoRead, value: guest.isWritable)
+ .flatMap {
+ guest.setOption(ChannelOptions.autoRead, value: host.isWritable)
+ }
+ }
+ .flatMapError { error in
+ guest.close(promise: nil)
+ return host.eventLoop.makeFailedFuture(error)
+ }
}
.whenComplete { result in
switch result {
case .success:
- host.setOption(ChannelOptions.autoRead, value: true).cascade(to: promise)
+ promise.succeed(())
case let .failure(error):
print("[api] guest relay failed: \(error)")
promise.fail(error)
@@ -129,6 +140,7 @@ private final class ByteRelay: ChannelInboundHandler, @unchecked Sendable {
private let connection: VZVirtioSocketConnection
private let lock = NSLock()
private var _peer: Channel?
+ private var lastWrite: EventLoopFuture<Void>?
var peer: Channel? {
get {
@@ -149,7 +161,7 @@ private final class ByteRelay: ChannelInboundHandler, @unchecked Sendable {
func channelRead(context _: ChannelHandlerContext, data: NIOAny) {
guard let peer else { return }
- peer.writeAndFlush(unwrapInboundIn(data), promise: nil)
+ lastWrite = peer.writeAndFlush(unwrapInboundIn(data))
}
func channelWritabilityChanged(context: ChannelHandlerContext) {
@@ -162,7 +174,22 @@ private final class ByteRelay: ChannelInboundHandler, @unchecked Sendable {
let other = _peer
_peer = nil
lock.unlock()
- other?.close(promise: nil)
+ if let other {
+ if let lastWrite {
+ // A close can follow the last TCP chunk before the other event
+ // loop has written it. Drain that write before closing its socket.
+ let timeout = context.eventLoop.scheduleTask(in: .seconds(5)) {
+ other.close(promise: nil)
+ }
+ lastWrite.whenComplete { _ in
+ timeout.cancel()
+ other.close(promise: nil)
+ }
+ } else {
+ other.close(promise: nil)
+ }
+ }
+ lastWrite = nil
context.fireChannelInactive()
}