Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Connect to vphone.sock through one helper

Jacky80d47350b6c0
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift
index a610fe36..38fcd8d1 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift
@@ -1,5 +1,6 @@
import Darwin
import Foundation
+import VPhoneCoreKit
/// Requests to a running VM's control socket, `vphone.sock`. `vm create` pings
/// through it instead of parsing the VM process's buffered stdout, and
@@ -12,20 +13,7 @@ enum VPhoneHostAutomationProbe {
/// One request, one reply line. Nil when the socket is not there or the
/// reply is not JSON.
static func send(_ request: [String: Any], socketPath: String, timeout seconds: Int = 2) -> [String: Any]? {
- let path = socketPath.utf8CString
- var address = sockaddr_un()
- guard path.count <= MemoryLayout.size(ofValue: address.sun_path) else { return nil }
- address.sun_family = sa_family_t(AF_UNIX)
- withUnsafeMutablePointer(to: &address.sun_path) { pointer in
- pointer.withMemoryRebound(to: CChar.self, capacity: path.count) { destination in
- for (index, byte) in path.enumerated() {
- destination[index] = byte
- }
- }
- }
-
- let fd = socket(AF_UNIX, SOCK_STREAM, 0)
- guard fd >= 0 else { return nil }
+ guard case let .success(fd) = VPhoneUnixSocket.connect(to: socketPath) else { return nil }
defer { close(fd) }
var timeout = timeval(tv_sec: seconds, tv_usec: 0)
@@ -36,14 +24,7 @@ enum VPhoneHostAutomationProbe {
_ = withUnsafePointer(to: &noSigPipe) {
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, $0, socklen_t(MemoryLayout<Int32>.size))
}
- let connected = withUnsafePointer(to: &address) { pointer in
- pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {
- connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
- }
- }
- guard connected == 0,
- var request = try? JSONSerialization.data(withJSONObject: request)
- else { return nil }
+ guard var request = try? JSONSerialization.data(withJSONObject: request) else { return nil }
request.append(0x0A)
let written = request.withUnsafeBytes { bytes in
Darwin.write(fd, bytes.baseAddress, bytes.count)
diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift
index a48fa8ec..7ed95f89 100644
--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift
+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleActivity.swift
@@ -89,34 +89,22 @@ public enum VPhoneBundleActivity {
/// fails with EACCES while the VM runs, and its processes are hidden from
/// `processesHolding` too.
private static func controlSocketIsLive(_ url: URL) -> Bool {
- let path = url.path
var info = stat()
- guard lstat(path, &info) == 0, info.st_mode & S_IFMT == S_IFSOCK else { return false }
- var address = sockaddr_un()
- let capacity = MemoryLayout.size(ofValue: address.sun_path)
- // A path too long for sun_path cannot be probed. A socket is there all
- // the same, and calling it stale would let a clone or revert copy or
- // replace the state files of a running guest, so it counts as live;
- // removing a stale one by hand clears the refusal.
- guard path.utf8.count < capacity else { return true }
- address.sun_family = sa_family_t(AF_UNIX)
- withUnsafeMutableBytes(of: &address.sun_path) { buffer in
- for (index, byte) in path.utf8.enumerated() {
- buffer[index] = byte
- }
- }
- // Without a socket to probe with, the same reasoning applies.
- let fd = socket(AF_UNIX, SOCK_STREAM, 0)
- guard fd >= 0 else { return true }
- defer { close(fd) }
- let result = withUnsafePointer(to: &address) { pointer in
- pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {
- connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
- }
+ guard lstat(url.path, &info) == 0, info.st_mode & S_IFMT == S_IFSOCK else { return false }
+ switch VPhoneUnixSocket.connect(to: url.path) {
+ case let .success(fd):
+ close(fd)
+ return true
+ case let .failure(.connect(failure)):
+ return failure != ECONNREFUSED && failure != ENOENT
+ case .failure(.pathTooLong), .failure(.socket):
+ // A socket that cannot be probed (a path too long for sun_path, or
+ // no descriptor to probe with) is there all the same, and calling
+ // it stale would let a clone or revert copy or replace the state
+ // files of a running guest, so it counts as live; removing a stale
+ // one by hand clears the refusal.
+ return true
}
- if result == 0 { return true }
- let failure = errno
- return failure != ECONNREFUSED && failure != ENOENT
}
}
diff --git a/VPhoneKit/VPhoneCoreKit/Process/VPhoneUnixSocket.swift b/VPhoneKit/VPhoneCoreKit/Process/VPhoneUnixSocket.swift
new file mode 100644
index 00000000..84701745
--- /dev/null
+++ b/VPhoneKit/VPhoneCoreKit/Process/VPhoneUnixSocket.swift
@@ -0,0 +1,48 @@
+import Darwin
+import Foundation
+
+// MARK: - Unix Socket
+
+/// A client connection to a Unix-domain stream socket by path: the one place
+/// that packs a `sockaddr_un`. Used for a VM's control socket, `vphone.sock`,
+/// both to talk to it and to tell a live VM from a stale socket file.
+public enum VPhoneUnixSocket {
+ public enum ConnectError: Error, Equatable {
+ /// The path does not fit `sun_path` with its terminating NUL.
+ case pathTooLong
+ /// `socket(2)` failed, with its errno.
+ case socket(Int32)
+ /// `connect(2)` failed, with its errno: ECONNREFUSED for a socket
+ /// file nobody listens on, ENOENT for no file, EACCES for one this
+ /// user may not write.
+ case connect(Int32)
+ }
+
+ /// A connected descriptor, which the caller closes.
+ public static func connect(to path: String) -> Result<Int32, ConnectError> {
+ let bytes = path.utf8CString
+ var address = sockaddr_un()
+ guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else {
+ return .failure(.pathTooLong)
+ }
+ address.sun_family = sa_family_t(AF_UNIX)
+ withUnsafeMutableBytes(of: &address.sun_path) { buffer in
+ for (index, byte) in bytes.enumerated() {
+ buffer[index] = UInt8(bitPattern: byte)
+ }
+ }
+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)
+ guard fd >= 0 else { return .failure(.socket(errno)) }
+ let connected = withUnsafePointer(to: &address) { pointer in
+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ Darwin.connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
+ }
+ }
+ guard connected == 0 else {
+ let failure = errno
+ close(fd)
+ return .failure(.connect(failure))
+ }
+ return .success(fd)
+ }
+}
diff --git a/VPhoneKit/VPhoneCoreKitTests/Process/UnixSocketTests.swift b/VPhoneKit/VPhoneCoreKitTests/Process/UnixSocketTests.swift
new file mode 100644
index 00000000..392bb92f
--- /dev/null
+++ b/VPhoneKit/VPhoneCoreKitTests/Process/UnixSocketTests.swift
@@ -0,0 +1,50 @@
+import Darwin
+import Foundation
+import Testing
+@testable import VPhoneCoreKit
+
+/// Connecting to a Unix-domain socket by path, and the errors that tell a
+/// stale or missing socket from one that refuses this user.
+struct UnixSocketTests {
+ @Test func `a path that does not fit sun_path is refused before any socket is made`() {
+ let path = "/tmp/" + String(repeating: "a", count: 200)
+ #expect(VPhoneUnixSocket.connect(to: path) == .failure(.pathTooLong))
+ }
+
+ @Test func `a missing socket file fails to connect with ENOENT`() {
+ let path = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString).path
+ #expect(VPhoneUnixSocket.connect(to: path) == .failure(.connect(ENOENT)))
+ }
+
+ @Test func `a listening socket connects and a closed one is refused`() throws {
+ let path = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString.prefix(8)).sock").path
+ try #require(path.utf8.count < 104)
+ defer { unlink(path) }
+
+ let server = socket(AF_UNIX, SOCK_STREAM, 0)
+ try #require(server >= 0)
+ var address = sockaddr_un()
+ address.sun_family = sa_family_t(AF_UNIX)
+ withUnsafeMutableBytes(of: &address.sun_path) { buffer in
+ for (index, byte) in path.utf8.enumerated() {
+ buffer[index] = byte
+ }
+ }
+ let bound = withUnsafePointer(to: &address) { pointer in
+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ bind(server, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
+ }
+ }
+ try #require(bound == 0)
+ try #require(listen(server, 1) == 0)
+
+ guard case let .success(fd) = VPhoneUnixSocket.connect(to: path) else {
+ Issue.record("A listening socket did not accept the connection")
+ close(server)
+ return
+ }
+ close(fd)
+ close(server)
+ #expect(VPhoneUnixSocket.connect(to: path) == .failure(.connect(ECONNREFUSED)))
+ }
+}