// SPDX-License-Identifier: GPL-3.0-or-later import Foundation import Darwin /// A connection-scoped, revocable write grant. It never follows a user-selected /// path supplied over MCP: the destination was selected in the native app. final class MCPBuildExporter: @unchecked Sendable { static let maximumFiles = 64 static let maximumSetBytes = 128 * 1024 * 1024 static let maximumSessionBytes = 512 * 1024 * 1024 static let maximumRequests = 64 struct Identity: Equatable, Sendable { let device: dev_t let inode: ino_t init(_ value: stat) { device = value.st_dev; inode = value.st_ino } } struct Source: Sendable { let artifactID: UUID let directory: URL let products: [CMOCBuildOutputProduct] let identity: Identity init(_ artifact: CMOCBuildArtifact) throws { artifactID = artifact.id; directory = artifact.directory; products = artifact.exportProducts let fd = try MCPBuildExporter.directory(artifact.directory) defer { close(fd) } identity = try MCPBuildExporter.identity(fd) } } struct Delivery: Sendable { let directory: String let products: [CMOCBuildOutputProduct] } let destinationID = UUID().uuidString private let root: URL private let rootIdentity: Identity private let state = NSLock() private var valid = true // Only used by authored race/failure fixtures, never populated by public input. var beforeCommit: (@Sendable () throws -> Void)? var afterFile: (@Sendable (Int) throws -> Void)? init(destination: URL) throws { root = destination.standardizedFileURL let fd = try Self.directory(root); defer { close(fd) } rootIdentity = try Self.identity(fd) } func invalidate() { state.lock(); valid = false; state.unlock() } private func check() throws { try Task.checkCancellation() state.lock(); defer { state.unlock() } guard valid else { throw Self.failure("access_denied") } } private static func failure(_ text: String) -> CMOCBuildError { .message(text) } private static func identity(_ descriptor: Int32) throws -> Identity { var value = stat() guard fstat(descriptor, &value) == 0, value.st_mode & S_IFMT == S_IFDIR else { throw failure("export_directory_unavailable") } return Identity(value) } /// Follow only Apple's standard /tmp and /var aliases, never arbitrary links. private static func canonicalPath(_ url: URL) -> String { let path = url.standardizedFileURL.path return path == "/tmp" || path.hasPrefix("/tmp/") || path == "/var" || path.hasPrefix("/var/") ? "/private" + path : path } private static func directory(_ url: URL) throws -> Int32 { let normalized = canonicalPath(url) guard normalized.hasPrefix("/") else { throw failure("invalid_export_directory") } var held = open("/", O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) guard held >= 0 else { throw failure("export_directory_unavailable") } do { for component in normalized.split(separator: "/") { let next = openat(held, String(component), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) guard next >= 0 else { throw failure("export_directory_changed_or_linked") } close(held); held = next } return held } catch { close(held); throw error } } private func destination() throws -> Int32 { try check() let fd = try Self.directory(root) do { guard try Self.identity(fd) == rootIdentity else { throw Self.failure("export_destination_changed") } return fd } catch { close(fd); throw error } } private func source(_ value: Source) throws -> Int32 { try check() let fd = try Self.directory(value.directory) do { guard try Self.identity(fd) == value.identity else { throw Self.failure("export_artifact_changed") } return fd } catch { close(fd); throw error } } private static func parent(_ root: Int32, path: String, create: Bool) throws -> (Int32, String) { try CMOCProject.validateRelativePath(path) let components = path.split(separator: "/").map(String.init) guard components.count <= 32, components.allSatisfy({ $0.utf8.count <= 255 }) else { throw failure("invalid_export_path") } var held = dup(root) guard held >= 0 else { throw failure("export_directory_unavailable") } do { for component in components.dropLast() { if create, mkdirat(held, component, 0o700) != 0, errno != EEXIST { throw failure("export_write_failed") } let next = openat(held, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) guard next >= 0 else { throw failure("export_path_changed_or_linked") } close(held); held = next } return (held, components.last!) } catch { close(held); throw error } } private func read(_ product: CMOCBuildOutputProduct, from directory: Int32) throws -> Data { try check() guard (0...CMOCProject.maximumFileBytes).contains(product.byteCount) else { throw Self.failure("export_output_too_large") } let (parent, leaf) = try Self.parent(directory, path: product.relativePath, create: false) defer { close(parent) } let fd = openat(parent, leaf, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) guard fd >= 0 else { throw Self.failure("export_output_unavailable") } let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true) defer { try? file.close() } var before = stat() guard fstat(fd, &before) == 0, before.st_mode & S_IFMT == S_IFREG, before.st_nlink == 1, before.st_size == off_t(product.byteCount) else { throw Self.failure("export_output_changed_or_linked") } var data = Data() while data.count < product.byteCount { try check() let chunk = try file.read(upToCount: min(65536, product.byteCount - data.count)) ?? Data() guard !chunk.isEmpty else { throw Self.failure("export_output_changed") } data.append(chunk) } var after = stat(), named = stat() guard fstat(fd, &after) == 0, Identity(before) == Identity(after), before.st_size == after.st_size, before.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec, before.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec, fstatat(parent, leaf, &named, AT_SYMLINK_NOFOLLOW) == 0, named.st_mode & S_IFMT == S_IFREG, named.st_nlink == 1, Identity(named) == Identity(after), CMOCProject.sha256(data) == product.sha256 else { throw Self.failure("export_output_changed") } return data } private func verifyContents(_ descriptor: Int32, products: [CMOCBuildOutputProduct], flush: Bool = false) throws { let expected = Set(products.map(\.relativePath)) var observed: Set = [] var visited = 0 func walk(_ fd: Int32, prefix: String, depth: Int) throws { try check() guard depth <= 32 else { throw Self.failure("export_delivery_changed") } let copy = dup(fd) guard copy >= 0, let stream = fdopendir(copy) else { if copy >= 0 { close(copy) }; throw Self.failure("export_delivery_changed") } defer { closedir(stream) } while let entry = readdir(stream) { let name = withUnsafePointer(to: &entry.pointee.d_name) { $0.withMemoryRebound(to: CChar.self, capacity: Int(entry.pointee.d_namlen) + 1) { String(cString: $0) } } if name == "." || name == ".." { continue } visited += 1 guard visited <= Self.maximumFiles * 33 else { throw Self.failure("export_delivery_changed") } let path = prefix.isEmpty ? name : prefix + "/" + name var info = stat() guard fstatat(fd, name, &info, AT_SYMLINK_NOFOLLOW) == 0 else { throw Self.failure("export_delivery_changed") } if info.st_mode & S_IFMT == S_IFDIR { guard expected.contains(where: { $0.hasPrefix(path + "/") }) else { throw Self.failure("export_delivery_changed") } let child = openat(fd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) guard child >= 0 else { throw Self.failure("export_delivery_changed") } defer { close(child) } try walk(child, prefix: path, depth: depth + 1) } else { guard info.st_mode & S_IFMT == S_IFREG, info.st_nlink == 1, expected.contains(path) else { throw Self.failure("export_delivery_changed") } observed.insert(path) } } if flush, fsync(fd) != 0 { throw Self.failure("export_write_failed") } } try walk(descriptor, prefix: "", depth: 0) guard observed == expected else { throw Self.failure("export_delivery_changed") } for product in products { _ = try read(product, from: descriptor) } } /// Creates a complete new set with an exclusive atomic directory rename. /// No existing delivery is removed or repaired. The caller binds Source and /// the request ID to the original connection/build/revision before calling. func export(source value: Source, products: [CMOCBuildOutputProduct], setName: String) throws -> Delivery { guard !products.isEmpty, products.count <= Self.maximumFiles, Set(products.map { $0.relativePath.lowercased() }).count == products.count, products.allSatisfy({ value.products.contains($0) && (0...CMOCProject.maximumFileBytes).contains($0.byteCount) }), products.reduce(0, { $0 + $1.byteCount }) <= Self.maximumSetBytes, setName.hasPrefix("VCC-"), setName.utf8.count < 200, !setName.contains("/") else { throw Self.failure("invalid_export_selection") } let sourcePath = Self.canonicalPath(value.directory), destinationPath = Self.canonicalPath(root) guard destinationPath != sourcePath, !destinationPath.hasPrefix(sourcePath + "/") else { throw Self.failure("export_destination_overlaps_artifact") } let destination = try destination(), source = try source(value) defer { close(destination); close(source) } let stageName = ".vccplus-export-" + UUID().uuidString guard mkdirat(destination, stageName, 0o700) == 0 else { throw Self.failure("export_write_failed") } let stage = openat(destination, stageName, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) guard stage >= 0 else { throw Self.failure("export_write_failed") } defer { close(stage) } var created: [(String, Identity)] = [] var committed = false defer { if !committed { // Remove only this transaction's unchanged files; never recursively // erase unexpected files planted in a failed staging directory. for (path, identity) in created.reversed() { if let (parent, leaf) = try? Self.parent(stage, path: path, create: false) { var named = stat() if fstatat(parent, leaf, &named, AT_SYMLINK_NOFOLLOW) == 0, Identity(named) == identity { _ = unlinkat(parent, leaf, 0) } close(parent) } } let directories = Set(products.flatMap { product -> [String] in let parts = product.relativePath.split(separator: "/"); return (1.. $1.count } for path in directories { if let (parent, leaf) = try? Self.parent(stage, path: path, create: false) { _ = unlinkat(parent, leaf, AT_REMOVEDIR); close(parent) } } _ = unlinkat(destination, stageName, AT_REMOVEDIR) } } for (index, product) in products.enumerated() { let checkDestination = try self.destination(); close(checkDestination) let checkSource = try self.source(value); close(checkSource) let bytes = try read(product, from: source) let (parent, leaf) = try Self.parent(stage, path: product.relativePath, create: true) defer { close(parent) } let fd = openat(parent, leaf, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) guard fd >= 0 else { throw Self.failure("export_write_failed") } let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true) defer { try? file.close() } var info = stat() guard fstat(fd, &info) == 0 else { throw Self.failure("export_write_failed") } created.append((product.relativePath, Identity(info))) for offset in stride(from: 0, to: bytes.count, by: 65536) { try check() try file.write(contentsOf: bytes.subdata(in: offset..= 0 else { throw Self.failure("export_delivery_changed") } defer { close(directory) } try verifyContents(directory, products: delivery.products) let current = try self.destination(); close(current) } }