Publish VCC Plus OSS source distribution for 3.6.2 build 60

This commit is contained in:
Brian Holman committed 2026-11-13 00:14:03 -07:00
commit c652a5276d
1192 files changed
+272368

No files matched your search

@@ -0,0 +1,41 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
/// Immutable disk copies only. No writable file URL is passed between hosts.
enum CompanionDiskTransfer {
static let version = 1
struct Slot: Codable, Identifiable, Sendable {
let number: Int
let name: String?
let editing: Bool
var mediaID: UUID? = nil
var id: Int { number }
}
struct Destination: Codable, Identifiable, Sendable {
let id: UUID
let name: String
let permissionGranted: Bool
let slots: [Slot]
}
struct Request: Codable, Sendable {
let destination: UUID
let drive: Int
let name: String
let bytes: Data
let expectedDiskName: String?
var expectedMediaID: UUID? = nil
}
struct Receipt: Codable, Sendable {
enum Status: String, Codable { case waitingForPermission, received, denied }
let id: UUID
let status: Status
let message: String
}
}
struct CompanionCapabilities: Codable, Sendable {
let protocolVersion: Int
let productVersion: String
let diskEditor: Bool
let diskLibrary: Bool
}
@@ -0,0 +1,446 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
import Darwin
import Security
/// Private, authenticated, one-request-per-connection companion IPC. Both apps
/// compile this exact source; no database, disk, or emulator commands live here.
enum CompanionTransport {
static var publisherTeamID: String {
(Bundle.main.object(forInfoDictionaryKey: "VCCCompanionTeamIdentifier") as? String ?? "")
.trimmingCharacters(in: .whitespacesAndNewlines)
}
static let protocolVersion = 1
static let maximumPayloadBytes = 24 * 1024 * 1024
private static let maximumFrameBytes = 32 * 1024 * 1024 + 4096
struct Configuration: Sendable {
var directory: URL
var timeout: TimeInterval = 120
var socketName = "service.sock"
var teamID = CompanionTransport.publisherTeamID
var serverBundleIDs: Set<String> = ["com.brianholman.vccplus.oss.mac"]
var clientBundleIDs: Set<String> = ["com.brianholman.vccplus.oss.drivewire"]
#if VCC_COMPANION_TESTING
var allowUnsignedTestPeers = false
#endif
static var production: Configuration {
Configuration(directory: URL(fileURLWithPath: "/private/tmp/vccplus-oss-companion-\(geteuid())", isDirectory: true))
}
static var vccPlus: Configuration { .production }
static var driveWire: Configuration {
var configuration = production
configuration.socketName = "drivewire.sock"
configuration.serverBundleIDs = ["com.brianholman.vccplus.oss.drivewire"]
configuration.clientBundleIDs = ["com.brianholman.vccplus.oss.mac"]
return configuration
}
var expectedServerBundleIDs: Set<String> {
get { serverBundleIDs }
set { serverBundleIDs = newValue }
}
var expectedClientBundleIDs: Set<String> {
get { clientBundleIDs }
set { clientBundleIDs = newValue }
}
var socketPath: String { directory.appendingPathComponent(socketName).path }
}
enum Failure: LocalizedError {
case unavailable, busy, untrustedPeer, unsafeEndpoint, unsupportedVersion, malformedFrame, tooLarge, timedOut
case remote(String)
var errorDescription: String? {
switch self {
case .unavailable: "VCC Plus's companion service is not available."
case .busy: "Another VCC Plus companion service is already running."
case .untrustedPeer: "The companion application's identity could not be verified."
case .unsafeEndpoint: "The companion service location is not private or has changed."
case .unsupportedVersion: "These application versions do not support the same companion protocol."
case .malformedFrame: "The companion service returned an invalid response."
case .tooLarge: "The companion request or response exceeds the supported size."
case .timedOut: "The companion operation timed out."
case .remote(let message): message
}
}
}
private struct Request: Codable {
let version: Int
let id: UUID
let method: String
let payload: Data
}
private struct Response: Codable {
let version: Int
let id: UUID
let payload: Data?
let error: String?
}
struct Client: Sendable {
let configuration: Configuration
init(configuration: Configuration = .production) { self.configuration = configuration }
func request(method: String, payload: Data = Data()) async throws -> Data {
guard !method.isEmpty, method.utf8.count <= 128 else { throw Failure.malformedFrame }
guard payload.count <= maximumPayloadBytes else { throw Failure.tooLarge }
let state = Connection()
return try await withTaskCancellationHandler {
try Task.checkCancellation()
return try await withCheckedThrowingContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
defer { state.finish() }
do {
let fd = try makeSocket()
try state.attach(fd)
try checkDirectory(configuration.directory, create: false)
try checkSocket(configuration.socketPath)
let deadline = Date().addingTimeInterval(configuration.timeout)
try connect(fd, path: configuration.socketPath, deadline: deadline, state: state)
try authenticate(fd, configuration: configuration, permittedIDs: configuration.serverBundleIDs)
let id = UUID()
try writeFrame(JSONEncoder().encode(Request(version: protocolVersion, id: id, method: method, payload: payload)), fd: fd, deadline: deadline, state: state)
let result = try JSONDecoder().decode(Response.self, from: readFrame(fd, deadline: deadline, state: state))
guard result.version == protocolVersion else { throw Failure.unsupportedVersion }
guard result.id == id else { throw Failure.malformedFrame }
if let error = result.error { throw Failure.remote(error) }
guard let data = result.payload, data.count <= maximumPayloadBytes else { throw Failure.malformedFrame }
continuation.resume(returning: data)
} catch { continuation.resume(throwing: state.isCancelled ? CancellationError() : error) }
}
}
} onCancel: { state.cancel() }
}
}
final class Server: @unchecked Sendable {
typealias Handler = @Sendable (String, Data) async throws -> Data
let configuration: Configuration
private let handler: Handler
private let stateLock = NSLock()
private let queue = DispatchQueue(label: "com.brianholman.vccplus.companion.accept")
private let slots = DispatchSemaphore(value: 4)
private var listener: DispatchSourceRead?
private var lockFD: Int32 = -1
private var endpoint: (dev_t, ino_t)?
private var connections: [UUID: Connection] = [:]
private var stopped = false
init(configuration: Configuration = .production, handler: @escaping Handler) throws {
self.configuration = configuration; self.handler = handler
try checkDirectory(configuration.directory, create: true)
let lockPath = configuration.directory.appendingPathComponent(configuration.socketName + ".lock").path
lockFD = open(lockPath, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, 0o600)
guard lockFD >= 0 else { throw Failure.unsafeEndpoint }
var lockInfo = stat()
guard fstat(lockFD, &lockInfo) == 0, lockInfo.st_uid == geteuid(),
lockInfo.st_mode & S_IFMT == S_IFREG, lockInfo.st_mode & 0o777 == 0o600 else {
close(lockFD); lockFD = -1; throw Failure.unsafeEndpoint
}
guard flock(lockFD, LOCK_EX | LOCK_NB) == 0 else {
close(lockFD); lockFD = -1; throw Failure.busy
}
var fd: Int32 = -1
do {
try removeStaleSocket(configuration.socketPath)
fd = try makeSocket()
var address = try unixAddress(configuration.socketPath)
try checked(withUnsafePointer(to: &address) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.bind(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
})
guard chmod(configuration.socketPath, 0o600) == 0 else { throw Failure.unsafeEndpoint }
var info = stat(); guard lstat(configuration.socketPath, &info) == 0 else { throw Failure.unsafeEndpoint }
endpoint = (info.st_dev, info.st_ino)
try checked(Darwin.listen(fd, 8))
let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: queue)
let socketFD = fd
source.setEventHandler { [weak self] in self?.acceptConnection(socketFD) }
source.setCancelHandler { close(socketFD) }
listener = source; source.resume()
} catch {
if fd >= 0 { close(fd) }
removeOwnedEndpoint()
flock(lockFD, LOCK_UN); close(lockFD); lockFD = -1
throw error
}
}
private func acceptConnection(_ fd: Int32) {
while true {
let peer = Darwin.accept(fd, nil, nil)
guard peer >= 0 else { return }
guard slots.wait(timeout: .now()) == .success else { close(peer); continue }
let connection = Connection(), id = UUID()
do { try configureSocket(peer); try connection.attach(peer) }
catch { close(peer); slots.signal(); continue }
stateLock.lock()
let accepting = !stopped
if accepting { connections[id] = connection }
stateLock.unlock()
guard accepting else { connection.finish(); slots.signal(); return }
DispatchQueue.global(qos: .utility).async { [self] in
do {
try authenticate(peer, configuration: configuration, permittedIDs: configuration.clientBundleIDs)
let deadline = Date().addingTimeInterval(configuration.timeout)
let request = try JSONDecoder().decode(Request.self, from: readFrame(peer, deadline: deadline, state: connection))
guard request.version == protocolVersion else { throw Failure.unsupportedVersion }
guard !request.method.isEmpty, request.method.utf8.count <= 128,
request.payload.count <= maximumPayloadBytes else { throw Failure.malformedFrame }
let task = Task { [self] in
let response: Response
do {
let payload = try await withThrowingTaskGroup(of: Data.self) { group in
group.addTask { try await self.handler(request.method, request.payload) }
group.addTask {
while true {
try Task.checkCancellation()
if Date() >= deadline { throw Failure.timedOut }
if connection.isCancelled { throw CancellationError() }
var byte: UInt8 = 0
let count = recv(peer, &byte, 1, MSG_PEEK | MSG_DONTWAIT)
if count == 0 { throw CancellationError() }
if count > 0 { throw Failure.malformedFrame } // exactly one request per connection
if errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR { throw Failure.unavailable }
try await Task.sleep(nanoseconds: 100_000_000)
}
}
defer { group.cancelAll() }
return try await group.next()!
}
guard payload.count <= maximumPayloadBytes else { throw Failure.tooLarge }
response = Response(version: protocolVersion, id: request.id, payload: payload, error: nil)
} catch {
response = Response(version: protocolVersion, id: request.id, payload: nil, error: String(error.localizedDescription.prefix(2048)))
}
await withCheckedContinuation { (done: CheckedContinuation<Void, Never>) in
DispatchQueue.global(qos: .utility).async { [self] in
defer { finish(id, connection: connection); done.resume() }
if let bytes = try? JSONEncoder().encode(response) {
try? writeFrame(bytes, fd: peer, deadline: deadline, state: connection)
}
}
}
}
connection.setTask(task)
} catch { finish(id, connection: connection) }
}
}
}
private func finish(_ id: UUID, connection: Connection) {
connection.finish()
stateLock.lock(); let removed = connections.removeValue(forKey: id); stateLock.unlock()
if removed != nil { slots.signal() }
}
func stop() {
stateLock.lock()
guard !stopped else { stateLock.unlock(); return }
stopped = true
let source = listener; listener = nil
let active = Array(connections.values)
stateLock.unlock()
source?.cancel()
for connection in active { connection.cancel() }
removeOwnedEndpoint()
if lockFD >= 0 { flock(lockFD, LOCK_UN); close(lockFD); lockFD = -1 }
}
private func removeOwnedEndpoint() {
guard let endpoint else { return }
var info = stat()
if lstat(configuration.socketPath, &info) == 0, info.st_uid == geteuid(),
info.st_mode & S_IFMT == S_IFSOCK, info.st_dev == endpoint.0, info.st_ino == endpoint.1 {
_ = unlink(configuration.socketPath)
}
self.endpoint = nil
}
deinit { stop() }
}
/// A descriptor is closed once, by its IO worker. Cancellation only shuts it
/// down under a lock so a recycled descriptor can never be closed by a task.
private final class Connection: @unchecked Sendable {
private let lock = NSLock()
private var fd: Int32 = -1
private var cancelled = false
private var finished = false
private var task: Task<Void, Never>?
var isCancelled: Bool { lock.lock(); defer { lock.unlock() }; return cancelled }
func attach(_ value: Int32) throws {
lock.lock(); defer { lock.unlock() }
if cancelled { close(value); throw CancellationError() }
fd = value
}
func setTask(_ value: Task<Void, Never>) {
lock.lock(); let cancel = cancelled || finished
if !cancel { task = value }
lock.unlock()
if cancel { value.cancel() }
}
func cancel() {
lock.lock(); cancelled = true
if fd >= 0 { _ = shutdown(fd, SHUT_RDWR) }
let running = task; lock.unlock(); running?.cancel()
}
func finish() {
lock.lock(); let value = fd; fd = -1; task = nil; finished = true; lock.unlock()
if value >= 0 { close(value) }
}
}
private static func checked(_ value: Int32) throws {
guard value >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
}
private static func makeSocket() throws -> Int32 {
let fd = socket(AF_UNIX, SOCK_STREAM, 0)
guard fd >= 0 else { throw Failure.unavailable }
do { try configureSocket(fd); return fd } catch { close(fd); throw error }
}
private static func configureSocket(_ fd: Int32) throws {
try checked(fcntl(fd, F_SETFL, O_NONBLOCK)); try checked(fcntl(fd, F_SETFD, FD_CLOEXEC))
var yes: Int32 = 1
try checked(setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &yes, socklen_t(MemoryLayout.size(ofValue: yes))))
}
private static func unixAddress(_ path: String) throws -> sockaddr_un {
var address = sockaddr_un()
address.sun_family = sa_family_t(AF_UNIX); address.sun_len = UInt8(MemoryLayout<sockaddr_un>.size)
let bytes = Array(path.utf8CString)
guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else { throw Failure.unsafeEndpoint }
withUnsafeMutableBytes(of: &address.sun_path) { target in bytes.withUnsafeBytes { target.copyBytes(from: $0) } }
return address
}
private static func checkDirectory(_ url: URL, create: Bool) throws {
if create, mkdir(url.path, 0o700) != 0, errno != EEXIST { throw Failure.unsafeEndpoint }
var info = stat()
guard lstat(url.path, &info) == 0, info.st_uid == geteuid(), info.st_mode & S_IFMT == S_IFDIR,
info.st_mode & 0o777 == 0o700 else { throw Failure.unsafeEndpoint }
}
private static func checkSocket(_ path: String) throws {
var info = stat()
guard lstat(path, &info) == 0 else { throw Failure.unavailable }
guard info.st_uid == geteuid(), info.st_mode & S_IFMT == S_IFSOCK,
info.st_mode & 0o777 == 0o600 else { throw Failure.unsafeEndpoint }
}
private static func removeStaleSocket(_ path: String) throws {
var before = stat()
guard lstat(path, &before) == 0 else {
if errno == ENOENT { return }; throw Failure.unsafeEndpoint
}
try checkSocket(path)
let fd = try makeSocket(); defer { close(fd) }
var address = try unixAddress(path)
let rc = withUnsafePointer(to: &address) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
}
guard rc < 0, errno == ECONNREFUSED || errno == ENOENT else { throw Failure.busy }
var after = stat()
guard lstat(path, &after) == 0, after.st_uid == geteuid(), after.st_mode & S_IFMT == S_IFSOCK,
before.st_dev == after.st_dev, before.st_ino == after.st_ino else { throw Failure.unsafeEndpoint }
try checked(unlink(path))
}
private static func connect(_ fd: Int32, path: String, deadline: Date, state: Connection) throws {
var address = try unixAddress(path)
let rc = withUnsafePointer(to: &address) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
}
if rc < 0 {
guard errno == EINPROGRESS || errno == EAGAIN else { throw Failure.unavailable }
try wait(fd, events: Int16(POLLOUT), deadline: deadline, state: state)
var error: Int32 = 0, length = socklen_t(MemoryLayout<Int32>.size)
guard getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &length) == 0, error == 0 else { throw Failure.unavailable }
}
}
private static func wait(_ fd: Int32, events: Int16, deadline: Date, state: Connection) throws {
while true {
if state.isCancelled { throw CancellationError() }
guard Date() < deadline else { throw Failure.timedOut }
var descriptor = pollfd(fd: fd, events: events, revents: 0)
let rc = poll(&descriptor, 1, 100)
if rc > 0 {
if descriptor.revents & events != 0 { return }
throw Failure.unavailable
}
if rc < 0 && errno != EINTR { throw Failure.unavailable }
}
}
private static func readBytes(_ count: Int, fd: Int32, deadline: Date, state: Connection) throws -> Data {
var result = Data(count: count)
try result.withUnsafeMutableBytes { buffer in
var offset = 0
while offset < count {
try wait(fd, events: Int16(POLLIN), deadline: deadline, state: state)
let size = recv(fd, buffer.baseAddress! + offset, count - offset, 0)
if size > 0 { offset += size }
else if size == 0 { throw Failure.unavailable }
else if errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK { throw Failure.unavailable }
}
}
return result
}
private static func readFrame(_ fd: Int32, deadline: Date, state: Connection) throws -> Data {
let prefix = try readBytes(4, fd: fd, deadline: deadline, state: state)
let size = prefix.reduce(UInt32(0)) { ($0 << 8) | UInt32($1) }
guard size > 0, size <= maximumFrameBytes else { throw Failure.tooLarge }
return try readBytes(Int(size), fd: fd, deadline: deadline, state: state)
}
private static func writeFrame(_ data: Data, fd: Int32, deadline: Date, state: Connection) throws {
guard data.count <= maximumFrameBytes else { throw Failure.tooLarge }
var size = UInt32(data.count).bigEndian
let frame = withUnsafeBytes(of: &size) { Data($0) } + data
try frame.withUnsafeBytes { buffer in
var offset = 0
while offset < frame.count {
try wait(fd, events: Int16(POLLOUT), deadline: deadline, state: state)
let sent = send(fd, buffer.baseAddress! + offset, frame.count - offset, 0)
if sent > 0 { offset += sent }
else if sent == 0 { throw Failure.unavailable }
else if errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK { throw Failure.unavailable }
}
}
}
/// Validate a discovered/selected companion before asking Launch Services to
/// run it. Bundle metadata alone is not authorization to execute an app.
/// This reads and verifies code on disk; callers should run it off the main actor.
static func validateApplication(at url: URL, permittedBundleIDs: Set<String>,
teamID: String = CompanionTransport.publisherTeamID) throws {
guard !teamID.isEmpty, url.isFileURL, !permittedBundleIDs.isEmpty else { throw Failure.untrustedPeer }
var code: SecStaticCode?
guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess, let code else { throw Failure.untrustedPeer }
var info: CFDictionary?
guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess,
let values = info as? [String: Any], let identifier = values[kSecCodeInfoIdentifier as String] as? String,
permittedBundleIDs.contains(identifier), values[kSecCodeInfoTeamIdentifier as String] as? String == teamID else {
throw Failure.untrustedPeer
}
var requirement: SecRequirement?
guard SecRequirementCreateWithString("anchor apple generic" as CFString, [], &requirement) == errSecSuccess,
SecStaticCodeCheckValidity(code, SecCSFlags(rawValue: kSecCSStrictValidate | kSecCSCheckAllArchitectures), requirement) == errSecSuccess else {
throw Failure.untrustedPeer
}
}
private static func authenticate(_ fd: Int32, configuration: Configuration, permittedIDs: Set<String>) throws {
var uid: uid_t = 0, gid: gid_t = 0
guard getpeereid(fd, &uid, &gid) == 0, uid == geteuid() else { throw Failure.untrustedPeer }
#if VCC_COMPANION_TESTING
if configuration.allowUnsignedTestPeers { return }
#endif
guard !configuration.teamID.isEmpty else { throw Failure.untrustedPeer }
var pid: pid_t = 0, length = socklen_t(MemoryLayout<pid_t>.size)
guard getsockopt(fd, SOL_LOCAL, LOCAL_PEERPID, &pid, &length) == 0, pid > 0 else { throw Failure.untrustedPeer }
var guest: SecCode?
let attributes = [kSecGuestAttributePid: NSNumber(value: pid)] as CFDictionary
guard SecCodeCopyGuestWithAttributes(nil, attributes, [], &guest) == errSecSuccess, let guest else { throw Failure.untrustedPeer }
var staticCode: SecStaticCode?
guard SecCodeCopyStaticCode(guest, [], &staticCode) == errSecSuccess, let staticCode else { throw Failure.untrustedPeer }
var info: CFDictionary?
guard SecCodeCopySigningInformation(staticCode, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess,
let values = info as? [String: Any], let identifier = values[kSecCodeInfoIdentifier as String] as? String,
permittedIDs.contains(identifier), values[kSecCodeInfoTeamIdentifier as String] as? String == configuration.teamID else { throw Failure.untrustedPeer }
// A matching string in an unsigned plist or an ad-hoc signature is not trust.
var requirement: SecRequirement?
guard SecRequirementCreateWithString("anchor apple generic" as CFString, [], &requirement) == errSecSuccess,
SecCodeCheckValidity(guest, SecCSFlags(rawValue: kSecCSStrictValidate), requirement) == errSecSuccess else { throw Failure.untrustedPeer }
}
}
@@ -0,0 +1,89 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
import Darwin
/// Explicit, isolated native companion fixtures. Shipping identities cannot opt
/// into this mode, and its peers still need normal same-team Apple signatures.
enum CompanionValidation {
static let vccPlusBundleID = "com.brianholman.vccplus.oss.mac.uitesting"
static let driveWireBundleID = "com.brianholman.vccplus.oss.drivewire.companionpreview"
private static let rootArgument = "--companion-validation-root"
private static let peerArgument = "--companion-validation-peer"
static var requested: Bool {
CommandLine.arguments.contains(rootArgument) || CommandLine.arguments.contains(peerArgument)
}
static var enabled: Bool { (try? context()) != nil }
static var root: URL? { (try? context())?.directory }
static var vccApplicationURL: URL? { (try? context())?.peer }
/// Invalid explicit fixture arguments never fall through to a real listener.
/// Both apps use this helper for every server and client endpoint selection.
static func configuration(forVCCPlus: Bool) throws -> CompanionTransport.Configuration {
let production: CompanionTransport.Configuration = forVCCPlus ? .vccPlus : .driveWire
guard requested else {
// An isolated preview accidentally launched without its arguments
// must never occupy the real application's service endpoint.
guard ![vccPlusBundleID, driveWireBundleID].contains(Bundle.main.bundleIdentifier ?? "") else {
throw CompanionTransport.Failure.unsafeEndpoint
}
return production
}
guard let fixture = try context() else { throw CompanionTransport.Failure.unsafeEndpoint }
var config = production
config.directory = fixture.directory
config.expectedServerBundleIDs = [forVCCPlus ? vccPlusBundleID : driveWireBundleID]
config.expectedClientBundleIDs = [forVCCPlus ? driveWireBundleID : vccPlusBundleID]
return config
}
private struct Context { let directory: URL; let peer: URL? }
private static func context() throws -> Context? {
guard requested else { return nil }
#if DEBUG
guard let identifier = Bundle.main.bundleIdentifier,
[vccPlusBundleID, driveWireBundleID].contains(identifier) else {
throw CompanionTransport.Failure.untrustedPeer
}
let arguments = CommandLine.arguments
func value(_ flag: String) throws -> String? {
let positions = arguments.indices.filter { arguments[$0] == flag }
guard positions.count <= 1 else { throw CompanionTransport.Failure.unsafeEndpoint }
guard let position = positions.first else { return nil }
guard arguments.indices.contains(position + 1), !arguments[position + 1].hasPrefix("--") else {
throw CompanionTransport.Failure.unsafeEndpoint
}
return arguments[position + 1]
}
guard let supplied = try value(rootArgument), supplied.hasPrefix("/") else {
throw CompanionTransport.Failure.unsafeEndpoint
}
let url = URL(fileURLWithPath: supplied, isDirectory: true).standardizedFileURL
let canonical = url.resolvingSymlinksInPath()
var info = stat()
// Foundation canonicalizes /private/tmp to /tmp on some macOS builds.
// Both aliases name the system temporary directory; the final component
// is checked without following a supplied root symlink.
var rawRoot = supplied
while rawRoot.count > 1 && rawRoot.hasSuffix("/") { rawRoot.removeLast() }
guard (canonical.path.hasPrefix("/private/tmp/") || canonical.path.hasPrefix("/tmp/")),
lstat(rawRoot, &info) == 0, info.st_uid == geteuid(),
info.st_mode & S_IFMT == S_IFDIR, info.st_mode & 0o777 == 0o700,
canonical.appendingPathComponent("drivewire.sock").path.utf8.count < MemoryLayout.size(ofValue: sockaddr_un().sun_path) else {
throw CompanionTransport.Failure.unsafeEndpoint
}
var peer: URL?
if let path = try value(peerArgument) {
guard path.hasPrefix("/") else { throw CompanionTransport.Failure.untrustedPeer }
let url = URL(fileURLWithPath: path).standardizedFileURL
guard Bundle(url: url)?.bundleIdentifier == vccPlusBundleID else { throw CompanionTransport.Failure.untrustedPeer }
// The launch path is additionally checked with validateApplication
// off the main actor before it is ever executed.
peer = url
}
return Context(directory: canonical, peer: peer)
#else
throw CompanionTransport.Failure.untrustedPeer
#endif
}
}
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
struct SecondaryCard<Content: View>: View {
private let content: Content
init(@ViewBuilder content: () -> Content) { self.content = content() }
var body: some View {
VStack(alignment: .leading, spacing: 12) { content }
.frame(maxWidth: .infinity, alignment: .leading).padding(14)
.background(Color.primary.opacity(0.035), in: RoundedRectangle(cornerRadius: 10))
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.primary.opacity(0.07)))
}
}
struct SecondaryHelp<Content: View>: View {
let title: String
private let content: Content
@State private var expanded = false
init(title: String, @ViewBuilder content: () -> Content) {
self.title = title; self.content = content()
}
var body: some View {
DisclosureGroup(isExpanded: $expanded) {
VStack(alignment: .leading, spacing: 8) { content }
.font(.callout).foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true).padding(.top, 6)
} label: {
Label(title, systemImage: "questionmark.circle").font(.callout)
}
}
}
struct SecondaryAction: View {
let title: String
let systemImage: String
let action: () -> Void
var body: some View {
Button(action: action) { Label(title, systemImage: systemImage).foregroundStyle(.primary) }
.buttonStyle(.bordered)
}
}
@@ -0,0 +1,66 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
/// VCC Plus owns one catalog and installation authority. Only the authenticated,
/// disk-only request vocabulary crosses this boundary; no machine is exposed.
final class VCCCompanionService: @unchecked Sendable {
private let server: CompanionTransport.Server
@MainActor
init(library: SoftwareLibraryModel, configuration: CompanionTransport.Configuration = .vccPlus) throws {
let authority = CompanionLibraryAuthority(model: library)
let capabilities = CompanionCapabilities(protocolVersion: CompanionTransport.protocolVersion,
productVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "",
diskEditor: true, diskLibrary: true)
server = try CompanionTransport.Server(configuration: configuration) { method, payload in
try await Self.handle(method: method, payload: payload, authority: authority, capabilities: capabilities)
}
}
nonisolated private static func handle(method: String, payload: Data,
authority: CompanionLibraryAuthority, capabilities: CompanionCapabilities) async throws -> Data {
try Task.checkCancellation()
switch method {
case "capabilities":
guard payload.isEmpty else { throw CompanionLibraryFailure(message: "Invalid companion capabilities request.") }
return try JSONEncoder().encode(capabilities)
case "library":
guard payload.count <= 32 * 1024 else { throw CompanionLibraryFailure(message: "The library request is too large.") }
let request = try JSONDecoder().decode(CompanionLibraryRequest.self, from: payload)
let response = try await authority.handle(request)
try Task.checkCancellation()
// A complete catalog snapshot can be several MiB. Its encoding must
// not occupy the native window's main actor.
return try await Task.detached(priority: .utility) { try JSONEncoder().encode(response) }.value
default:
throw CompanionLibraryFailure(message: "This VCC Plus version does not support that companion operation.")
}
}
func stop() { server.stop() }
deinit { server.stop() }
}
import AppKit
import SwiftUI
/// A background catalog request creates no Metal display, polling timer, input
/// owner or saved machine-window placement. The same window hosts MachineView
/// only after an explicit activation of VCC Plus.
struct VCCCompanionDeferredMachineView: NSViewRepresentable {
let onWindow: @MainActor (NSWindow) -> Void
func makeNSView(context: Context) -> Anchor {
let view = Anchor(); view.onWindow = onWindow; return view
}
func updateNSView(_ view: Anchor, context: Context) { view.onWindow = onWindow }
final class Anchor: NSView {
var onWindow: (@MainActor (NSWindow) -> Void)?
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
guard let window else { return }
DispatchQueue.main.async { [weak self, weak window] in
guard let window else { return }
self?.onWindow?(window)
}
}
}
}
@@ -0,0 +1,211 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
/// Explicit immutable copies from an emulated floppy to an already running host.
/// This view never opens the source file, pauses/restarts the machine or launches DriveWire.
struct VCCDriveWireTransferView: View {
@ObservedObject var machine: MachineModel
let drive: Int
let sourceName: String
let sourceEpoch: UInt64
@Environment(\.dismiss) private var dismiss
@State private var destinations: [CompanionDiskTransfer.Destination] = []
@State private var destinationID: UUID?
@State private var selectedDrive = 0
@State private var loading = false
@State private var busy = false
@State private var canceling = false
@State private var receipt: CompanionDiskTransfer.Receipt?
@State private var error: String?
@State private var sending: Task<Void, Never>?
private var client: CompanionTransport.Client {
get throws { CompanionTransport.Client(configuration: try CompanionValidation.configuration(forVCCPlus: false)) }
}
private var destination: CompanionDiskTransfer.Destination? { destinations.first { $0.id == destinationID } }
private var slot: CompanionDiskTransfer.Slot? { destination?.slots.first { $0.number == selectedDrive } }
private var sourceFormatSupported: Bool {
guard (0..<machine.disks.count).contains(drive), let ext = machine.disks[drive].floppyExtension?.lowercased() else { return false }
let disk = machine.disks[drive]
return ["dsk", "os9", "jvc"].contains(ext) && disk.byteCount > 0 && disk.byteCount % 256 == 0
}
private var completed: Bool { receipt?.status == .received }
private var waiting: Bool { receipt?.status == .waitingForPermission }
var body: some View {
VStack(alignment: .leading, spacing: 0) {
SecondaryHeader(title: "Send a Copy to DriveWire", symbol: "paperplane",
subtitle: "Copy FD\(drive)'s current disk to your real CoCo's DriveWire host.")
.padding(20)
Divider()
ScrollView {
VStack(alignment: .leading, spacing: 16) {
SecondaryCard {
Label("Source disk", systemImage: "externaldrive").font(.headline)
Text(sourceName).font(.callout.weight(.medium)).textSelection(.enabled)
if !sourceFormatSupported {
Label("This image uses an encoded disk format. Convert a compatible raw DSK copy before sending it to DriveWire.", systemImage: "info.circle")
.font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
}
Label("Includes current changes in memory. The emulator, source disk and save mode stay as they are.", systemImage: "doc.on.doc")
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
}
if loading {
ProgressView("Looking for DriveWire sessions…").frame(maxWidth: .infinity)
} else if destinations.isEmpty {
ContentUnavailableView {
Label("No DriveWire sessions available", systemImage: "cable.connector")
} description: {
Text("Open DriveWire for VCC Plus and start the serial session you want to use, then choose Refresh. This window does not start or reconnect it.")
} actions: {
Button("Refresh", systemImage: "arrow.clockwise") { Task { await refresh() } }
}
} else {
SecondaryCard {
Label("Destination", systemImage: "paperplane").font(.headline)
Picker("DriveWire session", selection: $destinationID) {
Text("Choose a session").tag(UUID?.none)
ForEach(destinations) { destination in Text(destination.name).tag(Optional(destination.id)) }
}.accessibilityIdentifier("drivewire-copy-session")
if let destination {
Picker("Drive", selection: $selectedDrive) {
ForEach(destination.slots) { slot in
Text("DW\(slot.number) — " + (slot.editing ? "Editing" : slot.name ?? "Empty"))
.tag(slot.number).disabled(slot.editing)
}
}.accessibilityIdentifier("drivewire-copy-slot")
if let slot, slot.editing {
Label("Finish editing this DriveWire disk before sending a copy.", systemImage: "pencil")
.font(.callout).foregroundStyle(.secondary)
} else if let name = slot?.name {
Label("DW\(selectedDrive) currently holds \(name). DriveWire will retain its current bytes as a recoverable copy before replacing it.", systemImage: "doc.on.doc")
.font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
}
Label(destination.permissionGranted
? "This DriveWire connection has already allowed copies from VCC Plus."
: "DriveWire will ask for permission before accepting the first copy on this connection.",
systemImage: destination.permissionGranted ? "checkmark.shield" : "hand.raised")
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
}
Button("Refresh Sessions", systemImage: "arrow.clockwise") { Task { await refresh() } }
.disabled(busy)
}.disabled(busy || completed)
}
if let receipt {
Label(receipt.message, systemImage: completed ? "checkmark.circle" : waiting ? "hand.raised" : "xmark.circle")
.font(.callout).foregroundStyle(completed ? Color.green : Color.secondary)
.fixedSize(horizontal: false, vertical: true).textSelection(.enabled)
.accessibilityIdentifier("drivewire-copy-status")
}
if let error {
Label(error, systemImage: "exclamationmark.circle").font(.callout).foregroundStyle(.red)
.fixedSize(horizontal: false, vertical: true).textSelection(.enabled)
.accessibilityIdentifier("drivewire-copy-error")
}
}.padding(20)
}
Divider()
HStack {
if busy { ProgressView().controlSize(.small) }
Button(completed ? "Done" : "Cancel", role: completed ? nil : .cancel) { cancelOrClose() }
.disabled(canceling || (busy && receipt == nil))
.keyboardShortcut(.cancelAction)
Spacer()
if !completed {
Button("Send Copy", systemImage: "paperplane") { beginSend() }
.keyboardShortcut(.defaultAction)
.disabled(!sourceFormatSupported || loading || busy || canceling || destination == nil || slot == nil || slot?.editing == true)
.accessibilityIdentifier("drivewire-send-copy")
}
}.padding(16)
}
.frame(width: 600, height: 580)
.interactiveDismissDisabled(busy || canceling)
.task { await refresh() }
.onDisappear { sending?.cancel() }
}
private func refresh() async {
guard !busy else { return }
loading = true; error = nil
defer { loading = false }
do {
let bytes = try await client.request(method: "destinations")
try Task.checkCancellation()
let available = try JSONDecoder().decode([CompanionDiskTransfer.Destination].self, from: bytes)
destinations = available
if destinationID == nil || !available.contains(where: { $0.id == destinationID }) { destinationID = available.first?.id }
if let destination, !destination.slots.contains(where: { $0.number == selectedDrive && !$0.editing }) {
selectedDrive = destination.slots.first(where: { !$0.editing })?.number ?? 0
}
} catch {
guard !Task.isCancelled else { return }
destinations = []; destinationID = nil
self.error = "DriveWire could not be reached. Open a compatible signed DriveWire for VCC Plus build and try Refresh. " + error.localizedDescription
}
}
private func beginSend() {
guard let destination, let slot, !slot.editing, !busy else { return }
error = nil; receipt = nil; busy = true
sending = Task {
defer { busy = false; sending = nil }
do {
try checkSource()
let bytes = try await machine.snapshotDiskCopy(inDrive: drive)
try Task.checkCancellation(); try checkSource()
guard !bytes.isEmpty, bytes.count <= 16 * 1024 * 1024 else {
throw TransferFailure(message: "Choose a floppy image within the 16 MiB transfer limit.")
}
guard bytes.count % 256 == 0 else {
throw TransferFailure(message: "This image contains a file-format header. DriveWire needs a raw image of 256-byte sectors; export or convert a compatible disk copy first.")
}
let request = CompanionDiskTransfer.Request(destination: destination.id, drive: slot.number,
name: transferName, bytes: bytes, expectedDiskName: slot.name, expectedMediaID: slot.mediaID)
let response = try await client.request(method: "sendDisk", payload: JSONEncoder().encode(request))
var result = try JSONDecoder().decode(CompanionDiskTransfer.Receipt.self, from: response)
receipt = result
while result.status == .waitingForPermission {
try await Task.sleep(nanoseconds: 350_000_000)
let data = try await client.request(method: "transferStatus", payload: JSONEncoder().encode(result.id))
try Task.checkCancellation()
result = try JSONDecoder().decode(CompanionDiskTransfer.Receipt.self, from: data)
receipt = result
}
if result.status == .denied { error = result.message }
} catch {
if !Task.isCancelled { self.error = error.localizedDescription }
}
}
}
private var transferName: String {
let file = URL(fileURLWithPath: sourceName).lastPathComponent
let stem = (file as NSString).deletingPathExtension
return (stem.isEmpty ? "Disk" : stem) + ".dsk"
}
private func checkSource() throws {
guard machine.inputEpoch == sourceEpoch, machine.state != .closed, (0..<machine.disks.count).contains(drive),
machine.disks[drive].mounted, machine.disks[drive].name == sourceName else {
throw TransferFailure(message: "The source disk or machine changed. Close this window and choose Send a Copy again.")
}
guard let ext = machine.disks[drive].floppyExtension?.lowercased(), ["dsk", "os9", "jvc"].contains(ext) else {
throw TransferFailure(message: "DriveWire accepts raw sector images. DMK and VDK containers cannot be sent directly; export or convert a compatible raw disk copy first.")
}
}
private func cancelOrClose() {
guard waiting, let id = receipt?.id else { dismiss(); return }
sending?.cancel(); canceling = true
Task {
defer { canceling = false }
do {
let response = try await client.request(method: "cancelTransfer", payload: JSONEncoder().encode(id))
let result = try JSONDecoder().decode(CompanionDiskTransfer.Receipt.self, from: response)
receipt = result
if result.status != .received { dismiss() }
} catch { self.error = "The transfer could not be canceled. Check DriveWire before retrying. " + error.localizedDescription }
}
}
private struct TransferFailure: LocalizedError {
let message: String
var errorDescription: String? { message }
}
}