{"repo_name": "container", "file_name": "/container/Sources/CLI/Builder/BuilderStop.swift", "inference_info": {"prefix_code": "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderStop: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"stop\"\n config._superCommandName = \"builder\"\n config.abstract = \"Stop builder\"\n config.usage = \"\\n\\t builder stop\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n ", "suffix_code": "\n }\n}\n", "middle_code": "func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n try await container.stop()\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n print(\"builder is not running\")\n return\n }\n }\n throw error\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/container/Sources/CLI/Builder/BuilderDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderDelete: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"delete\"\n config._superCommandName = \"builder\"\n config.abstract = \"Delete builder\"\n config.usage = \"\\n\\t builder delete [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Flag(name: .shortAndLong, help: \"Force delete builder even if it is running\")\n var force = false\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n if container.status != .stopped {\n guard force else {\n throw ContainerizationError(.invalidState, message: \"BuildKit container is not stopped, use --force to override\")\n }\n try await container.stop()\n }\n try await container.delete()\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderStatus: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"status\"\n config._superCommandName = \"builder\"\n config.abstract = \"Print builder status\"\n config.usage = \"\\n\\t builder status [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Flag(name: .long, help: ArgumentHelp(\"Display detailed status in json format\"))\n var json: Bool = false\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n if json {\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.prettyPrinted, .sortedKeys]\n let jsonData = try encoder.encode(container)\n\n guard let jsonString = String(data: jsonData, encoding: .utf8) else {\n throw ContainerizationError(.internalError, message: \"failed to encode BuildKit container as json\")\n }\n print(jsonString)\n return\n }\n\n let image = container.configuration.image.reference\n let resources = container.configuration.resources\n let cpus = resources.cpus\n let memory = resources.memoryInBytes / (1024 * 1024) // bytes to MB\n let addr = \"\"\n\n print(\"ID IMAGE STATE ADDR CPUS MEMORY\")\n print(\"\\(container.id) \\(image) \\(container.status.rawValue.uppercased()) \\(addr) \\(cpus) \\(memory) MB\")\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n print(\"builder is not running\")\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerBuild\nimport ContainerClient\nimport ContainerNetworkService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct BuilderStart: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"start\"\n config._superCommandName = \"builder\"\n config.abstract = \"Start builder\"\n config.usage = \"\\nbuilder start [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64 = 2\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n public var memory: String = \"2048MB\"\n\n func run() async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n totalTasks: 4\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n try await Self.start(cpus: self.cpus, memory: self.memory, progressUpdate: progress.handler)\n progress.finish()\n }\n\n static func start(cpus: Int64?, memory: String?, progressUpdate: @escaping ProgressUpdateHandler) async throws {\n await progressUpdate([\n .setDescription(\"Fetching BuildKit image\"),\n .setItemsName(\"blobs\"),\n ])\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n\n let builderImage: String = ClientDefaults.get(key: .defaultBuilderImage)\n let exportsMount: String = Application.appRoot.appendingPathComponent(\".build\").absolutePath()\n\n if !FileManager.default.fileExists(atPath: exportsMount) {\n try FileManager.default.createDirectory(\n atPath: exportsMount,\n withIntermediateDirectories: true,\n attributes: nil\n )\n }\n\n let builderPlatform = ContainerizationOCI.Platform(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n\n let existingContainer = try? await ClientContainer.get(id: \"buildkit\")\n if let existingContainer {\n let existingImage = existingContainer.configuration.image.reference\n let existingResources = existingContainer.configuration.resources\n\n // Check if we need to recreate the builder due to different image\n let imageChanged = existingImage != builderImage\n let cpuChanged = {\n if let cpus {\n if existingResources.cpus != cpus {\n return true\n }\n }\n return false\n }()\n let memChanged = try {\n if let memory {\n let memoryInBytes = try Parser.resources(cpus: nil, memory: memory).memoryInBytes\n if existingResources.memoryInBytes != memoryInBytes {\n return true\n }\n }\n return false\n }()\n\n switch existingContainer.status {\n case .running:\n guard imageChanged || cpuChanged || memChanged else {\n // If image, mem and cpu are the same, continue using the existing builder\n return\n }\n // If they changed, stop and delete the existing builder\n try await existingContainer.stop()\n try await existingContainer.delete()\n case .stopped:\n // If the builder is stopped and matches our requirements, start it\n // Otherwise, delete it and create a new one\n guard imageChanged || cpuChanged || memChanged else {\n try await existingContainer.startBuildKit(progressUpdate, nil)\n return\n }\n try await existingContainer.delete()\n case .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"builder is stopping, please wait until it is fully stopped before proceeding\"\n )\n case .unknown:\n break\n }\n }\n\n let shimArguments: [String] = [\n \"--debug\",\n \"--vsock\",\n ]\n\n let id = \"buildkit\"\n try ContainerClient.Utility.validEntityName(id)\n\n let processConfig = ProcessConfiguration(\n executable: \"/usr/local/bin/container-builder-shim\",\n arguments: shimArguments,\n environment: [],\n workingDirectory: \"/\",\n terminal: false,\n user: .id(uid: 0, gid: 0)\n )\n\n let resources = try Parser.resources(\n cpus: cpus,\n memory: memory\n )\n\n let image = try await ClientImage.fetch(\n reference: builderImage,\n platform: builderPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progressUpdate)\n )\n // Unpack fetched image before use\n await progressUpdate([\n .setDescription(\"Unpacking BuildKit image\"),\n .setItemsName(\"entries\"),\n ])\n\n let unpackTask = await taskManager.startTask()\n _ = try await image.getCreateSnapshot(\n platform: builderPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progressUpdate)\n )\n let imageConfig = ImageDescription(\n reference: builderImage,\n descriptor: image.descriptor\n )\n\n var config = ContainerConfiguration(id: id, image: imageConfig, process: processConfig)\n config.resources = resources\n config.mounts = [\n .init(\n type: .tmpfs,\n source: \"\",\n destination: \"/run\",\n options: []\n ),\n .init(\n type: .virtiofs,\n source: exportsMount,\n destination: \"/var/lib/container-builder-shim/exports\",\n options: []\n ),\n ]\n // Enable Rosetta only if the user didn't ask to disable it\n config.rosetta = ClientDefaults.getBool(key: .buildRosetta) ?? true\n\n let network = try await ClientNetwork.get(id: ClientNetwork.defaultNetworkName)\n guard case .running(_, let networkStatus) = network else {\n throw ContainerizationError(.invalidState, message: \"default network is not running\")\n }\n config.networks = [network.id]\n let subnet = try CIDRAddress(networkStatus.address)\n let nameserver = IPv4Address(fromValue: subnet.lower.value + 1).description\n let nameservers = [nameserver]\n config.dns = ContainerConfiguration.DNSConfiguration(nameservers: nameservers)\n\n let kernel = try await {\n await progressUpdate([\n .setDescription(\"Fetching kernel\"),\n .setItemsName(\"binary\"),\n ])\n\n let kernel = try await ClientKernel.getDefaultKernel(for: .current)\n return kernel\n }()\n\n await progressUpdate([\n .setDescription(\"Starting BuildKit container\")\n ])\n\n let container = try await ClientContainer.create(\n configuration: config,\n options: .default,\n kernel: kernel\n )\n\n try await container.startBuildKit(progressUpdate, taskManager)\n }\n }\n}\n\n// MARK: - ClientContainer Extension for BuildKit\n\nextension ClientContainer {\n /// Starts the BuildKit process within the container\n /// This method handles bootstrapping the container and starting the BuildKit process\n fileprivate func startBuildKit(_ progress: @escaping ProgressUpdateHandler, _ taskManager: ProgressTaskCoordinator? = nil) async throws {\n do {\n let io = try ProcessIO.create(\n tty: false,\n interactive: false,\n detach: true\n )\n defer { try? io.close() }\n let process = try await bootstrap()\n _ = try await process.start(io.stdio)\n await taskManager?.finish()\n try io.closeAfterStart()\n log.debug(\"starting BuildKit and BuildKit-shim\")\n } catch {\n try? await stop()\n try? await delete()\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to start BuildKit: \\(error)\")\n }\n }\n}\n"], ["/container/Sources/CLI/BuildCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerBuild\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport NIO\nimport TerminalProgress\n\nextension Application {\n struct BuildCommand: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"build\"\n config.abstract = \"Build an image from a Dockerfile\"\n config._superCommandName = \"container\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64 = 2\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n var memory: String = \"2048MB\"\n\n @Option(name: .long, help: ArgumentHelp(\"Set build-time variables\", valueName: \"key=val\"))\n var buildArg: [String] = []\n\n @Argument(help: \"Build directory\")\n var contextDir: String = \".\"\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Path to Dockerfile\", valueName: \"path\"))\n var file: String = \"Dockerfile\"\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Set a label\", valueName: \"key=val\"))\n var label: [String] = []\n\n @Flag(name: .long, help: \"Do not use cache\")\n var noCache: Bool = false\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Output configuration for the build\", valueName: \"value\"))\n var output: [String] = {\n [\"type=oci\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Cache imports for the build\", valueName: \"value\", visibility: .hidden))\n var cacheIn: [String] = {\n []\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Cache exports for the build\", valueName: \"value\", visibility: .hidden))\n var cacheOut: [String] = {\n []\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"set the build architecture\", valueName: \"value\"))\n var arch: [String] = {\n [\"arm64\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"set the build os\", valueName: \"value\"))\n var os: [String] = {\n [\"linux\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Progress type - one of [auto|plain|tty]\", valueName: \"type\"))\n var progress: String = \"auto\"\n\n @Option(name: .long, help: ArgumentHelp(\"Builder-shim vsock port\", valueName: \"port\"))\n var vsockPort: UInt32 = 8088\n\n @Option(name: [.customShort(\"t\"), .customLong(\"tag\")], help: ArgumentHelp(\"Name for the built image\", valueName: \"name\"))\n var targetImageName: String = UUID().uuidString.lowercased()\n\n @Option(name: .long, help: ArgumentHelp(\"Set the target build stage\", valueName: \"stage\"))\n var target: String = \"\"\n\n @Flag(name: .shortAndLong, help: \"Suppress build output\")\n var quiet: Bool = false\n\n func run() async throws {\n do {\n let timeout: Duration = .seconds(300)\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Dialing builder\")\n\n let builder: Builder? = try await withThrowingTaskGroup(of: Builder.self) { group in\n defer {\n group.cancelAll()\n }\n\n group.addTask {\n while true {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n let fh = try await container.dial(self.vsockPort)\n\n let threadGroup: MultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n let b = try Builder(socket: fh, group: threadGroup)\n\n // If this call succeeds, then BuildKit is running.\n let _ = try await b.info()\n return b\n } catch {\n // If we get here, \"Dialing builder\" is shown for such a short period\n // of time that it's invisible to the user.\n progress.set(tasks: 0)\n progress.set(totalTasks: 3)\n\n try await BuilderStart.start(\n cpus: self.cpus,\n memory: self.memory,\n progressUpdate: progress.handler\n )\n\n // wait (seconds) for builder to start listening on vsock\n try await Task.sleep(for: .seconds(5))\n continue\n }\n }\n }\n\n group.addTask {\n try await Task.sleep(for: timeout)\n throw ValidationError(\n \"\"\"\n Timeout waiting for connection to builder\n \"\"\"\n )\n }\n\n return try await group.next()\n }\n\n guard let builder else {\n throw ValidationError(\"builder is not running\")\n }\n\n let dockerfile = try Data(contentsOf: URL(filePath: file))\n let exportPath = Application.appRoot.appendingPathComponent(\".build\")\n\n let buildID = UUID().uuidString\n let tempURL = exportPath.appendingPathComponent(buildID)\n try FileManager.default.createDirectory(at: tempURL, withIntermediateDirectories: true, attributes: nil)\n defer {\n try? FileManager.default.removeItem(at: tempURL)\n }\n\n let imageName: String = try {\n let parsedReference = try Reference.parse(targetImageName)\n parsedReference.normalize()\n return parsedReference.description\n }()\n\n var terminal: Terminal?\n switch self.progress {\n case \"tty\":\n terminal = try Terminal(descriptor: STDERR_FILENO)\n case \"auto\":\n terminal = try? Terminal(descriptor: STDERR_FILENO)\n case \"plain\":\n terminal = nil\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid progress mode \\(self.progress)\")\n }\n\n defer { terminal?.tryReset() }\n\n let exports: [Builder.BuildExport] = try output.map { output in\n var exp = try Builder.BuildExport(from: output)\n if exp.destination == nil {\n exp.destination = tempURL.appendingPathComponent(\"out.tar\")\n }\n return exp\n }\n\n try await withThrowingTaskGroup(of: Void.self) { [terminal] group in\n defer {\n group.cancelAll()\n }\n group.addTask {\n let handler = AsyncSignalHandler.create(notify: [SIGTERM, SIGINT, SIGUSR1, SIGUSR2])\n for await sig in handler.signals {\n throw ContainerizationError(.interrupted, message: \"exiting on signal \\(sig)\")\n }\n }\n let platforms: [Platform] = try {\n var results: [Platform] = []\n for o in self.os {\n for a in self.arch {\n guard let platform = try? Platform(from: \"\\(o)/\\(a)\") else {\n throw ValidationError(\"invalid os/architecture combination \\(o)/\\(a)\")\n }\n results.append(platform)\n }\n }\n return results\n }()\n group.addTask { [terminal] in\n let config = ContainerBuild.Builder.BuildConfig(\n buildID: buildID,\n contentStore: RemoteContentStoreClient(),\n buildArgs: buildArg,\n contextDir: contextDir,\n dockerfile: dockerfile,\n labels: label,\n noCache: noCache,\n platforms: platforms,\n terminal: terminal,\n tag: imageName,\n target: target,\n quiet: quiet,\n exports: exports,\n cacheIn: cacheIn,\n cacheOut: cacheOut\n )\n progress.finish()\n\n try await builder.build(config)\n }\n\n try await group.next()\n }\n\n let unpackProgressConfig = try ProgressConfig(\n description: \"Unpacking built image\",\n itemsName: \"entries\",\n showTasks: exports.count > 1,\n totalTasks: exports.count\n )\n let unpackProgress = ProgressBar(config: unpackProgressConfig)\n defer {\n unpackProgress.finish()\n }\n unpackProgress.start()\n\n var finalMessage = \"Successfully built \\(imageName)\"\n let taskManager = ProgressTaskCoordinator()\n // Currently, only a single export can be specified.\n for exp in exports {\n unpackProgress.add(tasks: 1)\n let unpackTask = await taskManager.startTask()\n switch exp.type {\n case \"oci\":\n try Task.checkCancellation()\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let loaded = try await ClientImage.load(from: dest.absolutePath())\n\n for image in loaded {\n try Task.checkCancellation()\n try await image.unpack(platform: nil, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: unpackProgress.handler))\n }\n case \"tar\":\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let tarURL = tempURL.appendingPathComponent(\"out.tar\")\n try FileManager.default.moveItem(at: tarURL, to: dest)\n finalMessage = \"Successfully exported to \\(dest.absolutePath())\"\n case \"local\":\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let localDir = tempURL.appendingPathComponent(\"local\")\n\n guard FileManager.default.fileExists(atPath: localDir.path) else {\n throw ContainerizationError(.invalidArgument, message: \"expected local output not found\")\n }\n try FileManager.default.copyItem(at: localDir, to: dest)\n finalMessage = \"Successfully exported to \\(dest.absolutePath())\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid exporter \\(exp.rawValue)\")\n }\n }\n await taskManager.finish()\n unpackProgress.finish()\n print(finalMessage)\n } catch {\n throw NSError(domain: \"Build\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"\\(error)\"])\n }\n }\n\n func validate() throws {\n guard FileManager.default.fileExists(atPath: file) else {\n throw ValidationError(\"Dockerfile does not exist at path: \\(file)\")\n }\n guard FileManager.default.fileExists(atPath: contextDir) else {\n throw ValidationError(\"context dir does not exist \\(contextDir)\")\n }\n guard let _ = try? Reference.parse(targetImageName) else {\n throw ValidationError(\"invalid reference \\(targetImageName)\")\n }\n }\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/SandboxService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\nimport SocketForwarder\n\nimport struct ContainerizationOCI.Mount\nimport struct ContainerizationOCI.Process\n\n/// An XPC service that manages the lifecycle of a single VM-backed container.\npublic actor SandboxService {\n private let root: URL\n private let interfaceStrategy: InterfaceStrategy\n private var container: ContainerInfo?\n private let monitor: ExitMonitor\n private let eventLoopGroup: any EventLoopGroup\n private var waiters: [String: [CheckedContinuation]] = [:]\n private let lock: AsyncLock = AsyncLock()\n private let log: Logging.Logger\n private var state: State = .created\n private var processes: [String: ProcessInfo] = [:]\n private var socketForwarders: [SocketForwarderResult] = []\n\n /// Create an instance with a bundle that describes the container.\n ///\n /// - Parameters:\n /// - root: The file URL for the bundle root.\n /// - interfaceStrategy: The strategy for producing network interface\n /// objects for each network to which the container attaches.\n /// - log: The destination for log messages.\n public init(root: URL, interfaceStrategy: InterfaceStrategy, eventLoopGroup: any EventLoopGroup, log: Logger) {\n self.root = root\n self.interfaceStrategy = interfaceStrategy\n self.log = log\n self.monitor = ExitMonitor(log: log)\n self.eventLoopGroup = eventLoopGroup\n }\n\n /// Start the VM and the guest agent process for a container.\n ///\n /// - Parameters:\n /// - message: An XPC message with no parameters.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func bootstrap(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`bootstrap` xpc handler\")\n return try await self.lock.withLock { _ in\n guard await self.state == .created else {\n throw ContainerizationError(\n .invalidState,\n message: \"container expected to be in created state, got: \\(await self.state)\"\n )\n }\n\n let bundle = ContainerClient.Bundle(path: self.root)\n try bundle.createLogFile()\n\n let vmm = VZVirtualMachineManager(\n kernel: try bundle.kernel,\n initialFilesystem: bundle.initialFilesystem.asMount,\n bootlog: bundle.bootlog.path,\n logger: self.log\n )\n var config = try bundle.configuration\n let container = LinuxContainer(\n config.id,\n rootfs: try bundle.containerRootfs.asMount,\n vmm: vmm,\n logger: self.log\n )\n\n // dynamically configure the DNS nameserver from a network if no explicit configuration\n if let dns = config.dns, dns.nameservers.isEmpty {\n if let nameserver = try await self.getDefaultNameserver(networks: config.networks) {\n config.dns = ContainerConfiguration.DNSConfiguration(\n nameservers: [nameserver],\n domain: dns.domain,\n searchDomains: dns.searchDomains,\n options: dns.options\n )\n }\n }\n\n try await self.configureContainer(container: container, config: config)\n\n let fqdn: String\n if let hostname = config.hostname {\n if let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName),\n let dnsDomain = suite.string(forKey: \"dns.domain\"),\n !hostname.contains(\".\")\n {\n // TODO: Make the suiteName a constant defined in ClientDefaults and use that.\n // This will need some re-working of dependencies between SandboxService and Client\n fqdn = \"\\(hostname).\\(dnsDomain).\"\n } else {\n fqdn = \"\\(hostname).\"\n }\n } else {\n fqdn = config.id\n }\n\n var attachments: [Attachment] = []\n for index in 0.. XPCMessage {\n self.log.info(\"`start` xpc handler\")\n return try await self.lock.withLock { lock in\n let id = try message.id()\n let stdio = message.stdio()\n let containerInfo = try await self.getContainer()\n let containerId = containerInfo.container.id\n if id == containerId {\n try await self.startInitProcess(stdio: stdio, lock: lock)\n await self.setState(.running)\n try await self.sendContainerEvent(.containerStart(id: id))\n } else {\n try await self.startExecProcess(processId: id, stdio: stdio, lock: lock)\n }\n return message.reply()\n }\n }\n\n private func startInitProcess(stdio: [FileHandle?], lock: AsyncLock.Context) async throws {\n let info = try self.getContainer()\n let container = info.container\n let bundle = info.bundle\n let id = container.id\n guard self.state == .booted else {\n throw ContainerizationError(\n .invalidState,\n message: \"container expected to be in booted state, got: \\(self.state)\"\n )\n }\n let containerLog = try FileHandle(forWritingTo: bundle.containerLog)\n let config = info.config\n let stdout = {\n if let h = stdio[1] {\n return MultiWriter(handles: [h, containerLog])\n }\n return MultiWriter(handles: [containerLog])\n }()\n let stderr: MultiWriter? = {\n if !config.initProcess.terminal {\n if let h = stdio[2] {\n return MultiWriter(handles: [h, containerLog])\n }\n return MultiWriter(handles: [containerLog])\n }\n return nil\n }()\n if let h = stdio[0] {\n container.stdin = h\n }\n container.stdout = stdout\n if let stderr {\n container.stderr = stderr\n }\n self.setState(.starting)\n do {\n try await container.start()\n let waitFunc: ExitMonitor.WaitHandler = {\n let code = try await container.wait()\n if let out = stdio[1] {\n try self.closeHandle(out.fileDescriptor)\n }\n if let err = stdio[2] {\n try self.closeHandle(err.fileDescriptor)\n }\n return code\n }\n try await self.monitor.track(id: id, waitingOn: waitFunc)\n } catch {\n try? await self.cleanupContainer()\n self.setState(.created)\n try await self.sendContainerEvent(.containerExit(id: id, exitCode: -1))\n throw error\n }\n }\n\n private func startExecProcess(processId id: String, stdio: [FileHandle?], lock: AsyncLock.Context) async throws {\n let container = try self.getContainer().container\n guard let processInfo = self.processes[id] else {\n throw ContainerizationError(.notFound, message: \"Process with id \\(id)\")\n }\n let ociConfig = self.configureProcessConfig(config: processInfo.config)\n let stdin: ReaderStream? = {\n if let h = stdio[0] {\n return h\n }\n return nil\n }()\n let process = try await container.exec(\n id,\n configuration: ociConfig,\n stdin: stdin,\n stdout: stdio[1],\n stderr: stdio[2]\n )\n try self.setUnderlyingProcess(id, process)\n try await process.start()\n let waitFunc: ExitMonitor.WaitHandler = {\n let code = try await process.wait()\n if let out = stdio[1] {\n try self.closeHandle(out.fileDescriptor)\n }\n if let err = stdio[2] {\n try self.closeHandle(err.fileDescriptor)\n }\n return code\n }\n try await self.monitor.track(id: id, waitingOn: waitFunc)\n }\n\n private func startSocketForwarders(containerIpAddress: String, publishedPorts: [PublishPort]) async throws {\n var forwarders: [SocketForwarderResult] = []\n try await withThrowingTaskGroup(of: SocketForwarderResult.self) { group in\n for publishedPort in publishedPorts {\n let proxyAddress = try SocketAddress(ipAddress: publishedPort.hostAddress, port: Int(publishedPort.hostPort))\n let serverAddress = try SocketAddress(ipAddress: containerIpAddress, port: Int(publishedPort.containerPort))\n log.info(\n \"creating forwarder for\",\n metadata: [\n \"proxy\": \"\\(proxyAddress)\",\n \"server\": \"\\(serverAddress)\",\n \"protocol\": \"\\(publishedPort.proto)\",\n ])\n group.addTask {\n let forwarder: SocketForwarder\n switch publishedPort.proto {\n case .tcp:\n forwarder = try TCPForwarder(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: self.log\n )\n case .udp:\n forwarder = try UDPForwarder(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: self.log\n )\n }\n return try await forwarder.run().get()\n }\n }\n for try await result in group {\n forwarders.append(result)\n }\n }\n\n self.socketForwarders = forwarders\n }\n\n private func stopSocketForwarders() async {\n log.info(\"closing forwarders\")\n for forwarder in self.socketForwarders {\n forwarder.close()\n try? await forwarder.wait()\n }\n log.info(\"closed forwarders\")\n }\n\n /// Create a process inside the virtual machine for the container.\n ///\n /// Use this procedure to run ad hoc processes in the virtual\n /// machine (`container exec`).\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: A client identifier for the process.\n /// - processConfig: JSON serialization of the `ProcessConfiguration`\n /// containing the process attributes.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func createProcess(_ message: XPCMessage) async throws -> XPCMessage {\n log.info(\"`createProcess` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped(_), .starting, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot exec: container is not running\"\n )\n case .running, .booted:\n let id = try message.id()\n let config = try message.processConfig()\n await self.addNewProcess(id, config)\n try await self.monitor.registerProcess(\n id: id,\n onExit: { id, code in\n guard let process = await self.processes[id]?.process else {\n throw ContainerizationError(.invalidState, message: \"ProcessInfo missing for process \\(id)\")\n }\n for cc in await self.waiters[id] ?? [] {\n cc.resume(returning: code)\n }\n await self.removeWaiters(for: id)\n try await process.delete()\n try await self.setProcessState(id: id, state: .stopped(code))\n })\n return message.reply()\n }\n }\n }\n\n /// Return the state for the sandbox and its containers.\n ///\n /// - Parameters:\n /// - message: An XPC message with no parameters.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - snapshot: The JSON serialization of the `SandboxSnapshot`\n /// that contains the state information.\n @Sendable\n public func state(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`state` xpc handler\")\n var status: RuntimeStatus = .unknown\n var networks: [Attachment] = []\n var cs: ContainerSnapshot?\n\n switch state {\n case .created, .stopped(_), .starting, .booted:\n status = .stopped\n case .stopping:\n status = .stopping\n case .running:\n let ctr = try getContainer()\n\n status = .running\n networks = ctr.attachments\n cs = ContainerSnapshot(\n configuration: ctr.config,\n status: RuntimeStatus.running,\n networks: networks\n )\n }\n\n let reply = message.reply()\n try reply.setState(\n .init(\n status: status,\n networks: networks,\n containers: cs != nil ? [cs!] : []\n )\n )\n return reply\n }\n\n /// Stop the container workload, any ad hoc processes, and the underlying\n /// virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - stopOptions: JSON serialization of `ContainerStopOptions`\n /// that modify stop behavior.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func stop(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`stop` xpc handler\")\n let reply = try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .stopped(_), .created, .stopping:\n return message.reply()\n case .starting:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot stop: container is not running\"\n )\n case .running, .booted:\n let ctr = try await getContainer()\n let stopOptions = try message.stopOptions()\n do {\n try await gracefulStopContainer(\n ctr.container,\n stopOpts: stopOptions\n )\n } catch {\n log.notice(\"failed to stop sandbox gracefully: \\(error)\")\n }\n await setState(.stopping)\n return message.reply()\n }\n }\n do {\n try await cleanupContainer()\n } catch {\n self.log.error(\"failed to cleanup container: \\(error)\")\n }\n return reply\n }\n\n /// Signal a process running in the virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n /// - signal: The signal value.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func kill(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`kill` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped, .starting, .booted, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot kill: container is not running\"\n )\n case .running:\n let ctr = try await getContainer()\n let id = try message.id()\n if id != ctr.container.id {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) does not exist\")\n }\n\n guard let proc = processInfo.process else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not started\")\n }\n try await proc.kill(Int32(try message.signal()))\n return message.reply()\n }\n\n // TODO: fix underlying signal value to int64\n try await ctr.container.kill(Int32(try message.signal()))\n return message.reply()\n }\n }\n }\n\n /// Resize the terminal for a process.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n /// - width: The terminal width.\n /// - height: The terminal height.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func resize(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`resize` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped, .starting, .booted, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot resize: container is not running\"\n )\n case .running:\n let id = try message.id()\n let ctr = try await getContainer()\n let width = message.uint64(key: .width)\n let height = message.uint64(key: .height)\n if id != ctr.container.id {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) does not exist\")\n }\n\n guard let proc = processInfo.process else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not started\")\n }\n\n try await proc.resize(to: .init(width: UInt16(width), height: UInt16(height)))\n return message.reply()\n }\n\n try await ctr.container.resize(to: .init(width: UInt16(width), height: UInt16(height)))\n return message.reply()\n }\n }\n }\n\n /// Wait for a process.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - exitCode: The exit code for the process.\n @Sendable\n public func wait(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`wait` xpc handler\")\n guard let id = message.string(key: .id) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing id in wait xpc message\")\n }\n\n let cachedCode: Int32? = try await self.lock.withLock { _ in\n let ctrInfo = try await self.getContainer()\n let ctr = ctrInfo.container\n if id == ctr.id {\n switch await self.state {\n case .stopped(let code):\n return code\n default:\n break\n }\n } else {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.notFound, message: \"Process with id \\(id)\")\n }\n switch processInfo.state {\n case .stopped(let code):\n return code\n default:\n break\n }\n }\n return nil\n }\n if let cachedCode {\n let reply = message.reply()\n reply.set(key: .exitCode, value: Int64(cachedCode))\n return reply\n }\n\n let exitCode = await withCheckedContinuation { cc in\n // Is this safe since we are in an actor? :(\n self.addWaiter(id: id, cont: cc)\n }\n let reply = message.reply()\n reply.set(key: .exitCode, value: Int64(exitCode))\n return reply\n }\n\n /// Dial a vsock port on the virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - port: The port number.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - fd: The file descriptor for the vsock.\n @Sendable\n public func dial(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`dial` xpc handler\")\n switch self.state {\n case .starting, .created, .stopped, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot dial: container is not running\"\n )\n case .running, .booted:\n let port = message.uint64(key: .port)\n guard port > 0 else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"no vsock port supplied for dial\"\n )\n }\n\n let ctr = try getContainer()\n let fh = try await ctr.container.dialVsock(port: UInt32(port))\n\n let reply = message.reply()\n reply.set(key: .fd, value: fh)\n return reply\n }\n }\n\n private func onContainerExit(id: String, code: Int32) async throws {\n self.log.info(\"init process exited with: \\(code)\")\n\n try await self.lock.withLock { [self] _ in\n let ctrInfo = try await getContainer()\n let ctr = ctrInfo.container\n // Did someone explicitly call stop and we're already\n // cleaning up?\n switch await self.state {\n case .stopped(_):\n return\n default:\n break\n }\n\n do {\n try await ctr.stop()\n } catch {\n log.notice(\"failed to stop sandbox gracefully: \\(error)\")\n }\n\n do {\n try await cleanupContainer()\n } catch {\n self.log.error(\"failed to cleanup container: \\(error)\")\n }\n await setState(.stopped(code))\n let waiters = await self.waiters[id] ?? []\n for cc in waiters {\n cc.resume(returning: code)\n }\n await self.removeWaiters(for: id)\n try await self.sendContainerEvent(.containerExit(id: id, exitCode: Int64(code)))\n exit(code)\n }\n }\n\n private func configureContainer(container: LinuxContainer, config: ContainerConfiguration) throws {\n container.cpus = config.resources.cpus\n container.memoryInBytes = config.resources.memoryInBytes\n container.rosetta = config.rosetta\n container.sysctl = config.sysctls.reduce(into: [String: String]()) {\n $0[$1.key] = $1.value\n }\n\n for mount in config.mounts {\n if try mount.isSocket() {\n let socket = UnixSocketConfiguration(\n source: URL(filePath: mount.source),\n destination: URL(filePath: mount.destination)\n )\n container.sockets.append(socket)\n } else {\n container.mounts.append(mount.asMount)\n }\n }\n\n for publishedSocket in config.publishedSockets {\n let socketConfig = UnixSocketConfiguration(\n source: publishedSocket.containerPath,\n destination: publishedSocket.hostPath,\n permissions: publishedSocket.permissions,\n direction: .outOf\n )\n container.sockets.append(socketConfig)\n }\n\n container.hostname = config.hostname ?? config.id\n\n if let dns = config.dns {\n container.dns = DNS(\n nameservers: dns.nameservers, domain: dns.domain,\n searchDomains: dns.searchDomains, options: dns.options)\n }\n\n configureInitialProcess(container: container, process: config.initProcess)\n }\n\n private func getDefaultNameserver(networks: [String]) async throws -> String? {\n for network in networks {\n let client = NetworkClient(id: network)\n let state = try await client.state()\n guard case .running(_, let status) = state else {\n continue\n }\n return status.gateway\n }\n\n return nil\n }\n\n private func configureInitialProcess(container: LinuxContainer, process: ProcessConfiguration) {\n container.arguments = [process.executable] + process.arguments\n container.environment = modifyingEnvironment(process)\n container.terminal = process.terminal\n container.workingDirectory = process.workingDirectory\n container.rlimits = process.rlimits.map {\n .init(type: $0.limit, hard: $0.hard, soft: $0.soft)\n }\n switch process.user {\n case .raw(let name):\n container.user = .init(\n uid: 0,\n gid: 0,\n umask: nil,\n additionalGids: process.supplementalGroups,\n username: name\n )\n case .id(let uid, let gid):\n container.user = .init(\n uid: uid,\n gid: gid,\n umask: nil,\n additionalGids: process.supplementalGroups,\n username: \"\"\n )\n }\n }\n\n private nonisolated func configureProcessConfig(config: ProcessConfiguration) -> ContainerizationOCI.Process {\n var proc = ContainerizationOCI.Process()\n proc.args = [config.executable] + config.arguments\n proc.env = modifyingEnvironment(config)\n proc.terminal = config.terminal\n proc.cwd = config.workingDirectory\n proc.rlimits = config.rlimits.map {\n .init(type: $0.limit, hard: $0.hard, soft: $0.soft)\n }\n switch config.user {\n case .raw(let name):\n proc.user = .init(\n uid: 0,\n gid: 0,\n umask: nil,\n additionalGids: config.supplementalGroups,\n username: name\n )\n case .id(let uid, let gid):\n proc.user = .init(\n uid: uid,\n gid: gid,\n umask: nil,\n additionalGids: config.supplementalGroups,\n username: \"\"\n )\n }\n\n return proc\n }\n\n private nonisolated func closeHandle(_ handle: Int32) throws {\n guard close(handle) == 0 else {\n guard let errCode = POSIXErrorCode(rawValue: errno) else {\n fatalError(\"failed to convert errno to POSIXErrorCode\")\n }\n throw POSIXError(errCode)\n }\n }\n\n private nonisolated func modifyingEnvironment(_ config: ProcessConfiguration) -> [String] {\n guard config.terminal else {\n return config.environment\n }\n // Prepend the TERM env var. If the user has it specified our value will be overridden.\n return [\"TERM=xterm\"] + config.environment\n }\n\n private func getContainer() throws -> ContainerInfo {\n guard let container else {\n throw ContainerizationError(\n .invalidState,\n message: \"no container found\"\n )\n }\n return container\n }\n\n private func gracefulStopContainer(_ lc: LinuxContainer, stopOpts: ContainerStopOptions) async throws {\n // Try and gracefully shut down the process. Even if this succeeds we need to power off\n // the vm, but we should try this first always.\n do {\n try await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n try await lc.wait()\n }\n group.addTask {\n try await lc.kill(stopOpts.signal)\n try await Task.sleep(for: .seconds(stopOpts.timeoutInSeconds))\n try await lc.kill(SIGKILL)\n }\n try await group.next()\n group.cancelAll()\n }\n } catch {}\n // Now actually bring down the vm.\n try await lc.stop()\n }\n\n private func cleanupContainer() async throws {\n // Give back our lovely IP(s)\n await self.stopSocketForwarders()\n let containerInfo = try self.getContainer()\n for attachment in containerInfo.attachments {\n let client = NetworkClient(id: attachment.network)\n do {\n try await client.deallocate(hostname: attachment.hostname)\n } catch {\n self.log.error(\"failed to deallocate hostname \\(attachment.hostname) on network \\(attachment.network): \\(error)\")\n }\n }\n }\n\n private func sendContainerEvent(_ event: ContainerEvent) async throws {\n let serviceIdentifier = \"com.apple.container.apiserver\"\n let client = XPCClient(service: serviceIdentifier)\n let message = XPCMessage(route: .containerEvent)\n\n let data = try JSONEncoder().encode(event)\n message.set(key: .containerEvent, value: data)\n try await client.send(message)\n }\n\n}\n\nextension XPCMessage {\n fileprivate func signal() throws -> Int64 {\n self.int64(key: .signal)\n }\n\n fileprivate func stopOptions() throws -> ContainerStopOptions {\n guard let data = self.dataNoCopy(key: .stopOptions) else {\n throw ContainerizationError(.invalidArgument, message: \"empty StopOptions\")\n }\n return try JSONDecoder().decode(ContainerStopOptions.self, from: data)\n }\n\n fileprivate func setState(_ state: SandboxSnapshot) throws {\n let data = try JSONEncoder().encode(state)\n self.set(key: .snapshot, value: data)\n }\n\n fileprivate func stdio() -> [FileHandle?] {\n var handles = [FileHandle?](repeating: nil, count: 3)\n if let stdin = self.fileHandle(key: .stdin) {\n handles[0] = stdin\n }\n if let stdout = self.fileHandle(key: .stdout) {\n handles[1] = stdout\n }\n if let stderr = self.fileHandle(key: .stderr) {\n handles[2] = stderr\n }\n return handles\n }\n\n fileprivate func setFileHandle(_ handle: FileHandle) {\n self.set(key: .fd, value: handle)\n }\n\n fileprivate func processConfig() throws -> ProcessConfiguration {\n guard let data = self.dataNoCopy(key: .processConfig) else {\n throw ContainerizationError(.invalidArgument, message: \"empty process configuration\")\n }\n return try JSONDecoder().decode(ProcessConfiguration.self, from: data)\n }\n}\n\nextension ContainerClient.Bundle {\n /// The pathname for the workload log file.\n public var containerLog: URL {\n path.appendingPathComponent(\"stdio.log\")\n }\n\n func createLogFile() throws {\n // Create the log file we'll write stdio to.\n // O_TRUNC resolves a log delay issue on restarted containers by force-updating internal state\n let fd = Darwin.open(self.containerLog.path, O_CREAT | O_RDONLY | O_TRUNC, 0o644)\n guard fd > 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n close(fd)\n }\n}\n\nextension Filesystem {\n var asMount: Containerization.Mount {\n switch self.type {\n case .tmpfs:\n return .any(\n type: \"tmpfs\",\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n case .virtiofs:\n return .share(\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n case .block(let format, _, _):\n return .block(\n format: format,\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n }\n }\n\n func isSocket() throws -> Bool {\n if !self.isVirtiofs {\n return false\n }\n let info = try File.info(self.source)\n return info.isSocket\n }\n}\n\nstruct MultiWriter: Writer {\n let handles: [FileHandle]\n\n func write(_ data: Data) throws {\n for handle in self.handles {\n try handle.write(contentsOf: data)\n }\n }\n}\n\nextension FileHandle: @retroactive ReaderStream, @retroactive Writer {\n public func write(_ data: Data) throws {\n try self.write(contentsOf: data)\n }\n\n public func stream() -> AsyncStream {\n .init { cont in\n self.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n self.readabilityHandler = nil\n cont.finish()\n return\n }\n cont.yield(data)\n }\n }\n }\n}\n\n// MARK: State handler helpers\n\nextension SandboxService {\n private func addWaiter(id: String, cont: CheckedContinuation) {\n var current = self.waiters[id] ?? []\n current.append(cont)\n self.waiters[id] = current\n }\n\n private func removeWaiters(for id: String) {\n self.waiters[id] = []\n }\n\n private func setUnderlyingProcess(_ id: String, _ process: LinuxProcess) throws {\n guard var info = self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not found\")\n }\n info.process = process\n self.processes[id] = info\n }\n\n private func setProcessState(id: String, state: State) throws {\n guard var info = self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not found\")\n }\n info.state = state\n self.processes[id] = info\n }\n\n private func setContainer(_ info: ContainerInfo) {\n self.container = info\n }\n\n private func addNewProcess(_ id: String, _ config: ProcessConfiguration) {\n self.processes[id] = ProcessInfo(config: config, process: nil, state: .created)\n }\n\n private struct ProcessInfo {\n let config: ProcessConfiguration\n var process: LinuxProcess?\n var state: State\n }\n\n private struct ContainerInfo {\n let container: LinuxContainer\n let config: ContainerConfiguration\n let attachments: [Attachment]\n let bundle: ContainerClient.Bundle\n }\n\n public enum State: Sendable, Equatable {\n case created\n case booted\n case starting\n case running\n case stopping\n case stopped(Int32)\n }\n\n func setState(_ new: State) {\n self.state = new\n }\n}\n"], ["/container/Sources/CLI/Application.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerPlugin\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport TerminalProgress\n\n// `log` is updated only once in the `validate()` method.\nnonisolated(unsafe) var log = {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"CLI\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n log.logLevel = .debug\n return log\n}()\n\n@main\nstruct Application: AsyncParsableCommand {\n @OptionGroup\n var global: Flags.Global\n\n static let configuration = CommandConfiguration(\n commandName: \"container\",\n abstract: \"A container platform for macOS\",\n version: releaseVersion(),\n subcommands: [\n DefaultCommand.self\n ],\n groupedSubcommands: [\n CommandGroup(\n name: \"Container\",\n subcommands: [\n ContainerCreate.self,\n ContainerDelete.self,\n ContainerExec.self,\n ContainerInspect.self,\n ContainerKill.self,\n ContainerList.self,\n ContainerLogs.self,\n ContainerRunCommand.self,\n ContainerStart.self,\n ContainerStop.self,\n ]\n ),\n CommandGroup(\n name: \"Image\",\n subcommands: [\n BuildCommand.self,\n ImagesCommand.self,\n RegistryCommand.self,\n ]\n ),\n CommandGroup(\n name: \"Other\",\n subcommands: Self.otherCommands()\n ),\n ],\n // Hidden command to handle plugins on unrecognized input.\n defaultSubcommand: DefaultCommand.self\n )\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n static let pluginLoader: PluginLoader = {\n let installRoot = CommandLine.executablePathUrl\n .deletingLastPathComponent()\n .appendingPathComponent(\"..\")\n .standardized\n let pluginsURL = PluginLoader.userPluginsDir(root: installRoot)\n var directoryExists: ObjCBool = false\n _ = FileManager.default.fileExists(atPath: pluginsURL.path, isDirectory: &directoryExists)\n let userPluginsURL = directoryExists.boolValue ? pluginsURL : nil\n\n // plugins built into the application installed as a macOS app bundle\n let appBundlePluginsURL = Bundle.main.resourceURL?.appending(path: \"plugins\")\n\n // plugins built into the application installed as a Unix-like application\n let installRootPluginsURL =\n installRoot\n .appendingPathComponent(\"libexec\")\n .appendingPathComponent(\"container\")\n .appendingPathComponent(\"plugins\")\n .standardized\n\n let pluginDirectories = [\n userPluginsURL,\n appBundlePluginsURL,\n installRootPluginsURL,\n ].compactMap { $0 }\n\n let pluginFactories = [\n DefaultPluginFactory()\n ]\n\n let statePath = PluginLoader.defaultPluginResourcePath(root: Self.appRoot)\n try! FileManager.default.createDirectory(at: statePath, withIntermediateDirectories: true)\n return PluginLoader(pluginDirectories: pluginDirectories, pluginFactories: pluginFactories, defaultResourcePath: statePath, log: log)\n }()\n\n public static func main() async throws {\n restoreCursorAtExit()\n\n #if DEBUG\n let warning = \"Running debug build. Performance may be degraded.\"\n let formattedWarning = \"\\u{001B}[33mWarning!\\u{001B}[0m \\(warning)\\n\"\n let warningData = Data(formattedWarning.utf8)\n FileHandle.standardError.write(warningData)\n #endif\n\n let fullArgs = CommandLine.arguments\n let args = Array(fullArgs.dropFirst())\n\n do {\n // container -> defaultHelpCommand\n var command = try Application.parseAsRoot(args)\n if var asyncCommand = command as? AsyncParsableCommand {\n try await asyncCommand.run()\n } else {\n try command.run()\n }\n } catch {\n // Regular ol `command` with no args will get caught by DefaultCommand. --help\n // on the root command will land here.\n let containsHelp = fullArgs.contains(\"-h\") || fullArgs.contains(\"--help\")\n if fullArgs.count <= 2 && containsHelp {\n Self.printModifiedHelpText()\n return\n }\n let errorAsString: String = String(describing: error)\n if errorAsString.contains(\"XPC connection error\") {\n let modifiedError = ContainerizationError(.interrupted, message: \"\\(error)\\nEnsure container system service has been started with `container system start`.\")\n Application.exit(withError: modifiedError)\n } else {\n Application.exit(withError: error)\n }\n }\n }\n\n static func handleProcess(io: ProcessIO, process: ClientProcess) async throws -> Int32 {\n let signals = AsyncSignalHandler.create(notify: Application.signalSet)\n return try await withThrowingTaskGroup(of: Int32?.self, returning: Int32.self) { group in\n let waitAdded = group.addTaskUnlessCancelled {\n let code = try await process.wait()\n try await io.wait()\n return code\n }\n\n guard waitAdded else {\n group.cancelAll()\n return -1\n }\n\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n\n if let current = io.console {\n let size = try current.size\n // It's supremely possible the process could've exited already. We shouldn't treat\n // this as fatal.\n try? await process.resize(size)\n _ = group.addTaskUnlessCancelled {\n let winchHandler = AsyncSignalHandler.create(notify: [SIGWINCH])\n for await _ in winchHandler.signals {\n do {\n try await process.resize(try current.size)\n } catch {\n log.error(\n \"failed to send terminal resize event\",\n metadata: [\n \"error\": \"\\(error)\"\n ]\n )\n }\n }\n return nil\n }\n } else {\n _ = group.addTaskUnlessCancelled {\n for await sig in signals.signals {\n do {\n try await process.kill(sig)\n } catch {\n log.error(\n \"failed to send signal\",\n metadata: [\n \"signal\": \"\\(sig)\",\n \"error\": \"\\(error)\",\n ]\n )\n }\n }\n return nil\n }\n }\n\n while true {\n let result = try await group.next()\n if result == nil {\n return -1\n }\n let status = result!\n if let status {\n group.cancelAll()\n return status\n }\n }\n return -1\n }\n }\n\n func validate() throws {\n // Not really a \"validation\", but a cheat to run this before\n // any of the commands do their business.\n let debugEnvVar = ProcessInfo.processInfo.environment[\"CONTAINER_DEBUG\"]\n if self.global.debug || debugEnvVar != nil {\n log.logLevel = .debug\n }\n // Ensure we're not running under Rosetta.\n if try isTranslated() {\n throw ValidationError(\n \"\"\"\n `container` is currently running under Rosetta Translation, which could be\n caused by your terminal application. Please ensure this is turned off.\n \"\"\"\n )\n }\n }\n\n private static func otherCommands() -> [any ParsableCommand.Type] {\n guard #available(macOS 26, *) else {\n return [\n BuilderCommand.self,\n SystemCommand.self,\n ]\n }\n\n return [\n BuilderCommand.self,\n NetworkCommand.self,\n SystemCommand.self,\n ]\n }\n\n private static func restoreCursorAtExit() {\n let signalHandler: @convention(c) (Int32) -> Void = { signal in\n let exitCode = ExitCode(signal + 128)\n Application.exit(withError: exitCode)\n }\n // Termination by Ctrl+C.\n signal(SIGINT, signalHandler)\n // Termination using `kill`.\n signal(SIGTERM, signalHandler)\n // Normal and explicit exit.\n atexit {\n if let progressConfig = try? ProgressConfig() {\n let progressBar = ProgressBar(config: progressConfig)\n progressBar.resetCursor()\n }\n }\n }\n}\n\nextension Application {\n // Because we support plugins, we need to modify the help text to display\n // any if we found some.\n static func printModifiedHelpText() {\n let altered = Self.pluginLoader.alterCLIHelpText(\n original: Application.helpMessage(for: Application.self)\n )\n print(altered)\n }\n\n enum ListFormat: String, CaseIterable, ExpressibleByArgument {\n case json\n case table\n }\n\n static let signalSet: [Int32] = [\n SIGTERM,\n SIGINT,\n SIGUSR1,\n SIGUSR2,\n SIGWINCH,\n ]\n\n func isTranslated() throws -> Bool {\n do {\n return try Sysctl.byName(\"sysctl.proc_translated\") == 1\n } catch let posixErr as POSIXError {\n if posixErr.code == .ENOENT {\n return false\n }\n throw posixErr\n }\n }\n\n private static func releaseVersion() -> String {\n var versionDetails: [String: String] = [\"build\": \"release\"]\n #if DEBUG\n versionDetails[\"build\"] = \"debug\"\n #endif\n let gitCommit = {\n let sha = get_git_commit().map { String(cString: $0) }\n guard let sha else {\n return \"unspecified\"\n }\n return String(sha.prefix(7))\n }()\n versionDetails[\"commit\"] = gitCommit\n let extras: String = versionDetails.map { \"\\($0): \\($1)\" }.sorted().joined(separator: \", \")\n\n let bundleVersion = (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String)\n let releaseVersion = bundleVersion ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n\n return \"container CLI version \\(releaseVersion) (\\(extras))\"\n }\n}\n"], ["/container/Sources/APIServer/Containers/ContainersService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CVersion\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerSandboxService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ContainersService {\n private static let machServicePrefix = \"com.apple.container\"\n private static let launchdDomainString = try! ServiceManager.getDomainString()\n\n private let log: Logger\n private let containerRoot: URL\n private let pluginLoader: PluginLoader\n private let runtimePlugins: [Plugin]\n\n private let lock = AsyncLock()\n private var containers: [String: Item]\n\n struct Item: Sendable {\n let bundle: ContainerClient.Bundle\n var state: State\n\n enum State: Sendable {\n case dead\n case alive(SandboxClient)\n case exited(Int32)\n\n func isDead() -> Bool {\n switch self {\n case .dead: return true\n default: return false\n }\n }\n }\n }\n\n public init(root: URL, pluginLoader: PluginLoader, log: Logger) throws {\n let containerRoot = root.appendingPathComponent(\"containers\")\n try FileManager.default.createDirectory(at: containerRoot, withIntermediateDirectories: true)\n self.containerRoot = containerRoot\n self.pluginLoader = pluginLoader\n self.log = log\n self.runtimePlugins = pluginLoader.findPlugins().filter { $0.hasType(.runtime) }\n self.containers = try Self.loadAtBoot(root: containerRoot, loader: pluginLoader, log: log)\n }\n\n static func loadAtBoot(root: URL, loader: PluginLoader, log: Logger) throws -> [String: Item] {\n var directories = try FileManager.default.contentsOfDirectory(\n at: root,\n includingPropertiesForKeys: [.isDirectoryKey]\n )\n directories = directories.filter {\n $0.isDirectory\n }\n\n let runtimePlugins = loader.findPlugins().filter { $0.hasType(.runtime) }\n var results = [String: Item]()\n for dir in directories {\n do {\n let bundle = ContainerClient.Bundle(path: dir)\n let config = try bundle.configuration\n results[config.id] = .init(bundle: bundle, state: .dead)\n let plugin = runtimePlugins.first { $0.name == config.runtimeHandler }\n guard let plugin else {\n throw ContainerizationError(.internalError, message: \"Failed to find runtime plugin \\(config.runtimeHandler)\")\n }\n try Self.registerService(plugin: plugin, loader: loader, configuration: config, path: dir)\n } catch {\n try? FileManager.default.removeItem(at: dir)\n log.warning(\"failed to load container bundle at \\(dir.path)\")\n }\n }\n return results\n }\n\n private func setContainer(_ id: String, _ item: Item, context: AsyncLock.Context) async {\n self.containers[id] = item\n }\n\n /// List all containers registered with the service.\n public func list() async throws -> [ContainerSnapshot] {\n self.log.debug(\"\\(#function)\")\n return await lock.withLock { context in\n var snapshots = [ContainerSnapshot]()\n\n for (id, item) in await self.containers {\n do {\n let result = try await item.asSnapshot()\n snapshots.append(result.0)\n } catch {\n self.log.error(\"unable to load bundle for \\(id) \\(error)\")\n }\n }\n return snapshots\n }\n }\n\n /// Create a new container from the provided id and configuration.\n public func create(configuration: ContainerConfiguration, kernel: Kernel, options: ContainerCreateOptions) async throws {\n self.log.debug(\"\\(#function)\")\n\n let runtimePlugin = self.runtimePlugins.filter {\n $0.name == configuration.runtimeHandler\n }.first\n guard let runtimePlugin else {\n throw ContainerizationError(.notFound, message: \"unable to locate runtime plugin \\(configuration.runtimeHandler)\")\n }\n\n let path = self.containerRoot.appendingPathComponent(configuration.id)\n let systemPlatform = kernel.platform\n let initFs = try await getInitBlock(for: systemPlatform.ociPlatform())\n\n let bundle = try ContainerClient.Bundle.create(\n path: path,\n initialFilesystem: initFs,\n kernel: kernel,\n containerConfiguration: configuration\n )\n do {\n let containerImage = ClientImage(description: configuration.image)\n let imageFs = try await containerImage.getCreateSnapshot(platform: configuration.platform)\n try bundle.setContainerRootFs(cloning: imageFs)\n try bundle.write(filename: \"options.json\", value: options)\n\n try Self.registerService(\n plugin: runtimePlugin,\n loader: self.pluginLoader,\n configuration: configuration,\n path: path\n )\n } catch {\n do {\n try bundle.delete()\n } catch {\n self.log.error(\"failed to delete bundle for container \\(configuration.id): \\(error)\")\n }\n throw error\n }\n self.containers[configuration.id] = Item(bundle: bundle, state: .dead)\n }\n\n private func getInitBlock(for platform: Platform) async throws -> Filesystem {\n let initImage = try await ClientImage.fetch(reference: ClientImage.initImageRef, platform: platform)\n var fs = try await initImage.getCreateSnapshot(platform: platform)\n fs.options = [\"ro\"]\n return fs\n }\n\n private static func registerService(\n plugin: Plugin,\n loader: PluginLoader,\n configuration: ContainerConfiguration,\n path: URL\n ) throws {\n let args = [\n \"--root\", path.path,\n \"--uuid\", configuration.id,\n \"--debug\",\n ]\n try loader.registerWithLaunchd(\n plugin: plugin,\n rootURL: path,\n args: args,\n instanceId: configuration.id\n )\n }\n\n private func get(id: String, context: AsyncLock.Context) throws -> Item {\n try self._get(id: id)\n }\n\n private func _get(id: String) throws -> Item {\n let item = self.containers[id]\n guard let item else {\n throw ContainerizationError(\n .notFound,\n message: \"container with ID \\(id) not found\"\n )\n }\n return item\n }\n\n /// Delete a container and its resources.\n public func delete(id: String) async throws {\n self.log.debug(\"\\(#function)\")\n let item = try self._get(id: id)\n switch item.state {\n case .alive(let client):\n let state = try await client.state()\n if state.status == .running || state.status == .stopping {\n throw ContainerizationError(\n .invalidState,\n message: \"container \\(id) is not yet stopped and can not be deleted\"\n )\n }\n try self._cleanup(id: id, item: item)\n case .dead, .exited(_):\n try self._cleanup(id: id, item: item)\n }\n }\n\n private static func fullLaunchdServiceLabel(runtimeName: String, instanceId: String) -> String {\n \"\\(Self.launchdDomainString)/\\(Self.machServicePrefix).\\(runtimeName).\\(instanceId)\"\n }\n\n private func _cleanup(id: String, item: Item) throws {\n self.log.debug(\"\\(#function)\")\n let config = try item.bundle.configuration\n let label = Self.fullLaunchdServiceLabel(runtimeName: config.runtimeHandler, instanceId: id)\n try ServiceManager.deregister(fullServiceLabel: label)\n try item.bundle.delete()\n self.containers.removeValue(forKey: id)\n }\n\n private func _shutdown(id: String, item: Item) throws {\n let config = try item.bundle.configuration\n let label = Self.fullLaunchdServiceLabel(runtimeName: config.runtimeHandler, instanceId: id)\n try ServiceManager.kill(fullServiceLabel: label)\n }\n\n private func cleanup(id: String, item: Item, context: AsyncLock.Context) async throws {\n try self._cleanup(id: id, item: item)\n }\n\n private func containerProcessExitHandler(_ id: String, _ exitCode: Int32, context: AsyncLock.Context) async {\n self.log.info(\"Handling container \\(id) exit. Code \\(exitCode)\")\n do {\n var item = try self.get(id: id, context: context)\n switch item.state {\n case .dead, .exited(_):\n break\n case .alive(_):\n item.state = .exited(exitCode)\n await self.setContainer(id, item, context: context)\n }\n let options: ContainerCreateOptions = try item.bundle.load(filename: \"options.json\")\n if options.autoRemove {\n try await self.cleanup(id: id, item: item, context: context)\n }\n } catch {\n self.log.error(\n \"Failed to handle container exit\",\n metadata: [\n \"id\": .string(id),\n \"error\": .string(String(describing: error)),\n ])\n }\n }\n\n private func containerStartHandler(_ id: String, context: AsyncLock.Context) async throws {\n self.log.debug(\"\\(#function)\")\n self.log.info(\"Handling container \\(id) Start.\")\n do {\n var item = try self.get(id: id, context: context)\n let configuration = try item.bundle.configuration\n let client = SandboxClient(id: configuration.id, runtime: configuration.runtimeHandler)\n item.state = .alive(client)\n await self.setContainer(id, item, context: context)\n } catch {\n self.log.error(\n \"Failed to handle container start\",\n metadata: [\n \"id\": .string(id),\n \"error\": .string(String(describing: error)),\n ])\n }\n }\n}\n\nextension ContainersService {\n public func handleContainerEvents(event: ContainerEvent) async throws {\n self.log.debug(\"\\(#function)\")\n try await self.lock.withLock { context in\n switch event {\n case .containerExit(let id, let code):\n await self.containerProcessExitHandler(id, Int32(code), context: context)\n case .containerStart(let id):\n try await self.containerStartHandler(id, context: context)\n }\n }\n }\n\n /// Stop all containers inside the sandbox, aborting any processes currently\n /// executing inside the container, before stopping the underlying sandbox.\n public func stop(id: String, options: ContainerStopOptions) async throws {\n self.log.debug(\"\\(#function)\")\n try await lock.withLock { context in\n let item = try await self.get(id: id, context: context)\n switch item.state {\n case .dead, .exited(_):\n return\n case .alive(let client):\n try await client.stop(options: options)\n }\n }\n }\n\n public func logs(id: String) async throws -> [FileHandle] {\n self.log.debug(\"\\(#function)\")\n // Logs doesn't care if the container is running or not, just that\n // the bundle is there, and that the files actually exist.\n do {\n let item = try self._get(id: id)\n return [\n try FileHandle(forReadingFrom: item.bundle.containerLog),\n try FileHandle(forReadingFrom: item.bundle.bootlog),\n ]\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to open container logs: \\(error)\"\n )\n }\n }\n}\n\nextension ContainersService.Item {\n func asSnapshot() async throws -> (ContainerSnapshot, RuntimeStatus) {\n let config = try self.bundle.configuration\n\n switch self.state {\n case .dead, .exited(_):\n return (\n .init(\n configuration: config,\n status: RuntimeStatus.stopped,\n networks: []\n ), .stopped\n )\n case .alive(let client):\n let state = try await client.state()\n return (\n .init(\n configuration: config,\n status: state.status,\n networks: state.networks\n ), state.status\n )\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct ContainerStop: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"stop\",\n abstract: \"Stop one or more running containers\")\n\n @Flag(name: .shortAndLong, help: \"Stop all running containers\")\n var all = false\n\n @Option(name: .shortAndLong, help: \"Signal to send the container(s)\")\n var signal: String = \"SIGTERM\"\n\n @Option(name: .shortAndLong, help: \"Seconds to wait before killing the container(s)\")\n var time: Int32 = 5\n\n @Argument\n var containerIDs: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument, message: \"explicitly supplied container IDs conflicts with the --all flag\")\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n var containers = [ClientContainer]()\n if self.all {\n containers = try await ClientContainer.list()\n } else {\n containers = try await ClientContainer.list().filter { c in\n set.contains(c.id)\n }\n }\n\n let opts = ContainerStopOptions(\n timeoutInSeconds: self.time,\n signal: try Signals.parseSignal(self.signal)\n )\n let failed = try await Self.stopContainers(containers: containers, stopOptions: opts)\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"stop failed for one or more containers \\(failed.joined(separator: \",\"))\")\n }\n }\n\n static func stopContainers(containers: [ClientContainer], stopOptions: ContainerStopOptions) async throws -> [String] {\n var failed: [String] = []\n try await withThrowingTaskGroup(of: ClientContainer?.self) { group in\n for container in containers {\n group.addTask {\n do {\n try await container.stop(opts: stopOptions)\n print(container.id)\n return nil\n } catch {\n log.error(\"failed to stop container \\(container.id): \\(error)\")\n return container\n }\n }\n }\n\n for try await ctr in group {\n guard let ctr else {\n continue\n }\n failed.append(ctr.id)\n }\n }\n\n return failed\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerExec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct ContainerExec: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"exec\",\n abstract: \"Run a new command in a running container\")\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Running containers ID\")\n var containerID: String\n\n @Argument(parsing: .captureForPassthrough, help: \"New process arguments\")\n var arguments: [String]\n\n func run() async throws {\n var exitCode: Int32 = 127\n let container = try await ClientContainer.get(id: containerID)\n try ensureRunning(container: container)\n\n let stdin = self.processFlags.interactive\n let tty = self.processFlags.tty\n\n var config = container.configuration.initProcess\n config.executable = arguments.first!\n config.arguments = [String](self.arguments.dropFirst())\n config.terminal = tty\n config.environment.append(\n contentsOf: try Parser.allEnv(\n imageEnvs: [],\n envFiles: self.processFlags.envFile,\n envs: self.processFlags.env\n ))\n\n if let cwd = self.processFlags.cwd {\n config.workingDirectory = cwd\n }\n\n let defaultUser = config.user\n let (user, additionalGroups) = Parser.user(\n user: processFlags.user, uid: processFlags.uid,\n gid: processFlags.gid, defaultUser: defaultUser)\n config.user = user\n config.supplementalGroups.append(contentsOf: additionalGroups)\n\n do {\n let io = try ProcessIO.create(tty: tty, interactive: stdin, detach: false)\n\n if !self.processFlags.tty {\n var handler = SignalThreshold(threshold: 3, signals: [SIGINT, SIGTERM])\n handler.start {\n print(\"Received 3 SIGINT/SIGTERM's, forcefully exiting.\")\n Darwin.exit(1)\n }\n }\n\n let process = try await container.createProcess(\n id: UUID().uuidString.lowercased(),\n configuration: config)\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to exec process \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct ContainerDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete one or more containers\",\n aliases: [\"rm\"])\n\n @Flag(name: .shortAndLong, help: \"Force the removal of one or more running containers\")\n var force = false\n\n @Flag(name: .shortAndLong, help: \"Remove all containers\")\n var all = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Container IDs/names\")\n var containerIDs: [String] = []\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument,\n message: \"explicitly supplied container ID(s) conflict with the --all flag\"\n )\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n var containers = [ClientContainer]()\n\n if all {\n containers = try await ClientContainer.list()\n } else {\n let ctrs = try await ClientContainer.list()\n containers = ctrs.filter { c in\n set.contains(c.id)\n }\n // If one of the containers requested isn't present, let's throw. We don't need to do\n // this for --all as --all should be perfectly usable with no containers to remove; otherwise,\n // it'd be quite clunky.\n if containers.count != set.count {\n let missing = set.filter { id in\n !containers.contains { c in\n c.id == id\n }\n }\n throw ContainerizationError(\n .notFound,\n message: \"failed to delete one or more containers: \\(missing)\"\n )\n }\n }\n\n var failed = [String]()\n let force = self.force\n let all = self.all\n try await withThrowingTaskGroup(of: ClientContainer?.self) { group in\n for container in containers {\n group.addTask {\n do {\n // First we need to find if the container supports auto-remove\n // and if so we need to skip deletion.\n if container.status == .running {\n if !force {\n // We don't want to error if the user just wants all containers deleted.\n // It's implied we'll skip containers we can't actually delete.\n if all {\n return nil\n }\n throw ContainerizationError(.invalidState, message: \"container is running\")\n }\n let stopOpts = ContainerStopOptions(\n timeoutInSeconds: 5,\n signal: SIGKILL\n )\n try await container.stop(opts: stopOpts)\n }\n try await container.delete()\n print(container.id)\n return nil\n } catch {\n log.error(\"failed to delete container \\(container.id): \\(error)\")\n return container\n }\n }\n }\n\n for try await ctr in group {\n guard let ctr else {\n continue\n }\n failed.append(ctr.id)\n }\n }\n\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"delete failed for one or more containers: \\(failed)\")\n }\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nextension Application {\n struct SystemStop: AsyncParsableCommand {\n private static let stopTimeoutSeconds: Int32 = 5\n private static let shutdownTimeoutSeconds: Int32 = 20\n\n static let configuration = CommandConfiguration(\n commandName: \"stop\",\n abstract: \"Stop all `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Launchd prefix for `container` services\")\n var prefix: String = \"com.apple.container.\"\n\n func run() async throws {\n let log = Logger(\n label: \"com.apple.container.cli\",\n factory: { label in\n StreamLogHandler.standardOutput(label: label)\n }\n )\n\n let launchdDomainString = try ServiceManager.getDomainString()\n let fullLabel = \"\\(launchdDomainString)/\\(prefix)apiserver\"\n\n log.info(\"stopping containers\", metadata: [\"stopTimeoutSeconds\": \"\\(Self.stopTimeoutSeconds)\"])\n do {\n let containers = try await ClientContainer.list()\n let signal = try Signals.parseSignal(\"SIGTERM\")\n let opts = ContainerStopOptions(timeoutInSeconds: Self.stopTimeoutSeconds, signal: signal)\n let failed = try await ContainerStop.stopContainers(containers: containers, stopOptions: opts)\n if !failed.isEmpty {\n log.warning(\"some containers could not be stopped gracefully\", metadata: [\"ids\": \"\\(failed)\"])\n }\n\n } catch {\n log.warning(\"failed to stop all containers\", metadata: [\"error\": \"\\(error)\"])\n }\n\n log.info(\"waiting for containers to exit\")\n do {\n for _ in 0.. 0 && all {\n throw ContainerizationError(\n .invalidArgument,\n message: \"explicitly supplied network name(s) conflict with the --all flag\"\n )\n }\n }\n\n mutating func run() async throws {\n let uniqueNetworkNames = Set(networkNames)\n let networks: [NetworkState]\n\n if all {\n networks = try await ClientNetwork.list()\n } else {\n networks = try await ClientNetwork.list()\n .filter { c in\n uniqueNetworkNames.contains(c.id)\n }\n\n // If one of the networks requested isn't present lets throw. We don't need to do\n // this for --all as --all should be perfectly usable with no networks to remove,\n // otherwise it'd be quite clunky.\n if networks.count != uniqueNetworkNames.count {\n let missing = uniqueNetworkNames.filter { id in\n !networks.contains { n in\n n.id == id\n }\n }\n throw ContainerizationError(\n .notFound,\n message: \"failed to delete one or more networks: \\(missing)\"\n )\n }\n }\n\n if uniqueNetworkNames.contains(ClientNetwork.defaultNetworkName) {\n throw ContainerizationError(\n .invalidArgument,\n message: \"cannot delete the default network\"\n )\n }\n\n var failed = [String]()\n try await withThrowingTaskGroup(of: NetworkState?.self) { group in\n for network in networks {\n group.addTask {\n do {\n // delete atomically disables the IP allocator, then deletes\n // the allocator disable fails if any IPs are still in use\n try await ClientNetwork.delete(id: network.id)\n print(network.id)\n return nil\n } catch {\n log.error(\"failed to delete network \\(network.id): \\(error)\")\n return network\n }\n }\n }\n\n for try await network in group {\n guard let network else {\n continue\n }\n failed.append(network.id)\n }\n }\n\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"delete failed for one or more networks: \\(failed)\")\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerLogs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Darwin\nimport Dispatch\nimport Foundation\n\nextension Application {\n struct ContainerLogs: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"logs\",\n abstract: \"Fetch container stdio or boot logs\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Flag(name: .shortAndLong, help: \"Follow log output\")\n var follow: Bool = false\n\n @Flag(name: .long, help: \"Display the boot log for the container instead of stdio\")\n var boot: Bool = false\n\n @Option(name: [.customShort(\"n\")], help: \"Number of lines to show from the end of the logs. If not provided this will print all of the logs\")\n var numLines: Int?\n\n @Argument(help: \"Container to fetch logs for\")\n var container: String\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: container)\n let fhs = try await container.logs()\n let fileHandle = boot ? fhs[1] : fhs[0]\n\n try await Self.tail(\n fh: fileHandle,\n n: numLines,\n follow: follow\n )\n } catch {\n throw ContainerizationError(\n .invalidArgument,\n message: \"failed to fetch container logs for \\(container): \\(error)\"\n )\n }\n }\n\n private static func tail(\n fh: FileHandle,\n n: Int?,\n follow: Bool\n ) async throws {\n if let n {\n var buffer = Data()\n let size = try fh.seekToEnd()\n var offset = size\n var lines: [String] = []\n\n while offset > 0, lines.count < n {\n let readSize = min(1024, offset)\n offset -= readSize\n try fh.seek(toOffset: offset)\n\n let data = fh.readData(ofLength: Int(readSize))\n buffer.insert(contentsOf: data, at: 0)\n\n if let chunk = String(data: buffer, encoding: .utf8) {\n lines = chunk.components(separatedBy: .newlines)\n lines = lines.filter { !$0.isEmpty }\n }\n }\n\n lines = Array(lines.suffix(n))\n for line in lines {\n print(line)\n }\n } else {\n // Fast path if all they want is the full file.\n guard let data = try fh.readToEnd() else {\n // Seems you get nil if it's a zero byte read, or you\n // try and read from dev/null.\n return\n }\n guard let str = String(data: data, encoding: .utf8) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to convert container logs to utf8\"\n )\n }\n print(str.trimmingCharacters(in: .newlines))\n }\n\n fflush(stdout)\n if follow {\n setbuf(stdout, nil)\n try await Self.followFile(fh: fh)\n }\n }\n\n private static func followFile(fh: FileHandle) async throws {\n _ = try fh.seekToEnd()\n let stream = AsyncStream { cont in\n fh.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n // Triggers on container restart - can exit here as well\n do {\n _ = try fh.seekToEnd() // To continue streaming existing truncated log files\n } catch {\n fh.readabilityHandler = nil\n cont.finish()\n return\n }\n }\n if let str = String(data: data, encoding: .utf8), !str.isEmpty {\n var lines = str.components(separatedBy: .newlines)\n lines = lines.filter { !$0.isEmpty }\n for line in lines {\n cont.yield(line)\n }\n }\n }\n }\n\n for await line in stream {\n print(line)\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImageList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ListImageOptions: ParsableArguments {\n @Flag(name: .shortAndLong, help: \"Only output the image name\")\n var quiet = false\n\n @Flag(name: .shortAndLong, help: \"Verbose output\")\n var verbose = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n }\n\n struct ListImageImplementation {\n static private func createHeader() -> [[String]] {\n [[\"NAME\", \"TAG\", \"DIGEST\"]]\n }\n\n static private func createVerboseHeader() -> [[String]] {\n [[\"NAME\", \"TAG\", \"INDEX DIGEST\", \"OS\", \"ARCH\", \"VARIANT\", \"SIZE\", \"CREATED\", \"MANIFEST DIGEST\"]]\n }\n\n static private func printImagesVerbose(images: [ClientImage]) async throws {\n\n var rows = createVerboseHeader()\n for image in images {\n let formatter = ByteCountFormatter()\n for descriptor in try await image.index().manifests {\n // Don't list attestation manifests\n if let referenceType = descriptor.annotations?[\"vnd.docker.reference.type\"],\n referenceType == \"attestation-manifest\"\n {\n continue\n }\n\n guard let platform = descriptor.platform else {\n continue\n }\n\n let os = platform.os\n let arch = platform.architecture\n let variant = platform.variant ?? \"\"\n\n var config: ContainerizationOCI.Image\n var manifest: ContainerizationOCI.Manifest\n do {\n config = try await image.config(for: platform)\n manifest = try await image.manifest(for: platform)\n } catch {\n continue\n }\n\n let created = config.created ?? \"\"\n let size = descriptor.size + manifest.config.size + manifest.layers.reduce(0, { (l, r) in l + r.size })\n let formattedSize = formatter.string(fromByteCount: size)\n\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n let reference = try ContainerizationOCI.Reference.parse(processedReferenceString)\n let row = [\n reference.name,\n reference.tag ?? \"\",\n Utility.trimDigest(digest: image.descriptor.digest),\n os,\n arch,\n variant,\n formattedSize,\n created,\n Utility.trimDigest(digest: descriptor.digest),\n ]\n rows.append(row)\n }\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n\n static private func printImages(images: [ClientImage], format: ListFormat, options: ListImageOptions) async throws {\n var images = images\n images.sort {\n $0.reference < $1.reference\n }\n\n if format == .json {\n let data = try JSONEncoder().encode(images.map { $0.description })\n print(String(data: data, encoding: .utf8)!)\n return\n }\n\n if options.quiet {\n try images.forEach { image in\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n print(processedReferenceString)\n }\n return\n }\n\n if options.verbose {\n try await Self.printImagesVerbose(images: images)\n return\n }\n\n var rows = createHeader()\n for image in images {\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n let reference = try ContainerizationOCI.Reference.parse(processedReferenceString)\n rows.append([\n reference.name,\n reference.tag ?? \"\",\n Utility.trimDigest(digest: image.descriptor.digest),\n ])\n }\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n\n static func validate(options: ListImageOptions) throws {\n if options.quiet && options.verbose {\n throw ContainerizationError(.invalidArgument, message: \"Cannot use flag --quite and --verbose together\")\n }\n let modifier = options.quiet || options.verbose\n if modifier && options.format == .json {\n throw ContainerizationError(.invalidArgument, message: \"Cannot use flag --quite or --verbose along with --format json\")\n }\n }\n\n static func listImages(options: ListImageOptions) async throws {\n let images = try await ClientImage.list().filter { img in\n !Utility.isInfraImage(name: img.reference)\n }\n try await printImages(images: images, format: options.format, options: options)\n }\n }\n\n struct ImageList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List images\",\n aliases: [\"ls\"])\n\n @OptionGroup\n var options: ListImageOptions\n\n mutating func run() async throws {\n try ListImageImplementation.validate(options: options)\n try await ListImageImplementation.listImages(options: options)\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport TerminalProgress\n\nextension Application {\n struct ContainerStart: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Start a container\")\n\n @Flag(name: .shortAndLong, help: \"Attach STDOUT/STDERR\")\n var attach = false\n\n @Flag(name: .shortAndLong, help: \"Attach container's STDIN\")\n var interactive = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Container's ID\")\n var containerID: String\n\n func run() async throws {\n var exitCode: Int32 = 127\n\n let progressConfig = try ProgressConfig(\n description: \"Starting container\"\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let container = try await ClientContainer.get(id: containerID)\n let process = try await container.bootstrap()\n\n progress.set(description: \"Starting init process\")\n let detach = !self.attach && !self.interactive\n do {\n let io = try ProcessIO.create(\n tty: container.configuration.initProcess.terminal,\n interactive: self.interactive,\n detach: detach\n )\n progress.finish()\n if detach {\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n print(self.containerID)\n return\n }\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n try? await container.stop()\n\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to start container: \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIO\nimport NIOHPACK\nimport NIOHTTP2\n\npublic struct Builder: Sendable {\n let client: BuilderClientProtocol\n let clientAsync: BuilderClientAsyncProtocol\n let group: EventLoopGroup\n let builderShimSocket: FileHandle\n let channel: GRPCChannel\n\n public init(socket: FileHandle, group: EventLoopGroup) throws {\n try socket.setSendBufSize(4 << 20)\n try socket.setRecvBufSize(2 << 20)\n var config = ClientConnection.Configuration.default(\n target: .connectedSocket(socket.fileDescriptor),\n eventLoopGroup: group\n )\n config.connectionIdleTimeout = TimeAmount(.seconds(600))\n config.connectionKeepalive = .init(\n interval: TimeAmount(.seconds(600)),\n timeout: TimeAmount(.seconds(500)),\n permitWithoutCalls: true\n )\n config.connectionBackoff = .init(\n initialBackoff: TimeInterval(1),\n maximumBackoff: TimeInterval(10)\n )\n config.callStartBehavior = .fastFailure\n config.httpMaxFrameSize = 8 << 10\n config.maximumReceiveMessageLength = 512 << 20\n config.httpTargetWindowSize = 16 << 10\n\n let channel = ClientConnection(configuration: config)\n self.channel = channel\n self.clientAsync = BuilderClientAsync(channel: channel)\n self.client = BuilderClient(channel: channel)\n self.group = group\n self.builderShimSocket = socket\n }\n\n public func info() throws -> InfoResponse {\n let resp = self.client.info(InfoRequest(), callOptions: CallOptions())\n return try resp.response.wait()\n }\n\n public func info() async throws -> InfoResponse {\n let opts = CallOptions(timeLimit: .timeout(.seconds(30)))\n return try await self.clientAsync.info(InfoRequest(), callOptions: opts)\n }\n\n // TODO\n // - Symlinks in build context dir\n // - cache-to, cache-from\n // - output (other than the default OCI image output, e.g., local, tar, Docker)\n public func build(_ config: BuildConfig) async throws {\n var continuation: AsyncStream.Continuation?\n let reqStream = AsyncStream { (cont: AsyncStream.Continuation) in\n continuation = cont\n }\n guard let continuation else {\n throw Error.invalidContinuation\n }\n\n defer {\n continuation.finish()\n }\n\n if let terminal = config.terminal {\n Task {\n let winchHandler = AsyncSignalHandler.create(notify: [SIGWINCH])\n let setWinch = { (rows: UInt16, cols: UInt16) in\n var winch = ClientStream()\n winch.command = .init()\n if let cmdString = try TerminalCommand(rows: rows, cols: cols).json() {\n winch.command.command = cmdString\n continuation.yield(winch)\n }\n }\n let size = try terminal.size\n var width = size.width\n var height = size.height\n try setWinch(height, width)\n\n for await _ in winchHandler.signals {\n let size = try terminal.size\n let cols = size.width\n let rows = size.height\n if cols != width || rows != height {\n width = cols\n height = rows\n try setWinch(height, width)\n }\n }\n }\n }\n\n let respStream = self.clientAsync.performBuild(reqStream, callOptions: try CallOptions(config))\n let pipeline = try await BuildPipeline(config)\n do {\n try await pipeline.run(sender: continuation, receiver: respStream)\n } catch Error.buildComplete {\n _ = channel.close()\n try await group.shutdownGracefully()\n return\n }\n }\n\n public struct BuildExport: Sendable {\n public let type: String\n public var destination: URL?\n public let additionalFields: [String: String]\n public let rawValue: String\n\n public init(type: String, destination: URL?, additionalFields: [String: String], rawValue: String) {\n self.type = type\n self.destination = destination\n self.additionalFields = additionalFields\n self.rawValue = rawValue\n }\n\n public init(from input: String) throws {\n var typeValue: String?\n var destinationValue: URL?\n var additionalFields: [String: String] = [:]\n\n let pairs = input.components(separatedBy: \",\")\n for pair in pairs {\n let parts = pair.components(separatedBy: \"=\")\n guard parts.count == 2 else { continue }\n\n let key = parts[0].trimmingCharacters(in: .whitespaces)\n let value = parts[1].trimmingCharacters(in: .whitespaces)\n\n switch key {\n case \"type\":\n typeValue = value\n case \"dest\":\n destinationValue = try Self.resolveDestination(dest: value)\n default:\n additionalFields[key] = value\n }\n }\n\n guard let type = typeValue else {\n throw Builder.Error.invalidExport(input, \"type field is required\")\n }\n\n switch type {\n case \"oci\":\n break\n case \"tar\":\n if destinationValue == nil {\n throw Builder.Error.invalidExport(input, \"dest field is required\")\n }\n case \"local\":\n if destinationValue == nil {\n throw Builder.Error.invalidExport(input, \"dest field is required\")\n }\n default:\n throw Builder.Error.invalidExport(input, \"unsupported output type\")\n }\n\n self.init(type: type, destination: destinationValue, additionalFields: additionalFields, rawValue: input)\n }\n\n public var stringValue: String {\n get throws {\n var components = [\"type=\\(type)\"]\n\n switch type {\n case \"oci\", \"tar\", \"local\":\n break // ignore destination\n default:\n throw Builder.Error.invalidExport(rawValue, \"unsupported output type\")\n }\n\n for (key, value) in additionalFields {\n components.append(\"\\(key)=\\(value)\")\n }\n\n return components.joined(separator: \",\")\n }\n }\n\n static func resolveDestination(dest: String) throws -> URL {\n let destination = URL(fileURLWithPath: dest)\n let fileManager = FileManager.default\n\n if fileManager.fileExists(atPath: destination.path) {\n let resourceValues = try destination.resourceValues(forKeys: [.isDirectoryKey])\n let isDir = resourceValues.isDirectory\n if isDir != nil && isDir == false {\n throw Builder.Error.invalidExport(dest, \"dest path already exists\")\n }\n\n var finalDestination = destination.appendingPathComponent(\"out.tar\")\n var index = 1\n while fileManager.fileExists(atPath: finalDestination.path) {\n let path = \"out.tar.\\(index)\"\n finalDestination = destination.appendingPathComponent(path)\n index += 1\n }\n return finalDestination\n } else {\n let parentDirectory = destination.deletingLastPathComponent()\n try? fileManager.createDirectory(at: parentDirectory, withIntermediateDirectories: true, attributes: nil)\n }\n\n return destination\n }\n }\n\n public struct BuildConfig: Sendable {\n public let buildID: String\n public let contentStore: ContentStore\n public let buildArgs: [String]\n public let contextDir: String\n public let dockerfile: Data\n public let labels: [String]\n public let noCache: Bool\n public let platforms: [Platform]\n public let terminal: Terminal?\n public let tag: String\n public let target: String\n public let quiet: Bool\n public let exports: [BuildExport]\n public let cacheIn: [String]\n public let cacheOut: [String]\n\n public init(\n buildID: String,\n contentStore: ContentStore,\n buildArgs: [String],\n contextDir: String,\n dockerfile: Data,\n labels: [String],\n noCache: Bool,\n platforms: [Platform],\n terminal: Terminal?,\n tag: String,\n target: String,\n quiet: Bool,\n exports: [BuildExport],\n cacheIn: [String],\n cacheOut: [String],\n ) {\n self.buildID = buildID\n self.contentStore = contentStore\n self.buildArgs = buildArgs\n self.contextDir = contextDir\n self.dockerfile = dockerfile\n self.labels = labels\n self.noCache = noCache\n self.platforms = platforms\n self.terminal = terminal\n self.tag = tag\n self.target = target\n self.quiet = quiet\n self.exports = exports\n self.cacheIn = cacheIn\n self.cacheOut = cacheOut\n }\n }\n}\n\nextension Builder {\n enum Error: Swift.Error, CustomStringConvertible {\n case invalidContinuation\n case buildComplete\n case invalidExport(String, String)\n\n var description: String {\n switch self {\n case .invalidContinuation:\n return \"continuation could not created\"\n case .buildComplete:\n return \"build completed\"\n case .invalidExport(let exp, let reason):\n return \"export entry \\(exp) is invalid: \\(reason)\"\n }\n }\n }\n}\n\nextension CallOptions {\n public init(_ config: Builder.BuildConfig) throws {\n var headers: [(String, String)] = [\n (\"build-id\", config.buildID),\n (\"context\", URL(filePath: config.contextDir).path(percentEncoded: false)),\n (\"dockerfile\", config.dockerfile.base64EncodedString()),\n (\"progress\", config.terminal != nil ? \"tty\" : \"plain\"),\n (\"tag\", config.tag),\n (\"target\", config.target),\n ]\n for platform in config.platforms {\n headers.append((\"platforms\", platform.description))\n }\n if config.noCache {\n headers.append((\"no-cache\", \"\"))\n }\n for label in config.labels {\n headers.append((\"labels\", label))\n }\n for buildArg in config.buildArgs {\n headers.append((\"build-args\", buildArg))\n }\n for output in config.exports {\n headers.append((\"outputs\", try output.stringValue))\n }\n for cacheIn in config.cacheIn {\n headers.append((\"cache-in\", cacheIn))\n }\n for cacheOut in config.cacheOut {\n headers.append((\"cache-out\", cacheOut))\n }\n\n self.init(\n customMetadata: HPACKHeaders(headers)\n )\n }\n}\n\nextension FileHandle {\n @discardableResult\n func setSendBufSize(_ bytes: Int) throws -> Int {\n try setSockOpt(\n level: SOL_SOCKET,\n name: SO_SNDBUF,\n value: bytes)\n return bytes\n }\n\n @discardableResult\n func setRecvBufSize(_ bytes: Int) throws -> Int {\n try setSockOpt(\n level: SOL_SOCKET,\n name: SO_RCVBUF,\n value: bytes)\n return bytes\n }\n\n private func setSockOpt(level: Int32, name: Int32, value: Int) throws {\n var v = Int32(value)\n let res = withUnsafePointer(to: &v) { ptr -> Int32 in\n ptr.withMemoryRebound(\n to: UInt8.self,\n capacity: MemoryLayout.size\n ) { raw in\n #if canImport(Darwin)\n return setsockopt(\n self.fileDescriptor,\n level, name,\n raw,\n socklen_t(MemoryLayout.size))\n #else\n fatalError(\"unsupported platform\")\n #endif\n }\n }\n if res == -1 {\n throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EPERM)\n }\n }\n}\n"], ["/container/Sources/APIServer/APIServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerPlugin\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport DNSServer\nimport Foundation\nimport Logging\n\n@main\nstruct APIServer: AsyncParsableCommand {\n static let listenAddress = \"127.0.0.1\"\n static let dnsPort = 2053\n\n static let configuration = CommandConfiguration(\n commandName: \"container-apiserver\",\n abstract: \"Container management API server\",\n version: releaseVersion()\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .shortAndLong, help: \"Daemon root directory\")\n var root = Self.appRoot.path\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n func run() async throws {\n let commandName = Self.configuration.commandName ?? \"container-apiserver\"\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n do {\n log.info(\"configuring XPC server\")\n let root = URL(filePath: root)\n var routes = [XPCRoute: XPCServer.RouteHandler]()\n let pluginLoader = try initializePluginLoader(log: log)\n try await initializePlugins(pluginLoader: pluginLoader, log: log, routes: &routes)\n try initializeContainerService(root: root, pluginLoader: pluginLoader, log: log, routes: &routes)\n let networkService = try await initializeNetworkService(\n root: root,\n pluginLoader: pluginLoader,\n log: log,\n routes: &routes\n )\n initializeHealthCheckService(log: log, routes: &routes)\n try initializeKernelService(log: log, routes: &routes)\n\n let server = XPCServer(\n identifier: \"com.apple.container.apiserver\",\n routes: routes.reduce(\n into: [String: XPCServer.RouteHandler](),\n {\n $0[$1.key.rawValue] = $1.value\n }), log: log)\n\n await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n log.info(\"starting XPC server\")\n try await server.listen()\n }\n // start up host table DNS\n group.addTask {\n let hostsResolver = ContainerDNSHandler(networkService: networkService)\n let nxDomainResolver = NxDomainResolver()\n let compositeResolver = CompositeResolver(handlers: [hostsResolver, nxDomainResolver])\n let hostsQueryValidator = StandardQueryValidator(handler: compositeResolver)\n let dnsServer: DNSServer = DNSServer(handler: hostsQueryValidator, log: log)\n log.info(\n \"starting DNS host query resolver\",\n metadata: [\n \"host\": \"\\(Self.listenAddress)\",\n \"port\": \"\\(Self.dnsPort)\",\n ]\n )\n try await dnsServer.run(host: Self.listenAddress, port: Self.dnsPort)\n }\n }\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n APIServer.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"APIServer\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n return log\n }\n\n private func initializePluginLoader(log: Logger) throws -> PluginLoader {\n let installRoot = CommandLine.executablePathUrl\n .deletingLastPathComponent()\n .appendingPathComponent(\"..\")\n .standardized\n let pluginsURL = PluginLoader.userPluginsDir(root: installRoot)\n var directoryExists: ObjCBool = false\n _ = FileManager.default.fileExists(atPath: pluginsURL.path, isDirectory: &directoryExists)\n let userPluginsURL = directoryExists.boolValue ? pluginsURL : nil\n\n // plugins built into the application installed as a macOS app bundle\n let appBundlePluginsURL = Bundle.main.resourceURL?.appending(path: \"plugins\")\n\n // plugins built into the application installed as a Unix-like application\n let installRootPluginsURL =\n installRoot\n .appendingPathComponent(\"libexec\")\n .appendingPathComponent(\"container\")\n .appendingPathComponent(\"plugins\")\n .standardized\n\n let pluginDirectories = [\n userPluginsURL,\n appBundlePluginsURL,\n installRootPluginsURL,\n ].compactMap { $0 }\n\n let pluginFactories: [PluginFactory] = [\n DefaultPluginFactory(),\n AppBundlePluginFactory(),\n ]\n\n log.info(\"PLUGINS: \\(pluginDirectories)\")\n let statePath = PluginLoader.defaultPluginResourcePath(root: Self.appRoot)\n try FileManager.default.createDirectory(at: statePath, withIntermediateDirectories: true)\n return PluginLoader(pluginDirectories: pluginDirectories, pluginFactories: pluginFactories, defaultResourcePath: statePath, log: log)\n }\n\n // First load all of the plugins we can find. Then just expose\n // the handlers for clients to do whatever they want.\n private func initializePlugins(\n pluginLoader: PluginLoader,\n log: Logger,\n routes: inout [XPCRoute: XPCServer.RouteHandler]\n ) async throws {\n let bootPlugins = pluginLoader.findPlugins().filter { $0.shouldBoot }\n\n let service = PluginsService(pluginLoader: pluginLoader, log: log)\n try await service.loadAll(bootPlugins)\n\n let harness = PluginsHarness(service: service, log: log)\n routes[XPCRoute.pluginGet] = harness.get\n routes[XPCRoute.pluginList] = harness.list\n routes[XPCRoute.pluginLoad] = harness.load\n routes[XPCRoute.pluginUnload] = harness.unload\n routes[XPCRoute.pluginRestart] = harness.restart\n }\n\n private func initializeHealthCheckService(log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) {\n let svc = HealthCheckHarness(log: log)\n routes[XPCRoute.ping] = svc.ping\n }\n\n private func initializeKernelService(log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) throws {\n let svc = try KernelService(log: log, appRoot: Self.appRoot)\n let harness = KernelHarness(service: svc, log: log)\n routes[XPCRoute.installKernel] = harness.install\n routes[XPCRoute.getDefaultKernel] = harness.getDefaultKernel\n }\n\n private func initializeContainerService(root: URL, pluginLoader: PluginLoader, log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) throws {\n let service = try ContainersService(\n root: root,\n pluginLoader: pluginLoader,\n log: log\n )\n let harness = ContainersHarness(service: service, log: log)\n\n routes[XPCRoute.listContainer] = harness.list\n routes[XPCRoute.createContainer] = harness.create\n routes[XPCRoute.deleteContainer] = harness.delete\n routes[XPCRoute.containerLogs] = harness.logs\n routes[XPCRoute.containerEvent] = harness.eventHandler\n }\n\n private func initializeNetworkService(\n root: URL,\n pluginLoader: PluginLoader,\n log: Logger,\n routes: inout [XPCRoute: XPCServer.RouteHandler]\n ) async throws -> NetworksService {\n let resourceRoot = root.appendingPathComponent(\"networks\")\n let service = try await NetworksService(\n pluginLoader: pluginLoader,\n resourceRoot: resourceRoot,\n log: log\n )\n\n let defaultNetwork = try await service.list()\n .filter { $0.id == ClientNetwork.defaultNetworkName }\n .first\n if defaultNetwork == nil {\n let config = NetworkConfiguration(id: ClientNetwork.defaultNetworkName, mode: .nat)\n _ = try await service.create(configuration: config)\n }\n\n let harness = NetworksHarness(service: service, log: log)\n\n routes[XPCRoute.networkCreate] = harness.create\n routes[XPCRoute.networkDelete] = harness.delete\n routes[XPCRoute.networkList] = harness.list\n return service\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/Helpers/NetworkVmnet/NetworkVmnetHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\n@main\nstruct NetworkVmnetHelper: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"container-network-vmnet\",\n abstract: \"XPC service for managing a vmnet network\",\n version: releaseVersion(),\n subcommands: [\n Start.self\n ]\n )\n}\n\nextension NetworkVmnetHelper {\n struct Start: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Starts the network plugin\"\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .long, help: \"XPC service identifier\")\n var serviceIdentifier: String\n\n @Option(name: .shortAndLong, help: \"Network identifier\")\n var id: String\n\n @Option(name: .shortAndLong, help: \"CIDR address for the subnet\")\n var subnet: String?\n\n func run() async throws {\n let commandName = NetworkVmnetHelper._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n do {\n log.info(\"configuring XPC server\")\n let subnet = try self.subnet.map { try CIDRAddress($0) }\n let configuration = NetworkConfiguration(id: id, mode: .nat, subnet: subnet?.description)\n let network = try Self.createNetwork(configuration: configuration, log: log)\n try await network.start()\n let server = try await NetworkService(network: network, log: log)\n let xpc = XPCServer(\n identifier: serviceIdentifier,\n routes: [\n NetworkRoutes.state.rawValue: server.state,\n NetworkRoutes.allocate.rawValue: server.allocate,\n NetworkRoutes.deallocate.rawValue: server.deallocate,\n NetworkRoutes.lookup.rawValue: server.lookup,\n NetworkRoutes.disableAllocator.rawValue: server.disableAllocator,\n ],\n log: log\n )\n\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n NetworkVmnetHelper.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"NetworkVmnetHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n log[metadataKey: \"id\"] = \"\\(id)\"\n return log\n }\n\n private static func createNetwork(configuration: NetworkConfiguration, log: Logger) throws -> Network {\n guard #available(macOS 26, *) else {\n return try AllocationOnlyVmnetNetwork(configuration: configuration, log: log)\n }\n\n return try ReservedVmnetNetwork(configuration: configuration, log: log)\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct ClientContainer: Sendable, Codable {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n\n private var sandboxClient: SandboxClient {\n SandboxClient(id: configuration.id, runtime: configuration.runtimeHandler)\n }\n\n /// Identifier of the container.\n public var id: String {\n configuration.id\n }\n\n public let status: RuntimeStatus\n\n /// Configured platform for the container.\n public var platform: ContainerizationOCI.Platform {\n configuration.platform\n }\n\n /// Configuration for the container.\n public let configuration: ContainerConfiguration\n\n /// Network allocated to the container.\n public let networks: [Attachment]\n\n package init(configuration: ContainerConfiguration) {\n self.configuration = configuration\n self.status = .stopped\n self.networks = []\n }\n\n init(snapshot: ContainerSnapshot) {\n self.configuration = snapshot.configuration\n self.status = snapshot.status\n self.networks = snapshot.networks\n }\n\n public var initProcess: ClientProcess {\n ClientProcessImpl(containerId: self.id, client: self.sandboxClient)\n }\n}\n\nextension ClientContainer {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n @discardableResult\n private static func xpcSend(\n client: XPCClient,\n message: XPCMessage,\n timeout: Duration? = .seconds(15)\n ) async throws -> XPCMessage {\n try await client.send(message, responseTimeout: timeout)\n }\n\n public static func create(\n configuration: ContainerConfiguration,\n options: ContainerCreateOptions = .default,\n kernel: Kernel\n ) async throws -> ClientContainer {\n do {\n let client = Self.newClient()\n let request = XPCMessage(route: .createContainer)\n\n let data = try JSONEncoder().encode(configuration)\n let kdata = try JSONEncoder().encode(kernel)\n let odata = try JSONEncoder().encode(options)\n request.set(key: .containerConfig, value: data)\n request.set(key: .kernel, value: kdata)\n request.set(key: .containerOptions, value: odata)\n\n try await xpcSend(client: client, message: request)\n return ClientContainer(configuration: configuration)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to create container\",\n cause: error\n )\n }\n }\n\n public static func list() async throws -> [ClientContainer] {\n do {\n let client = Self.newClient()\n let request = XPCMessage(route: .listContainer)\n\n let response = try await xpcSend(\n client: client,\n message: request,\n timeout: .seconds(10)\n )\n let data = response.dataNoCopy(key: .containers)\n guard let data else {\n return []\n }\n let configs = try JSONDecoder().decode([ContainerSnapshot].self, from: data)\n return configs.map { ClientContainer(snapshot: $0) }\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to list containers\",\n cause: error\n )\n }\n }\n\n /// Get the container for the provided id.\n public static func get(id: String) async throws -> ClientContainer {\n let containers = try await list()\n guard let container = containers.first(where: { $0.id == id }) else {\n throw ContainerizationError(\n .notFound,\n message: \"get failed: container \\(id) not found\"\n )\n }\n return container\n }\n}\n\nextension ClientContainer {\n public func bootstrap() async throws -> ClientProcess {\n let client = self.sandboxClient\n try await client.bootstrap()\n return ClientProcessImpl(containerId: self.id, client: self.sandboxClient)\n }\n\n /// Stop the container and all processes currently executing inside.\n public func stop(opts: ContainerStopOptions = ContainerStopOptions.default) async throws {\n do {\n let client = self.sandboxClient\n try await client.stop(options: opts)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to stop container\",\n cause: error\n )\n }\n }\n\n /// Delete the container along with any resources.\n public func delete() async throws {\n do {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .deleteContainer)\n request.set(key: .id, value: self.id)\n try await client.send(request)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to delete container\",\n cause: error\n )\n }\n }\n}\n\nextension ClientContainer {\n /// Execute a new process inside a running container.\n public func createProcess(id: String, configuration: ProcessConfiguration) async throws -> ClientProcess {\n do {\n let client = self.sandboxClient\n try await client.createProcess(id, config: configuration)\n return ClientProcessImpl(containerId: self.id, processId: id, client: client)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to exec in container\",\n cause: error\n )\n }\n }\n\n /// Send or \"kill\" a signal to the initial process of the container.\n /// Kill does not wait for the process to exit, it only delivers the signal.\n public func kill(_ signal: Int32) async throws {\n do {\n let client = self.sandboxClient\n try await client.kill(self.id, signal: Int64(signal))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill container \\(self.id)\",\n cause: error\n )\n }\n }\n\n public func logs() async throws -> [FileHandle] {\n do {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .containerLogs)\n request.set(key: .id, value: self.id)\n\n let response = try await client.send(request)\n let fds = response.fileHandles(key: .logs)\n guard let fds else {\n throw ContainerizationError(\n .internalError,\n message: \"No log fds returned\"\n )\n }\n return fds\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get logs for container \\(self.id)\",\n cause: error\n )\n }\n }\n\n public func dial(_ port: UInt32) async throws -> FileHandle {\n do {\n let client = self.sandboxClient\n return try await client.dial(port)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to dial \\(port) in container \\(self.id)\",\n cause: error\n )\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Utility.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct Utility {\n private static let infraImages = [\n ClientDefaults.get(key: .defaultBuilderImage),\n ClientDefaults.get(key: .defaultInitImage),\n ]\n\n public static func createContainerID(name: String?) -> String {\n guard let name else {\n return UUID().uuidString.lowercased()\n }\n return name\n }\n\n public static func isInfraImage(name: String) -> Bool {\n for infraImage in infraImages {\n if name == infraImage {\n return true\n }\n }\n return false\n }\n\n public static func trimDigest(digest: String) -> String {\n var digest = digest\n digest.trimPrefix(\"sha256:\")\n if digest.count > 24 {\n digest = String(digest.prefix(24)) + \"...\"\n }\n return digest\n }\n\n public static func validEntityName(_ name: String) throws {\n let pattern = #\"^[a-zA-Z0-9][a-zA-Z0-9_.-]+$\"#\n let regex = try Regex(pattern)\n if try regex.firstMatch(in: name) == nil {\n throw ContainerizationError(.invalidArgument, message: \"invalid entity name \\(name)\")\n }\n }\n\n public static func containerConfigFromFlags(\n id: String,\n image: String,\n arguments: [String],\n process: Flags.Process,\n management: Flags.Management,\n resource: Flags.Resource,\n registry: Flags.Registry,\n progressUpdate: @escaping ProgressUpdateHandler\n ) async throws -> (ContainerConfiguration, Kernel) {\n let requestedPlatform = Parser.platform(os: management.os, arch: management.arch)\n let scheme = try RequestScheme(registry.scheme)\n\n await progressUpdate([\n .setDescription(\"Fetching image\"),\n .setItemsName(\"blobs\"),\n ])\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n let img = try await ClientImage.fetch(\n reference: image,\n platform: requestedPlatform,\n scheme: scheme,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progressUpdate)\n )\n\n // Unpack a fetched image before use\n await progressUpdate([\n .setDescription(\"Unpacking image\"),\n .setItemsName(\"entries\"),\n ])\n let unpackTask = await taskManager.startTask()\n try await img.getCreateSnapshot(\n platform: requestedPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progressUpdate))\n\n await progressUpdate([\n .setDescription(\"Fetching kernel\"),\n .setItemsName(\"binary\"),\n ])\n\n let kernel = try await self.getKernel(management: management)\n\n // Pull and unpack the initial filesystem\n await progressUpdate([\n .setDescription(\"Fetching init image\"),\n .setItemsName(\"blobs\"),\n ])\n let fetchInitTask = await taskManager.startTask()\n let initImage = try await ClientImage.fetch(\n reference: ClientImage.initImageRef, platform: .current, scheme: scheme,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchInitTask, from: progressUpdate))\n\n await progressUpdate([\n .setDescription(\"Unpacking init image\"),\n .setItemsName(\"entries\"),\n ])\n let unpackInitTask = await taskManager.startTask()\n _ = try await initImage.getCreateSnapshot(\n platform: .current,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackInitTask, from: progressUpdate))\n\n await taskManager.finish()\n\n let imageConfig = try await img.config(for: requestedPlatform).config\n let description = img.description\n let pc = try Parser.process(\n arguments: arguments,\n processFlags: process,\n managementFlags: management,\n config: imageConfig\n )\n\n var config = ContainerConfiguration(id: id, image: description, process: pc)\n config.platform = requestedPlatform\n config.hostname = id\n\n config.resources = try Parser.resources(\n cpus: resource.cpus,\n memory: resource.memory\n )\n\n let tmpfs = try Parser.tmpfsMounts(management.tmpFs)\n let volumes = try Parser.volumes(management.volumes)\n var mounts = try Parser.mounts(management.mounts)\n mounts.append(contentsOf: tmpfs)\n mounts.append(contentsOf: volumes)\n config.mounts = mounts\n\n if management.networks.isEmpty {\n config.networks = [ClientNetwork.defaultNetworkName]\n } else {\n // networks may only be specified for macOS 26+\n guard #available(macOS 26, *) else {\n throw ContainerizationError(.invalidArgument, message: \"non-default network configuration requires macOS 26 or newer\")\n }\n config.networks = management.networks\n }\n\n var networkStatuses: [NetworkStatus] = []\n for networkName in config.networks {\n let network: NetworkState = try await ClientNetwork.get(id: networkName)\n guard case .running(_, let networkStatus) = network else {\n throw ContainerizationError(.invalidState, message: \"network \\(networkName) is not running\")\n }\n networkStatuses.append(networkStatus)\n }\n\n if management.dnsDisabled {\n config.dns = nil\n } else {\n let domain = management.dnsDomain ?? ClientDefaults.getOptional(key: .defaultDNSDomain)\n config.dns = .init(\n nameservers: management.dnsNameservers,\n domain: domain,\n searchDomains: management.dnsSearchDomains,\n options: management.dnsOptions\n )\n }\n\n if Platform.current.architecture == \"arm64\" && requestedPlatform.architecture == \"amd64\" {\n config.rosetta = true\n }\n\n config.labels = try Parser.labels(management.labels)\n\n config.publishedPorts = try Parser.publishPorts(management.publishPorts)\n\n // Parse --publish-socket arguments and add to container configuration\n // to enable socket forwarding from container to host.\n config.publishedSockets = try Parser.publishSockets(management.publishSockets)\n\n return (config, kernel)\n }\n\n private static func getKernel(management: Flags.Management) async throws -> Kernel {\n // For the image itself we'll take the user input and try with it as we can do userspace\n // emulation for x86, but for the kernel we need it to match the hosts architecture.\n let s: SystemPlatform = .current\n if let userKernel = management.kernel {\n guard FileManager.default.fileExists(atPath: userKernel) else {\n throw ContainerizationError(.notFound, message: \"Kernel file not found at path \\(userKernel)\")\n }\n let p = URL(filePath: userKernel)\n return .init(path: p, platform: s)\n }\n return try await ClientKernel.getDefaultKernel(for: s)\n }\n}\n"], ["/container/Sources/CLI/System/Kernel/KernelSet.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct KernelSet: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default kernel\"\n )\n\n @Option(name: .customLong(\"binary\"), help: \"Path to the binary to set as the default kernel. If used with --tar, this points to a location inside the tar\")\n var binaryPath: String? = nil\n\n @Option(name: .customLong(\"tar\"), help: \"Filesystem path or remote URL to a tar ball that contains the kernel to use\")\n var tarPath: String? = nil\n\n @Option(name: .customLong(\"arch\"), help: \"The architecture of the kernel binary. One of (amd64, arm64)\")\n var architecture: String = ContainerizationOCI.Platform.current.architecture.description\n\n @Flag(name: .customLong(\"recommended\"), help: \"Download and install the recommended kernel as the default. This flag ignores any other arguments\")\n var recommended: Bool = false\n\n func run() async throws {\n if recommended {\n let url = ClientDefaults.get(key: .defaultKernelURL)\n let path = ClientDefaults.get(key: .defaultKernelBinaryPath)\n print(\"Installing the recommended kernel from \\(url)...\")\n try await Self.downloadAndInstallWithProgressBar(tarRemoteURL: url, kernelFilePath: path)\n return\n }\n guard tarPath != nil else {\n return try await self.setKernelFromBinary()\n }\n try await self.setKernelFromTar()\n }\n\n private func setKernelFromBinary() async throws {\n guard let binaryPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--binary'\")\n }\n let absolutePath = URL(fileURLWithPath: binaryPath, relativeTo: .currentDirectory()).absoluteURL.absoluteString\n let platform = try getSystemPlatform()\n try await ClientKernel.installKernel(kernelFilePath: absolutePath, platform: platform)\n }\n\n private func setKernelFromTar() async throws {\n guard let binaryPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--binary'\")\n }\n guard let tarPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--tar\")\n }\n let platform = try getSystemPlatform()\n let localTarPath = URL(fileURLWithPath: tarPath, relativeTo: .currentDirectory()).absoluteString\n let fm = FileManager.default\n if fm.fileExists(atPath: localTarPath) {\n try await ClientKernel.installKernelFromTar(tarFile: localTarPath, kernelFilePath: binaryPath, platform: platform)\n return\n }\n guard let remoteURL = URL(string: tarPath) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid remote URL '\\(tarPath)' for argument '--tar'. Missing protocol?\")\n }\n try await Self.downloadAndInstallWithProgressBar(tarRemoteURL: remoteURL.absoluteString, kernelFilePath: binaryPath, platform: platform)\n }\n\n private func getSystemPlatform() throws -> SystemPlatform {\n switch architecture {\n case \"arm64\":\n return .linuxArm\n case \"amd64\":\n return .linuxAmd\n default:\n throw ContainerizationError(.unsupported, message: \"Unsupported architecture \\(architecture)\")\n }\n }\n\n public static func downloadAndInstallWithProgressBar(tarRemoteURL: String, kernelFilePath: String, platform: SystemPlatform = .current) async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n totalTasks: 2\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n try await ClientKernel.installKernelFromTar(tarFile: tarRemoteURL, kernelFilePath: kernelFilePath, platform: platform, progressUpdate: progress.handler)\n progress.finish()\n }\n\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/RuntimeLinuxHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\nimport NIO\n\n@main\nstruct RuntimeLinuxHelper: AsyncParsableCommand {\n static let label = \"com.apple.container.runtime.container-runtime-linux\"\n\n static let configuration = CommandConfiguration(\n commandName: \"container-runtime-linux\",\n abstract: \"XPC Service for managing a Linux sandbox\",\n version: releaseVersion()\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .shortAndLong, help: \"Sandbox UUID\")\n var uuid: String\n\n @Option(name: .shortAndLong, help: \"Root directory for the sandbox\")\n var root: String\n\n var machServiceLabel: String {\n \"\\(Self.label).\\(uuid)\"\n }\n\n func run() async throws {\n let commandName = Self._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n do {\n try adjustLimits()\n signal(SIGPIPE, SIG_IGN)\n\n log.info(\"configuring XPC server\")\n let interfaceStrategy: any InterfaceStrategy\n if #available(macOS 26, *) {\n interfaceStrategy = NonisolatedInterfaceStrategy(log: log)\n } else {\n interfaceStrategy = IsolatedInterfaceStrategy()\n }\n let server = SandboxService(root: .init(fileURLWithPath: root), interfaceStrategy: interfaceStrategy, eventLoopGroup: eventLoopGroup, log: log)\n let xpc = XPCServer(\n identifier: machServiceLabel,\n routes: [\n SandboxRoutes.bootstrap.rawValue: server.bootstrap,\n SandboxRoutes.createProcess.rawValue: server.createProcess,\n SandboxRoutes.state.rawValue: server.state,\n SandboxRoutes.stop.rawValue: server.stop,\n SandboxRoutes.kill.rawValue: server.kill,\n SandboxRoutes.resize.rawValue: server.resize,\n SandboxRoutes.wait.rawValue: server.wait,\n SandboxRoutes.start.rawValue: server.startProcess,\n SandboxRoutes.dial.rawValue: server.dial,\n ],\n log: log\n )\n\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n try? await eventLoopGroup.shutdownGracefully()\n RuntimeLinuxHelper.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"RuntimeLinuxHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n log[metadataKey: \"uuid\"] = \"\\(uuid)\"\n return log\n }\n\n private func adjustLimits() throws {\n var limits = rlimit()\n guard getrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n limits.rlim_cur = 65536\n limits.rlim_max = 65536\n guard setrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/CLI/System/SystemStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct SystemStart: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Start `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Path to the `container-apiserver` binary\")\n var path: String = Bundle.main.executablePath ?? \"\"\n\n @Flag(name: .long, help: \"Enable debug logging for the runtime daemon.\")\n var debug = false\n\n @Flag(\n name: .long, inversion: .prefixedEnableDisable,\n help: \"Specify whether the default kernel should be installed or not. The default behavior is to prompt the user for a response.\")\n var kernelInstall: Bool?\n\n func run() async throws {\n // Without the true path to the binary in the plist, `container-apiserver` won't launch properly.\n let executableUrl = URL(filePath: path)\n .resolvingSymlinksInPath()\n .deletingLastPathComponent()\n .appendingPathComponent(\"container-apiserver\")\n\n var args = [executableUrl.absolutePath()]\n if debug {\n args.append(\"--debug\")\n }\n\n let apiServerDataUrl = appRoot.appending(path: \"apiserver\")\n try! FileManager.default.createDirectory(at: apiServerDataUrl, withIntermediateDirectories: true)\n let env = ProcessInfo.processInfo.environment.filter { key, _ in\n key.hasPrefix(\"CONTAINER_\")\n }\n\n let logURL = apiServerDataUrl.appending(path: \"apiserver.log\")\n let plist = LaunchPlist(\n label: \"com.apple.container.apiserver\",\n arguments: args,\n environment: env,\n limitLoadToSessionType: [.Aqua, .Background, .System],\n runAtLoad: true,\n stdout: logURL.path,\n stderr: logURL.path,\n machServices: [\"com.apple.container.apiserver\"]\n )\n\n let plistURL = apiServerDataUrl.appending(path: \"apiserver.plist\")\n let data = try plist.encode()\n try data.write(to: plistURL)\n\n try ServiceManager.register(plistPath: plistURL.path)\n\n // Now ping our friendly daemon. Fail if we don't get a response.\n do {\n print(\"Verifying apiserver is running...\")\n try await ClientHealthCheck.ping(timeout: .seconds(10))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get a response from apiserver: \\(error)\"\n )\n }\n\n if await !initImageExists() {\n try? await installInitialFilesystem()\n }\n\n guard await !kernelExists() else {\n return\n }\n try await installDefaultKernel()\n }\n\n private func installInitialFilesystem() async throws {\n let dep = Dependencies.initFs\n let pullCommand = ImagePull(reference: dep.source)\n print(\"Installing base container filesystem...\")\n do {\n try await pullCommand.run()\n } catch {\n log.error(\"Failed to install base container filesystem: \\(error)\")\n }\n }\n\n private func installDefaultKernel() async throws {\n let kernelDependency = Dependencies.kernel\n let defaultKernelURL = kernelDependency.source\n let defaultKernelBinaryPath = ClientDefaults.get(key: .defaultKernelBinaryPath)\n\n var shouldInstallKernel = false\n if kernelInstall == nil {\n print(\"No default kernel configured.\")\n print(\"Install the recommended default kernel from [\\(kernelDependency.source)]? [Y/n]: \", terminator: \"\")\n guard let read = readLine(strippingNewline: true) else {\n throw ContainerizationError(.internalError, message: \"Failed to read user input\")\n }\n guard read.lowercased() == \"y\" || read.count == 0 else {\n print(\"Please use the `container system kernel set --recommended` command to configure the default kernel\")\n return\n }\n shouldInstallKernel = true\n } else {\n shouldInstallKernel = kernelInstall ?? false\n }\n guard shouldInstallKernel else {\n return\n }\n print(\"Installing kernel...\")\n try await KernelSet.downloadAndInstallWithProgressBar(tarRemoteURL: defaultKernelURL, kernelFilePath: defaultKernelBinaryPath)\n }\n\n private func initImageExists() async -> Bool {\n do {\n let img = try await ClientImage.get(reference: Dependencies.initFs.source)\n let _ = try await img.getSnapshot(platform: .current)\n return true\n } catch {\n return false\n }\n }\n\n private func kernelExists() async -> Bool {\n do {\n try await ClientKernel.getDefaultKernel(for: .current)\n return true\n } catch {\n return false\n }\n }\n }\n\n private enum Dependencies: String {\n case kernel\n case initFs\n\n var source: String {\n switch self {\n case .initFs:\n return ClientDefaults.get(key: .defaultInitImage)\n case .kernel:\n return ClientDefaults.get(key: .defaultKernelURL)\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationExtras\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct NetworkList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List networks\",\n aliases: [\"ls\"])\n\n @Flag(name: .shortAndLong, help: \"Only output the network name\")\n var quiet = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let networks = try await ClientNetwork.list()\n try printNetworks(networks: networks, format: format)\n }\n\n private func createHeader() -> [[String]] {\n [[\"NETWORK\", \"STATE\", \"SUBNET\"]]\n }\n\n private func printNetworks(networks: [NetworkState], format: ListFormat) throws {\n if format == .json {\n let printables = networks.map {\n PrintableNetwork($0)\n }\n let data = try JSONEncoder().encode(printables)\n print(String(data: data, encoding: .utf8)!)\n\n return\n }\n\n if self.quiet {\n networks.forEach {\n print($0.id)\n }\n return\n }\n\n var rows = createHeader()\n for network in networks {\n rows.append(network.asRow)\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n }\n}\n\nextension NetworkState {\n var asRow: [String] {\n switch self {\n case .created(_):\n return [self.id, self.state, \"none\"]\n case .running(_, let status):\n return [self.id, self.state, status.address]\n }\n }\n}\n\nstruct PrintableNetwork: Codable {\n let id: String\n let state: String\n let config: NetworkConfiguration\n let status: NetworkStatus?\n\n init(_ network: NetworkState) {\n self.id = network.id\n self.state = network.state\n switch network {\n case .created(let config):\n self.config = config\n self.status = nil\n case .running(let config, let status):\n self.config = config\n self.status = status\n }\n }\n}\n"], ["/container/Sources/CLI/Registry/RegistryDefault.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct RegistryDefault: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"default\",\n abstract: \"Manage the default image registry\",\n subcommands: [\n DefaultSetCommand.self,\n DefaultUnsetCommand.self,\n DefaultInspectCommand.self,\n ]\n )\n }\n\n struct DefaultSetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default registry\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @Argument\n var host: String\n\n func run() async throws {\n let scheme = try RequestScheme(registry.scheme).schemeFor(host: host)\n\n let _url = \"\\(scheme)://\\(host)\"\n guard let url = URL(string: _url), let domain = url.host() else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n let resolvedDomain = Reference.resolveDomain(domain: domain)\n let client = RegistryClient(host: resolvedDomain, scheme: scheme.rawValue, port: url.port)\n do {\n try await client.ping()\n } catch let err as RegistryClient.Error {\n switch err {\n case .invalidStatus(url: _, .unauthorized, _), .invalidStatus(url: _, .forbidden, _):\n break\n default:\n throw err\n }\n }\n ClientDefaults.set(value: host, key: .defaultRegistryDomain)\n print(\"Set default registry to \\(host)\")\n }\n }\n\n struct DefaultUnsetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"unset\",\n abstract: \"Unset the default registry\",\n aliases: [\"clear\"]\n )\n\n func run() async throws {\n ClientDefaults.unset(key: .defaultRegistryDomain)\n print(\"Unset the default registry domain\")\n }\n }\n\n struct DefaultInspectCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display the default registry domain\"\n )\n\n func run() async throws {\n print(ClientDefaults.get(key: .defaultRegistryDomain))\n }\n }\n}\n"], ["/container/Sources/CLI/RunCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Foundation\nimport NIOCore\nimport NIOPosix\nimport TerminalProgress\n\nextension Application {\n struct ContainerRunCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"run\",\n abstract: \"Run a container\")\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var resourceFlags: Flags.Resource\n\n @OptionGroup\n var managementFlags: Flags.Management\n\n @OptionGroup\n var registryFlags: Flags.Registry\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Argument(help: \"Image name\")\n var image: String\n\n @Argument(parsing: .captureForPassthrough, help: \"Container init process arguments\")\n var arguments: [String] = []\n\n func run() async throws {\n var exitCode: Int32 = 127\n let id = Utility.createContainerID(name: self.managementFlags.name)\n\n var progressConfig: ProgressConfig\n if progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 6\n )\n }\n\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n try Utility.validEntityName(id)\n\n // Check if container with id already exists.\n let existing = try? await ClientContainer.get(id: id)\n guard existing == nil else {\n throw ContainerizationError(\n .exists,\n message: \"container with id \\(id) already exists\"\n )\n }\n\n let ck = try await Utility.containerConfigFromFlags(\n id: id,\n image: image,\n arguments: arguments,\n process: processFlags,\n management: managementFlags,\n resource: resourceFlags,\n registry: registryFlags,\n progressUpdate: progress.handler\n )\n\n progress.set(description: \"Starting container\")\n\n let options = ContainerCreateOptions(autoRemove: managementFlags.remove)\n let container = try await ClientContainer.create(\n configuration: ck.0,\n options: options,\n kernel: ck.1\n )\n\n let detach = self.managementFlags.detach\n\n let process = try await container.bootstrap()\n progress.finish()\n\n do {\n let io = try ProcessIO.create(\n tty: self.processFlags.tty,\n interactive: self.processFlags.interactive,\n detach: detach\n )\n\n if !self.managementFlags.cidfile.isEmpty {\n let path = self.managementFlags.cidfile\n let data = id.data(using: .utf8)\n var attributes = [FileAttributeKey: Any]()\n attributes[.posixPermissions] = 0o644\n let success = FileManager.default.createFile(\n atPath: path,\n contents: data,\n attributes: attributes\n )\n guard success else {\n throw ContainerizationError(\n .internalError, message: \"failed to create cidfile at \\(path): \\(errno)\")\n }\n }\n\n if detach {\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n print(id)\n return\n }\n\n if !self.processFlags.tty {\n var handler = SignalThreshold(threshold: 3, signals: [SIGINT, SIGTERM])\n handler.start {\n print(\"Received 3 SIGINT/SIGTERM's, forcefully exiting.\")\n Darwin.exit(1)\n }\n }\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to run container: \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n\nstruct ProcessIO {\n let stdin: Pipe?\n let stdout: Pipe?\n let stderr: Pipe?\n var ioTracker: IoTracker?\n\n struct IoTracker {\n let stream: AsyncStream\n let cont: AsyncStream.Continuation\n let configuredStreams: Int\n }\n\n let stdio: [FileHandle?]\n\n let console: Terminal?\n\n func closeAfterStart() throws {\n try stdin?.fileHandleForReading.close()\n try stdout?.fileHandleForWriting.close()\n try stderr?.fileHandleForWriting.close()\n }\n\n func close() throws {\n try console?.reset()\n }\n\n static func create(tty: Bool, interactive: Bool, detach: Bool) throws -> ProcessIO {\n let current: Terminal? = try {\n if !tty || !interactive {\n return nil\n }\n let current = try Terminal.current\n try current.setraw()\n return current\n }()\n\n var stdio = [FileHandle?](repeating: nil, count: 3)\n\n let stdin: Pipe? = {\n if !interactive && !tty {\n return nil\n }\n return Pipe()\n }()\n\n if let stdin {\n if interactive {\n let pin = FileHandle.standardInput\n let stdinOSFile = OSFile(fd: pin.fileDescriptor)\n let pipeOSFile = OSFile(fd: stdin.fileHandleForWriting.fileDescriptor)\n try stdinOSFile.makeNonBlocking()\n nonisolated(unsafe) let buf = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n\n pin.readabilityHandler = { _ in\n Self.streamStdin(\n from: stdinOSFile,\n to: pipeOSFile,\n buffer: buf,\n ) {\n pin.readabilityHandler = nil\n buf.deallocate()\n try? stdin.fileHandleForWriting.close()\n }\n }\n }\n stdio[0] = stdin.fileHandleForReading\n }\n\n let stdout: Pipe? = {\n if detach {\n return nil\n }\n return Pipe()\n }()\n\n var configuredStreams = 0\n let (stream, cc) = AsyncStream.makeStream()\n if let stdout {\n configuredStreams += 1\n let pout: FileHandle = {\n if let current {\n return current.handle\n }\n return .standardOutput\n }()\n\n let rout = stdout.fileHandleForReading\n rout.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n rout.readabilityHandler = nil\n cc.yield()\n return\n }\n try! pout.write(contentsOf: data)\n }\n stdio[1] = stdout.fileHandleForWriting\n }\n\n let stderr: Pipe? = {\n if detach || tty {\n return nil\n }\n return Pipe()\n }()\n if let stderr {\n configuredStreams += 1\n let perr: FileHandle = .standardError\n let rerr = stderr.fileHandleForReading\n rerr.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n rerr.readabilityHandler = nil\n cc.yield()\n return\n }\n try! perr.write(contentsOf: data)\n }\n stdio[2] = stderr.fileHandleForWriting\n }\n\n var ioTracker: IoTracker? = nil\n if configuredStreams > 0 {\n ioTracker = .init(stream: stream, cont: cc, configuredStreams: configuredStreams)\n }\n\n return .init(\n stdin: stdin,\n stdout: stdout,\n stderr: stderr,\n ioTracker: ioTracker,\n stdio: stdio,\n console: current\n )\n }\n\n static func streamStdin(\n from: OSFile,\n to: OSFile,\n buffer: UnsafeMutableBufferPointer,\n onErrorOrEOF: () -> Void,\n ) {\n while true {\n let (bytesRead, action) = from.read(buffer)\n if bytesRead > 0 {\n let view = UnsafeMutableBufferPointer(\n start: buffer.baseAddress,\n count: bytesRead\n )\n\n let (bytesWritten, _) = to.write(view)\n if bytesWritten != bytesRead {\n onErrorOrEOF()\n return\n }\n }\n\n switch action {\n case .error(_), .eof, .brokenPipe:\n onErrorOrEOF()\n return\n case .again:\n return\n case .success:\n break\n }\n }\n }\n\n public func wait() async throws {\n guard let ioTracker = self.ioTracker else {\n return\n }\n do {\n try await Timeout.run(seconds: 3) {\n var counter = ioTracker.configuredStreams\n for await _ in ioTracker.stream {\n counter -= 1\n if counter == 0 {\n ioTracker.cont.finish()\n break\n }\n }\n }\n } catch {\n log.error(\"Timeout waiting for IO to complete : \\(error)\")\n throw error\n }\n }\n}\n\nstruct OSFile: Sendable {\n private let fd: Int32\n\n enum IOAction: Equatable {\n case eof\n case again\n case success\n case brokenPipe\n case error(_ errno: Int32)\n }\n\n init(fd: Int32) {\n self.fd = fd\n }\n\n init(handle: FileHandle) {\n self.fd = handle.fileDescriptor\n }\n\n func makeNonBlocking() throws {\n let flags = fcntl(fd, F_GETFL)\n guard flags != -1 else {\n throw POSIXError.fromErrno()\n }\n\n if fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1 {\n throw POSIXError.fromErrno()\n }\n }\n\n func write(_ buffer: UnsafeMutableBufferPointer) -> (wrote: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesWrote: Int = 0\n while true {\n let n = Darwin.write(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesWrote),\n buffer.count - bytesWrote\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesWrote, .again)\n }\n return (bytesWrote, .error(errno))\n }\n\n if n == 0 {\n return (bytesWrote, .brokenPipe)\n }\n\n bytesWrote += n\n if bytesWrote < buffer.count {\n continue\n }\n return (bytesWrote, .success)\n }\n }\n\n func read(_ buffer: UnsafeMutableBufferPointer) -> (read: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesRead: Int = 0\n while true {\n let n = Darwin.read(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesRead),\n buffer.count - bytesRead\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesRead, .again)\n }\n return (bytesRead, .error(errno))\n }\n\n if n == 0 {\n return (bytesRead, .eof)\n }\n\n bytesRead += n\n if bytesRead < buffer.count {\n continue\n }\n return (bytesRead, .success)\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImageRemove.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct RemoveImageOptions: ParsableArguments {\n @Flag(name: .shortAndLong, help: \"Remove all images\")\n var all: Bool = false\n\n @Argument\n var images: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n }\n\n struct RemoveImageImplementation {\n static func validate(options: RemoveImageOptions) throws {\n if options.images.count == 0 && !options.all {\n throw ContainerizationError(.invalidArgument, message: \"no image specified and --all not supplied\")\n }\n if options.images.count > 0 && options.all {\n throw ContainerizationError(.invalidArgument, message: \"explicitly supplied images conflict with the --all flag\")\n }\n }\n\n static func removeImage(options: RemoveImageOptions) async throws {\n let (found, notFound) = try await {\n if options.all {\n let found = try await ClientImage.list()\n let notFound: [String] = []\n return (found, notFound)\n }\n return try await ClientImage.get(names: options.images)\n }()\n var failures: [String] = notFound\n var didDeleteAnyImage = false\n for image in found {\n guard !Utility.isInfraImage(name: image.reference) else {\n continue\n }\n do {\n try await ClientImage.delete(reference: image.reference, garbageCollect: false)\n print(image.reference)\n didDeleteAnyImage = true\n } catch {\n log.error(\"failed to remove \\(image.reference): \\(error)\")\n failures.append(image.reference)\n }\n }\n let (_, size) = try await ClientImage.pruneImages()\n let formatter = ByteCountFormatter()\n let freed = formatter.string(fromByteCount: Int64(size))\n\n if didDeleteAnyImage {\n print(\"Reclaimed \\(freed) in disk space\")\n }\n if failures.count > 0 {\n throw ContainerizationError(.internalError, message: \"failed to delete one or more images: \\(failures)\")\n }\n }\n }\n\n struct ImageRemove: AsyncParsableCommand {\n @OptionGroup\n var options: RemoveImageOptions\n\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Remove one or more images\",\n aliases: [\"rm\"])\n\n func validate() throws {\n try RemoveImageImplementation.validate(options: options)\n }\n\n mutating func run() async throws {\n try await RemoveImageImplementation.removeImage(options: options)\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerKill.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Darwin\n\nextension Application {\n struct ContainerKill: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kill\",\n abstract: \"Kill one or more running containers\")\n\n @Option(name: .shortAndLong, help: \"Signal to send the container(s)\")\n var signal: String = \"KILL\"\n\n @Flag(name: .shortAndLong, help: \"Kill all running containers\")\n var all = false\n\n @Argument(help: \"Container IDs\")\n var containerIDs: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(.invalidArgument, message: \"explicitly supplied container IDs conflicts with the --all flag\")\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n\n var containers = try await ClientContainer.list().filter { c in\n c.status == .running\n }\n if !self.all {\n containers = containers.filter { c in\n set.contains(c.id)\n }\n }\n\n let signalNumber = try Signals.parseSignal(signal)\n\n var failed: [String] = []\n for container in containers {\n do {\n try await container.kill(signalNumber)\n print(container.id)\n } catch {\n log.error(\"failed to kill container \\(container.id): \\(error)\")\n failed.append(container.id)\n }\n }\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"kill failed for one or more containers\")\n }\n }\n }\n}\n"], ["/container/Sources/Helpers/Images/ImagesHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerImagesService\nimport ContainerImagesServiceClient\nimport ContainerLog\nimport ContainerXPC\nimport Containerization\nimport Foundation\nimport Logging\n\n@main\nstruct ImagesHelper: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"container-core-images\",\n abstract: \"XPC service for managing OCI images\",\n version: releaseVersion(),\n subcommands: [\n Start.self\n ]\n )\n}\n\nextension ImagesHelper {\n struct Start: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Starts the image plugin\"\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .long, help: \"XPC service prefix\")\n var serviceIdentifier: String = \"com.apple.container.core.container-core-images\"\n\n @Option(name: .shortAndLong, help: \"Daemon root directory\")\n var root = Self.appRoot.path\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n private static let unpackStrategy = SnapshotStore.defaultUnpackStrategy\n\n func run() async throws {\n let commandName = ImagesHelper._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n do {\n log.info(\"configuring XPC server\")\n let root = URL(filePath: root)\n var routes = [String: XPCServer.RouteHandler]()\n try self.initializeContentService(root: root, log: log, routes: &routes)\n try self.initializeImagesService(root: root, log: log, routes: &routes)\n let xpc = XPCServer(\n identifier: serviceIdentifier,\n routes: routes,\n log: log\n )\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n ImagesHelper.exit(withError: error)\n }\n }\n\n private func initializeImagesService(root: URL, log: Logger, routes: inout [String: XPCServer.RouteHandler]) throws {\n let contentStore = RemoteContentStoreClient()\n let imageStore = try ImageStore(path: root, contentStore: contentStore)\n let snapshotStore = try SnapshotStore(path: root, unpackStrategy: Self.unpackStrategy, log: log)\n let service = try ImagesService(contentStore: contentStore, imageStore: imageStore, snapshotStore: snapshotStore, log: log)\n let harness = ImagesServiceHarness(service: service, log: log)\n\n routes[ImagesServiceXPCRoute.imagePull.rawValue] = harness.pull\n routes[ImagesServiceXPCRoute.imageList.rawValue] = harness.list\n routes[ImagesServiceXPCRoute.imageDelete.rawValue] = harness.delete\n routes[ImagesServiceXPCRoute.imageTag.rawValue] = harness.tag\n routes[ImagesServiceXPCRoute.imagePush.rawValue] = harness.push\n routes[ImagesServiceXPCRoute.imageSave.rawValue] = harness.save\n routes[ImagesServiceXPCRoute.imageLoad.rawValue] = harness.load\n routes[ImagesServiceXPCRoute.imageUnpack.rawValue] = harness.unpack\n routes[ImagesServiceXPCRoute.imagePrune.rawValue] = harness.prune\n routes[ImagesServiceXPCRoute.snapshotDelete.rawValue] = harness.deleteSnapshot\n routes[ImagesServiceXPCRoute.snapshotGet.rawValue] = harness.getSnapshot\n }\n\n private func initializeContentService(root: URL, log: Logger, routes: inout [String: XPCServer.RouteHandler]) throws {\n let service = try ContentStoreService(root: root, log: log)\n let harness = ContentServiceHarness(service: service, log: log)\n\n routes[ImagesServiceXPCRoute.contentClean.rawValue] = harness.clean\n routes[ImagesServiceXPCRoute.contentGet.rawValue] = harness.get\n routes[ImagesServiceXPCRoute.contentDelete.rawValue] = harness.delete\n routes[ImagesServiceXPCRoute.contentIngestStart.rawValue] = harness.newIngestSession\n routes[ImagesServiceXPCRoute.contentIngestCancel.rawValue] = harness.cancelIngestSession\n routes[ImagesServiceXPCRoute.contentIngestComplete.rawValue] = harness.completeIngestSession\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"ImagesHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n return log\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/CLI/Registry/Login.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Login: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: \"Login to a registry\"\n )\n\n @Option(name: .shortAndLong, help: \"Username\")\n var username: String = \"\"\n\n @Flag(help: \"Take the password from stdin\")\n var passwordStdin: Bool = false\n\n @Argument(help: \"Registry server name\")\n var server: String\n\n @OptionGroup\n var registry: Flags.Registry\n\n func run() async throws {\n var username = self.username\n var password = \"\"\n if passwordStdin {\n if username == \"\" {\n throw ContainerizationError(\n .invalidArgument, message: \"must provide --username with --password-stdin\")\n }\n guard let passwordData = try FileHandle.standardInput.readToEnd() else {\n throw ContainerizationError(.invalidArgument, message: \"failed to read password from stdin\")\n }\n password = String(decoding: passwordData, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)\n }\n let keychain = KeychainHelper(id: Constants.keychainID)\n if username == \"\" {\n username = try keychain.userPrompt(domain: server)\n }\n if password == \"\" {\n password = try keychain.passwordPrompt()\n print()\n }\n\n let server = Reference.resolveDomain(domain: server)\n let scheme = try RequestScheme(registry.scheme).schemeFor(host: server)\n let _url = \"\\(scheme)://\\(server)\"\n guard let url = URL(string: _url) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n guard let host = url.host else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid host \\(server)\")\n }\n\n let client = RegistryClient(\n host: host,\n scheme: scheme.rawValue,\n port: url.port,\n authentication: BasicAuthentication(username: username, password: password),\n retryOptions: .init(\n maxRetries: 10,\n retryInterval: 300_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n )\n try await client.ping()\n try keychain.save(domain: server, username: username, password: password)\n print(\"Login succeeded\")\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nextension Application {\n struct SystemStatus: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"status\",\n abstract: \"Show the status of `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Launchd prefix for `container` services\")\n var prefix: String = \"com.apple.container.\"\n\n func run() async throws {\n let isRegistered = try ServiceManager.isRegistered(fullServiceLabel: \"\\(prefix)apiserver\")\n if !isRegistered {\n print(\"apiserver is not running and not registered with launchd\")\n Application.exit(withError: ExitCode(1))\n }\n\n // Now ping our friendly daemon. Fail after 10 seconds with no response.\n do {\n print(\"Verifying apiserver is running...\")\n try await ClientHealthCheck.ping(timeout: .seconds(10))\n print(\"apiserver is running\")\n } catch {\n print(\"apiserver is not running\")\n Application.exit(withError: ExitCode(1))\n }\n }\n }\n}\n"], ["/container/Sources/APIServer/Networks/NetworksService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerPersistence\nimport ContainerPlugin\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor NetworksService {\n private let resourceRoot: URL\n // FIXME: remove qualifier once we can update Containerization dependency.\n private let store: ContainerPersistence.FilesystemEntityStore\n private let pluginLoader: PluginLoader\n private let log: Logger\n private let networkPlugin: Plugin\n\n private var networkStates = [String: NetworkState]()\n private var busyNetworks = Set()\n\n public init(pluginLoader: PluginLoader, resourceRoot: URL, log: Logger) async throws {\n try FileManager.default.createDirectory(at: resourceRoot, withIntermediateDirectories: true)\n self.resourceRoot = resourceRoot\n self.store = try FilesystemEntityStore(path: resourceRoot, type: \"network\", log: log)\n self.pluginLoader = pluginLoader\n self.log = log\n\n let networkPlugin =\n pluginLoader\n .findPlugins()\n .filter { $0.hasType(.network) }\n .first\n guard let networkPlugin else {\n throw ContainerizationError(.internalError, message: \"cannot find network plugin\")\n }\n self.networkPlugin = networkPlugin\n\n let configurations = try await store.list()\n for configuration in configurations {\n do {\n try await registerService(configuration: configuration)\n } catch {\n log.error(\n \"failed to start network\",\n metadata: [\n \"id\": \"\\(configuration.id)\"\n ])\n }\n\n let client = NetworkClient(id: configuration.id)\n let networkState = try await client.state()\n networkStates[configuration.id] = networkState\n guard case .running = networkState else {\n log.error(\n \"network failed to start\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"state\": \"\\(networkState.state)\",\n ])\n return\n }\n }\n }\n\n /// List all networks registered with the service.\n public func list() async throws -> [NetworkState] {\n log.info(\"network service: list\")\n return networkStates.reduce(into: [NetworkState]()) {\n $0.append($1.value)\n }\n }\n\n /// Create a new network from the provided configuration.\n public func create(configuration: NetworkConfiguration) async throws -> NetworkState {\n guard !busyNetworks.contains(configuration.id) else {\n throw ContainerizationError(.exists, message: \"network \\(configuration.id) has a pending operation\")\n }\n\n busyNetworks.insert(configuration.id)\n defer { busyNetworks.remove(configuration.id) }\n\n log.info(\n \"network service: create\",\n metadata: [\n \"id\": \"\\(configuration.id)\"\n ])\n\n // Ensure the network doesn't already exist.\n guard networkStates[configuration.id] == nil else {\n throw ContainerizationError(.exists, message: \"network \\(configuration.id) already exists\")\n }\n\n // Create and start the network.\n try await registerService(configuration: configuration)\n let client = NetworkClient(id: configuration.id)\n let networkState = try await client.state()\n networkStates[configuration.id] = networkState\n\n // Persist the configuration data.\n do {\n try await store.create(configuration)\n return networkState\n } catch {\n networkStates.removeValue(forKey: configuration.id)\n do {\n try pluginLoader.deregisterWithLaunchd(plugin: networkPlugin, instanceId: configuration.id)\n } catch {\n log.error(\n \"failed to deregister network service after failed creation\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"error\": \"\\(error.localizedDescription)\",\n ])\n }\n\n throw error\n }\n }\n\n /// Delete a network.\n public func delete(id: String) async throws {\n guard !busyNetworks.contains(id) else {\n throw ContainerizationError(.exists, message: \"network \\(id) has a pending operation\")\n }\n\n busyNetworks.insert(id)\n defer { busyNetworks.remove(id) }\n\n log.info(\n \"network service: delete\",\n metadata: [\n \"id\": \"\\(id)\"\n ])\n if id == ClientNetwork.defaultNetworkName {\n throw ContainerizationError(.invalidArgument, message: \"cannot delete system subnet \\(ClientNetwork.defaultNetworkName)\")\n }\n\n guard let networkState = networkStates[id] else {\n throw ContainerizationError(.notFound, message: \"no network for id \\(id)\")\n }\n\n guard case .running = networkState else {\n throw ContainerizationError(.invalidState, message: \"cannot delete subnet \\(id) in state \\(networkState.state)\")\n }\n\n let client = NetworkClient(id: id)\n guard try await client.disableAllocator() else {\n throw ContainerizationError(.invalidState, message: \"cannot delete subnet \\(id) with containers attached\")\n }\n\n defer { networkStates.removeValue(forKey: id) }\n do {\n try pluginLoader.deregisterWithLaunchd(plugin: networkPlugin, instanceId: id)\n } catch {\n log.error(\n \"failed to deregister network service after failed creation\",\n metadata: [\n \"id\": \"\\(id)\",\n \"error\": \"\\(error.localizedDescription)\",\n ])\n }\n\n do {\n try await store.delete(id)\n } catch {\n throw ContainerizationError(.notFound, message: error.localizedDescription)\n }\n }\n\n /// Perform a hostname lookup on all networks.\n public func lookup(hostname: String) async throws -> Attachment? {\n for id in networkStates.keys {\n let client = NetworkClient(id: id)\n guard let allocation = try await client.lookup(hostname: hostname) else {\n continue\n }\n return allocation\n }\n return nil\n }\n\n private func registerService(configuration: NetworkConfiguration) async throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported network mode \\(configuration.mode.rawValue)\")\n }\n\n guard let serviceIdentifier = networkPlugin.getMachService(instanceId: configuration.id, type: .network) else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported network mode \\(configuration.mode.rawValue)\")\n }\n var args = [\n \"start\",\n \"--id\",\n configuration.id,\n \"--service-identifier\",\n serviceIdentifier,\n ]\n\n if let subnet = (try configuration.subnet.map { try CIDRAddress($0) }) {\n var existingCidrs: [CIDRAddress] = []\n for networkState in networkStates.values {\n if case .running(_, let status) = networkState {\n existingCidrs.append(try CIDRAddress(status.address))\n }\n }\n let overlap = existingCidrs.first { $0.overlaps(cidr: subnet) }\n if let overlap {\n throw ContainerizationError(.exists, message: \"subnet \\(subnet) overlaps an existing network with subnet \\(overlap)\")\n }\n\n args += [\"--subnet\", subnet.description]\n }\n\n try await pluginLoader.registerWithLaunchd(\n plugin: networkPlugin,\n rootURL: store.entityUrl(configuration.id),\n args: args,\n instanceId: configuration.id\n )\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientImage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\n// MARK: ClientImage structure\n\npublic struct ClientImage: Sendable {\n private let contentStore: ContentStore = RemoteContentStoreClient()\n public let description: ImageDescription\n\n public var digest: String { description.digest }\n public var descriptor: Descriptor { description.descriptor }\n public var reference: String { description.reference }\n\n public init(description: ImageDescription) {\n self.description = description\n }\n\n /// Returns the underlying OCI index for the image.\n public func index() async throws -> Index {\n guard let content: Content = try await contentStore.get(digest: description.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(description.digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the manifest for the specified platform.\n public func manifest(for platform: Platform) async throws -> Manifest {\n let index = try await self.index()\n let desc = index.manifests.first { desc in\n desc.platform == platform\n }\n guard let desc else {\n throw ContainerizationError(.unsupported, message: \"Platform \\(platform.description)\")\n }\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the OCI config for the specified platform.\n public func config(for platform: Platform) async throws -> ContainerizationOCI.Image {\n let manifest = try await self.manifest(for: platform)\n let desc = manifest.config\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n return try content.decode()\n }\n}\n\n// MARK: ClientImage constants\n\nextension ClientImage {\n private static let serviceIdentifier = \"com.apple.container.core.container-core-images\"\n public static let initImageRef = ClientDefaults.get(key: .defaultInitImage)\n\n private static func newXPCClient() -> XPCClient {\n XPCClient(service: Self.serviceIdentifier)\n }\n\n private static func newRequest(_ route: ImagesServiceXPCRoute) -> XPCMessage {\n XPCMessage(route: route)\n }\n\n private static var defaultRegistryDomain: String {\n ClientDefaults.get(key: .defaultRegistryDomain)\n }\n}\n\n// MARK: Static methods\n\nextension ClientImage {\n private static let legacyDockerRegistryHost = \"docker.io\"\n private static let dockerRegistryHost = \"registry-1.docker.io\"\n private static let defaultDockerRegistryRepo = \"library\"\n\n public static func normalizeReference(_ ref: String) throws -> String {\n guard ref != Self.initImageRef else {\n // Don't modify the default init image reference.\n // This is to allow for easier local development against\n // an updated containerization.\n return ref\n }\n // Check if the input reference has a domain specified\n var updatedRawReference: String = ref\n let r = try Reference.parse(ref)\n if r.domain == nil {\n updatedRawReference = \"\\(Self.defaultRegistryDomain)/\\(ref)\"\n }\n\n let updatedReference = try Reference.parse(updatedRawReference)\n\n // Handle adding the :latest tag if it isn't specified,\n // as well as adding the \"library/\" repository if it isn't set only if the host is docker.io\n updatedReference.normalize()\n return updatedReference.description\n }\n\n public static func denormalizeReference(_ ref: String) throws -> String {\n var updatedRawReference: String = ref\n let r = try Reference.parse(ref)\n let defaultRegistry = Self.defaultRegistryDomain\n if r.domain == defaultRegistry {\n updatedRawReference = \"\\(r.path)\"\n if let tag = r.tag {\n updatedRawReference += \":\\(tag)\"\n } else if let digest = r.digest {\n updatedRawReference += \"@\\(digest)\"\n }\n if defaultRegistry == dockerRegistryHost || defaultRegistry == legacyDockerRegistryHost {\n updatedRawReference.trimPrefix(\"\\(defaultDockerRegistryRepo)/\")\n }\n }\n return updatedRawReference\n }\n\n public static func list() async throws -> [ClientImage] {\n let client = newXPCClient()\n let request = newRequest(.imageList)\n let response = try await client.send(request)\n\n let imageDescriptions = try response.imageDescriptions()\n return imageDescriptions.map { desc in\n ClientImage(description: desc)\n }\n }\n\n public static func get(names: [String]) async throws -> (images: [ClientImage], error: [String]) {\n let all = try await self.list()\n var errors: [String] = []\n var found: [ClientImage] = []\n for name in names {\n do {\n guard let img = try Self._search(reference: name, in: all) else {\n errors.append(name)\n continue\n }\n found.append(img)\n } catch {\n errors.append(name)\n }\n }\n return (found, errors)\n }\n\n public static func get(reference: String) async throws -> ClientImage {\n let all = try await self.list()\n guard let found = try self._search(reference: reference, in: all) else {\n throw ContainerizationError(.notFound, message: \"Image with reference \\(reference)\")\n }\n return found\n }\n\n private static func _search(reference: String, in all: [ClientImage]) throws -> ClientImage? {\n let locallyBuiltImage = try {\n // Check if we have an image whose index descriptor contains the image name\n // as an annotation. Prefer this in all cases, since these are locally built images.\n let r = try Reference.parse(reference)\n r.normalize()\n let withDefaultTag = r.description\n\n let localImageMatches = all.filter { $0.description.nameFromAnnotation() == withDefaultTag }\n guard localImageMatches.count > 1 else {\n return localImageMatches.first\n }\n // More than one image matched. Check against the tagged reference\n return localImageMatches.first { $0.reference == withDefaultTag }\n }()\n if let locallyBuiltImage {\n return locallyBuiltImage\n }\n // If we don't find a match, try matching `ImageDescription.name` against the given\n // input string, while also checking against its normalized form.\n // Return the first match.\n let normalizedReference = try Self.normalizeReference(reference)\n return all.first(where: { image in\n image.reference == reference || image.reference == normalizedReference\n })\n }\n\n public static func pull(reference: String, platform: Platform? = nil, scheme: RequestScheme = .auto, progressUpdate: ProgressUpdateHandler? = nil) async throws -> ClientImage {\n let client = newXPCClient()\n let request = newRequest(.imagePull)\n\n let reference = try self.normalizeReference(reference)\n guard let host = try Reference.parse(reference).domain else {\n throw ContainerizationError(.invalidArgument, message: \"Could not extract host from reference \\(reference)\")\n }\n\n request.set(key: .imageReference, value: reference)\n try request.set(platform: platform)\n\n let insecure = try scheme.schemeFor(host: host) == .http\n request.set(key: .insecureFlag, value: insecure)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n\n let response = try await client.send(request)\n let description = try response.imageDescription()\n let image = ClientImage(description: description)\n\n await progressUpdateClient?.finish()\n return image\n }\n\n public static func delete(reference: String, garbageCollect: Bool = false) async throws {\n let client = newXPCClient()\n let request = newRequest(.imageDelete)\n request.set(key: .imageReference, value: reference)\n request.set(key: .garbageCollect, value: garbageCollect)\n let _ = try await client.send(request)\n }\n\n public static func load(from tarFile: String) async throws -> [ClientImage] {\n let client = newXPCClient()\n let request = newRequest(.imageLoad)\n request.set(key: .filePath, value: tarFile)\n let reply = try await client.send(request)\n\n let loaded = try reply.imageDescriptions()\n return loaded.map { desc in\n ClientImage(description: desc)\n }\n }\n\n public static func pruneImages() async throws -> ([String], UInt64) {\n let client = newXPCClient()\n let request = newRequest(.imagePrune)\n let response = try await client.send(request)\n let digests = try response.digests()\n let size = response.uint64(key: .size)\n return (digests, size)\n }\n\n public static func fetch(reference: String, platform: Platform? = nil, scheme: RequestScheme = .auto, progressUpdate: ProgressUpdateHandler? = nil) async throws -> ClientImage\n {\n do {\n let match = try await self.get(reference: reference)\n if let platform {\n // The image exists, but we dont know if we have the right platform pulled\n // Check if we do, if not pull the requested platform\n _ = try await match.config(for: platform)\n }\n return match\n } catch let err as ContainerizationError {\n guard err.isCode(.notFound) else {\n throw err\n }\n return try await Self.pull(reference: reference, platform: platform, scheme: scheme, progressUpdate: progressUpdate)\n }\n }\n}\n\n// MARK: Instance methods\n\nextension ClientImage {\n public func push(platform: Platform? = nil, scheme: RequestScheme, progressUpdate: ProgressUpdateHandler?) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imagePush)\n\n guard let host = try Reference.parse(reference).domain else {\n throw ContainerizationError(.invalidArgument, message: \"Could not extract host from reference \\(reference)\")\n }\n request.set(key: .imageReference, value: reference)\n\n let insecure = try scheme.schemeFor(host: host) == .http\n request.set(key: .insecureFlag, value: insecure)\n\n try request.set(platform: platform)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n _ = try await client.send(request)\n await progressUpdateClient?.finish()\n }\n\n @discardableResult\n public func tag(new: String) async throws -> ClientImage {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageTag)\n request.set(key: .imageReference, value: self.description.reference)\n request.set(key: .imageNewReference, value: new)\n let reply = try await client.send(request)\n let description = try reply.imageDescription()\n return ClientImage(description: description)\n }\n\n // MARK: Snapshot Methods\n\n public func save(out: String, platform: Platform? = nil) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageSave)\n try request.set(description: self.description)\n request.set(key: .filePath, value: out)\n try request.set(platform: platform)\n let _ = try await client.send(request)\n }\n\n public func unpack(platform: Platform?, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageUnpack)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n\n try await client.send(request)\n\n await progressUpdateClient?.finish()\n }\n\n public func deleteSnapshot(platform: Platform?) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.snapshotDelete)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n try await client.send(request)\n }\n\n public func getSnapshot(platform: Platform) async throws -> Filesystem {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.snapshotGet)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n let response = try await client.send(request)\n let fs = try response.filesystem()\n return fs\n }\n\n @discardableResult\n public func getCreateSnapshot(platform: Platform, progressUpdate: ProgressUpdateHandler? = nil) async throws -> Filesystem {\n do {\n return try await self.getSnapshot(platform: platform)\n } catch let err as ContainerizationError {\n guard err.code == .notFound else {\n throw err\n }\n try await self.unpack(platform: platform, progressUpdate: progressUpdate)\n return try await self.getSnapshot(platform: platform)\n }\n }\n}\n\nextension XPCMessage {\n fileprivate func set(description: ImageDescription) throws {\n let descData = try JSONEncoder().encode(description)\n self.set(key: .imageDescription, value: descData)\n }\n\n fileprivate func set(descriptions: [ImageDescription]) throws {\n let descData = try JSONEncoder().encode(descriptions)\n self.set(key: .imageDescriptions, value: descData)\n }\n\n fileprivate func set(platform: Platform?) throws {\n guard let platform else {\n return\n }\n let platformData = try JSONEncoder().encode(platform)\n self.set(key: .ociPlatform, value: platformData)\n }\n\n fileprivate func imageDescription() throws -> ImageDescription {\n let responseData = self.dataNoCopy(key: .imageDescription)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"imageDescription not received\")\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: responseData)\n return description\n }\n\n fileprivate func imageDescriptions() throws -> [ImageDescription] {\n let responseData = self.dataNoCopy(key: .imageDescriptions)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"imageDescriptions not received\")\n }\n let descriptions = try JSONDecoder().decode([ImageDescription].self, from: responseData)\n return descriptions\n }\n\n fileprivate func filesystem() throws -> Filesystem {\n let responseData = self.dataNoCopy(key: .filesystem)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"filesystem not received\")\n }\n let fs = try JSONDecoder().decode(Filesystem.self, from: responseData)\n return fs\n }\n\n fileprivate func digests() throws -> [String] {\n let responseData = self.dataNoCopy(key: .digests)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"digests not received\")\n }\n let digests = try JSONDecoder().decode([String].self, from: responseData)\n return digests\n }\n}\n\nextension ImageDescription {\n fileprivate func nameFromAnnotation() -> String? {\n guard let annotations = self.descriptor.annotations else {\n return nil\n }\n guard let name = annotations[AnnotationKeys.containerizationImageName] else {\n return nil\n }\n return name\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SendableProperty\nimport Synchronization\n\n/// A progress bar that updates itself as tasks are completed.\npublic final class ProgressBar: Sendable {\n let config: ProgressConfig\n let state: Mutex\n @SendableProperty\n var printedWidth = 0\n let term: FileHandle?\n let termQueue = DispatchQueue(label: \"com.apple.container.ProgressBar\")\n private let standardError = StandardError()\n\n /// Returns `true` if the progress bar has finished.\n public var isFinished: Bool {\n state.withLock { $0.finished }\n }\n\n /// Creates a new progress bar.\n /// - Parameter config: The configuration for the progress bar.\n public init(config: ProgressConfig) {\n self.config = config\n term = isatty(config.terminal.fileDescriptor) == 1 ? config.terminal : nil\n let state = State(\n description: config.initialDescription, itemsName: config.initialItemsName, totalTasks: config.initialTotalTasks,\n totalItems: config.initialTotalItems,\n totalSize: config.initialTotalSize)\n self.state = Mutex(state)\n display(EscapeSequence.hideCursor)\n }\n\n deinit {\n clear()\n }\n\n /// Allows resetting the progress state.\n public func reset() {\n state.withLock {\n $0 = State(description: config.initialDescription)\n }\n }\n\n /// Allows resetting the progress state of the current task.\n public func resetCurrentTask() {\n state.withLock {\n $0 = State(description: $0.description, itemsName: $0.itemsName, tasks: $0.tasks, totalTasks: $0.totalTasks, startTime: $0.startTime)\n }\n }\n\n private func printFullDescription() {\n let (description, subDescription) = state.withLock { ($0.description, $0.subDescription) }\n\n if subDescription != \"\" {\n standardError.write(\"\\(description) \\(subDescription)\")\n } else {\n standardError.write(description)\n }\n }\n\n /// Updates the description of the progress bar and increments the tasks by one.\n /// - Parameter description: The description of the action being performed.\n public func set(description: String) {\n resetCurrentTask()\n\n state.withLock {\n $0.description = description\n $0.subDescription = \"\"\n $0.tasks += 1\n }\n if config.disableProgressUpdates {\n printFullDescription()\n }\n }\n\n /// Updates the additional description of the progress bar.\n /// - Parameter subDescription: The additional description of the action being performed.\n public func set(subDescription: String) {\n resetCurrentTask()\n\n state.withLock { $0.subDescription = subDescription }\n if config.disableProgressUpdates {\n printFullDescription()\n }\n }\n\n private func start(intervalSeconds: TimeInterval) async {\n if config.disableProgressUpdates && !state.withLock({ $0.description.isEmpty }) {\n printFullDescription()\n }\n\n while !state.withLock({ $0.finished }) {\n let intervalNanoseconds = UInt64(intervalSeconds * 1_000_000_000)\n render()\n state.withLock { $0.iteration += 1 }\n if (try? await Task.sleep(nanoseconds: intervalNanoseconds)) == nil {\n return\n }\n }\n }\n\n /// Starts an animation of the progress bar.\n /// - Parameter intervalSeconds: The time interval between updates in seconds.\n public func start(intervalSeconds: TimeInterval = 0.04) {\n Task(priority: .utility) {\n await start(intervalSeconds: intervalSeconds)\n }\n }\n\n /// Finishes the progress bar.\n public func finish() {\n guard !state.withLock({ $0.finished }) else {\n return\n }\n\n state.withLock { $0.finished = true }\n\n // The last render.\n render(force: true)\n\n if !config.disableProgressUpdates && !config.clearOnFinish {\n displayText(state.withLock { $0.output }, terminating: \"\\n\")\n }\n\n if config.clearOnFinish {\n clearAndResetCursor()\n } else {\n resetCursor()\n }\n // Allow printed output to flush.\n usleep(100_000)\n }\n}\n\nextension ProgressBar {\n private func secondsSinceStart() -> Int {\n let timeDifferenceNanoseconds = DispatchTime.now().uptimeNanoseconds - state.withLock { $0.startTime.uptimeNanoseconds }\n let timeDifferenceSeconds = Int(floor(Double(timeDifferenceNanoseconds) / 1_000_000_000))\n return timeDifferenceSeconds\n }\n\n func render(force: Bool = false) {\n guard term != nil && !config.disableProgressUpdates && (force || !state.withLock { $0.finished }) else {\n return\n }\n let output = draw()\n displayText(output)\n }\n\n func draw() -> String {\n let state = self.state.withLock { $0 }\n\n var components = [String]()\n if config.showSpinner && !config.showProgressBar {\n if !state.finished {\n let spinnerIcon = config.theme.getSpinnerIcon(state.iteration)\n components.append(\"\\(spinnerIcon)\")\n } else {\n components.append(\"\\(config.theme.done)\")\n }\n }\n\n if config.showTasks, let totalTasks = state.totalTasks {\n let tasks = min(state.tasks, totalTasks)\n components.append(\"[\\(tasks)/\\(totalTasks)]\")\n }\n\n if config.showDescription && !state.description.isEmpty {\n components.append(\"\\(state.description)\")\n if !state.subDescription.isEmpty {\n components.append(\"\\(state.subDescription)\")\n }\n }\n\n let allowProgress = !config.ignoreSmallSize || state.totalSize == nil || state.totalSize! > Int64(1024 * 1024)\n\n let value = state.totalSize != nil ? state.size : Int64(state.items)\n let total = state.totalSize ?? Int64(state.totalItems ?? 0)\n\n if config.showPercent && total > 0 && allowProgress {\n components.append(\"\\(state.finished ? \"100%\" : state.percent)\")\n }\n\n if config.showProgressBar, total > 0, allowProgress {\n let usedWidth = components.joined(separator: \" \").count + 45 /* the maximum number of characters we may need */\n let remainingWidth = max(config.width - usedWidth, 1 /* the minimum width of a progress bar */)\n let barLength = state.finished ? remainingWidth : Int(Int64(remainingWidth) * value / total)\n let barPaddingLength = remainingWidth - barLength\n let bar = \"\\(String(repeating: config.theme.bar, count: barLength))\\(String(repeating: \" \", count: barPaddingLength))\"\n components.append(\"|\\(bar)|\")\n }\n\n var additionalComponents = [String]()\n\n if config.showItems, state.items > 0 {\n var itemsName = \"\"\n if !state.itemsName.isEmpty {\n itemsName = \" \\(state.itemsName)\"\n }\n if state.finished {\n if let totalItems = state.totalItems {\n additionalComponents.append(\"\\(totalItems.formattedNumber())\\(itemsName)\")\n }\n } else {\n if let totalItems = state.totalItems {\n additionalComponents.append(\"\\(state.items.formattedNumber()) of \\(totalItems.formattedNumber())\\(itemsName)\")\n } else {\n additionalComponents.append(\"\\(state.items.formattedNumber())\\(itemsName)\")\n }\n }\n }\n\n if state.size > 0 && allowProgress {\n if state.finished {\n if config.showSize {\n if let totalSize = state.totalSize {\n var formattedTotalSize = totalSize.formattedSize()\n formattedTotalSize = adjustFormattedSize(formattedTotalSize)\n additionalComponents.append(formattedTotalSize)\n }\n }\n } else {\n var formattedCombinedSize = \"\"\n if config.showSize {\n var formattedSize = state.size.formattedSize()\n formattedSize = adjustFormattedSize(formattedSize)\n if let totalSize = state.totalSize {\n var formattedTotalSize = totalSize.formattedSize()\n formattedTotalSize = adjustFormattedSize(formattedTotalSize)\n formattedCombinedSize = combineSize(size: formattedSize, totalSize: formattedTotalSize)\n } else {\n formattedCombinedSize = formattedSize\n }\n }\n\n var formattedSpeed = \"\"\n if config.showSpeed {\n formattedSpeed = \"\\(state.sizeSpeed ?? state.averageSizeSpeed)\"\n formattedSpeed = adjustFormattedSize(formattedSpeed)\n }\n\n if config.showSize && config.showSpeed {\n additionalComponents.append(formattedCombinedSize)\n additionalComponents.append(formattedSpeed)\n } else if config.showSize {\n additionalComponents.append(formattedCombinedSize)\n } else if config.showSpeed {\n additionalComponents.append(formattedSpeed)\n }\n }\n }\n\n if additionalComponents.count > 0 {\n let joinedAdditionalComponents = additionalComponents.joined(separator: \", \")\n components.append(\"(\\(joinedAdditionalComponents))\")\n }\n\n if config.showTime {\n let timeDifferenceSeconds = secondsSinceStart()\n let formattedTime = timeDifferenceSeconds.formattedTime()\n components.append(\"[\\(formattedTime)]\")\n }\n\n return components.joined(separator: \" \")\n }\n\n private func adjustFormattedSize(_ size: String) -> String {\n // Ensure we always have one digit after the decimal point to prevent flickering.\n let zero = Int64(0).formattedSize()\n guard !size.contains(\".\"), let first = size.first, first.isNumber || !size.contains(zero) else {\n return size\n }\n var size = size\n for unit in [\"MB\", \"GB\", \"TB\"] {\n size = size.replacingOccurrences(of: \" \\(unit)\", with: \".0 \\(unit)\")\n }\n return size\n }\n\n private func combineSize(size: String, totalSize: String) -> String {\n let sizeComponents = size.split(separator: \" \", maxSplits: 1)\n let totalSizeComponents = totalSize.split(separator: \" \", maxSplits: 1)\n guard sizeComponents.count == 2, totalSizeComponents.count == 2 else {\n return \"\\(size)/\\(totalSize)\"\n }\n let sizeNumber = sizeComponents[0]\n let sizeUnit = sizeComponents[1]\n let totalSizeNumber = totalSizeComponents[0]\n let totalSizeUnit = totalSizeComponents[1]\n guard sizeUnit == totalSizeUnit else {\n return \"\\(size)/\\(totalSize)\"\n }\n return \"\\(sizeNumber)/\\(totalSizeNumber) \\(totalSizeUnit)\"\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct NetworkCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a new network\")\n\n @Argument(help: \"Network name\")\n var name: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let config = NetworkConfiguration(id: self.name, mode: .nat)\n let state = try await ClientNetwork.create(configuration: config)\n print(state.id)\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImageInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ImageInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more images\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Images to inspect\")\n var images: [String]\n\n func run() async throws {\n var printable = [any Codable]()\n let result = try await ClientImage.get(names: images)\n let notFound = result.error\n for image in result.images {\n guard !Utility.isInfraImage(name: image.reference) else {\n continue\n }\n printable.append(try await image.details())\n }\n if printable.count > 0 {\n print(try printable.jsonArray())\n }\n if notFound.count > 0 {\n throw ContainerizationError(.notFound, message: \"Images: \\(notFound.joined(separator: \"\\n\"))\")\n }\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemLogs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport OSLog\n\nextension Application {\n struct SystemLogs: AsyncParsableCommand {\n static let subsystem = \"com.apple.container\"\n\n static let configuration = CommandConfiguration(\n commandName: \"logs\",\n abstract: \"Fetch system logs for `container` services\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(\n name: .long,\n help: \"Fetch logs starting from the specified time period (minus the current time); supported formats: m, h, d\"\n )\n var last: String = \"5m\"\n\n @Flag(name: .shortAndLong, help: \"Follow log output\")\n var follow: Bool = false\n\n func run() async throws {\n let process = Process()\n let sigHandler = AsyncSignalHandler.create(notify: [SIGINT, SIGTERM])\n\n Task {\n for await _ in sigHandler.signals {\n process.terminate()\n Darwin.exit(0)\n }\n }\n\n do {\n var args = [\"log\"]\n args.append(self.follow ? \"stream\" : \"show\")\n args.append(contentsOf: [\"--info\", \"--debug\"])\n if !self.follow {\n args.append(contentsOf: [\"--last\", last])\n }\n args.append(contentsOf: [\"--predicate\", \"subsystem = 'com.apple.container'\"])\n\n process.launchPath = \"/usr/bin/env\"\n process.arguments = args\n\n process.standardOutput = FileHandle.standardOutput\n process.standardError = FileHandle.standardError\n\n try process.run()\n process.waitUntilExit()\n } catch {\n throw ContainerizationError(\n .invalidArgument,\n message: \"failed to system logs: \\(error)\"\n )\n }\n throw ArgumentParser.ExitCode(process.terminationStatus)\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationExtras\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ContainerList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List containers\",\n aliases: [\"ls\"])\n\n @Flag(name: .shortAndLong, help: \"Show stopped containers as well\")\n var all = false\n\n @Flag(name: .shortAndLong, help: \"Only output the container ID\")\n var quiet = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let containers = try await ClientContainer.list()\n try printContainers(containers: containers, format: format)\n }\n\n private func createHeader() -> [[String]] {\n [[\"ID\", \"IMAGE\", \"OS\", \"ARCH\", \"STATE\", \"ADDR\"]]\n }\n\n private func printContainers(containers: [ClientContainer], format: ListFormat) throws {\n if format == .json {\n let printables = containers.map {\n PrintableContainer($0)\n }\n let data = try JSONEncoder().encode(printables)\n print(String(data: data, encoding: .utf8)!)\n\n return\n }\n\n if self.quiet {\n containers.forEach {\n if !self.all && $0.status != .running {\n return\n }\n print($0.id)\n }\n return\n }\n\n var rows = createHeader()\n for container in containers {\n if !self.all && container.status != .running {\n continue\n }\n rows.append(container.asRow)\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n }\n}\n\nextension ClientContainer {\n var asRow: [String] {\n [\n self.id,\n self.configuration.image.reference,\n self.configuration.platform.os,\n self.configuration.platform.architecture,\n self.status.rawValue,\n self.networks.compactMap { try? CIDRAddress($0.address).address.description }.joined(separator: \",\"),\n ]\n }\n}\n\nstruct PrintableContainer: Codable {\n let status: RuntimeStatus\n let configuration: ContainerConfiguration\n let networks: [Attachment]\n\n init(_ container: ClientContainer) {\n self.status = container.status\n self.configuration = container.configuration\n self.networks = container.networks\n }\n}\n"], ["/container/Sources/ContainerClient/Parser.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\npublic struct Parser {\n public static func memoryString(_ memory: String) throws -> Int64 {\n let ram = try Measurement.parse(parsing: memory)\n let mb = ram.converted(to: .mebibytes)\n return Int64(mb.value)\n }\n\n public static func user(\n user: String?, uid: UInt32?, gid: UInt32?,\n defaultUser: ProcessConfiguration.User = .id(uid: 0, gid: 0)\n ) -> (user: ProcessConfiguration.User, groups: [UInt32]) {\n\n var supplementalGroups: [UInt32] = []\n let user: ProcessConfiguration.User = {\n if let user = user, !user.isEmpty {\n return .raw(userString: user)\n }\n if let uid, let gid {\n return .id(uid: uid, gid: gid)\n }\n if uid == nil, gid == nil {\n // Neither uid nor gid is set. return the default user\n return defaultUser\n }\n // One of uid / gid is left unspecified. Set the user accordingly\n if let uid {\n return .raw(userString: \"\\(uid)\")\n }\n if let gid {\n supplementalGroups.append(gid)\n }\n return defaultUser\n }()\n return (user, supplementalGroups)\n }\n\n public static func platform(os: String, arch: String) -> ContainerizationOCI.Platform {\n .init(arch: arch, os: os)\n }\n\n public static func resources(cpus: Int64?, memory: String?) throws -> ContainerConfiguration.Resources {\n var resource = ContainerConfiguration.Resources()\n if let cpus {\n resource.cpus = Int(cpus)\n }\n if let memory {\n resource.memoryInBytes = try Parser.memoryString(memory).mib()\n }\n return resource\n }\n\n public static func allEnv(imageEnvs: [String], envFiles: [String], envs: [String]) throws -> [String] {\n var output: [String] = []\n output.append(contentsOf: Parser.env(envList: imageEnvs))\n for envFile in envFiles {\n let content = try Parser.envFile(path: envFile)\n output.append(contentsOf: content)\n }\n output.append(contentsOf: Parser.env(envList: envs))\n return output\n }\n\n static func envFile(path: String) throws -> [String] {\n guard FileManager.default.fileExists(atPath: path) else {\n throw ContainerizationError(.notFound, message: \"envfile at \\(path) not found\")\n }\n\n let data = try String(contentsOfFile: path, encoding: .utf8)\n let lines = data.components(separatedBy: .newlines)\n var envVars: [String] = []\n for line in lines {\n let line = line.trimmingCharacters(in: .whitespaces)\n if line.isEmpty {\n continue\n }\n if !line.hasPrefix(\"#\") {\n let keyVals = line.split(separator: \"=\")\n if keyVals.count != 2 {\n continue\n }\n let key = keyVals[0].trimmingCharacters(in: .whitespaces)\n let val = keyVals[1].trimmingCharacters(in: .whitespaces)\n if key.isEmpty || val.isEmpty {\n continue\n }\n envVars.append(\"\\(key)=\\(val)\")\n }\n }\n return envVars\n }\n\n static func env(envList: [String]) -> [String] {\n var envVar: [String] = []\n for env in envList {\n var env = env\n let parts = env.split(separator: \"=\", maxSplits: 2)\n if parts.count == 1 {\n guard let val = ProcessInfo.processInfo.environment[env] else {\n continue\n }\n env = \"\\(env)=\\(val)\"\n }\n envVar.append(env)\n }\n return envVar\n }\n\n static func labels(_ rawLabels: [String]) throws -> [String: String] {\n var result: [String: String] = [:]\n for label in rawLabels {\n if label.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"label cannot be an empty string\")\n }\n let parts = label.split(separator: \"=\", maxSplits: 2)\n switch parts.count {\n case 1:\n result[String(parts[0])] = \"\"\n case 2:\n result[String(parts[0])] = String(parts[1])\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid label format \\(label)\")\n }\n }\n return result\n }\n\n static func process(\n arguments: [String],\n processFlags: Flags.Process,\n managementFlags: Flags.Management,\n config: ContainerizationOCI.ImageConfig?\n ) throws -> ProcessConfiguration {\n\n let imageEnvVars = config?.env ?? []\n let envvars = try Parser.allEnv(imageEnvs: imageEnvVars, envFiles: processFlags.envFile, envs: processFlags.env)\n\n let workingDir: String = {\n if let cwd = processFlags.cwd {\n return cwd\n }\n if let cwd = config?.workingDir {\n return cwd\n }\n return \"/\"\n }()\n\n let processArguments: [String]? = {\n var result: [String] = []\n var hasEntrypointOverride: Bool = false\n // ensure the entrypoint is honored if it has been explicitly set by the user\n if let entrypoint = managementFlags.entryPoint, !entrypoint.isEmpty {\n result = [entrypoint]\n hasEntrypointOverride = true\n } else if let entrypoint = config?.entrypoint, !entrypoint.isEmpty {\n result = entrypoint\n }\n if !arguments.isEmpty {\n result.append(contentsOf: arguments)\n } else {\n if let cmd = config?.cmd, !hasEntrypointOverride, !cmd.isEmpty {\n result.append(contentsOf: cmd)\n }\n }\n return result.count > 0 ? result : nil\n }()\n\n guard let commandToRun = processArguments, commandToRun.count > 0 else {\n throw ContainerizationError(.invalidArgument, message: \"Command/Entrypoint not specified for container process\")\n }\n\n let defaultUser: ProcessConfiguration.User = {\n if let u = config?.user {\n return .raw(userString: u)\n }\n return .id(uid: 0, gid: 0)\n }()\n\n let (user, additionalGroups) = Parser.user(\n user: processFlags.user, uid: processFlags.uid,\n gid: processFlags.gid, defaultUser: defaultUser)\n\n return .init(\n executable: commandToRun.first!,\n arguments: [String](commandToRun.dropFirst()),\n environment: envvars,\n workingDirectory: workingDir,\n terminal: processFlags.tty,\n user: user,\n supplementalGroups: additionalGroups\n )\n }\n\n // MARK: Mounts\n\n static let mountTypes = [\n \"virtiofs\",\n \"bind\",\n \"tmpfs\",\n ]\n\n static let defaultDirectives = [\"type\": \"virtiofs\"]\n\n static func tmpfsMounts(_ mounts: [String]) throws -> [Filesystem] {\n var result: [Filesystem] = []\n let mounts = mounts.dedupe()\n for tmpfs in mounts {\n let fs = Filesystem.tmpfs(destination: tmpfs, options: [])\n try validateMount(fs)\n result.append(fs)\n }\n return result\n }\n\n static func mounts(_ rawMounts: [String]) throws -> [Filesystem] {\n var mounts: [Filesystem] = []\n let rawMounts = rawMounts.dedupe()\n for mount in rawMounts {\n let m = try Parser.mount(mount)\n try validateMount(m)\n mounts.append(m)\n }\n return mounts\n }\n\n static func mount(_ mount: String) throws -> Filesystem {\n let parts = mount.split(separator: \",\")\n if parts.count == 0 {\n throw ContainerizationError(.invalidArgument, message: \"invalid mount format: \\(mount)\")\n }\n var directives = defaultDirectives\n for part in parts {\n let keyVal = part.split(separator: \"=\", maxSplits: 2)\n var key = String(keyVal[0])\n var skipValue = false\n switch key {\n case \"type\", \"size\", \"mode\":\n break\n case \"source\", \"src\":\n key = \"source\"\n case \"destination\", \"dst\", \"target\":\n key = \"destination\"\n case \"readonly\", \"ro\":\n key = \"ro\"\n skipValue = true\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown directive \\(key) when parsing mount \\(mount)\")\n }\n var value = \"\"\n if !skipValue {\n if keyVal.count != 2 {\n throw ContainerizationError(.invalidArgument, message: \"invalid directive format missing value \\(part) in \\(mount)\")\n }\n value = String(keyVal[1])\n }\n directives[key] = value\n }\n\n var fs = Filesystem()\n for (key, val) in directives {\n var val = val\n let type = directives[\"type\"] ?? \"\"\n\n switch key {\n case \"type\":\n if val == \"bind\" {\n val = \"virtiofs\"\n }\n switch val {\n case \"virtiofs\":\n fs.type = Filesystem.FSType.virtiofs\n case \"tmpfs\":\n fs.type = Filesystem.FSType.tmpfs\n default:\n throw ContainerizationError(.invalidArgument, message: \"unsupported mount type \\(val)\")\n }\n\n case \"ro\":\n fs.options.append(\"ro\")\n case \"size\":\n if type != \"tmpfs\" {\n throw ContainerizationError(.invalidArgument, message: \"unsupported option size for \\(type) mount\")\n }\n var overflow: Bool\n var memory = try Parser.memoryString(val)\n (memory, overflow) = memory.multipliedReportingOverflow(by: 1024 * 1024)\n if overflow {\n throw ContainerizationError(.invalidArgument, message: \"overflow encountered when parsing memory string: \\(val)\")\n }\n let s = \"size=\\(memory)\"\n fs.options.append(s)\n case \"mode\":\n if type != \"tmpfs\" {\n throw ContainerizationError(.invalidArgument, message: \"unsupported option mode for \\(type) mount\")\n }\n let s = \"mode=\\(val)\"\n fs.options.append(s)\n case \"source\":\n let absPath = URL(filePath: val).absoluteURL.path\n switch type {\n case \"virtiofs\", \"bind\":\n fs.source = absPath\n case \"tmpfs\":\n throw ContainerizationError(.invalidArgument, message: \"cannot specify source for tmpfs mount\")\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown mount type \\(type)\")\n }\n case \"destination\":\n fs.destination = val\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown mount directive \\(key)\")\n }\n }\n return fs\n }\n\n static func volumes(_ rawVolumes: [String]) throws -> [Filesystem] {\n var mounts: [Filesystem] = []\n for volume in rawVolumes {\n let m = try Parser.volume(volume)\n try Parser.validateMount(m)\n mounts.append(m)\n }\n return mounts\n }\n\n private static func volume(_ volume: String) throws -> Filesystem {\n var vol = volume\n vol.trimLeft(char: \":\")\n\n let parts = vol.split(separator: \":\")\n switch parts.count {\n case 1:\n throw ContainerizationError(.invalidArgument, message: \"anonymous volumes are not supported\")\n case 2, 3:\n // Bind / volume mounts.\n let src = String(parts[0])\n let dst = String(parts[1])\n\n let abs = URL(filePath: src).absoluteURL.path\n if !FileManager.default.fileExists(atPath: abs) {\n throw ContainerizationError(.invalidArgument, message: \"named volumes are not supported\")\n }\n\n var fs = Filesystem.virtiofs(\n source: URL(fileURLWithPath: src).absolutePath(),\n destination: dst,\n options: []\n )\n if parts.count == 3 {\n fs.options = parts[2].split(separator: \",\").map { String($0) }\n }\n return fs\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid volume format \\(volume)\")\n }\n }\n\n static func validMountType(_ type: String) -> Bool {\n mountTypes.contains(type)\n }\n\n static func validateMount(_ mount: Filesystem) throws {\n if !mount.isTmpfs {\n if !mount.source.isAbsolutePath() {\n throw ContainerizationError(\n .invalidArgument, message: \"\\(mount.source) is not an absolute path on the host\")\n }\n if !FileManager.default.fileExists(atPath: mount.source) {\n throw ContainerizationError(.invalidArgument, message: \"file path '\\(mount.source)' does not exist\")\n }\n }\n\n if mount.destination.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"mount destination cannot be empty\")\n }\n }\n\n /// Parse --publish-port arguments into PublishPort objects\n /// The format of each argument is `[host-ip:]host-port:container-port[/protocol]`\n /// (e.g., \"127.0.0.1:8080:80/tcp\")\n ///\n /// - Parameter rawPublishPorts: Array of port arguments\n /// - Returns: Array of PublishPort objects\n /// - Throws: ContainerizationError if parsing fails\n static func publishPorts(_ rawPublishPorts: [String]) throws -> [PublishPort] {\n var sockets: [PublishPort] = []\n\n // Process each raw port string\n for socket in rawPublishPorts {\n let parsedSocket = try Parser.publishPort(socket)\n sockets.append(parsedSocket)\n }\n return sockets\n }\n\n // Parse a single `--publish-port` argument into a `PublishPort`.\n private static func publishPort(_ portText: String) throws -> PublishPort {\n let protoSplit = portText.split(separator: \"/\")\n let proto: PublishProtocol\n let addressAndPortText: String\n switch protoSplit.count {\n case 1:\n addressAndPortText = String(protoSplit[0])\n proto = .tcp\n case 2:\n addressAndPortText = String(protoSplit[0])\n let protoText = String(protoSplit[1])\n guard let parsedProto = PublishProtocol(protoText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish protocol: \\(protoText)\")\n }\n proto = parsedProto\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid publish value: \\(portText)\")\n }\n\n let hostAddress: String\n let hostPortText: String\n let containerPortText: String\n let parts = addressAndPortText.split(separator: \":\")\n switch parts.count {\n case 2:\n hostAddress = \"0.0.0.0\"\n hostPortText = String(parts[0])\n containerPortText = String(parts[1])\n case 3:\n hostAddress = String(parts[0])\n hostPortText = String(parts[1])\n containerPortText = String(parts[2])\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid publish address: \\(portText)\")\n }\n\n guard let hostPort = Int(hostPortText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish host port: \\(hostPortText)\")\n }\n\n guard let containerPort = Int(containerPortText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish container port: \\(containerPortText)\")\n }\n\n return PublishPort(\n hostAddress: hostAddress,\n hostPort: hostPort,\n containerPort: containerPort,\n proto: proto\n )\n }\n\n /// Parse --publish-socket arguments into PublishSocket objects\n /// The format of each argument is `host_path:container_path`\n /// (e.g., \"/tmp/docker.sock:/var/run/docker.sock\")\n ///\n /// - Parameter rawPublishSockets: Array of socket arguments\n /// - Returns: Array of PublishSocket objects\n /// - Throws: ContainerizationError if parsing fails or a path is invalid\n static func publishSockets(_ rawPublishSockets: [String]) throws -> [PublishSocket] {\n var sockets: [PublishSocket] = []\n\n // Process each raw socket string\n for socket in rawPublishSockets {\n let parsedSocket = try Parser.publishSocket(socket)\n sockets.append(parsedSocket)\n }\n return sockets\n }\n\n // Parse a single `--publish-socket`` argument into a `PublishSocket`.\n private static func publishSocket(_ socketText: String) throws -> PublishSocket {\n // Split by colon to two parts: [host_path, container_path]\n let parts = socketText.split(separator: \":\")\n\n switch parts.count {\n case 2:\n // Extract host and container paths\n let hostPath = String(parts[0])\n let containerPath = String(parts[1])\n\n // Validate paths are not empty\n if hostPath.isEmpty {\n throw ContainerizationError(\n .invalidArgument, message: \"host socket path cannot be empty\")\n }\n if containerPath.isEmpty {\n throw ContainerizationError(\n .invalidArgument, message: \"container socket path cannot be empty\")\n }\n\n // Ensure container path must start with /\n if !containerPath.hasPrefix(\"/\") {\n throw ContainerizationError(\n .invalidArgument,\n message: \"container socket path must be absolute: \\(containerPath)\")\n }\n\n // Convert host path to absolute path for consistency\n let hostURL = URL(fileURLWithPath: hostPath)\n let absoluteHostPath = hostURL.absoluteURL.path\n\n // Check if host socket already exists and might be in use\n if FileManager.default.fileExists(atPath: absoluteHostPath) {\n do {\n let attrs = try FileManager.default.attributesOfItem(atPath: absoluteHostPath)\n if let fileType = attrs[.type] as? FileAttributeType, fileType == .typeSocket {\n throw ContainerizationError(\n .invalidArgument,\n message: \"host socket \\(absoluteHostPath) already exists and may be in use\")\n }\n // If it exists but is not a socket, we can remove it and create socket\n try FileManager.default.removeItem(atPath: absoluteHostPath)\n } catch let error as ContainerizationError {\n throw error\n } catch {\n // For other file system errors, continue with creation\n }\n }\n\n // Create host directory if it doesn't exist\n let hostDir = hostURL.deletingLastPathComponent()\n if !FileManager.default.fileExists(atPath: hostDir.path) {\n try FileManager.default.createDirectory(\n at: hostDir, withIntermediateDirectories: true)\n }\n\n // Create and return PublishSocket object with validated paths\n return PublishSocket(\n containerPath: URL(fileURLWithPath: containerPath),\n hostPath: URL(fileURLWithPath: absoluteHostPath),\n permissions: nil\n )\n\n default:\n throw ContainerizationError(\n .invalidArgument,\n message:\n \"invalid publish-socket format \\(socketText). Expected: host_path:container_path\")\n }\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\n\nextension Application {\n struct DNSCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a local DNS domain for containers (must run as an administrator)\"\n )\n\n @Argument(help: \"the local domain name\")\n var domainName: String\n\n func run() async throws {\n let resolver: HostDNSResolver = HostDNSResolver()\n do {\n try resolver.createDomain(name: domainName)\n print(domainName)\n } catch let error as ContainerizationError {\n throw error\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot create domain (try sudo?)\")\n }\n\n do {\n try HostDNSResolver.reinitialize()\n } catch {\n throw ContainerizationError(.invalidState, message: \"mDNSResponder restart failed, run `sudo killall -HUP mDNSResponder` to deactivate domain\")\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImageLoad.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ImageLoad: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"load\",\n abstract: \"Load images from an OCI compatible tar archive\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(\n name: .shortAndLong, help: \"Path to the tar archive to load images from\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var input: String\n\n func run() async throws {\n guard FileManager.default.fileExists(atPath: input) else {\n print(\"File does not exist \\(input)\")\n Application.exit(withError: ArgumentParser.ExitCode(1))\n }\n\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n totalTasks: 2\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Loading tar archive\")\n let loaded = try await ClientImage.load(from: input)\n\n let taskManager = ProgressTaskCoordinator()\n let unpackTask = await taskManager.startTask()\n progress.set(description: \"Unpacking image\")\n progress.set(itemsName: \"entries\")\n for image in loaded {\n try await image.unpack(platform: nil, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progress.handler))\n }\n await taskManager.finish()\n progress.finish()\n print(\"Loaded images:\")\n for image in loaded {\n print(image.reference)\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildPipelineHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport GRPC\nimport NIO\n\nprotocol BuildPipelineHandler: Sendable {\n func accept(_ packet: ServerStream) throws -> Bool\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws\n}\n\npublic actor BuildPipeline {\n let handlers: [BuildPipelineHandler]\n public init(_ config: Builder.BuildConfig) async throws {\n self.handlers =\n [\n try BuildFSSync(URL(filePath: config.contextDir)),\n try BuildRemoteContentProxy(config.contentStore),\n try BuildImageResolver(config.contentStore),\n try BuildStdio(quiet: config.quiet, output: config.terminal?.handle ?? FileHandle.standardError),\n ]\n }\n\n public func run(\n sender: AsyncStream.Continuation,\n receiver: GRPCAsyncResponseStream\n ) async throws {\n defer { sender.finish() }\n try await untilFirstError { group in\n for try await packet in receiver {\n try Task.checkCancellation()\n for handler in self.handlers {\n try Task.checkCancellation()\n guard try handler.accept(packet) else {\n continue\n }\n try Task.checkCancellation()\n try await handler.handle(sender, packet)\n break\n }\n }\n }\n }\n\n /// untilFirstError() throws when any one of its submitted tasks fail.\n /// This is useful for asynchronous packet processing scenarios which\n /// have the following 3 requirements:\n /// - the packet should be processed without blocking I/O\n /// - the packet stream is never-ending\n /// - when the first task fails, the error needs to be propagated to the caller\n ///\n /// Usage:\n ///\n /// ```\n /// try await untilFirstError { group in\n /// for try await packet in receiver {\n /// group.addTask {\n /// try await handler.handle(sender, packet)\n /// }\n /// }\n /// }\n /// ```\n ///\n ///\n /// WithThrowingTaskGroup cannot accomplish this because it\n /// doesn't provide a mechanism to exit when one of the tasks fail\n /// before all the tasks have been added. i.e. it is more suitable for\n /// tasks that are limited. Here's a sample code where withThrowingTaskGroup\n /// doesn't solve the problem:\n ///\n /// ```\n /// withThrowingTaskGroup { group in\n /// for try await packet in receiver {\n /// group.addTask {\n /// /* process packet */\n /// }\n /// } /* this loop blocks forever waiting for more packets */\n /// try await group.next() /* this never gets called */\n /// }\n /// ```\n /// The above closure never returns even when a handler encounters an error\n /// because the blocking operation `try await group.next()` cannot be\n /// called while iterating over the receiver stream.\n private func untilFirstError(body: @Sendable @escaping (UntilFirstError) async throws -> Void) async throws {\n let group = try await UntilFirstError()\n var taskContinuation: AsyncStream>.Continuation?\n let tasks = AsyncStream> { continuation in\n taskContinuation = continuation\n }\n guard let taskContinuation else {\n throw NSError(\n domain: \"untilFirstError\",\n code: 1,\n userInfo: [NSLocalizedDescriptionKey: \"Failed to initialize task continuation\"])\n }\n defer { taskContinuation.finish() }\n let stream = AsyncStream { continuation in\n let processTasks = Task {\n let taskStream = await group.tasks()\n defer {\n continuation.finish()\n }\n for await item in taskStream {\n try Task.checkCancellation()\n let addedTask = Task {\n try Task.checkCancellation()\n do {\n try await item()\n } catch {\n continuation.yield(error)\n await group.continuation?.finish()\n throw error\n }\n }\n taskContinuation.yield(addedTask)\n }\n }\n taskContinuation.yield(processTasks)\n\n let mainTask = Task { @Sendable in\n defer {\n continuation.finish()\n processTasks.cancel()\n taskContinuation.finish()\n }\n do {\n try Task.checkCancellation()\n try await body(group)\n } catch {\n continuation.yield(error)\n await group.continuation?.finish()\n throw error\n }\n }\n taskContinuation.yield(mainTask)\n }\n\n // when the first handler fails, cancel all tasks and throw error\n for await item in stream {\n try Task.checkCancellation()\n Task {\n for await task in tasks {\n task.cancel()\n }\n }\n throw item\n }\n // if none of the handlers fail, wait for all subtasks to complete\n for await task in tasks {\n try Task.checkCancellation()\n try await task.value\n }\n }\n\n private actor UntilFirstError {\n var stream: AsyncStream<@Sendable () async throws -> Void>?\n var continuation: AsyncStream<@Sendable () async throws -> Void>.Continuation?\n\n init() async throws {\n self.stream = AsyncStream { cont in\n self.continuation = cont\n }\n guard let _ = continuation else {\n throw NSError()\n }\n }\n\n func addTask(body: @Sendable @escaping () async throws -> Void) {\n if !Task.isCancelled {\n self.continuation?.yield(body)\n }\n }\n\n func tasks() -> AsyncStream<@Sendable () async throws -> Void> {\n self.stream!\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImageSave.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ImageSave: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"save\",\n abstract: \"Save an image as an OCI compatible tar archive\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Option(\n name: .shortAndLong, help: \"Path to save the image tar archive\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var output: String\n\n @Argument var reference: String\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let progressConfig = try ProgressConfig(\n description: \"Saving image\"\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let image = try await ClientImage.get(reference: reference)\n try await image.save(out: output, platform: p)\n\n progress.finish()\n print(\"Image saved\")\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ContainerCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a new container\")\n\n @Argument(help: \"Image name\")\n var image: String\n\n @Argument(help: \"Container init process arguments\")\n var arguments: [String] = []\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var resourceFlags: Flags.Resource\n\n @OptionGroup\n var managementFlags: Flags.Management\n\n @OptionGroup\n var registryFlags: Flags.Registry\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 3\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let id = Utility.createContainerID(name: self.managementFlags.name)\n try Utility.validEntityName(id)\n\n let ck = try await Utility.containerConfigFromFlags(\n id: id,\n image: image,\n arguments: arguments,\n process: processFlags,\n management: managementFlags,\n resource: resourceFlags,\n registry: registryFlags,\n progressUpdate: progress.handler\n )\n\n let options = ContainerCreateOptions(autoRemove: managementFlags.remove)\n let container = try await ClientContainer.create(configuration: ck.0, options: options, kernel: ck.1)\n\n if !self.managementFlags.cidfile.isEmpty {\n let path = self.managementFlags.cidfile\n let data = container.id.data(using: .utf8)\n var attributes = [FileAttributeKey: Any]()\n attributes[.posixPermissions] = 0o644\n let success = FileManager.default.createFile(\n atPath: path,\n contents: data,\n attributes: attributes\n )\n guard success else {\n throw ContainerizationError(\n .internalError, message: \"failed to create cidfile at \\(path): \\(errno)\")\n }\n }\n progress.finish()\n\n print(container.id)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/SandboxClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport TerminalProgress\n\n/// A client for interacting with a single sandbox.\npublic struct SandboxClient: Sendable, Codable {\n static let label = \"com.apple.container.runtime\"\n\n public static func machServiceLabel(runtime: String, id: String) -> String {\n \"\\(Self.label).\\(runtime).\\(id)\"\n }\n\n private var machServiceLabel: String {\n Self.machServiceLabel(runtime: runtime, id: id)\n }\n\n let id: String\n let runtime: String\n\n /// Create a container.\n public init(id: String, runtime: String) {\n self.id = id\n self.runtime = runtime\n }\n}\n\n// Runtime Methods\nextension SandboxClient {\n public func bootstrap() async throws {\n let request = XPCMessage(route: SandboxRoutes.bootstrap.rawValue)\n let client = createClient()\n defer { client.close() }\n\n try await client.send(request)\n }\n\n public func state() async throws -> SandboxSnapshot {\n let request = XPCMessage(route: SandboxRoutes.state.rawValue)\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.sandboxSnapshot()\n }\n\n public func createProcess(_ id: String, config: ProcessConfiguration) async throws {\n let request = XPCMessage(route: SandboxRoutes.createProcess.rawValue)\n request.set(key: .id, value: id)\n let data = try JSONEncoder().encode(config)\n request.set(key: .processConfig, value: data)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func startProcess(_ id: String, stdio: [FileHandle?]) async throws {\n let request = XPCMessage(route: SandboxRoutes.start.rawValue)\n for (i, h) in stdio.enumerated() {\n let key: XPCKeys = {\n switch i {\n case 0: .stdin\n case 1: .stdout\n case 2: .stderr\n default:\n fatalError(\"invalid fd \\(i)\")\n }\n }()\n\n if let h {\n request.set(key: key, value: h)\n }\n }\n request.set(key: .id, value: id)\n\n let client = createClient()\n defer { client.close() }\n\n try await client.send(request)\n }\n\n public func stop(options: ContainerStopOptions) async throws {\n let request = XPCMessage(route: SandboxRoutes.stop.rawValue)\n\n let data = try JSONEncoder().encode(options)\n request.set(key: .stopOptions, value: data)\n\n let client = createClient()\n defer { client.close() }\n let responseTimeout = Duration(.seconds(Int64(options.timeoutInSeconds + 1)))\n try await client.send(request, responseTimeout: responseTimeout)\n }\n\n public func kill(_ id: String, signal: Int64) async throws {\n let request = XPCMessage(route: SandboxRoutes.kill.rawValue)\n request.set(key: .id, value: id)\n request.set(key: .signal, value: signal)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func resize(_ id: String, size: Terminal.Size) async throws {\n let request = XPCMessage(route: SandboxRoutes.resize.rawValue)\n request.set(key: .id, value: id)\n request.set(key: .width, value: UInt64(size.width))\n request.set(key: .height, value: UInt64(size.height))\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func wait(_ id: String) async throws -> Int32 {\n let request = XPCMessage(route: SandboxRoutes.wait.rawValue)\n request.set(key: .id, value: id)\n\n let client = createClient()\n defer { client.close() }\n let response = try await client.send(request)\n let code = response.int64(key: .exitCode)\n return Int32(code)\n }\n\n public func dial(_ port: UInt32) async throws -> FileHandle {\n let request = XPCMessage(route: SandboxRoutes.dial.rawValue)\n request.set(key: .port, value: UInt64(port))\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n guard let fh = response.fileHandle(key: .fd) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get fd for vsock port \\(port)\"\n )\n }\n return fh\n }\n\n private func createClient() -> XPCClient {\n XPCClient(service: machServiceLabel)\n }\n}\n\nextension XPCMessage {\n public func id() throws -> String {\n let id = self.string(key: .id)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"No id\")\n }\n return id\n }\n\n func sandboxSnapshot() throws -> SandboxSnapshot {\n let data = self.dataNoCopy(key: .snapshot)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No state data returned\")\n }\n return try JSONDecoder().decode(SandboxSnapshot.self, from: data)\n }\n}\n"], ["/container/Sources/APIServer/Containers/ContainersHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nstruct ContainersHarness {\n let log: Logging.Logger\n let service: ContainersService\n\n init(service: ContainersService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let containers = try await service.list()\n let data = try JSONEncoder().encode(containers)\n\n let reply = message.reply()\n reply.set(key: .containers, value: data)\n return reply\n }\n\n @Sendable\n func create(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .containerConfig)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"container configuration cannot be empty\")\n }\n let kdata = message.dataNoCopy(key: .kernel)\n guard let kdata else {\n throw ContainerizationError(.invalidArgument, message: \"kernel cannot be empty\")\n }\n let odata = message.dataNoCopy(key: .containerOptions)\n var options: ContainerCreateOptions = .default\n if let odata {\n options = try JSONDecoder().decode(ContainerCreateOptions.self, from: odata)\n }\n let config = try JSONDecoder().decode(ContainerConfiguration.self, from: data)\n let kernel = try JSONDecoder().decode(Kernel.self, from: kdata)\n\n try await service.create(configuration: config, kernel: kernel, options: options)\n return message.reply()\n }\n\n @Sendable\n func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .id)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"id cannot be empty\")\n }\n try await service.delete(id: id)\n return message.reply()\n }\n\n @Sendable\n func logs(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .id)\n guard let id else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"id cannot be empty\"\n )\n }\n let fds = try await service.logs(id: id)\n let reply = message.reply()\n try reply.set(key: .logs, value: fds)\n return reply\n }\n\n @Sendable\n func eventHandler(_ message: XPCMessage) async throws -> XPCMessage {\n let event = try message.containerEvent()\n try await service.handleContainerEvents(event: event)\n return message.reply()\n }\n}\n\nextension XPCMessage {\n public func containerEvent() throws -> ContainerEvent {\n guard let data = self.dataNoCopy(key: .containerEvent) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing container event data\")\n }\n let event = try JSONDecoder().decode(ContainerEvent.self, from: data)\n return event\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginLoader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\npublic struct PluginLoader: Sendable {\n // A path on disk managed by the PluginLoader, where it stores\n // runtime data for loaded plugins. This includes the launchd plists\n // and logs files.\n private let defaultPluginResourcePath: URL\n\n private let pluginDirectories: [URL]\n\n private let pluginFactories: [PluginFactory]\n\n private let log: Logger?\n\n public typealias PluginQualifier = ((Plugin) -> Bool)\n\n public init(pluginDirectories: [URL], pluginFactories: [PluginFactory], defaultResourcePath: URL, log: Logger? = nil) {\n self.pluginDirectories = pluginDirectories\n self.pluginFactories = pluginFactories\n self.log = log\n self.defaultPluginResourcePath = defaultResourcePath\n }\n\n static public func defaultPluginResourcePath(root: URL) -> URL {\n root.appending(path: \"plugin-state\")\n }\n\n static public func userPluginsDir(root: URL) -> URL {\n root\n .appending(path: \"libexec\")\n .appending(path: \"container-plugins\")\n .resolvingSymlinksInPath()\n }\n}\n\nextension PluginLoader {\n public func alterCLIHelpText(original: String) -> String {\n var plugins = findPlugins()\n plugins = plugins.filter { $0.config.isCLI }\n guard !plugins.isEmpty else {\n return original\n }\n\n var lines = original.split(separator: \"\\n\").map { String($0) }\n\n let sectionHeader = \"PLUGINS:\"\n lines.append(sectionHeader)\n\n for plugin in plugins {\n let helpText = plugin.helpText(padding: 24)\n lines.append(helpText)\n }\n\n return lines.joined(separator: \"\\n\")\n }\n\n public func findPlugins() -> [Plugin] {\n let fm = FileManager.default\n\n var pluginNames = Set()\n var plugins: [Plugin] = []\n\n for pluginDir in pluginDirectories {\n if !fm.fileExists(atPath: pluginDir.path) {\n continue\n }\n\n guard\n var dirs = try? fm.contentsOfDirectory(\n at: pluginDir,\n includingPropertiesForKeys: [.isDirectoryKey],\n options: .skipsHiddenFiles\n )\n else {\n continue\n }\n dirs = dirs.filter {\n $0.isDirectory\n }\n\n for installURL in dirs {\n do {\n guard\n let plugin = try\n (pluginFactories.compactMap {\n try $0.create(installURL: installURL)\n }.first)\n else {\n log?.warning(\n \"Not installing plugin with missing configuration\",\n metadata: [\n \"path\": \"\\(installURL.path)\"\n ]\n )\n continue\n }\n\n guard !pluginNames.contains(plugin.name) else {\n log?.warning(\n \"Not installing shadowed plugin\",\n metadata: [\n \"path\": \"\\(installURL.path)\",\n \"name\": \"\\(plugin.name)\",\n ])\n continue\n }\n\n plugins.append(plugin)\n pluginNames.insert(plugin.name)\n } catch {\n log?.warning(\n \"Not installing plugin with invalid configuration\",\n metadata: [\n \"path\": \"\\(installURL.path)\",\n \"error\": \"\\(error)\",\n ]\n )\n }\n }\n }\n\n return plugins\n }\n\n public func findPlugin(name: String, log: Logger? = nil) -> Plugin? {\n do {\n return\n try pluginDirectories\n .compactMap { installURL in\n try pluginFactories.compactMap { try $0.create(installURL: installURL.appending(path: name)) }.first\n }\n .first\n } catch {\n log?.warning(\n \"Not installing plugin with invalid configuration\",\n metadata: [\n \"name\": \"\\(name)\",\n \"error\": \"\\(error)\",\n ]\n )\n return nil\n }\n }\n}\n\nextension PluginLoader {\n public func registerWithLaunchd(\n plugin: Plugin,\n rootURL: URL? = nil,\n args: [String]? = nil,\n instanceId: String? = nil\n ) throws {\n // We only care about loading plugins that have a service\n // to expose; otherwise, they may just be CLI commands.\n guard let serviceConfig = plugin.config.servicesConfig else {\n return\n }\n\n let id = plugin.getLaunchdLabel(instanceId: instanceId)\n log?.info(\"Registering plugin\", metadata: [\"id\": \"\\(id)\"])\n let rootURL = rootURL ?? self.defaultPluginResourcePath.appending(path: plugin.name)\n try FileManager.default.createDirectory(at: rootURL, withIntermediateDirectories: true)\n let env = ProcessInfo.processInfo.environment.filter { key, _ in\n key.hasPrefix(\"CONTAINER_\")\n }\n let logUrl = rootURL.appendingPathComponent(\"service.log\")\n let plist = LaunchPlist(\n label: id,\n arguments: [plugin.binaryURL.path] + (args ?? serviceConfig.defaultArguments),\n environment: env,\n limitLoadToSessionType: [.Aqua, .Background, .System],\n runAtLoad: serviceConfig.runAtLoad,\n stdout: logUrl.path,\n stderr: logUrl.path,\n machServices: plugin.getMachServices(instanceId: instanceId)\n )\n\n let plistUrl = rootURL.appendingPathComponent(\"service.plist\")\n let data = try plist.encode()\n try data.write(to: plistUrl)\n try ServiceManager.register(plistPath: plistUrl.path)\n }\n\n public func deregisterWithLaunchd(plugin: Plugin, instanceId: String? = nil) throws {\n // We only care about loading plugins that have a service\n // to expose; otherwise, they may just be CLI commands.\n guard plugin.config.servicesConfig != nil else {\n return\n }\n let domain = try ServiceManager.getDomainString()\n let label = \"\\(domain)/\\(plugin.getLaunchdLabel(instanceId: instanceId))\"\n log?.info(\"Deregistering plugin\", metadata: [\"id\": \"\\(plugin.getLaunchdLabel())\"])\n try ServiceManager.deregister(fullServiceLabel: label)\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/SnapshotStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport TerminalProgress\n\npublic actor SnapshotStore {\n private static let snapshotFileName = \"snapshot\"\n private static let snapshotInfoFileName = \"snapshot-info\"\n private static let ingestDirName = \"ingest\"\n\n /// Return the Unpacker to use for a given image.\n /// If the given platform for the image cannot be unpacked return `nil`.\n public typealias UnpackStrategy = @Sendable (Containerization.Image, Platform) async throws -> Unpacker?\n\n public static let defaultUnpackStrategy: UnpackStrategy = { image, platform in\n guard platform.os == \"linux\" else {\n return nil\n }\n var minBlockSize = 512.gib()\n if image.reference == ClientDefaults.get(key: .defaultInitImage) {\n minBlockSize = 512.mib()\n }\n return EXT4Unpacker(blockSizeInBytes: minBlockSize)\n }\n\n let path: URL\n let fm = FileManager.default\n let ingestDir: URL\n let unpackStrategy: UnpackStrategy\n let log: Logger?\n\n public init(path: URL, unpackStrategy: @escaping UnpackStrategy, log: Logger?) throws {\n let root = path.appendingPathComponent(\"snapshots\")\n self.path = root\n self.ingestDir = self.path.appendingPathComponent(Self.ingestDirName)\n self.unpackStrategy = unpackStrategy\n self.log = log\n try self.fm.createDirectory(at: root, withIntermediateDirectories: true)\n try self.fm.createDirectory(at: self.ingestDir, withIntermediateDirectories: true)\n }\n\n public func unpack(image: Containerization.Image, platform: Platform? = nil, progressUpdate: ProgressUpdateHandler?) async throws {\n var toUnpack: [Descriptor] = []\n if let platform {\n let desc = try await image.descriptor(for: platform)\n toUnpack = [desc]\n } else {\n toUnpack = try await image.unpackableDescriptors()\n }\n\n let taskManager = ProgressTaskCoordinator()\n var taskUpdateProgress: ProgressUpdateHandler?\n\n for desc in toUnpack {\n try Task.checkCancellation()\n let snapshotDir = self.snapshotDir(desc)\n guard !self.fm.fileExists(atPath: snapshotDir.absolutePath()) else {\n // We have already unpacked this image + platform. Skip\n continue\n }\n guard let platform = desc.platform else {\n throw ContainerizationError(.internalError, message: \"Missing platform for descriptor \\(desc.digest)\")\n }\n guard let unpacker = try await self.unpackStrategy(image, platform) else {\n self.log?.warning(\"Skipping unpack for \\(image.reference) for platform \\(platform.description). No unpacker configured.\")\n continue\n }\n let currentSubTask = await taskManager.startTask()\n if let progressUpdate {\n let _taskUpdateProgress = ProgressTaskCoordinator.handler(for: currentSubTask, from: progressUpdate)\n await _taskUpdateProgress([\n .setSubDescription(\"for platform \\(platform.description)\")\n ])\n taskUpdateProgress = _taskUpdateProgress\n }\n\n let tempDir = try self.tempUnpackDir()\n\n let tempSnapshotPath = tempDir.appendingPathComponent(Self.snapshotFileName, isDirectory: false)\n let infoPath = tempDir.appendingPathComponent(Self.snapshotInfoFileName, isDirectory: false)\n do {\n let progress = ContainerizationProgressAdapter.handler(from: taskUpdateProgress)\n let mount = try await unpacker.unpack(image, for: platform, at: tempSnapshotPath, progress: progress)\n let fs = Filesystem.block(\n format: mount.type,\n source: self.snapshotPath(desc).absolutePath(),\n destination: mount.destination,\n options: mount.options\n )\n let snapshotInfo = try JSONEncoder().encode(fs)\n self.fm.createFile(atPath: infoPath.absolutePath(), contents: snapshotInfo)\n } catch {\n try? self.fm.removeItem(at: tempDir)\n throw error\n }\n do {\n try fm.moveItem(at: tempDir, to: snapshotDir)\n } catch let err as NSError {\n guard err.code == NSFileWriteFileExistsError else {\n throw err\n }\n try? self.fm.removeItem(at: tempDir)\n }\n }\n await taskManager.finish()\n }\n\n public func delete(for image: Containerization.Image, platform: Platform? = nil) async throws {\n var toDelete: [Descriptor] = []\n if let platform {\n let desc = try await image.descriptor(for: platform)\n toDelete.append(desc)\n } else {\n toDelete = try await image.unpackableDescriptors()\n }\n for desc in toDelete {\n let p = self.snapshotDir(desc)\n guard self.fm.fileExists(atPath: p.absolutePath()) else {\n continue\n }\n try self.fm.removeItem(at: p)\n }\n }\n\n public func get(for image: Containerization.Image, platform: Platform) async throws -> Filesystem {\n let desc = try await image.descriptor(for: platform)\n let infoPath = snapshotInfoPath(desc)\n let fsPath = snapshotPath(desc)\n\n guard self.fm.fileExists(atPath: infoPath.absolutePath()),\n self.fm.fileExists(atPath: fsPath.absolutePath())\n else {\n throw ContainerizationError(.notFound, message: \"image snapshot for \\(image.reference) with platform \\(platform.description)\")\n }\n let decoder = JSONDecoder()\n let data = try Data(contentsOf: infoPath)\n let fs = try decoder.decode(Filesystem.self, from: data)\n return fs\n }\n\n public func clean(keepingSnapshotsFor images: [Containerization.Image] = []) async throws -> UInt64 {\n var toKeep: [String] = [Self.ingestDirName]\n for image in images {\n for manifest in try await image.index().manifests {\n guard let platform = manifest.platform else {\n continue\n }\n let desc = try await image.descriptor(for: platform)\n toKeep.append(desc.digest.trimmingDigestPrefix)\n }\n }\n let all = try self.fm.contentsOfDirectory(at: self.path, includingPropertiesForKeys: [.totalFileAllocatedSizeKey]).map {\n $0.lastPathComponent\n }\n let delete = Set(all).subtracting(Set(toKeep))\n var deletedBytes: UInt64 = 0\n for dir in delete {\n let unpackedPath = self.path.appending(path: dir, directoryHint: .isDirectory)\n guard self.fm.fileExists(atPath: unpackedPath.absolutePath()) else {\n continue\n }\n deletedBytes += (try? self.fm.directorySize(dir: unpackedPath)) ?? 0\n try self.fm.removeItem(at: unpackedPath)\n }\n return deletedBytes\n }\n\n private func snapshotDir(_ desc: Descriptor) -> URL {\n let p = self.path.appendingPathComponent(desc.digest.trimmingDigestPrefix, isDirectory: true)\n return p\n }\n\n private func snapshotPath(_ desc: Descriptor) -> URL {\n let p = self.snapshotDir(desc)\n .appendingPathComponent(Self.snapshotFileName, isDirectory: false)\n return p\n }\n\n private func snapshotInfoPath(_ desc: Descriptor) -> URL {\n let p = self.snapshotDir(desc)\n .appendingPathComponent(Self.snapshotInfoFileName, isDirectory: false)\n return p\n }\n\n private func tempUnpackDir() throws -> URL {\n let uniqueDirectoryURL = ingestDir.appendingPathComponent(UUID().uuidString, isDirectory: true)\n try self.fm.createDirectory(at: uniqueDirectoryURL, withIntermediateDirectories: true, attributes: nil)\n return uniqueDirectoryURL\n }\n}\n\nextension FileManager {\n fileprivate func directorySize(dir: URL) throws -> UInt64 {\n var size = 0\n let resourceKeys: [URLResourceKey] = [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey]\n let contents = try self.contentsOfDirectory(\n at: dir,\n includingPropertiesForKeys: resourceKeys)\n\n for p in contents {\n let val = try p.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey])\n size += val.totalFileAllocatedSize ?? val.fileAllocatedSize ?? 0\n }\n return UInt64(size)\n }\n}\n\nextension Containerization.Image {\n fileprivate func unpackableDescriptors() async throws -> [Descriptor] {\n let index = try await self.index()\n return index.manifests.filter { desc in\n guard desc.platform != nil else {\n return false\n }\n if let referenceType = desc.annotations?[\"vnd.docker.reference.type\"], referenceType == \"attestation-manifest\" {\n return false\n }\n return true\n }\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSDefault.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\n\nextension Application {\n struct DNSDefault: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"default\",\n abstract: \"Set or unset the default local DNS domain\",\n subcommands: [\n DefaultSetCommand.self,\n DefaultUnsetCommand.self,\n DefaultInspectCommand.self,\n ]\n )\n\n struct DefaultSetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default local DNS domain\"\n\n )\n\n @Argument(help: \"the default `--domain-name` to use for the `create` or `run` command\")\n var domainName: String\n\n func run() async throws {\n ClientDefaults.set(value: domainName, key: .defaultDNSDomain)\n print(domainName)\n }\n }\n\n struct DefaultUnsetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"unset\",\n abstract: \"Unset the default local DNS domain\",\n aliases: [\"clear\"]\n )\n\n func run() async throws {\n ClientDefaults.unset(key: .defaultDNSDomain)\n print(\"Unset the default local DNS domain\")\n }\n }\n\n struct DefaultInspectCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display the default local DNS domain\"\n )\n\n func run() async throws {\n print(ClientDefaults.getOptional(key: .defaultDNSDomain) ?? \"\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/HostDNSResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n/// Functions for managing local DNS domains for containers.\npublic struct HostDNSResolver {\n public static let defaultConfigPath = URL(filePath: \"/etc/resolver\")\n\n // prefix used to mark our files as /etc/resolver/{prefix}{domainName}\n private static let containerizationPrefix = \"containerization.\"\n\n private let configURL: URL\n\n public init(configURL: URL = Self.defaultConfigPath) {\n self.configURL = configURL\n }\n\n /// Creates a DNS resolver configuration file for domain resolved by the application.\n public func createDomain(name: String) throws {\n let path = self.configURL.appending(path: \"\\(Self.containerizationPrefix)\\(name)\").path\n let fm: FileManager = FileManager.default\n\n if fm.fileExists(atPath: self.configURL.path) {\n guard let isDir = try self.configURL.resourceValues(forKeys: [.isDirectoryKey]).isDirectory, isDir else {\n throw ContainerizationError(.invalidState, message: \"expected \\(self.configURL.path) to be a directory, but found a file\")\n }\n } else {\n try fm.createDirectory(at: self.configURL, withIntermediateDirectories: true)\n }\n\n guard !fm.fileExists(atPath: path) else {\n throw ContainerizationError(.exists, message: \"domain \\(name) already exists\")\n }\n\n let resolverText = \"\"\"\n domain \\(name)\n search \\(name)\n nameserver 127.0.0.1\n port 2053\n \"\"\"\n\n do {\n try resolverText.write(toFile: path, atomically: true, encoding: .utf8)\n } catch {\n throw ContainerizationError(.invalidState, message: \"failed to write resolver configuration for \\(name)\")\n }\n }\n\n /// Removes a DNS resolver configuration file for domain resolved by the application.\n public func deleteDomain(name: String) throws {\n let path = self.configURL.appending(path: \"\\(Self.containerizationPrefix)\\(name)\").path\n let fm = FileManager.default\n guard fm.fileExists(atPath: path) else {\n throw ContainerizationError(.notFound, message: \"domain \\(name) at \\(path) not found\")\n }\n\n do {\n try fm.removeItem(atPath: path)\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot delete domain (try sudo?)\")\n }\n }\n\n /// Lists application-created local DNS domains.\n public func listDomains() -> [String] {\n let fm: FileManager = FileManager.default\n guard\n let resolverPaths = try? fm.contentsOfDirectory(\n at: self.configURL,\n includingPropertiesForKeys: [.isDirectoryKey]\n )\n else {\n return []\n }\n\n return\n resolverPaths\n .filter { $0.lastPathComponent.starts(with: Self.containerizationPrefix) }\n .compactMap { try? getDomainFromResolver(url: $0) }\n .sorted()\n }\n\n /// Reinitializes the macOS DNS daemon.\n public static func reinitialize() throws {\n do {\n let kill = Foundation.Process()\n kill.executableURL = URL(fileURLWithPath: \"/usr/bin/killall\")\n kill.arguments = [\"-HUP\", \"mDNSResponder\"]\n\n let null = FileHandle.nullDevice\n kill.standardOutput = null\n kill.standardError = null\n\n try kill.run()\n kill.waitUntilExit()\n let status = kill.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(.internalError, message: \"mDNSResponder restart failed with status \\(status)\")\n }\n }\n }\n\n private func getDomainFromResolver(url: URL) throws -> String? {\n let text = try String(contentsOf: url, encoding: .utf8)\n for line in text.components(separatedBy: .newlines) {\n let trimmed = line.trimmingCharacters(in: .whitespaces)\n let components = trimmed.split(whereSeparator: { $0.isWhitespace })\n guard components.count == 2 else {\n continue\n }\n guard components[0] == \"domain\" else {\n continue\n }\n\n return String(components[1])\n }\n\n return nil\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\nimport Logging\nimport os\nimport Synchronization\n\npublic struct XPCServer: Sendable {\n public typealias RouteHandler = @Sendable (XPCMessage) async throws -> XPCMessage\n\n private let routes: [String: RouteHandler]\n // Access to `connection` is protected by a lock\n private nonisolated(unsafe) let connection: xpc_connection_t\n private let lock = NSLock()\n\n let log: Logging.Logger\n\n public init(identifier: String, routes: [String: RouteHandler], log: Logging.Logger) {\n let connection = xpc_connection_create_mach_service(\n identifier,\n nil,\n UInt64(XPC_CONNECTION_MACH_SERVICE_LISTENER))\n\n self.routes = routes\n self.connection = connection\n self.log = log\n }\n\n public func listen() async throws {\n let connections = AsyncStream { cont in\n lock.withLock {\n xpc_connection_set_event_handler(self.connection) { object in\n switch xpc_get_type(object) {\n case XPC_TYPE_CONNECTION:\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n cont.yield(object)\n case XPC_TYPE_ERROR:\n if object.connectionError {\n cont.finish()\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(object))\")\n }\n }\n }\n }\n\n defer {\n lock.withLock {\n xpc_connection_cancel(self.connection)\n }\n }\n\n lock.withLock {\n xpc_connection_activate(self.connection)\n }\n try await withThrowingDiscardingTaskGroup { group in\n for await conn in connections {\n // `conn` isn't used concurrently.\n nonisolated(unsafe) let conn = conn\n let added = group.addTaskUnlessCancelled { @Sendable in\n try await self.handleClientConnection(connection: conn)\n xpc_connection_cancel(conn)\n }\n\n if !added {\n break\n }\n }\n\n group.cancelAll()\n }\n }\n\n func handleClientConnection(connection: xpc_connection_t) async throws {\n let replySent = Mutex(false)\n\n let objects = AsyncStream { cont in\n xpc_connection_set_event_handler(connection) { object in\n switch xpc_get_type(object) {\n case XPC_TYPE_DICTIONARY:\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n cont.yield(object)\n case XPC_TYPE_ERROR:\n if object.connectionError {\n cont.finish()\n }\n if !(replySent.withLock({ $0 }) && object.connectionClosed) {\n // When a xpc connection is closed, the framework sends a final XPC_ERROR_CONNECTION_INVALID message.\n // We can ignore this if we know we have already handled the request.\n self.log.error(\"xpc client handler connection error \\(object.errorDescription ?? \"no description\")\")\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(object))\")\n }\n }\n }\n defer {\n xpc_connection_cancel(connection)\n }\n\n xpc_connection_activate(connection)\n try await withThrowingDiscardingTaskGroup { group in\n // `connection` isn't used concurrently.\n nonisolated(unsafe) let connection = connection\n for await object in objects {\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n let added = group.addTaskUnlessCancelled { @Sendable in\n try await self.handleMessage(connection: connection, object: object)\n replySent.withLock { $0 = true }\n }\n if !added {\n break\n }\n }\n group.cancelAll()\n }\n }\n\n func handleMessage(connection: xpc_connection_t, object: xpc_object_t) async throws {\n guard let route = object.route else {\n log.error(\"empty route\")\n return\n }\n\n if let handler = routes[route] {\n let message = XPCMessage(object: object)\n do {\n let response = try await handler(message)\n xpc_connection_send_message(connection, response.underlying)\n } catch let error as ContainerizationError {\n let reply = message.reply()\n log.error(\"handler for \\(route) threw error \\(error)\")\n reply.set(error: error)\n xpc_connection_send_message(connection, reply.underlying)\n } catch {\n let reply = message.reply()\n log.error(\"handler for \\(route) threw error \\(error)\")\n let err = ContainerizationError(.unknown, message: String(describing: error))\n reply.set(error: err)\n xpc_connection_send_message(connection, reply.underlying)\n }\n }\n }\n}\n\nextension xpc_object_t {\n var route: String? {\n let croute = xpc_dictionary_get_string(self, XPCMessage.routeKey)\n guard let croute else {\n return nil\n }\n return String(cString: croute)\n }\n\n var connectionError: Bool {\n precondition(isError, \"Not an error\")\n return xpc_equal(self, XPC_ERROR_CONNECTION_INVALID) || xpc_equal(self, XPC_ERROR_CONNECTION_INTERRUPTED)\n }\n\n var connectionClosed: Bool {\n precondition(isError, \"Not an error\")\n return xpc_equal(self, XPC_ERROR_CONNECTION_INVALID)\n }\n\n var isError: Bool {\n xpc_get_type(self) == XPC_TYPE_ERROR\n }\n\n var errorDescription: String? {\n precondition(isError, \"Not an error\")\n let cstring = xpc_dictionary_get_string(self, XPC_ERROR_KEY_DESCRIPTION)\n guard let cstring else {\n return nil\n }\n return String(cString: cstring)\n }\n}\n\n#endif\n"], ["/container/Sources/CLI/System/DNS/DNSDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct DNSDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete a local DNS domain (must run as an administrator)\",\n aliases: [\"rm\"]\n )\n\n @Argument(help: \"the local domain name\")\n var domainName: String\n\n func run() async throws {\n let resolver = HostDNSResolver()\n do {\n try resolver.deleteDomain(name: domainName)\n print(domainName)\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot create domain (try sudo?)\")\n }\n\n do {\n try HostDNSResolver.reinitialize()\n } catch {\n throw ContainerizationError(.invalidState, message: \"mDNSResponder restart failed, run `sudo killall -HUP mDNSResponder` to deactivate domain\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\n\npublic struct XPCClient: Sendable {\n private nonisolated(unsafe) let connection: xpc_connection_t\n private let q: DispatchQueue?\n private let service: String\n\n public init(service: String, queue: DispatchQueue? = nil) {\n let connection = xpc_connection_create_mach_service(service, queue, 0)\n self.connection = connection\n self.q = queue\n self.service = service\n\n xpc_connection_set_event_handler(connection) { _ in }\n xpc_connection_set_target_queue(connection, self.q)\n xpc_connection_activate(connection)\n }\n}\n\nextension XPCClient {\n /// Close the underlying XPC connection.\n public func close() {\n xpc_connection_cancel(connection)\n }\n\n /// Returns the pid of process to which we have a connection.\n /// Note: `xpc_connection_get_pid` returns 0 if no activity\n /// has taken place on the connection prior to it being called.\n public func remotePid() -> pid_t {\n xpc_connection_get_pid(self.connection)\n }\n\n /// Send the provided message to the service.\n @discardableResult\n public func send(_ message: XPCMessage, responseTimeout: Duration? = nil) async throws -> XPCMessage {\n try await withThrowingTaskGroup(of: XPCMessage.self, returning: XPCMessage.self) { group in\n if let responseTimeout {\n group.addTask {\n try await Task.sleep(for: responseTimeout)\n let route = message.string(key: XPCMessage.routeKey) ?? \"nil\"\n throw ContainerizationError(.internalError, message: \"XPC timeout for request to \\(self.service)/\\(route)\")\n }\n }\n\n group.addTask {\n try await withCheckedThrowingContinuation { cont in\n xpc_connection_send_message_with_reply(self.connection, message.underlying, nil) { reply in\n do {\n let message = try self.parseReply(reply)\n cont.resume(returning: message)\n } catch {\n cont.resume(throwing: error)\n }\n }\n }\n }\n\n let response = try await group.next()\n // once one task has finished, cancel the rest.\n group.cancelAll()\n // we don't really care about the second error here\n // as it's most likely a `CancellationError`.\n try? await group.waitForAll()\n\n guard let response else {\n throw ContainerizationError(.invalidState, message: \"failed to receive XPC response\")\n }\n return response\n }\n }\n\n private func parseReply(_ reply: xpc_object_t) throws -> XPCMessage {\n switch xpc_get_type(reply) {\n case XPC_TYPE_ERROR:\n var code = ContainerizationError.Code.invalidState\n if reply.connectionError {\n code = .interrupted\n }\n throw ContainerizationError(\n code,\n message: \"XPC connection error: \\(reply.errorDescription ?? \"unknown\")\"\n )\n case XPC_TYPE_DICTIONARY:\n let message = XPCMessage(object: reply)\n // check errors from our protocol\n try message.error()\n return message\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(reply))\")\n }\n }\n}\n\n#endif\n"], ["/container/Sources/CLI/Image/ImagePull.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport TerminalProgress\n\nextension Application {\n struct ImagePull: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"pull\",\n abstract: \"Pull an image\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Argument var reference: String\n\n init() {}\n\n init(platform: String? = nil, scheme: String = \"auto\", reference: String, disableProgress: Bool = false) {\n self.global = Flags.Global()\n self.registry = Flags.Registry(scheme: scheme)\n self.progressFlags = Flags.Progress(disableProgressUpdates: disableProgress)\n self.platform = platform\n self.reference = reference\n }\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let scheme = try RequestScheme(registry.scheme)\n\n let processedReference = try ClientImage.normalizeReference(reference)\n\n var progressConfig: ProgressConfig\n if self.progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: self.progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 2\n )\n }\n\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Fetching image\")\n progress.set(itemsName: \"blobs\")\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n let image = try await ClientImage.pull(\n reference: processedReference, platform: p, scheme: scheme, progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progress.handler)\n )\n\n progress.set(description: \"Unpacking image\")\n progress.set(itemsName: \"entries\")\n let unpackTask = await taskManager.startTask()\n try await image.unpack(platform: p, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progress.handler))\n await taskManager.finish()\n progress.finish()\n }\n }\n}\n"], ["/container/Sources/CLI/Builder/Builder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct BuilderCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"builder\",\n abstract: \"Manage an image builder instance\",\n subcommands: [\n BuilderStart.self,\n BuilderStatus.self,\n BuilderStop.self,\n BuilderDelete.self,\n ])\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/ReservedVmnetNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport Dispatch\nimport Foundation\nimport Logging\nimport SendableProperty\nimport SystemConfiguration\nimport XPC\nimport vmnet\n\n/// Creates a vmnet network with reservation APIs.\n@available(macOS 26, *)\npublic final class ReservedVmnetNetwork: Network {\n @SendablePropertyUnchecked\n private var _state: NetworkState\n private let log: Logger\n\n @SendableProperty\n private var network: vmnet_network_ref?\n @SendableProperty\n private var interface: interface_ref?\n private let networkLock = NSLock()\n\n /// Configure a bridge network that allows external system access using\n /// network address translation.\n public init(\n configuration: NetworkConfiguration,\n log: Logger\n ) throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.unsupported, message: \"invalid network mode \\(configuration.mode)\")\n }\n\n log.info(\"creating vmnet network\")\n self.log = log\n _state = .created(configuration)\n log.info(\"created vmnet network\")\n }\n\n public var state: NetworkState {\n get async { _state }\n }\n\n public nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws {\n try networkLock.withLock {\n try handler(network.map { try Self.serialize_network_ref(ref: $0) })\n }\n }\n\n public func start() async throws {\n guard case .created(let configuration) = _state else {\n throw ContainerizationError(.invalidArgument, message: \"cannot start network that is in \\(_state.state) state\")\n }\n\n try startNetwork(configuration: configuration, log: log)\n }\n\n private static func serialize_network_ref(ref: vmnet_network_ref) throws -> XPCMessage {\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let refObject = vmnet_network_copy_serialization(ref, &status) else {\n throw ContainerizationError(.invalidArgument, message: \"cannot serialize vmnet_network_ref to XPC object, status \\(status)\")\n }\n return XPCMessage(object: refObject)\n }\n\n private func startNetwork(configuration: NetworkConfiguration, log: Logger) throws {\n log.info(\n \"starting vmnet network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n ]\n )\n let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName)\n let subnetText = configuration.subnet ?? suite?.string(forKey: \"network.subnet\")\n\n // with the reservation API, subnet priority is CLI argument, UserDefault, auto\n let subnet = try subnetText.map { try CIDRAddress($0) }\n\n // set up the vmnet configuration\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let vmnetConfiguration = vmnet_network_configuration_create(vmnet.operating_modes_t.VMNET_SHARED_MODE, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet config with status \\(status)\")\n }\n\n vmnet_network_configuration_disable_dhcp(vmnetConfiguration)\n\n // set the subnet if the caller provided one\n if let subnet {\n let gateway = IPv4Address(fromValue: subnet.lower.value + 1)\n var gatewayAddr = in_addr()\n inet_pton(AF_INET, gateway.description, &gatewayAddr)\n let mask = IPv4Address(fromValue: subnet.prefixLength.prefixMask32)\n var maskAddr = in_addr()\n inet_pton(AF_INET, mask.description, &maskAddr)\n log.info(\n \"configuring vmnet subnet\",\n metadata: [\"cidr\": \"\\(subnet)\"]\n )\n let status = vmnet_network_configuration_set_ipv4_subnet(vmnetConfiguration, &gatewayAddr, &maskAddr)\n guard status == .VMNET_SUCCESS else {\n throw ContainerizationError(.internalError, message: \"failed to set subnet \\(subnet) for network \\(configuration.id)\")\n }\n }\n\n // reserve the network\n guard let network = vmnet_network_create(vmnetConfiguration, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet network with status \\(status)\")\n }\n self.network = network\n\n // retrieve the subnet since the caller may not have provided one\n var subnetAddr = in_addr()\n var maskAddr = in_addr()\n vmnet_network_get_ipv4_subnet(network, &subnetAddr, &maskAddr)\n let subnetValue = UInt32(bigEndian: subnetAddr.s_addr)\n let maskValue = UInt32(bigEndian: maskAddr.s_addr)\n let lower = IPv4Address(fromValue: subnetValue & maskValue)\n let upper = IPv4Address(fromValue: lower.value + ~maskValue)\n let runningSubnet = try CIDRAddress(lower: lower, upper: upper)\n let runningGateway = IPv4Address(fromValue: runningSubnet.lower.value + 1)\n self._state = .running(configuration, NetworkStatus(address: runningSubnet.description, gateway: runningGateway.description))\n log.info(\n \"started vmnet network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n \"cidr\": \"\\(runningSubnet)\",\n ]\n )\n }\n}\n"], ["/container/Sources/ContainerClient/Flags.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationError\nimport Foundation\n\npublic struct Flags {\n public struct Global: ParsableArguments {\n public init() {}\n\n @Flag(name: .long, help: \"Enable debug output [environment: CONTAINER_DEBUG]\")\n public var debug = false\n }\n\n public struct Process: ParsableArguments {\n public init() {}\n\n @Option(\n name: [.customLong(\"cwd\"), .customShort(\"w\"), .customLong(\"workdir\")],\n help: \"Current working directory for the container\")\n public var cwd: String?\n\n @Option(name: [.customLong(\"env\"), .customShort(\"e\")], help: \"Set environment variables\")\n public var env: [String] = []\n\n @Option(name: .customLong(\"env-file\"), help: \"Read in a file of environment variables\")\n public var envFile: [String] = []\n\n @Option(name: .customLong(\"uid\"), help: \"Set the uid for the process\")\n public var uid: UInt32?\n\n @Option(name: .customLong(\"gid\"), help: \"Set the gid for the process\")\n public var gid: UInt32?\n\n @Flag(name: [.customLong(\"interactive\"), .customShort(\"i\")], help: \"Keep Stdin open even if not attached\")\n public var interactive = false\n\n @Flag(name: [.customLong(\"tty\"), .customShort(\"t\")], help: \"Open a tty with the process\")\n public var tty = false\n\n @Option(name: [.customLong(\"user\"), .customShort(\"u\")], help: \"Set the user for the process\")\n public var user: String?\n }\n\n public struct Resource: ParsableArguments {\n public init() {}\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64?\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n public var memory: String?\n }\n\n public struct Registry: ParsableArguments {\n public init() {}\n\n public init(scheme: String) {\n self.scheme = scheme\n }\n\n @Option(help: \"Scheme to use when connecting to the container registry. One of (http, https, auto)\")\n public var scheme: String = \"auto\"\n }\n\n public struct Management: ParsableArguments {\n public init() {}\n\n @Flag(name: [.customLong(\"detach\"), .short], help: \"Run the container and detach from the process\")\n public var detach = false\n\n @Option(name: .customLong(\"entrypoint\"), help: \"Override the entrypoint of the image\")\n public var entryPoint: String?\n\n @Option(name: .customLong(\"mount\"), help: \"Add a mount to the container (type=<>,source=<>,target=<>,readonly)\")\n public var mounts: [String] = []\n\n @Option(name: [.customLong(\"publish\"), .short], help: \"Publish a port from container to host (format: [host-ip:]host-port:container-port[/protocol])\")\n public var publishPorts: [String] = []\n\n @Option(name: .customLong(\"publish-socket\"), help: \"Publish a socket from container to host (format: host_path:container_path)\")\n public var publishSockets: [String] = []\n\n @Option(name: .customLong(\"tmpfs\"), help: \"Add a tmpfs mount to the container at the given path\")\n public var tmpFs: [String] = []\n\n @Option(name: .customLong(\"name\"), help: \"Assign a name to the container. If excluded will be a generated UUID\")\n public var name: String?\n\n @Flag(name: [.customLong(\"remove\"), .customLong(\"rm\")], help: \"Remove the container after it stops\")\n public var remove = false\n\n @Option(name: .customLong(\"os\"), help: \"Set OS if image can target multiple operating systems\")\n public var os = \"linux\"\n\n @Option(\n name: [.customLong(\"arch\"), .short], help: \"Set arch if image can target multiple architectures\")\n public var arch: String = Arch.hostArchitecture().rawValue\n\n @Option(name: [.customLong(\"volume\"), .short], help: \"Bind mount a volume into the container\")\n public var volumes: [String] = []\n\n @Option(\n name: [.customLong(\"kernel\"), .short], help: \"Set a custom kernel path\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n public var kernel: String?\n\n @Option(name: [.customLong(\"network\")], help: \"Attach the container to a network\")\n public var networks: [String] = []\n\n @Option(name: .customLong(\"cidfile\"), help: \"Write the container ID to the path provided\")\n public var cidfile = \"\"\n\n @Flag(name: [.customLong(\"no-dns\")], help: \"Do not configure DNS in the container\")\n public var dnsDisabled = false\n\n @Option(name: .customLong(\"dns\"), help: \"DNS nameserver IP address\")\n public var dnsNameservers: [String] = []\n\n @Option(name: .customLong(\"dns-domain\"), help: \"Default DNS domain\")\n public var dnsDomain: String? = nil\n\n @Option(name: .customLong(\"dns-search\"), help: \"DNS search domains\")\n public var dnsSearchDomains: [String] = []\n\n @Option(name: .customLong(\"dns-option\"), help: \"DNS options\")\n public var dnsOptions: [String] = []\n\n @Option(name: [.customLong(\"label\"), .short], help: \"Add a key=value label to the container\")\n public var labels: [String] = []\n }\n\n public struct Progress: ParsableArguments {\n public init() {}\n\n public init(disableProgressUpdates: Bool) {\n self.disableProgressUpdates = disableProgressUpdates\n }\n\n @Flag(name: .customLong(\"disable-progress-updates\"), help: \"Disable progress bar updates\")\n public var disableProgressUpdates = false\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePush.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport TerminalProgress\n\nextension Application {\n struct ImagePush: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"push\",\n abstract: \"Push an image\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Argument var reference: String\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let scheme = try RequestScheme(registry.scheme)\n let image = try await ClientImage.get(reference: reference)\n\n var progressConfig: ProgressConfig\n if progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n description: \"Pushing image \\(image.reference)\",\n itemsName: \"blobs\",\n showItems: true,\n showSpeed: false,\n ignoreSmallSize: true\n )\n }\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n _ = try await image.push(platform: p, scheme: scheme, progressUpdate: progress.handler)\n progress.finish()\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientKernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct ClientKernel {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n}\n\nextension ClientKernel {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public static func installKernel(kernelFilePath: String, platform: SystemPlatform) async throws {\n let client = newClient()\n let message = XPCMessage(route: .installKernel)\n\n message.set(key: .kernelFilePath, value: kernelFilePath)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n try await client.send(message)\n }\n\n public static func installKernelFromTar(tarFile: String, kernelFilePath: String, platform: SystemPlatform, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let client = newClient()\n let message = XPCMessage(route: .installKernel)\n\n message.set(key: .kernelTarURL, value: tarFile)\n message.set(key: .kernelFilePath, value: kernelFilePath)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: message)\n }\n\n try await client.send(message)\n await progressUpdateClient?.finish()\n }\n\n @discardableResult\n public static func getDefaultKernel(for platform: SystemPlatform) async throws -> Kernel {\n let client = newClient()\n let message = XPCMessage(route: .getDefaultKernel)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n do {\n let reply = try await client.send(message)\n guard let kData = reply.dataNoCopy(key: .kernel) else {\n throw ContainerizationError(.internalError, message: \"Missing kernel data from XPC response\")\n }\n\n let kernel = try JSONDecoder().decode(Kernel.self, from: kData)\n return kernel\n } catch let err as ContainerizationError {\n guard err.isCode(.notFound) else {\n throw err\n }\n throw ContainerizationError(\n .notFound, message: \"Default kernel not configured for architecture \\(platform.architecture). Please use the `container system kernel set` command to configure it\")\n }\n }\n}\n\nextension SystemPlatform {\n public static var current: SystemPlatform {\n switch Platform.current.architecture {\n case \"arm64\":\n return .linuxArm\n case \"amd64\":\n return .linuxAmd\n default:\n fatalError(\"Unknown architecture\")\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/RemoteContentStoreClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Crypto\nimport ContainerizationError\nimport Foundation\nimport ContainerizationOCI\nimport ContainerXPC\n\npublic struct RemoteContentStoreClient: ContentStore {\n private static let serviceIdentifier = \"com.apple.container.core.container-core-images\"\n private static let encoder = JSONEncoder()\n\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public init() {}\n\n private func _get(digest: String) async throws -> URL? {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentGet)\n request.set(key: .digest, value: digest)\n do {\n let response = try await client.send(request)\n guard let path = response.string(key: .contentPath) else {\n return nil\n }\n return URL(filePath: path)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return nil\n }\n throw error\n }\n }\n\n public func get(digest: String) async throws -> Content? {\n guard let url = try await self._get(digest: digest) else {\n return nil\n }\n return try LocalContent(path: url)\n }\n\n public func get(digest: String) async throws -> T? {\n guard let content: Content = try await self.get(digest: digest) else {\n return nil\n }\n return try content.decode()\n }\n\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentClean)\n\n let d = try Self.encoder.encode(keeping)\n request.set(key: .digests, value: d)\n let response = try await client.send(request)\n\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let deleted = try decoder.decode([String].self, from: data)\n let size = response.uint64(key: .size)\n return (deleted, size)\n }\n\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentDelete)\n\n let d = try Self.encoder.encode(digests)\n request.set(key: .digests, value: d)\n let response = try await client.send(request)\n\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let deleted = try decoder.decode([String].self, from: data)\n let size = response.uint64(key: .size)\n return (deleted, size)\n }\n\n @discardableResult\n public func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String] {\n let (id, tempPath) = try await self.newIngestSession()\n try await body(tempPath)\n return try await self.completeIngestSession(id)\n }\n\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestStart)\n let response = try await client.send(request)\n guard let id = response.string(key: .ingestSessionId) else {\n throw ContainerizationError.init(.internalError, message: \"failed create new ingest session\")\n }\n guard let dir = response.string(key: .directory) else {\n throw ContainerizationError.init(.internalError, message: \"failed create new ingest session\")\n }\n return (id, URL(filePath: dir))\n }\n\n @discardableResult\n public func completeIngestSession(_ id: String) async throws -> [String] {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestComplete)\n\n request.set(key: .ingestSessionId, value: id)\n\n let response = try await client.send(request)\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let ingested = try decoder.decode([String].self, from: data)\n return ingested\n }\n\n public func cancelIngestSession(_ id: String) async throws {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestCancel)\n request.set(key: .ingestSessionId, value: id)\n try await client.send(request)\n }\n}\n\n#endif\n"], ["/container/Sources/Services/ContainerImagesService/Server/ImageService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport Logging\nimport TerminalProgress\n\npublic actor ImagesService {\n public static let keychainID = \"com.apple.container\"\n\n private let log: Logger\n private let contentStore: ContentStore\n private let imageStore: ImageStore\n private let snapshotStore: SnapshotStore\n\n public init(contentStore: ContentStore, imageStore: ImageStore, snapshotStore: SnapshotStore, log: Logger) throws {\n self.contentStore = contentStore\n self.imageStore = imageStore\n self.snapshotStore = snapshotStore\n self.log = log\n }\n\n private func _list() async throws -> [Containerization.Image] {\n try await imageStore.list()\n }\n\n private func _get(_ reference: String) async throws -> Containerization.Image {\n try await imageStore.get(reference: reference)\n }\n\n private func _get(_ description: ImageDescription) async throws -> Containerization.Image {\n let exists = try await self._get(description.reference)\n guard exists.descriptor == description.descriptor else {\n throw ContainerizationError(.invalidState, message: \"Descriptor mismatch. Expected \\(description.descriptor), got \\(exists.descriptor)\")\n }\n return exists\n }\n\n public func list() async throws -> [ImageDescription] {\n self.log.info(\"ImagesService: \\(#function)\")\n return try await imageStore.list().map { $0.description.fromCZ }\n }\n\n public func pull(reference: String, platform: Platform?, insecure: Bool, progressUpdate: ProgressUpdateHandler?) async throws -> ImageDescription {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference), platform: \\(String(describing: platform)), insecure: \\(insecure)\")\n let img = try await Self.withAuthentication(ref: reference) { auth in\n try await self.imageStore.pull(\n reference: reference, platform: platform, insecure: insecure, auth: auth, progress: ContainerizationProgressAdapter.handler(from: progressUpdate))\n }\n guard let img else {\n throw ContainerizationError(.internalError, message: \"Failed to pull image \\(reference)\")\n }\n return img.description.fromCZ\n }\n\n public func push(reference: String, platform: Platform?, insecure: Bool, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference), platform: \\(String(describing: platform)), insecure: \\(insecure)\")\n try await Self.withAuthentication(ref: reference) { auth in\n try await self.imageStore.push(\n reference: reference, platform: platform, insecure: insecure, auth: auth, progress: ContainerizationProgressAdapter.handler(from: progressUpdate))\n }\n }\n\n public func tag(old: String, new: String) async throws -> ImageDescription {\n self.log.info(\"ImagesService: \\(#function) - old: \\(old), new: \\(new)\")\n let img = try await self.imageStore.tag(existing: old, new: new)\n return img.description.fromCZ\n }\n\n public func delete(reference: String, garbageCollect: Bool) async throws {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference)\")\n try await self.imageStore.delete(reference: reference, performCleanup: garbageCollect)\n }\n\n public func save(reference: String, out: URL, platform: Platform?) async throws {\n self.log.info(\"ImagesService: \\(#function) - reference: \\(reference) , platform: \\(String(describing: platform))\")\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try await self.imageStore.save(references: [reference], out: tempDir, platform: platform)\n let writer = try ArchiveWriter(format: .pax, filter: .none, file: out)\n try writer.archiveDirectory(tempDir)\n try writer.finishEncoding()\n }\n\n public func load(from tarFile: URL) async throws -> [ImageDescription] {\n self.log.info(\"ImagesService: \\(#function) from: \\(tarFile.absolutePath())\")\n let reader = try ArchiveReader(file: tarFile)\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try reader.extractContents(to: tempDir)\n let loaded = try await self.imageStore.load(from: tempDir)\n var images: [ImageDescription] = []\n for image in loaded {\n images.append(image.description.fromCZ)\n }\n return images\n }\n\n public func prune() async throws -> ([String], UInt64) {\n let images = try await self._list()\n let freedSnapshotBytes = try await self.snapshotStore.clean(keepingSnapshotsFor: images)\n let (deleted, freedContentBytes) = try await self.imageStore.prune()\n return (deleted, freedContentBytes + freedSnapshotBytes)\n }\n}\n\n// MARK: Image Snapshot Methods\n\nextension ImagesService {\n public func unpack(description: ImageDescription, platform: Platform?, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n try await self.snapshotStore.unpack(image: img, platform: platform, progressUpdate: progressUpdate)\n }\n\n public func deleteImageSnapshot(description: ImageDescription, platform: Platform?) async throws {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n try await self.snapshotStore.delete(for: img, platform: platform)\n }\n\n public func getImageSnapshot(description: ImageDescription, platform: Platform) async throws -> Filesystem {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n return try await self.snapshotStore.get(for: img, platform: platform)\n }\n}\n\n// MARK: Static Methods\n\nextension ImagesService {\n private static func withAuthentication(\n ref: String, _ body: @Sendable @escaping (_ auth: Authentication?) async throws -> T?\n ) async throws -> T? {\n var authentication: Authentication?\n let ref = try Reference.parse(ref)\n guard let host = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"No host specified in image reference: \\(ref)\")\n }\n authentication = Self.authenticationFromEnv(host: host)\n if let authentication {\n return try await body(authentication)\n }\n let keychain = KeychainHelper(id: Self.keychainID)\n do {\n authentication = try keychain.lookup(domain: host)\n } catch let err as KeychainHelper.Error {\n guard case .keyNotFound = err else {\n throw ContainerizationError(.internalError, message: \"Error querying keychain for \\(host)\", cause: err)\n }\n }\n do {\n return try await body(authentication)\n } catch let err as RegistryClient.Error {\n guard case .invalidStatus(_, let status, _) = err else {\n throw err\n }\n guard status == .unauthorized || status == .forbidden else {\n throw err\n }\n guard authentication != nil else {\n throw ContainerizationError(.internalError, message: \"\\(String(describing: err)). No credentials found for host \\(host)\")\n }\n throw err\n }\n }\n\n private static func authenticationFromEnv(host: String) -> Authentication? {\n let env = ProcessInfo.processInfo.environment\n guard env[\"CONTAINER_REGISTRY_HOST\"] == host else {\n return nil\n }\n guard let user = env[\"CONTAINER_REGISTRY_USER\"], let password = env[\"CONTAINER_REGISTRY_TOKEN\"] else {\n return nil\n }\n return BasicAuthentication(username: user, password: password)\n }\n}\n\nextension ImageDescription {\n public var toCZ: Containerization.Image.Description {\n .init(reference: self.reference, descriptor: self.descriptor)\n }\n}\n\nextension Containerization.Image.Description {\n public var fromCZ: ImageDescription {\n .init(\n reference: self.reference,\n descriptor: self.descriptor\n )\n }\n}\n"], ["/container/Sources/ContainerPlugin/Plugin.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\n/// Value type that contains the plugin configuration, the parsed name of the\n/// plugin and whether a CLI surface for the plugin was found.\npublic struct Plugin: Sendable, Codable {\n private static let machServicePrefix = \"com.apple.container.\"\n\n /// Pathname to installation directory for plugins.\n public let binaryURL: URL\n\n /// Configuration for the plugin.\n public let config: PluginConfig\n\n public init(binaryURL: URL, config: PluginConfig) {\n self.binaryURL = binaryURL\n self.config = config\n }\n}\n\nextension Plugin {\n public var name: String { binaryURL.lastPathComponent }\n\n public var shouldBoot: Bool {\n guard let config = self.config.servicesConfig else {\n return false\n }\n\n return config.loadAtBoot\n }\n\n public func getLaunchdLabel(instanceId: String? = nil) -> String {\n // Use the plugin name for the launchd label.\n guard let instanceId else {\n return \"\\(Self.machServicePrefix)\\(self.name)\"\n }\n return \"\\(Self.machServicePrefix)\\(self.name).\\(instanceId)\"\n }\n\n public func getMachServices(instanceId: String? = nil) -> [String] {\n // Use the service type for the mach service.\n guard let config = self.config.servicesConfig else {\n return []\n }\n var services = [String]()\n for service in config.services {\n let serviceName: String\n if let instanceId {\n serviceName = \"\\(Self.machServicePrefix)\\(service.type.rawValue).\\(name).\\(instanceId)\"\n } else {\n serviceName = \"\\(Self.machServicePrefix)\\(service.type.rawValue).\\(name)\"\n }\n services.append(serviceName)\n }\n return services\n }\n\n public func getMachService(instanceId: String? = nil, type: PluginConfig.DaemonPluginType) -> String? {\n guard hasType(type) else {\n return nil\n }\n\n guard let instanceId else {\n return \"\\(Self.machServicePrefix)\\(type.rawValue).\\(name)\"\n }\n return \"\\(Self.machServicePrefix)\\(type.rawValue).\\(name).\\(instanceId)\"\n }\n\n public func hasType(_ type: PluginConfig.DaemonPluginType) -> Bool {\n guard let config = self.config.servicesConfig else {\n return false\n }\n\n guard !(config.services.filter { $0.type == type }.isEmpty) else {\n return false\n }\n\n return true\n }\n}\n\nextension Plugin {\n public func exec(args: [String]) throws {\n var args = args\n let executable = self.binaryURL.path\n args[0] = executable\n let argv = args.map { strdup($0) } + [nil]\n guard execvp(executable, argv) != -1 else {\n throw POSIXError.fromErrno()\n }\n fatalError(\"unreachable\")\n }\n\n func helpText(padding: Int) -> String {\n guard !self.name.isEmpty else {\n return \"\"\n }\n let namePadded = name.padding(toLength: padding, withPad: \" \", startingAt: 0)\n return \" \" + namePadded + self.config.abstract\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientProcess.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport NIOCore\nimport NIOPosix\nimport TerminalProgress\n\n/// A protocol that defines the methods and data members available to a process\n/// started inside of a container.\npublic protocol ClientProcess: Sendable {\n /// Identifier for the process.\n var id: String { get }\n\n /// Start the underlying process inside of the container.\n func start(_ stdio: [FileHandle?]) async throws\n /// Send a terminal resize request to the process `id`.\n func resize(_ size: Terminal.Size) async throws\n /// Send or \"kill\" a signal to the process `id`.\n /// Kill does not wait for the process to exit, it only delivers the signal.\n func kill(_ signal: Int32) async throws\n /// Wait for the process `id` to complete and return its exit code.\n /// This method blocks until the process exits and the code is obtained.\n func wait() async throws -> Int32\n}\n\nstruct ClientProcessImpl: ClientProcess, Sendable {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n /// Identifier of the container.\n public let containerId: String\n\n private let client: SandboxClient\n\n /// Identifier of a process. That is running inside of a container.\n /// This field is nil if the process this objects refers to is the\n /// init process of the container.\n public let processId: String?\n\n public var id: String {\n processId ?? containerId\n }\n\n init(containerId: String, processId: String? = nil, client: SandboxClient) {\n self.containerId = containerId\n self.processId = processId\n self.client = client\n }\n\n /// Start the container and return the initial process.\n public func start(_ stdio: [FileHandle?]) async throws {\n do {\n let client = self.client\n try await client.startProcess(self.id, stdio: stdio)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to start container\",\n cause: error\n )\n }\n }\n\n public func kill(_ signal: Int32) async throws {\n do {\n\n let client = self.client\n try await client.kill(self.id, signal: Int64(signal))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill process\",\n cause: error\n )\n }\n }\n\n public func resize(_ size: ContainerizationOS.Terminal.Size) async throws {\n do {\n\n let client = self.client\n try await client.resize(self.id, size: size)\n\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to resize process\",\n cause: error\n )\n }\n }\n\n public func wait() async throws -> Int32 {\n do {\n let client = self.client\n return try await client.wait(self.id)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to wait on process\",\n cause: error\n )\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ImageDetail.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationOCI\n\npublic struct ImageDetail: Codable {\n public let name: String\n public let index: Descriptor\n public let variants: [Variants]\n\n public struct Variants: Codable {\n public let platform: Platform\n public let config: ContainerizationOCI.Image\n public let size: Int64\n\n init(platform: Platform, size: Int64, config: ContainerizationOCI.Image) {\n self.platform = platform\n self.config = config\n self.size = size\n }\n }\n\n init(name: String, index: Descriptor, variants: [Variants]) {\n self.name = name\n self.index = index\n self.variants = variants\n }\n}\n\nextension ClientImage {\n public func details() async throws -> ImageDetail {\n let indexDescriptor = self.descriptor\n let reference = self.reference\n var variants: [ImageDetail.Variants] = []\n for desc in try await self.index().manifests {\n guard let platform = desc.platform else {\n continue\n }\n let config: ContainerizationOCI.Image\n let manifest: ContainerizationOCI.Manifest\n do {\n config = try await self.config(for: platform)\n manifest = try await self.manifest(for: platform)\n } catch {\n continue\n }\n let size = desc.size + manifest.config.size + manifest.layers.reduce(0, { (l, r) in l + r.size })\n variants.append(.init(platform: platform, size: size, config: config))\n }\n return ImageDetail(name: reference, index: indexDescriptor, variants: variants)\n }\n}\n"], ["/container/Sources/ContainerClient/Archiver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationArchive\nimport ContainerizationOS\nimport Foundation\n\npublic final class Archiver: Sendable {\n public struct ArchiveEntryInfo: Sendable {\n let pathOnHost: URL\n let pathInArchive: URL\n\n public init(pathOnHost: URL, pathInArchive: URL) {\n self.pathOnHost = pathOnHost\n self.pathInArchive = pathInArchive\n }\n }\n\n public static func compress(\n source: URL,\n destination: URL,\n followSymlinks: Bool = false,\n writerConfiguration: ArchiveWriterConfiguration = ArchiveWriterConfiguration(format: .paxRestricted, filter: .gzip),\n closure: (URL) -> ArchiveEntryInfo?\n ) throws {\n let source = source.standardizedFileURL\n let destination = destination.standardizedFileURL\n\n let fileManager = FileManager.default\n try? fileManager.removeItem(at: destination)\n\n do {\n let directory = destination.deletingLastPathComponent()\n try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)\n\n guard\n let enumerator = FileManager.default.enumerator(\n at: source,\n includingPropertiesForKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]\n )\n else {\n throw Error.fileDoesNotExist(source)\n }\n\n var entryInfo = [ArchiveEntryInfo]()\n if !source.isDirectory {\n if let info = closure(source) {\n entryInfo.append(info)\n }\n } else {\n while let url = enumerator.nextObject() as? URL {\n guard let info = closure(url) else {\n continue\n }\n entryInfo.append(info)\n }\n }\n\n let archiver = try ArchiveWriter(\n configuration: writerConfiguration\n )\n try archiver.open(file: destination)\n\n for info in entryInfo {\n guard let entry = try Self._createEntry(entryInfo: info) else {\n throw Error.failedToCreateEntry\n }\n try Self._compressFile(item: info.pathOnHost, entry: entry, archiver: archiver)\n }\n try archiver.finishEncoding()\n } catch {\n try? fileManager.removeItem(at: destination)\n throw error\n }\n }\n\n public static func uncompress(source: URL, destination: URL) throws {\n let source = source.standardizedFileURL\n let destination = destination.standardizedFileURL\n\n // TODO: ArchiveReader needs some enhancement to support buffered uncompression\n let reader = try ArchiveReader(\n format: .paxRestricted,\n filter: .gzip,\n file: source\n )\n\n for (entry, data) in reader {\n guard let path = entry.path else {\n continue\n }\n let uncompressPath = destination.appendingPathComponent(path)\n\n let fileManager = FileManager.default\n switch entry.fileType {\n case .blockSpecial, .characterSpecial, .socket:\n continue\n case .directory:\n try fileManager.createDirectory(\n at: uncompressPath,\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: entry.permissions\n ]\n )\n case .regular:\n try fileManager.createDirectory(\n at: uncompressPath.deletingLastPathComponent(),\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: 0o755\n ]\n )\n let success = fileManager.createFile(\n atPath: uncompressPath.path,\n contents: data,\n attributes: [\n FileAttributeKey.posixPermissions: entry.permissions\n ]\n )\n if !success {\n throw POSIXError.fromErrno()\n }\n try data.write(to: uncompressPath)\n case .symbolicLink:\n guard let target = entry.symlinkTarget else {\n continue\n }\n try fileManager.createDirectory(\n at: uncompressPath.deletingLastPathComponent(),\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: 0o755\n ]\n )\n try fileManager.createSymbolicLink(atPath: uncompressPath.path, withDestinationPath: target)\n continue\n default:\n continue\n }\n\n // FIXME: uid/gid for compress.\n try fileManager.setAttributes(\n [.posixPermissions: NSNumber(value: entry.permissions)],\n ofItemAtPath: uncompressPath.path\n )\n\n if let creationDate = entry.creationDate {\n try fileManager.setAttributes(\n [.creationDate: creationDate],\n ofItemAtPath: uncompressPath.path\n )\n }\n\n if let modificationDate = entry.modificationDate {\n try fileManager.setAttributes(\n [.modificationDate: modificationDate],\n ofItemAtPath: uncompressPath.path\n )\n }\n }\n }\n\n // MARK: private functions\n private static func _compressFile(item: URL, entry: WriteEntry, archiver: ArchiveWriter) throws {\n guard let stream = InputStream(url: item) else {\n return\n }\n\n let writer = archiver.makeTransactionWriter()\n\n let bufferSize = Int(1.mib())\n let readBuffer = UnsafeMutablePointer.allocate(capacity: bufferSize)\n\n stream.open()\n try writer.writeHeader(entry: entry)\n while true {\n let byteRead = stream.read(readBuffer, maxLength: bufferSize)\n if byteRead <= 0 {\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n try data.withUnsafeBytes { pointer in\n try writer.writeChunk(data: pointer)\n }\n }\n }\n stream.close()\n try writer.finish()\n }\n\n private static func _createEntry(entryInfo: ArchiveEntryInfo, pathPrefix: String = \"\") throws -> WriteEntry? {\n let entry = WriteEntry()\n let fileManager = FileManager.default\n let attributes = try fileManager.attributesOfItem(atPath: entryInfo.pathOnHost.path)\n\n if let fileType = attributes[.type] as? FileAttributeType {\n switch fileType {\n case .typeBlockSpecial, .typeCharacterSpecial, .typeSocket:\n return nil\n case .typeDirectory:\n entry.fileType = .directory\n case .typeRegular:\n entry.fileType = .regular\n case .typeSymbolicLink:\n entry.fileType = .symbolicLink\n let symlinkTarget = try fileManager.destinationOfSymbolicLink(atPath: entryInfo.pathOnHost.path)\n entry.symlinkTarget = symlinkTarget\n default:\n return nil\n }\n }\n if let posixPermissions = attributes[.posixPermissions] as? NSNumber {\n #if os(macOS)\n entry.permissions = posixPermissions.uint16Value\n #else\n entry.permissions = posixPermissions.uint32Value\n #endif\n }\n if let fileSize = attributes[.size] as? UInt64 {\n entry.size = Int64(fileSize)\n }\n if let uid = attributes[.ownerAccountID] as? NSNumber {\n entry.owner = uid.uint32Value\n }\n if let gid = attributes[.groupOwnerAccountID] as? NSNumber {\n entry.group = gid.uint32Value\n }\n if let creationDate = attributes[.creationDate] as? Date {\n entry.creationDate = creationDate\n }\n if let modificationDate = attributes[.modificationDate] as? Date {\n entry.modificationDate = modificationDate\n }\n\n let pathTrimmed = Self._trimPathPrefix(entryInfo.pathInArchive.relativePath, pathPrefix: pathPrefix)\n entry.path = pathTrimmed\n return entry\n }\n\n private static func _trimPathPrefix(_ path: String, pathPrefix: String) -> String {\n guard !path.isEmpty && !pathPrefix.isEmpty else {\n return path\n }\n\n let decodedPath = path.removingPercentEncoding ?? path\n\n guard decodedPath.hasPrefix(pathPrefix) else {\n return decodedPath\n }\n let trimmedPath = String(decodedPath.suffix(from: pathPrefix.endIndex))\n return trimmedPath\n }\n\n private static func _isSymbolicLink(_ path: URL) throws -> Bool {\n let resourceValues = try path.resourceValues(forKeys: [.isSymbolicLinkKey])\n if let isSymbolicLink = resourceValues.isSymbolicLink {\n if isSymbolicLink {\n return true\n }\n }\n return false\n }\n}\n\nextension Archiver {\n public enum Error: Swift.Error, CustomStringConvertible {\n case failedToCreateEntry\n case fileDoesNotExist(_ url: URL)\n\n public var description: String {\n switch self {\n case .failedToCreateEntry:\n return \"failed to create entry\"\n case .fileDoesNotExist(let url):\n return \"file \\(url.path) does not exist\"\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildFSSync.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport ContainerClient\nimport ContainerizationArchive\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\n\nactor BuildFSSync: BuildPipelineHandler {\n let contextDir: URL\n\n init(_ contextDir: URL) throws {\n guard FileManager.default.fileExists(atPath: contextDir.cleanPath) else {\n throw Error.contextNotFound(contextDir.cleanPath)\n }\n guard try contextDir.isDir() else {\n throw Error.contextIsNotDirectory(contextDir.cleanPath)\n }\n\n self.contextDir = contextDir\n }\n\n nonisolated func accept(_ packet: ServerStream) throws -> Bool {\n guard let buildTransfer = packet.getBuildTransfer() else {\n return false\n }\n guard buildTransfer.stage() == \"fssync\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let buildTransfer = packet.getBuildTransfer() else {\n throw Error.buildTransferMissing\n }\n guard let method = buildTransfer.method() else {\n throw Error.methodMissing\n }\n switch try FSSyncMethod(method) {\n case .read:\n try await self.read(sender, buildTransfer, packet.buildID)\n case .info:\n try await self.info(sender, buildTransfer, packet.buildID)\n case .walk:\n try await self.walk(sender, buildTransfer, packet.buildID)\n }\n }\n\n func read(_ sender: AsyncStream.Continuation, _ packet: BuildTransfer, _ buildID: String) async throws {\n let offset: UInt64 = packet.offset() ?? 0\n let size: Int = packet.len() ?? 0\n var path: URL\n if packet.source.hasPrefix(\"/\") {\n path = URL(fileURLWithPath: packet.source).standardizedFileURL\n } else {\n path =\n contextDir\n .appendingPathComponent(packet.source)\n .standardizedFileURL\n }\n if !FileManager.default.fileExists(atPath: path.cleanPath) {\n path = URL(filePath: self.contextDir.cleanPath)\n path.append(components: packet.source.cleanPathComponent)\n }\n let data = try {\n if try path.isDir() {\n return Data()\n }\n let file = try LocalContent(path: path.standardizedFileURL)\n return try file.data(offset: offset, length: size) ?? Data()\n }()\n\n let transfer = try path.buildTransfer(id: packet.id, contextDir: self.contextDir, complete: true, data: data)\n var response = ClientStream()\n response.buildID = buildID\n response.buildTransfer = transfer\n response.packetType = .buildTransfer(transfer)\n sender.yield(response)\n }\n\n func info(_ sender: AsyncStream.Continuation, _ packet: BuildTransfer, _ buildID: String) async throws {\n let path: URL\n if packet.source.hasPrefix(\"/\") {\n path = URL(fileURLWithPath: packet.source).standardizedFileURL\n } else {\n path =\n contextDir\n .appendingPathComponent(packet.source)\n .standardizedFileURL\n }\n let transfer = try path.buildTransfer(id: packet.id, contextDir: self.contextDir, complete: true)\n var response = ClientStream()\n response.buildID = buildID\n response.buildTransfer = transfer\n response.packetType = .buildTransfer(transfer)\n sender.yield(response)\n }\n\n private struct DirEntry: Hashable {\n let url: URL\n let isDirectory: Bool\n let relativePath: String\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(relativePath)\n }\n\n static func == (lhs: DirEntry, rhs: DirEntry) -> Bool {\n lhs.relativePath == rhs.relativePath\n }\n }\n\n func walk(\n _ sender: AsyncStream.Continuation,\n _ packet: BuildTransfer,\n _ buildID: String\n ) async throws {\n let wantsTar = packet.mode() == \"tar\"\n\n var entries: [String: Set] = [:]\n let followPaths: [String] = packet.followPaths() ?? []\n\n let followPathsWalked = try walk(root: self.contextDir, includePatterns: followPaths)\n for url in followPathsWalked {\n guard self.contextDir.absoluteURL.cleanPath != url.absoluteURL.cleanPath else {\n continue\n }\n guard self.contextDir.parentOf(url) else {\n continue\n }\n\n let relPath = try url.relativeChildPath(to: contextDir)\n let parentPath = try url.deletingLastPathComponent().relativeChildPath(to: contextDir)\n let entry = DirEntry(url: url, isDirectory: url.hasDirectoryPath, relativePath: relPath)\n entries[parentPath, default: []].insert(entry)\n\n if url.isSymlink {\n let target: URL = url.resolvingSymlinksInPath()\n if self.contextDir.parentOf(target) {\n let relPath = try target.relativeChildPath(to: self.contextDir)\n let entry = DirEntry(url: target, isDirectory: target.hasDirectoryPath, relativePath: relPath)\n let parentPath: String = try target.deletingLastPathComponent().relativeChildPath(to: self.contextDir)\n entries[parentPath, default: []].insert(entry)\n }\n }\n }\n\n var fileOrder = [String]()\n try processDirectory(\"\", inputEntries: entries, processedPaths: &fileOrder)\n\n if !wantsTar {\n let fileInfos = try fileOrder.map { rel -> FileInfo in\n try FileInfo(path: contextDir.appendingPathComponent(rel), contextDir: contextDir)\n }\n\n let data = try JSONEncoder().encode(fileInfos)\n let transfer = BuildTransfer(\n id: packet.id,\n source: packet.source,\n complete: true,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"json\",\n ],\n data: data\n )\n var resp = ClientStream()\n resp.buildID = buildID\n resp.buildTransfer = transfer\n resp.packetType = .buildTransfer(transfer)\n sender.yield(resp)\n return\n }\n\n let tarURL = URL.temporaryDirectory\n .appendingPathComponent(UUID().uuidString + \".tar\")\n\n defer { try? FileManager.default.removeItem(at: tarURL) }\n\n let writerCfg = ArchiveWriterConfiguration(\n format: .paxRestricted,\n filter: .none)\n\n try Archiver.compress(\n source: contextDir,\n destination: tarURL,\n writerConfiguration: writerCfg\n ) { url in\n guard let rel = try? url.relativeChildPath(to: contextDir) else {\n return nil\n }\n\n guard let parent = try? url.deletingLastPathComponent().relativeChildPath(to: self.contextDir) else {\n return nil\n }\n\n guard let items = entries[parent] else {\n return nil\n }\n\n let include = items.contains { item in\n item.relativePath == rel\n }\n\n guard include else {\n return nil\n }\n\n return Archiver.ArchiveEntryInfo(\n pathOnHost: url,\n pathInArchive: URL(fileURLWithPath: rel))\n }\n\n for try await chunk in try tarURL.bufferedCopyReader() {\n let part = BuildTransfer(\n id: packet.id,\n source: tarURL.path,\n complete: false,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"tar\",\n ],\n data: chunk\n )\n var resp = ClientStream()\n resp.buildID = buildID\n resp.buildTransfer = part\n resp.packetType = .buildTransfer(part)\n sender.yield(resp)\n }\n\n let done = BuildTransfer(\n id: packet.id,\n source: tarURL.path,\n complete: true,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"tar\",\n ],\n data: Data()\n )\n\n var finalResp = ClientStream()\n finalResp.buildID = buildID\n finalResp.buildTransfer = done\n finalResp.packetType = .buildTransfer(done)\n sender.yield(finalResp)\n }\n\n func walk(root: URL, includePatterns: [String]) throws -> [URL] {\n let globber = Globber(root)\n\n for p in includePatterns {\n try globber.match(p)\n }\n return Array(globber.results)\n }\n\n private func processDirectory(\n _ currentDir: String,\n inputEntries: [String: Set],\n processedPaths: inout [String]\n ) throws {\n guard let entries = inputEntries[currentDir] else {\n return\n }\n\n // Sort purely by lexicographical order of relativePath\n let sortedEntries = entries.sorted { $0.relativePath < $1.relativePath }\n\n for entry in sortedEntries {\n processedPaths.append(entry.relativePath)\n\n if entry.isDirectory {\n try processDirectory(\n entry.relativePath,\n inputEntries: inputEntries,\n processedPaths: &processedPaths\n )\n }\n }\n }\n\n struct FileInfo: Codable {\n let name: String\n let modTime: String\n let mode: UInt32\n let size: UInt64\n let isDir: Bool\n let uid: UInt32\n let gid: UInt32\n let target: String\n\n init(path: URL, contextDir: URL) throws {\n if path.isSymlink {\n let target: URL = path.resolvingSymlinksInPath()\n if contextDir.parentOf(target) {\n self.target = target.relativePathFrom(from: path)\n } else {\n self.target = target.cleanPath\n }\n } else {\n self.target = \"\"\n }\n\n self.name = try path.relativeChildPath(to: contextDir)\n self.modTime = try path.modTime()\n self.mode = try path.mode()\n self.size = try path.size()\n self.isDir = path.hasDirectoryPath\n self.uid = 0\n self.gid = 0\n }\n }\n\n enum FSSyncMethod: String {\n case read = \"Read\"\n case info = \"Info\"\n case walk = \"Walk\"\n\n init(_ method: String) throws {\n switch method {\n case \"Read\":\n self = .read\n case \"Info\":\n self = .info\n case \"Walk\":\n self = .walk\n default:\n throw Error.unknownMethod(method)\n }\n }\n }\n}\n\nextension BuildFSSync {\n enum Error: Swift.Error, CustomStringConvertible, Equatable {\n case buildTransferMissing\n case methodMissing\n case unknownMethod(String)\n case contextNotFound(String)\n case contextIsNotDirectory(String)\n case couldNotDetermineFileSize(String)\n case couldNotDetermineModTime(String)\n case couldNotDetermineFileMode(String)\n case invalidOffsetSizeForFile(String, UInt64, Int)\n case couldNotDetermineUID(String)\n case couldNotDetermineGID(String)\n case pathIsNotChild(String, String)\n\n var description: String {\n switch self {\n case .buildTransferMissing:\n return \"buildTransfer field missing in packet\"\n case .methodMissing:\n return \"method is missing in request\"\n case .unknownMethod(let m):\n return \"unknown content-store method \\(m)\"\n case .contextNotFound(let path):\n return \"context dir \\(path) not found\"\n case .contextIsNotDirectory(let path):\n return \"context \\(path) not a directory\"\n case .couldNotDetermineFileSize(let path):\n return \"could not determine size of file \\(path)\"\n case .couldNotDetermineModTime(let path):\n return \"could not determine last modified time of \\(path)\"\n case .couldNotDetermineFileMode(let path):\n return \"could not determine posix permissions (FileMode) of \\(path)\"\n case .invalidOffsetSizeForFile(let digest, let offset, let size):\n return \"invalid request for file: \\(digest) with offset: \\(offset) size: \\(size)\"\n case .couldNotDetermineUID(let path):\n return \"could not determine UID of file at path: \\(path)\"\n case .couldNotDetermineGID(let path):\n return \"could not determine GID of file at path: \\(path)\"\n case .pathIsNotChild(let path, let parent):\n return \"\\(path) is not a child of \\(parent)\"\n }\n }\n }\n}\n\nextension BuildTransfer {\n fileprivate init(id: String, source: String, complete: Bool, isDir: Bool, metadata: [String: String], data: Data? = nil) {\n self.init()\n self.id = id\n self.source = source\n self.direction = .outof\n self.complete = complete\n self.metadata = metadata\n self.isDirectory = isDir\n if let data {\n self.data = data\n }\n }\n}\n\nextension URL {\n fileprivate func size() throws -> UInt64 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let size = attrs[FileAttributeKey.size] as? UInt64 {\n return size\n }\n throw BuildFSSync.Error.couldNotDetermineFileSize(self.cleanPath)\n }\n\n fileprivate func modTime() throws -> String {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let date = attrs[FileAttributeKey.modificationDate] as? Date {\n return date.rfc3339()\n }\n throw BuildFSSync.Error.couldNotDetermineModTime(self.cleanPath)\n }\n\n fileprivate func isDir() throws -> Bool {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n guard let t = attrs[.type] as? FileAttributeType, t == .typeDirectory else {\n return false\n }\n return true\n }\n\n fileprivate func mode() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let mode = attrs[FileAttributeKey.posixPermissions] as? NSNumber {\n return mode.uint32Value\n }\n throw BuildFSSync.Error.couldNotDetermineFileMode(self.cleanPath)\n }\n\n fileprivate func uid() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let uid = attrs[.ownerAccountID] as? UInt32 {\n return uid\n }\n throw BuildFSSync.Error.couldNotDetermineUID(self.cleanPath)\n }\n\n fileprivate func gid() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let gid = attrs[.groupOwnerAccountID] as? UInt32 {\n return gid\n }\n throw BuildFSSync.Error.couldNotDetermineGID(self.cleanPath)\n }\n\n fileprivate func buildTransfer(\n id: String,\n contextDir: URL? = nil,\n complete: Bool = false,\n data: Data = Data()\n ) throws -> BuildTransfer {\n let p = try {\n if let contextDir { return try self.relativeChildPath(to: contextDir) }\n return self.cleanPath\n }()\n return BuildTransfer(\n id: id,\n source: String(p),\n complete: complete,\n isDir: try self.isDir(),\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": String(try self.mode()),\n \"size\": String(try self.size()),\n \"modified_at\": try self.modTime(),\n \"uid\": String(try self.uid()),\n \"gid\": String(try self.gid()),\n ],\n data: data\n )\n }\n}\n\nextension Date {\n fileprivate func rfc3339() -> String {\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"yyyy-MM-dd'T'HH:mm:ssZZZZZ\"\n dateFormatter.locale = Locale(identifier: \"en_US_POSIX\")\n dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // Adjust if necessary\n\n return dateFormatter.string(from: self)\n }\n}\n\nextension String {\n var cleanPathComponent: String {\n let trimmed = self.trimmingCharacters(in: CharacterSet(charactersIn: \"/\"))\n if let clean = trimmed.removingPercentEncoding {\n return clean\n }\n return trimmed\n }\n}\n"], ["/container/Sources/APIServer/Kernel/KernelService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\nimport TerminalProgress\n\nactor KernelService {\n private static let defaultKernelNamePrefix: String = \"default.kernel-\"\n\n private let log: Logger\n private let kernelDirectory: URL\n\n public init(log: Logger, appRoot: URL) throws {\n self.log = log\n self.kernelDirectory = appRoot.appending(path: \"kernels\")\n try FileManager.default.createDirectory(at: self.kernelDirectory, withIntermediateDirectories: true)\n }\n\n /// Copies a kernel binary from a local path on disk into the managed kernels directory\n /// as the default kernel for the provided platform.\n public func installKernel(kernelFile url: URL, platform: SystemPlatform = .linuxArm) throws {\n self.log.info(\"KernelService: \\(#function) - kernelFile: \\(url), platform: \\(String(describing: platform))\")\n let kFile = url.resolvingSymlinksInPath()\n let destPath = self.kernelDirectory.appendingPathComponent(kFile.lastPathComponent)\n try FileManager.default.copyItem(at: kFile, to: destPath)\n try Task.checkCancellation()\n do {\n try self.setDefaultKernel(name: kFile.lastPathComponent, platform: platform)\n } catch {\n try? FileManager.default.removeItem(at: destPath)\n throw error\n }\n }\n\n /// Copies a kernel binary from inside of tar file into the managed kernels directory\n /// as the default kernel for the provided platform.\n /// The parameter `tar` maybe a location to a local file on disk, or a remote URL.\n public func installKernelFrom(tar: URL, kernelFilePath: String, platform: SystemPlatform, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"KernelService: \\(#function) - tar: \\(tar), kernelFilePath: \\(kernelFilePath), platform: \\(String(describing: platform))\")\n\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n\n await progressUpdate?([\n .setDescription(\"Downloading kernel\")\n ])\n let taskManager = ProgressTaskCoordinator()\n let downloadTask = await taskManager.startTask()\n var tarFile = tar\n if !FileManager.default.fileExists(atPath: tar.absoluteString) {\n self.log.debug(\"KernelService: Downloading \\(tar)\")\n tarFile = tempDir.appendingPathComponent(tar.lastPathComponent)\n var downloadProgressUpdate: ProgressUpdateHandler?\n if let progressUpdate {\n downloadProgressUpdate = ProgressTaskCoordinator.handler(for: downloadTask, from: progressUpdate)\n }\n try await FileDownloader.downloadFile(url: tar, to: tarFile, progressUpdate: downloadProgressUpdate)\n }\n await taskManager.finish()\n\n await progressUpdate?([\n .setDescription(\"Unpacking kernel\")\n ])\n let archiveReader = try ArchiveReader(file: tarFile)\n let kernelFile = try archiveReader.extractFile(from: kernelFilePath, to: tempDir)\n try self.installKernel(kernelFile: kernelFile, platform: platform)\n\n if !FileManager.default.fileExists(atPath: tar.absoluteString) {\n try FileManager.default.removeItem(at: tarFile)\n }\n }\n\n private func setDefaultKernel(name: String, platform: SystemPlatform) throws {\n self.log.info(\"KernelService: \\(#function) - name: \\(name), platform: \\(String(describing: platform))\")\n let kernelPath = self.kernelDirectory.appendingPathComponent(name)\n guard FileManager.default.fileExists(atPath: kernelPath.path) else {\n throw ContainerizationError(.notFound, message: \"Kernel not found at \\(kernelPath)\")\n }\n let name = \"\\(Self.defaultKernelNamePrefix)\\(platform.architecture)\"\n let defaultKernelPath = self.kernelDirectory.appendingPathComponent(name)\n try? FileManager.default.removeItem(at: defaultKernelPath)\n try FileManager.default.createSymbolicLink(at: defaultKernelPath, withDestinationURL: kernelPath)\n }\n\n public func getDefaultKernel(platform: SystemPlatform = .linuxArm) async throws -> Kernel {\n self.log.info(\"KernelService: \\(#function) - platform: \\(String(describing: platform))\")\n let name = \"\\(Self.defaultKernelNamePrefix)\\(platform.architecture)\"\n let defaultKernelPath = self.kernelDirectory.appendingPathComponent(name).resolvingSymlinksInPath()\n guard FileManager.default.fileExists(atPath: defaultKernelPath.path) else {\n throw ContainerizationError(.notFound, message: \"Default kernel not found at \\(defaultKernelPath)\")\n }\n return Kernel(path: defaultKernelPath, platform: platform)\n }\n}\n\nextension ArchiveReader {\n fileprivate func extractFile(from: String, to directory: URL) throws -> URL {\n let (_, data) = try self.extractFile(path: from)\n try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)\n let fileName = URL(filePath: from).lastPathComponent\n let fileURL = directory.appendingPathComponent(fileName)\n try data.write(to: fileURL, options: .atomic)\n return fileURL\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/ExitMonitor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\n/// Track when long running work exits, and notify the caller via a callback.\npublic actor ExitMonitor {\n /// A callback that receives the client identifier and exit code.\n public typealias ExitCallback = @Sendable (String, Int32) async throws -> Void\n\n /// A function that waits for work to complete, returning an exit code.\n public typealias WaitHandler = @Sendable () async throws -> Int32\n\n /// Create a new monitor.\n ///\n /// - Parameters:\n /// - log: The destination for log messages.\n public init(log: Logger? = nil) {\n self.log = log\n }\n\n private var exitCallbacks: [String: ExitCallback] = [:]\n private var runningTasks: [String: Task] = [:]\n private let log: Logger?\n\n /// Remove tracked work from the monitor.\n ///\n /// - Parameters:\n /// - id: The client identifier for the tracked work.\n public func stopTracking(id: String) async {\n if let task = self.runningTasks[id] {\n task.cancel()\n }\n exitCallbacks.removeValue(forKey: id)\n runningTasks.removeValue(forKey: id)\n }\n\n /// Register long running work so that the monitor invokes\n /// a callback when the work completes.\n ///\n /// - Parameters:\n /// - id: The client identifier for the work.\n /// - onExit: The callback to invoke when the work completes.\n public func registerProcess(id: String, onExit: @escaping ExitCallback) async throws {\n guard self.exitCallbacks[id] == nil else {\n throw ContainerizationError(.invalidState, message: \"ExitMonitor already setup for process \\(id)\")\n }\n self.exitCallbacks[id] = onExit\n }\n\n /// Await the completion of previously registered item of work.\n ///\n /// - Parameters:\n /// - id: The client identifier for the work.\n /// - waitingOn: A function that waits for the work to complete,\n /// and then returns an exit code.\n public func track(id: String, waitingOn: @escaping WaitHandler) async throws {\n guard let onExit = self.exitCallbacks[id] else {\n throw ContainerizationError(.invalidState, message: \"ExitMonitor not setup for process \\(id)\")\n }\n guard self.runningTasks[id] == nil else {\n throw ContainerizationError(.invalidState, message: \"Already have a running task tracking process \\(id)\")\n }\n self.runningTasks[id] = Task {\n do {\n let exitStatus = try await waitingOn()\n try await onExit(id, exitStatus)\n } catch {\n self.log?.error(\"WaitHandler for \\(id) threw error \\(String(describing: error))\")\n try? await onExit(id, -1)\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension String {\n fileprivate var fs_cleaned: String {\n var value = self\n\n if value.hasPrefix(\"file://\") {\n value.removeFirst(\"file://\".count)\n }\n\n if value.count > 1 && value.last == \"/\" {\n value.removeLast()\n }\n\n return value.removingPercentEncoding ?? value\n }\n\n fileprivate var fs_components: [String] {\n var parts: [String] = []\n for segment in self.split(separator: \"/\", omittingEmptySubsequences: true) {\n switch segment {\n case \".\":\n continue\n case \"..\":\n if !parts.isEmpty { parts.removeLast() }\n default:\n parts.append(String(segment))\n }\n }\n return parts\n }\n\n fileprivate var fs_isAbsolute: Bool { first == \"/\" }\n}\n\nextension URL {\n var cleanPath: String {\n self.path.fs_cleaned\n }\n\n func parentOf(_ url: URL) -> Bool {\n let parentPath = self.absoluteURL.cleanPath\n let childPath = url.absoluteURL.cleanPath\n\n guard parentPath.fs_isAbsolute else {\n return true\n }\n\n let parentParts = parentPath.fs_components\n let childParts = childPath.fs_components\n\n guard parentParts.count <= childParts.count else { return false }\n return zip(parentParts, childParts).allSatisfy { $0 == $1 }\n }\n\n func relativeChildPath(to context: URL) throws -> String {\n guard context.parentOf(self) else {\n throw BuildFSSync.Error.pathIsNotChild(cleanPath, context.cleanPath)\n }\n\n let ctxParts = context.cleanPath.fs_components\n let selfParts = cleanPath.fs_components\n\n return selfParts.dropFirst(ctxParts.count).joined(separator: \"/\")\n }\n\n func relativePathFrom(from base: URL) -> String {\n let destParts = cleanPath.fs_components\n let baseParts = base.cleanPath.fs_components\n\n let common = zip(destParts, baseParts).prefix { $0 == $1 }.count\n guard common > 0 else { return cleanPath }\n\n let ups = Array(repeating: \"..\", count: baseParts.count - common)\n let remainder = destParts.dropFirst(common)\n return (ups + remainder).joined(separator: \"/\")\n }\n\n func zeroCopyReader(\n chunk: Int = 1024 * 1024,\n buffer: AsyncStream.Continuation.BufferingPolicy = .unbounded\n ) throws -> AsyncStream {\n\n let path = self.cleanPath\n let fd = open(path, O_RDONLY | O_NONBLOCK)\n guard fd >= 0 else { throw POSIXError.fromErrno() }\n\n let channel = DispatchIO(\n type: .stream,\n fileDescriptor: fd,\n queue: .global(qos: .userInitiated)\n ) { errno in\n close(fd)\n }\n\n channel.setLimit(highWater: chunk)\n return AsyncStream(bufferingPolicy: buffer) { continuation in\n\n channel.read(\n offset: 0, length: Int.max,\n queue: .global(qos: .userInitiated)\n ) { done, ddata, err in\n if err != 0 {\n continuation.finish()\n return\n }\n\n if let ddata, ddata.count > -1 {\n let data = Data(ddata)\n\n switch continuation.yield(data) {\n case .terminated:\n channel.close(flags: .stop)\n default: break\n }\n }\n\n if done {\n channel.close(flags: .stop)\n continuation.finish()\n }\n }\n }\n }\n\n func bufferedCopyReader(chunkSize: Int = 4 * 1024 * 1024) throws -> BufferedCopyReader {\n try BufferedCopyReader(url: self, chunkSize: chunkSize)\n }\n}\n\n/// A synchronous buffered reader that reads one chunk at a time from a file\n/// Uses a configurable buffer size (default 4MB) and only reads when nextChunk() is called\n/// Implements AsyncSequence for use with `for await` loops\npublic final class BufferedCopyReader: AsyncSequence {\n public typealias Element = Data\n public typealias AsyncIterator = BufferedCopyReaderIterator\n\n private let inputStream: InputStream\n private let chunkSize: Int\n private var isFinished: Bool = false\n private let reusableBuffer: UnsafeMutablePointer\n\n /// Initialize a buffered copy reader for the given URL\n /// - Parameters:\n /// - url: The file URL to read from\n /// - chunkSize: Size of each chunk to read (default: 4MB)\n public init(url: URL, chunkSize: Int = 4 * 1024 * 1024) throws {\n guard let stream = InputStream(url: url) else {\n throw CocoaError(.fileReadNoSuchFile)\n }\n self.inputStream = stream\n self.chunkSize = chunkSize\n self.reusableBuffer = UnsafeMutablePointer.allocate(capacity: chunkSize)\n self.inputStream.open()\n }\n\n deinit {\n inputStream.close()\n reusableBuffer.deallocate()\n }\n\n /// Create an async iterator for this sequence\n public func makeAsyncIterator() -> BufferedCopyReaderIterator {\n BufferedCopyReaderIterator(reader: self)\n }\n\n /// Read the next chunk of data from the file\n /// - Returns: Data chunk, or nil if end of file reached\n /// - Throws: Any file reading errors\n public func nextChunk() throws -> Data? {\n guard !isFinished else { return nil }\n\n // Read directly into our reusable buffer\n let bytesRead = inputStream.read(reusableBuffer, maxLength: chunkSize)\n\n // Check for errors\n if bytesRead < 0 {\n if let error = inputStream.streamError {\n throw error\n }\n throw CocoaError(.fileReadUnknown)\n }\n\n // If we read no data, we've reached the end\n if bytesRead == 0 {\n isFinished = true\n return nil\n }\n\n // If we read less than the chunk size, this is the last chunk\n if bytesRead < chunkSize {\n isFinished = true\n }\n\n // Create Data object only with the bytes actually read\n return Data(bytes: reusableBuffer, count: bytesRead)\n }\n\n /// Check if the reader has finished reading the file\n public var hasFinished: Bool {\n isFinished\n }\n\n /// Reset the reader to the beginning of the file\n /// Note: InputStream doesn't support seeking, so this recreates the stream\n /// - Throws: Any file opening errors\n public func reset() throws {\n inputStream.close()\n // Note: InputStream doesn't provide a way to get the original URL,\n // so reset functionality is limited. Consider removing this method\n // or storing the original URL if reset is needed.\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Reset not supported with InputStream-based implementation\"\n ])\n }\n\n /// Get the current file offset\n /// Note: InputStream doesn't provide offset information\n /// - Returns: Current position in the file\n /// - Throws: Unsupported operation error\n public func currentOffset() throws -> UInt64 {\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Offset tracking not supported with InputStream-based implementation\"\n ])\n }\n\n /// Seek to a specific offset in the file\n /// Note: InputStream doesn't support seeking\n /// - Parameter offset: The byte offset to seek to\n /// - Throws: Unsupported operation error\n public func seek(to offset: UInt64) throws {\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Seeking not supported with InputStream-based implementation\"\n ])\n }\n\n /// Close the input stream explicitly (called automatically in deinit)\n public func close() {\n inputStream.close()\n isFinished = true\n }\n}\n\n/// AsyncIteratorProtocol implementation for BufferedCopyReader\npublic struct BufferedCopyReaderIterator: AsyncIteratorProtocol {\n public typealias Element = Data\n\n private let reader: BufferedCopyReader\n\n init(reader: BufferedCopyReader) {\n self.reader = reader\n }\n\n /// Get the next chunk of data asynchronously\n /// - Returns: Next data chunk, or nil when finished\n /// - Throws: Any file reading errors\n public mutating func next() async throws -> Data? {\n // Yield control to allow other tasks to run, then read synchronously\n await Task.yield()\n return try reader.nextChunk()\n }\n}\n"], ["/container/Sources/APIServer/Networks/NetworksHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nstruct NetworksHarness: Sendable {\n let log: Logging.Logger\n let service: NetworksService\n\n init(service: NetworksService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let containers = try await service.list()\n let data = try JSONEncoder().encode(containers)\n\n let reply = message.reply()\n reply.set(key: .networkStates, value: data)\n return reply\n }\n\n @Sendable\n func create(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .networkConfig)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"network configuration cannot be empty\")\n }\n\n let config = try JSONDecoder().decode(NetworkConfiguration.self, from: data)\n let networkState = try await service.create(configuration: config)\n\n let networkData = try JSONEncoder().encode(networkState)\n\n let reply = message.reply()\n reply.set(key: .networkState, value: networkData)\n return reply\n }\n\n @Sendable\n func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .networkId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"id cannot be empty\")\n }\n try await service.delete(id: id)\n\n return message.reply()\n }\n}\n"], ["/container/Sources/ContainerPlugin/ServiceManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\npublic struct ServiceManager {\n private static func runLaunchctlCommand(args: [String]) throws -> Int32 {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = args\n\n let null = FileHandle.nullDevice\n launchctl.standardOutput = null\n launchctl.standardError = null\n\n try launchctl.run()\n launchctl.waitUntilExit()\n\n return launchctl.terminationStatus\n }\n\n /// Register a service by providing the path to a plist.\n public static func register(plistPath: String) throws {\n let domain = try Self.getDomainString()\n _ = try runLaunchctlCommand(args: [\"bootstrap\", domain, plistPath])\n }\n\n /// Deregister a service by a launchd label.\n public static func deregister(fullServiceLabel label: String) throws {\n _ = try runLaunchctlCommand(args: [\"bootout\", label])\n }\n\n /// Restart a service by a launchd label.\n public static func kickstart(fullServiceLabel label: String) throws {\n _ = try runLaunchctlCommand(args: [\"kickstart\", \"-k\", label])\n }\n\n /// Send a signal to a service by a launchd label.\n public static func kill(fullServiceLabel label: String, signal: Int32 = 15) throws {\n _ = try runLaunchctlCommand(args: [\"kill\", \"\\(signal)\", label])\n }\n\n /// Retrieve labels for all loaded launch units.\n public static func enumerate() throws -> [String] {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = [\"list\"]\n\n let stdoutPipe = Pipe()\n let stderrPipe = Pipe()\n launchctl.standardOutput = stdoutPipe\n launchctl.standardError = stderrPipe\n\n try launchctl.run()\n let outputData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()\n let stderrData = stderrPipe.fileHandleForReading.readDataToEndOfFile()\n launchctl.waitUntilExit()\n let status = launchctl.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(\n .internalError, message: \"Command `launchctl list` failed with status \\(status). Message: \\(String(data: stderrData, encoding: .utf8) ?? \"No error message\")\")\n }\n\n guard let outputText = String(data: outputData, encoding: .utf8) else {\n throw ContainerizationError(\n .internalError, message: \"Could not decode output of command `launchctl list`. Message: \\(String(data: stderrData, encoding: .utf8) ?? \"No error message\")\")\n }\n\n // The third field of each line of launchctl list output is the label\n return outputText.split { $0.isNewline }\n .map { String($0).split { $0.isWhitespace } }\n .filter { $0.count >= 3 }\n .map { String($0[2]) }\n }\n\n /// Check if a service has been registered or not.\n public static func isRegistered(fullServiceLabel label: String) throws -> Bool {\n let exitStatus = try runLaunchctlCommand(args: [\"list\", label])\n return exitStatus == 0\n }\n\n private static func getLaunchdSessionType() throws -> String {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = [\"managername\"]\n\n let null = FileHandle.nullDevice\n let stdoutPipe = Pipe()\n launchctl.standardOutput = stdoutPipe\n launchctl.standardError = null\n\n try launchctl.run()\n let outputData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()\n launchctl.waitUntilExit()\n let status = launchctl.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(.internalError, message: \"Command `launchctl managername` failed with status \\(status)\")\n }\n guard let outputText = String(data: outputData, encoding: .utf8) else {\n throw ContainerizationError(.internalError, message: \"Could not decode output of command `launchctl managername`\")\n }\n return outputText.trimmingCharacters(in: .whitespacesAndNewlines)\n }\n\n public static func getDomainString() throws -> String {\n let currentSessionType = try getLaunchdSessionType()\n switch currentSessionType {\n case LaunchPlist.Domain.System.rawValue:\n return LaunchPlist.Domain.System.rawValue.lowercased()\n case LaunchPlist.Domain.Background.rawValue:\n return \"user/\\(getuid())\"\n case LaunchPlist.Domain.Aqua.rawValue:\n return \"gui/\\(getuid())\"\n default:\n throw ContainerizationError(.internalError, message: \"Unsupported session type \\(currentSessionType)\")\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\npublic struct ClientNetwork {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n\n public static let defaultNetworkName = \"default\"\n}\n\nextension ClientNetwork {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n private static func xpcSend(\n client: XPCClient,\n message: XPCMessage,\n timeout: Duration? = .seconds(15)\n ) async throws -> XPCMessage {\n try await client.send(message, responseTimeout: timeout)\n }\n\n public static func create(configuration: NetworkConfiguration) async throws -> NetworkState {\n let client = Self.newClient()\n let request = XPCMessage(route: .networkCreate)\n request.set(key: .networkId, value: configuration.id)\n\n let data = try JSONEncoder().encode(configuration)\n request.set(key: .networkConfig, value: data)\n\n let response = try await xpcSend(client: client, message: request)\n let responseData = response.dataNoCopy(key: .networkState)\n guard let responseData else {\n throw ContainerizationError(.invalidArgument, message: \"network configuration not received\")\n }\n let state = try JSONDecoder().decode(NetworkState.self, from: responseData)\n return state\n }\n\n public static func list() async throws -> [NetworkState] {\n let client = Self.newClient()\n let request = XPCMessage(route: .networkList)\n\n let response = try await xpcSend(client: client, message: request, timeout: .seconds(1))\n let responseData = response.dataNoCopy(key: .networkStates)\n guard let responseData else {\n return []\n }\n let states = try JSONDecoder().decode([NetworkState].self, from: responseData)\n return states\n }\n\n /// Get the network for the provided id.\n public static func get(id: String) async throws -> NetworkState {\n let networks = try await list()\n guard let network = networks.first(where: { $0.id == id }) else {\n throw ContainerizationError(.notFound, message: \"network \\(id) not found\")\n }\n return network\n }\n\n /// Delete the network with the given id.\n public static func delete(id: String) async throws {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .networkDelete)\n request.set(key: .networkId, value: id)\n try await client.send(request)\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePrune.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\n\nextension Application {\n struct ImagePrune: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"prune\",\n abstract: \"Remove unreferenced and dangling images\")\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let (_, size) = try await ClientImage.pruneImages()\n let formatter = ByteCountFormatter()\n let freed = formatter.string(fromByteCount: Int64(size))\n print(\"Cleaned unreferenced images and snapshots\")\n print(\"Reclaimed \\(freed) in disk space\")\n }\n }\n}\n"], ["/container/Sources/CLI/DefaultCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\n\nstruct DefaultCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: nil,\n shouldDisplay: false\n )\n\n @OptionGroup(visibility: .hidden)\n var global: Flags.Global\n\n @Argument(parsing: .captureForPassthrough)\n var remaining: [String] = []\n\n func run() async throws {\n // See if we have a possible plugin command.\n guard let command = remaining.first else {\n Application.printModifiedHelpText()\n return\n }\n\n // Check for edge cases and unknown options to match the behavior in the absence of plugins.\n if command.isEmpty {\n throw ValidationError(\"Unknown argument '\\(command)'\")\n } else if command.starts(with: \"-\") {\n throw ValidationError(\"Unknown option '\\(command)'\")\n }\n\n let pluginLoader = Application.pluginLoader\n guard let plugin = pluginLoader.findPlugin(name: command), plugin.config.isCLI else {\n throw ValidationError(\"failed to find plugin named container-\\(command)\")\n }\n // Exec performs execvp (with no fork).\n try plugin.exec(args: remaining)\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildImageResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\nimport Logging\n\nstruct BuildImageResolver: BuildPipelineHandler {\n let contentStore: ContentStore\n\n public init(_ contentStore: ContentStore) throws {\n self.contentStore = contentStore\n }\n\n func accept(_ packet: ServerStream) throws -> Bool {\n guard let imageTransfer = packet.getImageTransfer() else {\n return false\n }\n guard imageTransfer.stage() == \"resolver\" else {\n return false\n }\n guard imageTransfer.method() == \"/resolve\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let imageTransfer = packet.getImageTransfer() else {\n throw Error.imageTransferMissing\n }\n guard let ref = imageTransfer.ref() else {\n throw Error.tagMissing\n }\n\n guard let platform = try imageTransfer.platform() else {\n throw Error.platformMissing\n }\n\n let img = try await {\n guard let img = try? await ClientImage.pull(reference: ref, platform: platform) else {\n return try await ClientImage.fetch(reference: ref, platform: platform)\n }\n return img\n }()\n\n let index: Index = try await img.index()\n let buildID = packet.buildID\n let platforms = index.manifests.compactMap { $0.platform }\n for pl in platforms {\n if pl == platform {\n let manifest = try await img.manifest(for: pl)\n guard let ociImage: ContainerizationOCI.Image = try await self.contentStore.get(digest: manifest.config.digest) else {\n continue\n }\n let enc = JSONEncoder()\n let data = try enc.encode(ociImage)\n let transfer = try ImageTransfer(\n id: imageTransfer.id,\n digest: img.descriptor.digest,\n ref: ref,\n platform: platform.description,\n data: data\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n return\n }\n }\n throw Error.unknownPlatformForImage(platform.description, ref)\n }\n}\n\nextension ImageTransfer {\n fileprivate init(id: String, digest: String, ref: String, platform: String, data: Data) throws {\n self.init()\n self.id = id\n self.tag = digest\n self.metadata = [\n \"os\": \"linux\",\n \"stage\": \"resolver\",\n \"method\": \"/resolve\",\n \"ref\": ref,\n \"platform\": platform,\n ]\n self.complete = true\n self.direction = .into\n self.data = data\n }\n}\n\nextension BuildImageResolver {\n enum Error: Swift.Error, CustomStringConvertible {\n case imageTransferMissing\n case tagMissing\n case platformMissing\n case imageNameMissing\n case imageTagMissing\n case imageNotFound\n case indexDigestMissing(String)\n case unknownRegistry(String)\n case digestIsNotIndex(String)\n case digestIsNotManifest(String)\n case unknownPlatformForImage(String, String)\n\n var description: String {\n switch self {\n case .imageTransferMissing:\n return \"imageTransfer is missing\"\n case .tagMissing:\n return \"tag parameter missing in metadata\"\n case .platformMissing:\n return \"platform parameter missing in metadata\"\n case .imageNameMissing:\n return \"image name missing in $ref parameter\"\n case .imageTagMissing:\n return \"image tag missing in $ref parameter\"\n case .imageNotFound:\n return \"image not found\"\n case .indexDigestMissing(let ref):\n return \"index digest is missing for image: \\(ref)\"\n case .unknownRegistry(let registry):\n return \"registry \\(registry) is unknown\"\n case .digestIsNotIndex(let digest):\n return \"digest \\(digest) is not a descriptor to an index\"\n case .digestIsNotManifest(let digest):\n return \"digest \\(digest) is not a descriptor to a manifest\"\n case .unknownPlatformForImage(let platform, let ref):\n return \"platform \\(platform) for image \\(ref) not found\"\n }\n }\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\n\nextension Application {\n struct DNSList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List local DNS domains\",\n aliases: [\"ls\"]\n )\n\n func run() async throws {\n let resolver: HostDNSResolver = HostDNSResolver()\n let domains = resolver.listDomains()\n print(domains.joined(separator: \"\\n\"))\n }\n\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ContainerInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more containers\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Containers to inspect\")\n var containers: [String]\n\n func run() async throws {\n let objects: [any Codable] = try await ClientContainer.list().filter {\n containers.contains($0.id)\n }.map {\n PrintableContainer($0)\n }\n print(try objects.jsonArray())\n }\n }\n}\n"], ["/container/Sources/APIServer/Kernel/FileDownloader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\ninternal struct FileDownloader {\n public static func downloadFile(url: URL, to destination: URL, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let request = try HTTPClient.Request(url: url)\n\n let delegate = try FileDownloadDelegate(\n path: destination.path(),\n reportHead: {\n let expectedSizeString = $0.headers[\"Content-Length\"].first ?? \"\"\n if let expectedSize = Int64(expectedSizeString) {\n if let progressUpdate {\n Task {\n await progressUpdate([\n .addTotalSize(expectedSize)\n ])\n }\n }\n }\n },\n reportProgress: {\n let receivedBytes = Int64($0.receivedBytes)\n if let progressUpdate {\n Task {\n await progressUpdate([\n .setSize(receivedBytes)\n ])\n }\n }\n })\n\n let client = FileDownloader.createClient()\n _ = try await client.execute(request: request, delegate: delegate).get()\n try await client.shutdown()\n }\n\n private static func createClient() -> HTTPClient {\n var httpConfiguration = HTTPClient.Configuration()\n let proxyConfig: HTTPClient.Configuration.Proxy? = {\n let proxyEnv = ProcessInfo.processInfo.environment[\"HTTP_PROXY\"]\n guard let proxyEnv else {\n return nil\n }\n guard let url = URL(string: proxyEnv), let host = url.host(), let port = url.port else {\n return nil\n }\n return .server(host: host, port: port)\n }()\n httpConfiguration.proxy = proxyConfig\n return HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration)\n }\n}\n"], ["/container/Sources/CLI/Image/ImageTag.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\n\nextension Application {\n struct ImageTag: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"tag\",\n abstract: \"Tag an image\")\n\n @Argument(help: \"SOURCE_IMAGE[:TAG]\")\n var source: String\n\n @Argument(help: \"TARGET_IMAGE[:TAG]\")\n var target: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let existing = try await ClientImage.get(reference: source)\n let targetReference = try ClientImage.normalizeReference(target)\n try await existing.tag(new: targetReference)\n print(\"Image \\(source) tagged as \\(target)\")\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginFactory.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\nprivate let configFilename: String = \"config.json\"\n\n/// Describes the configuration and binary file locations for a plugin.\npublic protocol PluginFactory: Sendable {\n /// Create a plugin conforming to the layout, if possible.\n func create(installURL: URL) throws -> Plugin?\n}\n\n/// Default layout which uses a Unix-like structure.\npublic struct DefaultPluginFactory: PluginFactory {\n public init() {}\n\n public func create(installURL: URL) throws -> Plugin? {\n let fm = FileManager.default\n\n let configURL = installURL.appending(path: configFilename)\n guard fm.fileExists(atPath: configURL.path) else {\n return nil\n }\n\n guard let config = try PluginConfig(configURL: configURL) else {\n return nil\n }\n\n let name = installURL.lastPathComponent\n let binaryURL = installURL.appending(path: \"bin\").appending(path: name)\n guard fm.fileExists(atPath: binaryURL.path) else {\n return nil\n }\n\n return Plugin(binaryURL: binaryURL, config: config)\n }\n}\n\n/// Layout which uses a macOS application bundle structure.\npublic struct AppBundlePluginFactory: PluginFactory {\n private static let appSuffix = \".app\"\n\n public init() {}\n\n public func create(installURL: URL) throws -> Plugin? {\n let fm = FileManager.default\n\n let configURL =\n installURL\n .appending(path: \"Contents\")\n .appending(path: \"Resources\")\n .appending(path: configFilename)\n guard fm.fileExists(atPath: configURL.path) else {\n return nil\n }\n\n guard let config = try PluginConfig(configURL: configURL) else {\n return nil\n }\n\n let appName = installURL.lastPathComponent\n guard appName.hasSuffix(Self.appSuffix) else {\n return nil\n }\n let name = String(appName.dropLast(Self.appSuffix.count))\n let binaryURL =\n installURL\n .appending(path: \"Contents\")\n .appending(path: \"MacOS\")\n .appending(path: name)\n guard fm.fileExists(atPath: binaryURL.path) else {\n return nil\n }\n\n return Plugin(binaryURL: binaryURL, config: config)\n }\n}\n"], ["/container/Sources/SocketForwarder/UDPForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\nimport Synchronization\n\n// Proxy backend for a single client address (clientIP, clientPort).\nprivate final class UDPProxyBackend: ChannelInboundHandler, Sendable {\n typealias InboundIn = AddressedEnvelope\n typealias OutboundOut = AddressedEnvelope\n\n private struct State {\n var queuedPayloads: Deque\n var channel: (any Channel)?\n }\n\n private let clientAddress: SocketAddress\n private let serverAddress: SocketAddress\n private let frontendChannel: any Channel\n private let log: Logger?\n private let state: Mutex\n\n init(clientAddress: SocketAddress, serverAddress: SocketAddress, frontendChannel: any Channel, log: Logger? = nil) {\n self.clientAddress = clientAddress\n self.serverAddress = serverAddress\n self.frontendChannel = frontendChannel\n self.log = log\n let state = State(queuedPayloads: Deque(), channel: nil)\n self.state = Mutex(state)\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n // relay data from server to client.\n let inbound = self.unwrapInboundIn(data)\n let outbound = OutboundOut(remoteAddress: self.clientAddress, data: inbound.data)\n self.log?.trace(\"backend - writing datagram to client\")\n _ = self.frontendChannel.writeAndFlush(outbound)\n }\n\n func channelActive(context: ChannelHandlerContext) {\n state.withLock {\n if !$0.queuedPayloads.isEmpty {\n self.log?.trace(\"backend - writing \\($0.queuedPayloads.count) queued datagrams to server\")\n while let queuedData = $0.queuedPayloads.popFirst() {\n let outbound: UDPProxyBackend.OutboundOut = OutboundOut(remoteAddress: self.serverAddress, data: queuedData)\n _ = context.channel.writeAndFlush(outbound)\n }\n }\n $0.channel = context.channel\n }\n }\n\n func write(data: ByteBuffer) {\n // change package remote address from proxy server to real server\n state.withLock {\n if let channel = $0.channel {\n // channel has been initialized, so relay any queued packets, along with this one to outbound\n self.log?.trace(\"backend - writing datagram to server\")\n let outbound: UDPProxyBackend.OutboundOut = OutboundOut(remoteAddress: self.serverAddress, data: data)\n _ = channel.writeAndFlush(outbound)\n } else {\n // channel is initializing, queue\n self.log?.trace(\"backend - queuing datagram\")\n $0.queuedPayloads.append(data)\n }\n }\n }\n\n func close() {\n state.withLock {\n guard let channel = $0.channel else {\n self.log?.warning(\"backend - close on inactive channel\")\n return\n }\n _ = channel.close()\n }\n }\n}\n\nprivate struct ProxyContext {\n public let proxy: UDPProxyBackend\n public let closeFuture: EventLoopFuture\n}\n\nprivate final class UDPProxyFrontend: ChannelInboundHandler, Sendable {\n typealias InboundIn = AddressedEnvelope\n typealias OutboundOut = AddressedEnvelope\n private let maxProxies = UInt(256)\n\n private let proxyAddress: SocketAddress\n private let serverAddress: SocketAddress\n private let eventLoopGroup: any EventLoopGroup\n private let log: Logger?\n\n private let proxies: Mutex>\n\n init(proxyAddress: SocketAddress, serverAddress: SocketAddress, eventLoopGroup: any EventLoopGroup, log: Logger? = nil) {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.proxies = Mutex(LRUCache(size: maxProxies))\n self.log = log\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n let inbound = self.unwrapInboundIn(data)\n\n guard let clientIP = inbound.remoteAddress.ipAddress else {\n log?.error(\"frontend - no client IP address in inbound payload\")\n return\n }\n\n guard let clientPort = inbound.remoteAddress.port else {\n log?.error(\"frontend - no client port in inbound payload\")\n return\n }\n\n let key = \"\\(clientIP):\\(clientPort)\"\n do {\n try proxies.withLock {\n if let context = $0.get(key) {\n context.proxy.write(data: inbound.data)\n } else {\n self.log?.trace(\"frontend - creating backend\")\n let proxy = UDPProxyBackend(\n clientAddress: inbound.remoteAddress,\n serverAddress: self.serverAddress,\n frontendChannel: context.channel,\n log: log\n )\n let proxyAddress = try SocketAddress(ipAddress: \"0.0.0.0\", port: 0)\n let proxyToServerFuture = DatagramBootstrap(group: self.eventLoopGroup)\n .channelInitializer {\n self.log?.trace(\"frontend - initializing backend\")\n return $0.pipeline.addHandler(proxy)\n }\n .bind(to: proxyAddress)\n .flatMap { $0.closeFuture }\n let context = ProxyContext(proxy: proxy, closeFuture: proxyToServerFuture)\n if let (_, evictedContext) = $0.put(key: key, value: context) {\n self.log?.trace(\"frontend - closing evicted backend\")\n evictedContext.proxy.close()\n }\n\n proxy.write(data: inbound.data)\n }\n }\n } catch {\n log?.error(\"server handler - backend channel creation failed with error: \\(error)\")\n return\n }\n }\n}\n\npublic struct UDPForwarder: SocketForwarder {\n private let proxyAddress: SocketAddress\n\n private let serverAddress: SocketAddress\n\n private let eventLoopGroup: any EventLoopGroup\n\n private let log: Logger?\n\n public init(\n proxyAddress: SocketAddress,\n serverAddress: SocketAddress,\n eventLoopGroup: any EventLoopGroup,\n log: Logger? = nil\n ) throws {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.log = log\n }\n\n public func run() throws -> EventLoopFuture {\n self.log?.trace(\"frontend - creating channel\")\n let proxyToServerHandler = UDPProxyFrontend(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: log\n )\n let bootstrap = DatagramBootstrap(group: self.eventLoopGroup)\n .channelInitializer { serverChannel in\n self.log?.trace(\"frontend - initializing channel\")\n return serverChannel.pipeline.addHandler(proxyToServerHandler)\n }\n return\n bootstrap\n .bind(to: proxyAddress)\n .flatMap { $0.eventLoop.makeSucceededFuture(SocketForwarderResult(channel: $0)) }\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct NetworkInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more networks\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Networks to inspect\")\n var networks: [String]\n\n func run() async throws {\n let objects: [any Codable] = try await ClientNetwork.list().filter {\n networks.contains($0.id)\n }.map {\n PrintableNetwork($0)\n }\n print(try objects.jsonArray())\n }\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCMessage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\n\n/// A message that can be pass across application boundaries via XPC.\npublic struct XPCMessage: Sendable {\n /// Defined message key storing the route value.\n public static let routeKey = \"com.apple.container.xpc.route\"\n /// Defined message key storing the error value.\n public static let errorKey = \"com.apple.container.xpc.error\"\n\n // Access to `object` is protected by a lock\n private nonisolated(unsafe) let object: xpc_object_t\n private let lock = NSLock()\n private let isErr: Bool\n\n /// The underlying xpc object that the message wraps.\n public var underlying: xpc_object_t {\n lock.withLock {\n object\n }\n }\n public var isErrorType: Bool { isErr }\n\n public init(object: xpc_object_t) {\n self.object = object\n self.isErr = xpc_get_type(self.object) == XPC_TYPE_ERROR\n }\n\n public init(route: String) {\n self.object = xpc_dictionary_create_empty()\n self.isErr = false\n xpc_dictionary_set_string(self.object, Self.routeKey, route)\n }\n}\n\nextension XPCMessage {\n public static func == (lhs: XPCMessage, rhs: xpc_object_t) -> Bool {\n xpc_equal(lhs.underlying, rhs)\n }\n\n public func reply() -> XPCMessage {\n lock.withLock {\n XPCMessage(object: xpc_dictionary_create_reply(object)!)\n }\n }\n\n public func errorKeyDescription() -> String? {\n guard self.isErr,\n let xpcErr = lock.withLock({\n xpc_dictionary_get_string(\n self.object,\n XPC_ERROR_KEY_DESCRIPTION\n )\n })\n else {\n return nil\n }\n return String(cString: xpcErr)\n }\n\n public func error() throws {\n let data = data(key: Self.errorKey)\n if let data {\n let item = try? JSONDecoder().decode(ContainerXPCError.self, from: data)\n precondition(item != nil, \"expected to receive a ContainerXPCXPCError\")\n\n throw ContainerizationError(item!.code, message: item!.message)\n }\n }\n\n public func set(error: ContainerizationError) {\n var message = error.message\n if let cause = error.cause {\n message += \" (cause: \\\"\\(cause)\\\")\"\n }\n let serializableError = ContainerXPCError(code: error.code.description, message: message)\n let data = try? JSONEncoder().encode(serializableError)\n precondition(data != nil)\n\n set(key: Self.errorKey, value: data!)\n }\n}\n\nstruct ContainerXPCError: Codable {\n let code: String\n let message: String\n}\n\nextension XPCMessage {\n public func data(key: String) -> Data? {\n var length: Int = 0\n let bytes = lock.withLock {\n xpc_dictionary_get_data(self.object, key, &length)\n }\n\n guard let bytes else {\n return nil\n }\n\n return Data(bytes: bytes, count: length)\n }\n\n /// dataNoCopy is similar to data, except the data is not copied\n /// to a new buffer. What this means in practice is the second the\n /// underlying xpc_object_t gets released by ARC the data will be\n /// released as well. This variant should be used when you know the\n /// data will be used before the object has no more references.\n public func dataNoCopy(key: String) -> Data? {\n var length: Int = 0\n let bytes = lock.withLock {\n xpc_dictionary_get_data(self.object, key, &length)\n }\n\n guard let bytes else {\n return nil\n }\n\n return Data(\n bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes),\n count: length,\n deallocator: .none\n )\n }\n\n public func set(key: String, value: Data) {\n value.withUnsafeBytes { ptr in\n if let addr = ptr.baseAddress {\n lock.withLock {\n xpc_dictionary_set_data(self.object, key, addr, value.count)\n }\n }\n }\n }\n\n public func string(key: String) -> String? {\n let _id = lock.withLock {\n xpc_dictionary_get_string(self.object, key)\n }\n if let _id {\n return String(cString: _id)\n }\n return nil\n }\n\n public func set(key: String, value: String) {\n lock.withLock {\n xpc_dictionary_set_string(self.object, key, value)\n }\n }\n\n public func bool(key: String) -> Bool {\n lock.withLock {\n xpc_dictionary_get_bool(self.object, key)\n }\n }\n\n public func set(key: String, value: Bool) {\n lock.withLock {\n xpc_dictionary_set_bool(self.object, key, value)\n }\n }\n\n public func uint64(key: String) -> UInt64 {\n lock.withLock {\n xpc_dictionary_get_uint64(self.object, key)\n }\n }\n\n public func set(key: String, value: UInt64) {\n lock.withLock {\n xpc_dictionary_set_uint64(self.object, key, value)\n }\n }\n\n public func int64(key: String) -> Int64 {\n lock.withLock {\n xpc_dictionary_get_int64(self.object, key)\n }\n }\n\n public func set(key: String, value: Int64) {\n lock.withLock {\n xpc_dictionary_set_int64(self.object, key, value)\n }\n }\n\n public func fileHandle(key: String) -> FileHandle? {\n let fd = lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n if let fd {\n let fd2 = xpc_fd_dup(fd)\n return FileHandle(fileDescriptor: fd2, closeOnDealloc: false)\n }\n return nil\n }\n\n public func set(key: String, value: FileHandle) {\n let fd = xpc_fd_create(value.fileDescriptor)\n close(value.fileDescriptor)\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, fd)\n }\n }\n\n public func fileHandles(key: String) -> [FileHandle]? {\n let fds = lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n if let fds {\n let fd1 = xpc_array_dup_fd(fds, 0)\n let fd2 = xpc_array_dup_fd(fds, 1)\n if fd1 == -1 || fd2 == -1 {\n return nil\n }\n return [\n FileHandle(fileDescriptor: fd1, closeOnDealloc: false),\n FileHandle(fileDescriptor: fd2, closeOnDealloc: false),\n ]\n }\n return nil\n }\n\n public func set(key: String, value: [FileHandle]) throws {\n let fdArray = xpc_array_create(nil, 0)\n for fh in value {\n guard let xpcFd = xpc_fd_create(fh.fileDescriptor) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to create xpc fd for \\(fh.fileDescriptor)\"\n )\n }\n xpc_array_append_value(fdArray, xpcFd)\n close(fh.fileDescriptor)\n }\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, fdArray)\n }\n }\n\n public func endpoint(key: String) -> xpc_endpoint_t? {\n lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n }\n\n public func set(key: String, value: xpc_endpoint_t) {\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, value)\n }\n }\n}\n\n#endif\n"], ["/container/Sources/Services/ContainerImagesService/Server/ImagesServiceHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\npublic struct ImagesServiceHarness: Sendable {\n let log: Logging.Logger\n let service: ImagesService\n\n public init(service: ImagesService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n public func pull(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let insecure = message.bool(key: .insecureFlag)\n\n let progressUpdateService = ProgressUpdateService(message: message)\n let imageDescription = try await service.pull(reference: ref, platform: platform, insecure: insecure, progressUpdate: progressUpdateService?.handler)\n\n let imageData = try JSONEncoder().encode(imageDescription)\n let reply = message.reply()\n reply.set(key: .imageDescription, value: imageData)\n return reply\n }\n\n @Sendable\n public func push(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let insecure = message.bool(key: .insecureFlag)\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await service.push(reference: ref, platform: platform, insecure: insecure, progressUpdate: progressUpdateService?.handler)\n\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func tag(_ message: XPCMessage) async throws -> XPCMessage {\n let old = message.string(key: .imageReference)\n guard let old else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let new = message.string(key: .imageNewReference)\n guard let new else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing new image reference\"\n )\n }\n let newDescription = try await service.tag(old: old, new: new)\n let descData = try JSONEncoder().encode(newDescription)\n let reply = message.reply()\n reply.set(key: .imageDescription, value: descData)\n return reply\n }\n\n @Sendable\n public func list(_ message: XPCMessage) async throws -> XPCMessage {\n let images = try await service.list()\n let imageData = try JSONEncoder().encode(images)\n let reply = message.reply()\n reply.set(key: .imageDescriptions, value: imageData)\n return reply\n }\n\n @Sendable\n public func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let garbageCollect = message.bool(key: .garbageCollect)\n try await self.service.delete(reference: ref, garbageCollect: garbageCollect)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func save(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .imageDescription)\n guard let data else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let imageDescription = try JSONDecoder().decode(ImageDescription.self, from: data)\n\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let out = message.string(key: .filePath)\n guard let out else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing output file path\"\n )\n }\n try await service.save(reference: imageDescription.reference, out: URL(filePath: out), platform: platform)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func load(_ message: XPCMessage) async throws -> XPCMessage {\n let input = message.string(key: .filePath)\n guard let input else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing input file path\"\n )\n }\n let images = try await service.load(from: URL(filePath: input))\n let data = try JSONEncoder().encode(images)\n let reply = message.reply()\n reply.set(key: .imageDescriptions, value: data)\n return reply\n }\n\n @Sendable\n public func prune(_ message: XPCMessage) async throws -> XPCMessage {\n let (deleted, size) = try await service.prune()\n let reply = message.reply()\n let data = try JSONEncoder().encode(deleted)\n reply.set(key: .digests, value: data)\n reply.set(key: .size, value: size)\n return reply\n }\n}\n\n// MARK: Image Snapshot Methods\n\nextension ImagesServiceHarness {\n @Sendable\n public func unpack(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing Image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n var platform: Platform?\n if let platformData = message.dataNoCopy(key: .ociPlatform) {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await self.service.unpack(description: description, platform: platform, progressUpdate: progressUpdateService?.handler)\n\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func deleteSnapshot(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform?\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n try await self.service.deleteImageSnapshot(description: description, platform: platform)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func getSnapshot(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n let platformData = message.dataNoCopy(key: .ociPlatform)\n guard let platformData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing OCI platform\"\n )\n }\n let platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n let fs = try await self.service.getImageSnapshot(description: description, platform: platform)\n let fsData = try JSONEncoder().encode(fs)\n let reply = message.reply()\n reply.set(key: .filesystem, value: fsData)\n return reply\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildStdio.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIO\n\nactor BuildStdio: BuildPipelineHandler {\n public let quiet: Bool\n public let handle: FileHandle\n\n init(quiet: Bool = false, output: FileHandle = FileHandle.standardError) throws {\n self.quiet = quiet\n self.handle = output\n }\n\n nonisolated func accept(_ packet: ServerStream) throws -> Bool {\n guard let _ = packet.getIO() else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard !quiet else {\n return\n }\n guard let io = packet.getIO() else {\n throw Error.ioMissing\n }\n if let cmdString = try TerminalCommand().json() {\n var response = ClientStream()\n response.buildID = packet.buildID\n response.command = .init()\n response.command.id = packet.buildID\n response.command.command = cmdString\n sender.yield(response)\n }\n handle.write(io.data)\n }\n}\n\nextension BuildStdio {\n enum Error: Swift.Error, CustomStringConvertible {\n case ioMissing\n case invalidContinuation\n var description: String {\n switch self {\n case .ioMissing:\n return \"io field missing in packet\"\n case .invalidContinuation:\n return \"continuation could not created\"\n }\n }\n }\n}\n"], ["/container/Sources/ContainerPersistence/EntityStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nlet metadataFilename: String = \"entity.json\"\n\npublic protocol EntityStore {\n associatedtype T: Codable & Identifiable & Sendable\n\n func list() async throws -> [T]\n func create(_ entity: T) async throws\n func retrieve(_ id: String) async throws -> T?\n func update(_ entity: T) async throws\n func upsert(_ entity: T) async throws\n func delete(_ id: String) async throws\n}\n\npublic actor FilesystemEntityStore: EntityStore where T: Codable & Identifiable & Sendable {\n typealias Index = [String: T]\n\n private let path: URL\n private let type: String\n private var index: Index\n private let log: Logger\n private let encoder = JSONEncoder()\n\n public init(path: URL, type: String, log: Logger) throws {\n self.path = path\n self.type = type\n self.log = log\n self.index = try Self.load(path: path, log: log)\n }\n\n public func list() async throws -> [T] {\n Array(index.values)\n }\n\n public func create(_ entity: T) async throws {\n let metadataUrl = metadataUrl(entity.id)\n guard !FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.exists, message: \"Entity \\(entity.id) already exist\")\n }\n\n try FileManager.default.createDirectory(at: entityUrl(entity.id), withIntermediateDirectories: true)\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func retrieve(_ id: String) throws -> T? {\n index[id]\n }\n\n public func update(_ entity: T) async throws {\n let metadataUrl: URL = metadataUrl(entity.id)\n guard FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.notFound, message: \"Entity \\(entity.id) not found\")\n }\n\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func upsert(_ entity: T) async throws {\n let metadataUrl: URL = metadataUrl(entity.id)\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func delete(_ id: String) async throws {\n let metadataUrl = entityUrl(id)\n guard FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.notFound, message: \"entity \\(id) not found\")\n }\n try FileManager.default.removeItem(at: metadataUrl)\n index.removeValue(forKey: id)\n }\n\n public func entityUrl(_ id: String) -> URL {\n path.appendingPathComponent(id)\n }\n\n private static func load(path: URL, log: Logger) throws -> Index {\n let directories = try FileManager.default.contentsOfDirectory(at: path, includingPropertiesForKeys: nil)\n var index: FilesystemEntityStore.Index = Index()\n let decoder = JSONDecoder()\n\n for entityUrl in directories {\n do {\n let metadataUrl = entityUrl.appendingPathComponent(metadataFilename)\n let data = try Data(contentsOf: metadataUrl)\n let entity = try decoder.decode(T.self, from: data)\n index[entity.id] = entity\n } catch {\n log.warning(\n \"failed to load entity, ignoring\",\n metadata: [\n \"path\": \"\\(entityUrl)\"\n ])\n }\n }\n\n return index\n }\n\n private func metadataUrl(_ id: String) -> URL {\n entityUrl(id).appendingPathComponent(metadataFilename)\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildRemoteContentProxy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\n\nstruct BuildRemoteContentProxy: BuildPipelineHandler {\n let local: ContentStore\n\n public init(_ contentStore: ContentStore) throws {\n self.local = contentStore\n }\n\n func accept(_ packet: ServerStream) throws -> Bool {\n guard let imageTransfer = packet.getImageTransfer() else {\n return false\n }\n guard imageTransfer.stage() == \"content-store\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let imageTransfer = packet.getImageTransfer() else {\n throw Error.imageTransferMissing\n }\n\n guard let method = imageTransfer.method() else {\n throw Error.methodMissing\n }\n\n switch try ContentStoreMethod(method) {\n case .info:\n try await self.info(sender, imageTransfer, packet.buildID)\n case .readerAt:\n try await self.readerAt(sender, imageTransfer, packet.buildID)\n default:\n throw Error.unknownMethod(method)\n }\n }\n\n func info(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer, _ buildID: String) async throws {\n let descriptor = try await local.get(digest: packet.tag)\n let size = try descriptor?.size()\n let transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.info.rawValue,\n size: size\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n }\n\n func readerAt(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer, _ buildID: String) async throws {\n let digest = packet.descriptor.digest\n let offset: UInt64 = packet.offset() ?? 0\n let size: Int = packet.len() ?? 0\n guard let descriptor = try await local.get(digest: digest) else {\n throw Error.contentMissing\n }\n if offset == 0 && size == 0 { // Metadata request\n var transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.readerAt.rawValue,\n size: descriptor.size(),\n data: Data()\n )\n transfer.complete = true\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n return\n }\n guard let data = try descriptor.data(offset: offset, length: size) else {\n throw Error.invalidOffsetSizeForContent(packet.descriptor.digest, offset, size)\n }\n\n let transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.readerAt.rawValue,\n size: UInt64(data.count),\n data: data\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n }\n\n func delete(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.delete)\"])\n }\n\n func update(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.update)\"])\n }\n\n func walk(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.walk)\"])\n }\n\n enum ContentStoreMethod: String {\n case info = \"/containerd.services.content.v1.Content/Info\"\n case readerAt = \"/containerd.services.content.v1.Content/ReaderAt\"\n case delete = \"/containerd.services.content.v1.Content/Delete\"\n case update = \"/containerd.services.content.v1.Content/Update\"\n case walk = \"/containerd.services.content.v1.Content/Walk\"\n\n init(_ method: String) throws {\n guard let value = ContentStoreMethod(rawValue: method) else {\n throw Error.unknownMethod(method)\n }\n self = value\n }\n }\n}\n\nextension ImageTransfer {\n fileprivate init(id: String, digest: String, method: String, size: UInt64? = nil, data: Data = Data()) throws {\n self.init()\n self.id = id\n self.tag = digest\n self.metadata = [\n \"os\": \"linux\",\n \"stage\": \"content-store\",\n \"method\": method,\n ]\n if let size {\n self.metadata[\"size\"] = String(size)\n }\n self.complete = true\n self.direction = .into\n self.data = data\n }\n}\n\nextension BuildRemoteContentProxy {\n enum Error: Swift.Error, CustomStringConvertible {\n case imageTransferMissing\n case methodMissing\n case contentMissing\n case unknownMethod(String)\n case invalidOffsetSizeForContent(String, UInt64, Int)\n\n var description: String {\n switch self {\n case .imageTransferMissing:\n return \"imageTransfer is missing\"\n case .methodMissing:\n return \"method is missing in request\"\n case .contentMissing:\n return \"content cannot be found\"\n case .unknownMethod(let m):\n return \"unknown content-store method \\(m)\"\n case .invalidOffsetSizeForContent(let digest, let offset, let size):\n return \"invalid request for content: \\(digest) with offset: \\(offset) size: \\(size)\"\n }\n }\n }\n\n}\n"], ["/container/Sources/DNSServer/DNSServer+Handle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport NIOCore\nimport NIOPosix\n\nextension DNSServer {\n /// Handles the DNS request.\n /// - Parameters:\n /// - outbound: The NIOAsyncChannelOutboundWriter for which to respond.\n /// - packet: The request packet.\n func handle(\n outbound: NIOAsyncChannelOutboundWriter>,\n packet: inout AddressedEnvelope\n ) async throws {\n let chunkSize = 512\n var data = Data()\n\n self.log?.debug(\"reading data\")\n while packet.data.readableBytes > 0 {\n if let chunk = packet.data.readBytes(length: min(chunkSize, packet.data.readableBytes)) {\n data.append(contentsOf: chunk)\n }\n }\n\n self.log?.debug(\"deserializing message\")\n let query = try Message(deserialize: data)\n self.log?.debug(\"processing query: \\(query.questions)\")\n\n // always send response\n let responseData: Data\n do {\n self.log?.debug(\"awaiting processing\")\n var response =\n try await handler.answer(query: query)\n ?? Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n\n // no responses\n if response.answers.isEmpty {\n response.returnCode = .nonExistentDomain\n }\n\n self.log?.debug(\"serializing response\")\n responseData = try response.serialize()\n } catch {\n self.log?.error(\"error processing message from \\(query): \\(error)\")\n let response = Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n responseData = try response.serialize()\n }\n\n self.log?.debug(\"sending response for \\(query.id)\")\n let rData = ByteBuffer(bytes: responseData)\n try? await outbound.write(AddressedEnvelope(remoteAddress: packet.remoteAddress, data: rData))\n\n self.log?.debug(\"processing done\")\n\n }\n}\n"], ["/container/Sources/SocketForwarder/ConnectHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Logging\nimport NIOCore\nimport NIOPosix\n\nfinal class ConnectHandler {\n private var pendingBytes: [NIOAny]\n private let serverAddress: SocketAddress\n private var log: Logger? = nil\n\n init(serverAddress: SocketAddress, log: Logger?) {\n self.pendingBytes = []\n self.serverAddress = serverAddress\n self.log = log\n }\n}\n\nextension ConnectHandler: ChannelInboundHandler {\n typealias InboundIn = ByteBuffer\n typealias OutboundOut = ByteBuffer\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n if self.pendingBytes.isEmpty {\n self.connectToServer(context: context)\n }\n self.pendingBytes.append(data)\n }\n\n func handlerAdded(context: ChannelHandlerContext) {\n // Add logger metadata.\n self.log?[metadataKey: \"proxy\"] = \"\\(context.channel.localAddress?.description ?? \"none\")\"\n self.log?[metadataKey: \"server\"] = \"\\(context.channel.remoteAddress?.description ?? \"none\")\"\n }\n}\n\nextension ConnectHandler: RemovableChannelHandler {\n func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) {\n var didRead = false\n\n // We are being removed, and need to deliver any pending bytes we may have if we're upgrading.\n while self.pendingBytes.count > 0 {\n let data = self.pendingBytes.removeFirst()\n context.fireChannelRead(data)\n didRead = true\n }\n\n if didRead {\n context.fireChannelReadComplete()\n }\n\n self.log?.trace(\"backend - removing connect handler from pipeline\")\n context.leavePipeline(removalToken: removalToken)\n }\n}\n\nextension ConnectHandler {\n private func connectToServer(context: ChannelHandlerContext) {\n self.log?.trace(\"backend - connecting\")\n\n ClientBootstrap(group: context.eventLoop)\n .connect(to: serverAddress)\n .assumeIsolatedUnsafeUnchecked()\n .whenComplete { result in\n switch result {\n case .success(let channel):\n self.log?.trace(\"backend - connected\")\n self.glue(channel, context: context)\n case .failure(let error):\n self.log?.error(\"backend - connect failed: \\(error)\")\n context.close(promise: nil)\n context.fireErrorCaught(error)\n }\n }\n }\n\n private func glue(_ peerChannel: Channel, context: ChannelHandlerContext) {\n self.log?.trace(\"backend - gluing channels\")\n\n // Now we need to glue our channel and the peer channel together.\n let (localGlue, peerGlue) = GlueHandler.matchedPair()\n do {\n try context.channel.pipeline.syncOperations.addHandler(localGlue)\n try peerChannel.pipeline.syncOperations.addHandler(peerGlue)\n context.pipeline.syncOperations.removeHandler(self, promise: nil)\n } catch {\n // Close connected peer channel before closing our channel.\n peerChannel.close(mode: .all, promise: nil)\n context.close(promise: nil)\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.pb.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// DO NOT EDIT.\n// swift-format-ignore-file\n// swiftlint:disable all\n//\n// Generated by the Swift generator plugin for the protocol buffer compiler.\n// Source: Builder.proto\n//\n// For information on using the generated types, please see the documentation:\n// https://github.com/apple/swift-protobuf/\n\nimport Foundation\nimport SwiftProtobuf\n\n// If the compiler emits an error on this type, it is because this file\n// was generated by a version of the `protoc` Swift plug-in that is\n// incompatible with the version of SwiftProtobuf to which you are linking.\n// Please ensure that you are building against the same version of the API\n// that was used to generate this file.\nfileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {\n struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}\n typealias Version = _2\n}\n\npublic enum Com_Apple_Container_Build_V1_TransferDirection: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case into // = 0\n case outof // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .into\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .into\n case 1: self = .outof\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .into: return 0\n case .outof: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_TransferDirection] = [\n .into,\n .outof,\n ]\n\n}\n\n/// Standard input/output.\npublic enum Com_Apple_Container_Build_V1_Stdio: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case stdin // = 0\n case stdout // = 1\n case stderr // = 2\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .stdin\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .stdin\n case 1: self = .stdout\n case 2: self = .stderr\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .stdin: return 0\n case .stdout: return 1\n case .stderr: return 2\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_Stdio] = [\n .stdin,\n .stdout,\n .stderr,\n ]\n\n}\n\n/// Build error type.\npublic enum Com_Apple_Container_Build_V1_BuildErrorType: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case buildFailed // = 0\n case `internal` // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .buildFailed\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .buildFailed\n case 1: self = .internal\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .buildFailed: return 0\n case .internal: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_BuildErrorType] = [\n .buildFailed,\n .internal,\n ]\n\n}\n\npublic struct Com_Apple_Container_Build_V1_InfoRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_InfoResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_CreateBuildRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The name of the build stage.\n public var stageName: String = String()\n\n /// The tag of the image to be created.\n public var tag: String = String()\n\n /// Any additional metadata to be associated with the build.\n public var metadata: Dictionary = [:]\n\n /// Additional build arguments.\n public var buildArgs: [String] = []\n\n /// Enable debug logging.\n public var debug: Bool = false\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_CreateBuildResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String = String()\n\n /// Any additional metadata to be associated with the build.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_ClientStream: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String {\n get {return _storage._buildID}\n set {_uniqueStorage()._buildID = newValue}\n }\n\n /// The packet type.\n public var packetType: OneOf_PacketType? {\n get {return _storage._packetType}\n set {_uniqueStorage()._packetType = newValue}\n }\n\n public var signal: Com_Apple_Container_Build_V1_Signal {\n get {\n if case .signal(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_Signal()\n }\n set {_uniqueStorage()._packetType = .signal(newValue)}\n }\n\n public var command: Com_Apple_Container_Build_V1_Run {\n get {\n if case .command(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_Run()\n }\n set {_uniqueStorage()._packetType = .command(newValue)}\n }\n\n public var buildTransfer: Com_Apple_Container_Build_V1_BuildTransfer {\n get {\n if case .buildTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildTransfer()\n }\n set {_uniqueStorage()._packetType = .buildTransfer(newValue)}\n }\n\n public var imageTransfer: Com_Apple_Container_Build_V1_ImageTransfer {\n get {\n if case .imageTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_ImageTransfer()\n }\n set {_uniqueStorage()._packetType = .imageTransfer(newValue)}\n }\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n /// The packet type.\n public enum OneOf_PacketType: Equatable, Sendable {\n case signal(Com_Apple_Container_Build_V1_Signal)\n case command(Com_Apple_Container_Build_V1_Run)\n case buildTransfer(Com_Apple_Container_Build_V1_BuildTransfer)\n case imageTransfer(Com_Apple_Container_Build_V1_ImageTransfer)\n\n }\n\n public init() {}\n\n fileprivate var _storage = _StorageClass.defaultInstance\n}\n\npublic struct Com_Apple_Container_Build_V1_Signal: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A POSIX signal to send to the build process.\n /// Can be used for cancelling builds.\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_Run: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the execution.\n public var id: String = String()\n\n /// The type of command to execute.\n public var command: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_RunComplete: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the execution.\n public var id: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_BuildTransfer: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the transfer.\n public var id: String = String()\n\n /// The direction for transferring data (either to the server or from the\n /// server).\n public var direction: Com_Apple_Container_Build_V1_TransferDirection = .into\n\n /// The absolute path to the source from the server perspective.\n public var source: String {\n get {return _source ?? String()}\n set {_source = newValue}\n }\n /// Returns true if `source` has been explicitly set.\n public var hasSource: Bool {return self._source != nil}\n /// Clears the value of `source`. Subsequent reads from it will return its default value.\n public mutating func clearSource() {self._source = nil}\n\n /// The absolute path for the destination from the server perspective.\n public var destination: String {\n get {return _destination ?? String()}\n set {_destination = newValue}\n }\n /// Returns true if `destination` has been explicitly set.\n public var hasDestination: Bool {return self._destination != nil}\n /// Clears the value of `destination`. Subsequent reads from it will return its default value.\n public mutating func clearDestination() {self._destination = nil}\n\n /// The actual data bytes to be transferred.\n public var data: Data = Data()\n\n /// Signal to indicate that the transfer of data for the request has finished.\n public var complete: Bool = false\n\n /// Boolean to indicate if the content is a directory.\n public var isDirectory: Bool = false\n\n /// Metadata for the transfer.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _source: String? = nil\n fileprivate var _destination: String? = nil\n}\n\npublic struct Com_Apple_Container_Build_V1_ImageTransfer: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the transfer.\n public var id: String = String()\n\n /// The direction for transferring data (either to the server or from the\n /// server).\n public var direction: Com_Apple_Container_Build_V1_TransferDirection = .into\n\n /// The tag for the image.\n public var tag: String = String()\n\n /// The descriptor for the image content.\n public var descriptor: Com_Apple_Container_Build_V1_Descriptor {\n get {return _descriptor ?? Com_Apple_Container_Build_V1_Descriptor()}\n set {_descriptor = newValue}\n }\n /// Returns true if `descriptor` has been explicitly set.\n public var hasDescriptor: Bool {return self._descriptor != nil}\n /// Clears the value of `descriptor`. Subsequent reads from it will return its default value.\n public mutating func clearDescriptor() {self._descriptor = nil}\n\n /// The actual data bytes to be transferred.\n public var data: Data = Data()\n\n /// Signal to indicate that the transfer of data for the request has finished.\n public var complete: Bool = false\n\n /// Metadata for the image.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _descriptor: Com_Apple_Container_Build_V1_Descriptor? = nil\n}\n\npublic struct Com_Apple_Container_Build_V1_ServerStream: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String {\n get {return _storage._buildID}\n set {_uniqueStorage()._buildID = newValue}\n }\n\n /// The packet type.\n public var packetType: OneOf_PacketType? {\n get {return _storage._packetType}\n set {_uniqueStorage()._packetType = newValue}\n }\n\n public var io: Com_Apple_Container_Build_V1_IO {\n get {\n if case .io(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_IO()\n }\n set {_uniqueStorage()._packetType = .io(newValue)}\n }\n\n public var buildError: Com_Apple_Container_Build_V1_BuildError {\n get {\n if case .buildError(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildError()\n }\n set {_uniqueStorage()._packetType = .buildError(newValue)}\n }\n\n public var commandComplete: Com_Apple_Container_Build_V1_RunComplete {\n get {\n if case .commandComplete(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_RunComplete()\n }\n set {_uniqueStorage()._packetType = .commandComplete(newValue)}\n }\n\n public var buildTransfer: Com_Apple_Container_Build_V1_BuildTransfer {\n get {\n if case .buildTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildTransfer()\n }\n set {_uniqueStorage()._packetType = .buildTransfer(newValue)}\n }\n\n public var imageTransfer: Com_Apple_Container_Build_V1_ImageTransfer {\n get {\n if case .imageTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_ImageTransfer()\n }\n set {_uniqueStorage()._packetType = .imageTransfer(newValue)}\n }\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n /// The packet type.\n public enum OneOf_PacketType: Equatable, Sendable {\n case io(Com_Apple_Container_Build_V1_IO)\n case buildError(Com_Apple_Container_Build_V1_BuildError)\n case commandComplete(Com_Apple_Container_Build_V1_RunComplete)\n case buildTransfer(Com_Apple_Container_Build_V1_BuildTransfer)\n case imageTransfer(Com_Apple_Container_Build_V1_ImageTransfer)\n\n }\n\n public init() {}\n\n fileprivate var _storage = _StorageClass.defaultInstance\n}\n\npublic struct Com_Apple_Container_Build_V1_IO: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The type of IO.\n public var type: Com_Apple_Container_Build_V1_Stdio = .stdin\n\n /// The IO data bytes.\n public var data: Data = Data()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_BuildError: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The type of build error.\n public var type: Com_Apple_Container_Build_V1_BuildErrorType = .buildFailed\n\n /// Additional message for the build failure.\n public var message: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n/// OCI Platform metadata.\npublic struct Com_Apple_Container_Build_V1_Platform: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var architecture: String = String()\n\n public var os: String = String()\n\n public var osVersion: String = String()\n\n public var osFeatures: [String] = []\n\n public var variant: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n/// OCI Descriptor metadata.\npublic struct Com_Apple_Container_Build_V1_Descriptor: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var mediaType: String = String()\n\n public var digest: String = String()\n\n public var size: Int64 = 0\n\n public var urls: [String] = []\n\n public var annotations: Dictionary = [:]\n\n public var platform: Com_Apple_Container_Build_V1_Platform {\n get {return _platform ?? Com_Apple_Container_Build_V1_Platform()}\n set {_platform = newValue}\n }\n /// Returns true if `platform` has been explicitly set.\n public var hasPlatform: Bool {return self._platform != nil}\n /// Clears the value of `platform`. Subsequent reads from it will return its default value.\n public mutating func clearPlatform() {self._platform = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _platform: Com_Apple_Container_Build_V1_Platform? = nil\n}\n\n// MARK: - Code below here is support for the SwiftProtobuf runtime.\n\nfileprivate let _protobuf_package = \"com.apple.container.build.v1\"\n\nextension Com_Apple_Container_Build_V1_TransferDirection: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"INTO\"),\n 1: .same(proto: \"OUTOF\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_Stdio: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"STDIN\"),\n 1: .same(proto: \"STDOUT\"),\n 2: .same(proto: \"STDERR\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_BuildErrorType: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"BUILD_FAILED\"),\n 1: .same(proto: \"INTERNAL\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_InfoRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".InfoRequest\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_InfoRequest, rhs: Com_Apple_Container_Build_V1_InfoRequest) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_InfoResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".InfoResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_InfoResponse, rhs: Com_Apple_Container_Build_V1_InfoResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_CreateBuildRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateBuildRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"stage_name\"),\n 2: .same(proto: \"tag\"),\n 3: .same(proto: \"metadata\"),\n 4: .standard(proto: \"build_args\"),\n 5: .same(proto: \"debug\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.stageName) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.tag) }()\n case 3: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.buildArgs) }()\n case 5: try { try decoder.decodeSingularBoolField(value: &self.debug) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.stageName.isEmpty {\n try visitor.visitSingularStringField(value: self.stageName, fieldNumber: 1)\n }\n if !self.tag.isEmpty {\n try visitor.visitSingularStringField(value: self.tag, fieldNumber: 2)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 3)\n }\n if !self.buildArgs.isEmpty {\n try visitor.visitRepeatedStringField(value: self.buildArgs, fieldNumber: 4)\n }\n if self.debug != false {\n try visitor.visitSingularBoolField(value: self.debug, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_CreateBuildRequest, rhs: Com_Apple_Container_Build_V1_CreateBuildRequest) -> Bool {\n if lhs.stageName != rhs.stageName {return false}\n if lhs.tag != rhs.tag {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.buildArgs != rhs.buildArgs {return false}\n if lhs.debug != rhs.debug {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_CreateBuildResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateBuildResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.buildID) }()\n case 2: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.buildID.isEmpty {\n try visitor.visitSingularStringField(value: self.buildID, fieldNumber: 1)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_CreateBuildResponse, rhs: Com_Apple_Container_Build_V1_CreateBuildResponse) -> Bool {\n if lhs.buildID != rhs.buildID {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ClientStream: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ClientStream\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"signal\"),\n 3: .same(proto: \"command\"),\n 4: .standard(proto: \"build_transfer\"),\n 5: .standard(proto: \"image_transfer\"),\n ]\n\n fileprivate class _StorageClass {\n var _buildID: String = String()\n var _packetType: Com_Apple_Container_Build_V1_ClientStream.OneOf_PacketType?\n\n // This property is used as the initial default value for new instances of the type.\n // The type itself is protecting the reference to its storage via CoW semantics.\n // This will force a copy to be made of this reference when the first mutation occurs;\n // hence, it is safe to mark this as `nonisolated(unsafe)`.\n static nonisolated(unsafe) let defaultInstance = _StorageClass()\n\n private init() {}\n\n init(copying source: _StorageClass) {\n _buildID = source._buildID\n _packetType = source._packetType\n }\n }\n\n fileprivate mutating func _uniqueStorage() -> _StorageClass {\n if !isKnownUniquelyReferenced(&_storage) {\n _storage = _StorageClass(copying: _storage)\n }\n return _storage\n }\n\n public mutating func decodeMessage(decoder: inout D) throws {\n _ = _uniqueStorage()\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &_storage._buildID) }()\n case 2: try {\n var v: Com_Apple_Container_Build_V1_Signal?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .signal(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .signal(v)\n }\n }()\n case 3: try {\n var v: Com_Apple_Container_Build_V1_Run?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .command(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .command(v)\n }\n }()\n case 4: try {\n var v: Com_Apple_Container_Build_V1_BuildTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildTransfer(v)\n }\n }()\n case 5: try {\n var v: Com_Apple_Container_Build_V1_ImageTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .imageTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .imageTransfer(v)\n }\n }()\n default: break\n }\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !_storage._buildID.isEmpty {\n try visitor.visitSingularStringField(value: _storage._buildID, fieldNumber: 1)\n }\n switch _storage._packetType {\n case .signal?: try {\n guard case .signal(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 2)\n }()\n case .command?: try {\n guard case .command(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 3)\n }()\n case .buildTransfer?: try {\n guard case .buildTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n }()\n case .imageTransfer?: try {\n guard case .imageTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 5)\n }()\n case nil: break\n }\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ClientStream, rhs: Com_Apple_Container_Build_V1_ClientStream) -> Bool {\n if lhs._storage !== rhs._storage {\n let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in\n let _storage = _args.0\n let rhs_storage = _args.1\n if _storage._buildID != rhs_storage._buildID {return false}\n if _storage._packetType != rhs_storage._packetType {return false}\n return true\n }\n if !storagesAreEqual {return false}\n }\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Signal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Signal\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Signal, rhs: Com_Apple_Container_Build_V1_Signal) -> Bool {\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Run: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Run\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"command\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.command) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if !self.command.isEmpty {\n try visitor.visitSingularStringField(value: self.command, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Run, rhs: Com_Apple_Container_Build_V1_Run) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.command != rhs.command {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_RunComplete: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".RunComplete\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_RunComplete, rhs: Com_Apple_Container_Build_V1_RunComplete) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_BuildTransfer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".BuildTransfer\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"direction\"),\n 3: .same(proto: \"source\"),\n 4: .same(proto: \"destination\"),\n 5: .same(proto: \"data\"),\n 6: .same(proto: \"complete\"),\n 7: .standard(proto: \"is_directory\"),\n 8: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularEnumField(value: &self.direction) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._source) }()\n case 4: try { try decoder.decodeSingularStringField(value: &self._destination) }()\n case 5: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n case 6: try { try decoder.decodeSingularBoolField(value: &self.complete) }()\n case 7: try { try decoder.decodeSingularBoolField(value: &self.isDirectory) }()\n case 8: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.direction != .into {\n try visitor.visitSingularEnumField(value: self.direction, fieldNumber: 2)\n }\n try { if let v = self._source {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try { if let v = self._destination {\n try visitor.visitSingularStringField(value: v, fieldNumber: 4)\n } }()\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 5)\n }\n if self.complete != false {\n try visitor.visitSingularBoolField(value: self.complete, fieldNumber: 6)\n }\n if self.isDirectory != false {\n try visitor.visitSingularBoolField(value: self.isDirectory, fieldNumber: 7)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 8)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_BuildTransfer, rhs: Com_Apple_Container_Build_V1_BuildTransfer) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.direction != rhs.direction {return false}\n if lhs._source != rhs._source {return false}\n if lhs._destination != rhs._destination {return false}\n if lhs.data != rhs.data {return false}\n if lhs.complete != rhs.complete {return false}\n if lhs.isDirectory != rhs.isDirectory {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ImageTransfer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ImageTransfer\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"direction\"),\n 3: .same(proto: \"tag\"),\n 4: .same(proto: \"descriptor\"),\n 5: .same(proto: \"data\"),\n 6: .same(proto: \"complete\"),\n 7: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularEnumField(value: &self.direction) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.tag) }()\n case 4: try { try decoder.decodeSingularMessageField(value: &self._descriptor) }()\n case 5: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n case 6: try { try decoder.decodeSingularBoolField(value: &self.complete) }()\n case 7: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.direction != .into {\n try visitor.visitSingularEnumField(value: self.direction, fieldNumber: 2)\n }\n if !self.tag.isEmpty {\n try visitor.visitSingularStringField(value: self.tag, fieldNumber: 3)\n }\n try { if let v = self._descriptor {\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n } }()\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 5)\n }\n if self.complete != false {\n try visitor.visitSingularBoolField(value: self.complete, fieldNumber: 6)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 7)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ImageTransfer, rhs: Com_Apple_Container_Build_V1_ImageTransfer) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.direction != rhs.direction {return false}\n if lhs.tag != rhs.tag {return false}\n if lhs._descriptor != rhs._descriptor {return false}\n if lhs.data != rhs.data {return false}\n if lhs.complete != rhs.complete {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ServerStream: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ServerStream\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"io\"),\n 3: .standard(proto: \"build_error\"),\n 4: .standard(proto: \"command_complete\"),\n 5: .standard(proto: \"build_transfer\"),\n 6: .standard(proto: \"image_transfer\"),\n ]\n\n fileprivate class _StorageClass {\n var _buildID: String = String()\n var _packetType: Com_Apple_Container_Build_V1_ServerStream.OneOf_PacketType?\n\n // This property is used as the initial default value for new instances of the type.\n // The type itself is protecting the reference to its storage via CoW semantics.\n // This will force a copy to be made of this reference when the first mutation occurs;\n // hence, it is safe to mark this as `nonisolated(unsafe)`.\n static nonisolated(unsafe) let defaultInstance = _StorageClass()\n\n private init() {}\n\n init(copying source: _StorageClass) {\n _buildID = source._buildID\n _packetType = source._packetType\n }\n }\n\n fileprivate mutating func _uniqueStorage() -> _StorageClass {\n if !isKnownUniquelyReferenced(&_storage) {\n _storage = _StorageClass(copying: _storage)\n }\n return _storage\n }\n\n public mutating func decodeMessage(decoder: inout D) throws {\n _ = _uniqueStorage()\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &_storage._buildID) }()\n case 2: try {\n var v: Com_Apple_Container_Build_V1_IO?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .io(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .io(v)\n }\n }()\n case 3: try {\n var v: Com_Apple_Container_Build_V1_BuildError?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildError(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildError(v)\n }\n }()\n case 4: try {\n var v: Com_Apple_Container_Build_V1_RunComplete?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .commandComplete(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .commandComplete(v)\n }\n }()\n case 5: try {\n var v: Com_Apple_Container_Build_V1_BuildTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildTransfer(v)\n }\n }()\n case 6: try {\n var v: Com_Apple_Container_Build_V1_ImageTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .imageTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .imageTransfer(v)\n }\n }()\n default: break\n }\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !_storage._buildID.isEmpty {\n try visitor.visitSingularStringField(value: _storage._buildID, fieldNumber: 1)\n }\n switch _storage._packetType {\n case .io?: try {\n guard case .io(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 2)\n }()\n case .buildError?: try {\n guard case .buildError(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 3)\n }()\n case .commandComplete?: try {\n guard case .commandComplete(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n }()\n case .buildTransfer?: try {\n guard case .buildTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 5)\n }()\n case .imageTransfer?: try {\n guard case .imageTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 6)\n }()\n case nil: break\n }\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ServerStream, rhs: Com_Apple_Container_Build_V1_ServerStream) -> Bool {\n if lhs._storage !== rhs._storage {\n let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in\n let _storage = _args.0\n let rhs_storage = _args.1\n if _storage._buildID != rhs_storage._buildID {return false}\n if _storage._packetType != rhs_storage._packetType {return false}\n return true\n }\n if !storagesAreEqual {return false}\n }\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_IO: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IO\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"data\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularEnumField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.type != .stdin {\n try visitor.visitSingularEnumField(value: self.type, fieldNumber: 1)\n }\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_IO, rhs: Com_Apple_Container_Build_V1_IO) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.data != rhs.data {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_BuildError: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".BuildError\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"message\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularEnumField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.message) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.type != .buildFailed {\n try visitor.visitSingularEnumField(value: self.type, fieldNumber: 1)\n }\n if !self.message.isEmpty {\n try visitor.visitSingularStringField(value: self.message, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_BuildError, rhs: Com_Apple_Container_Build_V1_BuildError) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.message != rhs.message {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Platform: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Platform\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"architecture\"),\n 2: .same(proto: \"os\"),\n 3: .standard(proto: \"os_version\"),\n 4: .standard(proto: \"os_features\"),\n 5: .same(proto: \"variant\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.architecture) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.os) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.osVersion) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.osFeatures) }()\n case 5: try { try decoder.decodeSingularStringField(value: &self.variant) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.architecture.isEmpty {\n try visitor.visitSingularStringField(value: self.architecture, fieldNumber: 1)\n }\n if !self.os.isEmpty {\n try visitor.visitSingularStringField(value: self.os, fieldNumber: 2)\n }\n if !self.osVersion.isEmpty {\n try visitor.visitSingularStringField(value: self.osVersion, fieldNumber: 3)\n }\n if !self.osFeatures.isEmpty {\n try visitor.visitRepeatedStringField(value: self.osFeatures, fieldNumber: 4)\n }\n if !self.variant.isEmpty {\n try visitor.visitSingularStringField(value: self.variant, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Platform, rhs: Com_Apple_Container_Build_V1_Platform) -> Bool {\n if lhs.architecture != rhs.architecture {return false}\n if lhs.os != rhs.os {return false}\n if lhs.osVersion != rhs.osVersion {return false}\n if lhs.osFeatures != rhs.osFeatures {return false}\n if lhs.variant != rhs.variant {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Descriptor: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Descriptor\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"media_type\"),\n 2: .same(proto: \"digest\"),\n 3: .same(proto: \"size\"),\n 4: .same(proto: \"urls\"),\n 5: .same(proto: \"annotations\"),\n 6: .same(proto: \"platform\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.mediaType) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.digest) }()\n case 3: try { try decoder.decodeSingularInt64Field(value: &self.size) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.urls) }()\n case 5: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.annotations) }()\n case 6: try { try decoder.decodeSingularMessageField(value: &self._platform) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.mediaType.isEmpty {\n try visitor.visitSingularStringField(value: self.mediaType, fieldNumber: 1)\n }\n if !self.digest.isEmpty {\n try visitor.visitSingularStringField(value: self.digest, fieldNumber: 2)\n }\n if self.size != 0 {\n try visitor.visitSingularInt64Field(value: self.size, fieldNumber: 3)\n }\n if !self.urls.isEmpty {\n try visitor.visitRepeatedStringField(value: self.urls, fieldNumber: 4)\n }\n if !self.annotations.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.annotations, fieldNumber: 5)\n }\n try { if let v = self._platform {\n try visitor.visitSingularMessageField(value: v, fieldNumber: 6)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Descriptor, rhs: Com_Apple_Container_Build_V1_Descriptor) -> Bool {\n if lhs.mediaType != rhs.mediaType {return false}\n if lhs.digest != rhs.digest {return false}\n if lhs.size != rhs.size {return false}\n if lhs.urls != rhs.urls {return false}\n if lhs.annotations != rhs.annotations {return false}\n if lhs._platform != rhs._platform {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n"], ["/container/Sources/ContainerClient/Core/Bundle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport Foundation\n\npublic struct Bundle: Sendable {\n private static let initfsFilename = \"initfs.ext4\"\n private static let kernelFilename = \"kernel.json\"\n private static let kernelBinaryFilename = \"kernel.bin\"\n private static let containerRootFsBlockFilename = \"rootfs.ext4\"\n private static let containerRootFsFilename = \"rootfs.json\"\n\n static let containerConfigFilename = \"config.json\"\n\n /// The path to the bundle.\n public let path: URL\n\n public init(path: URL) {\n self.path = path\n }\n\n public var bootlog: URL {\n self.path.appendingPathComponent(\"vminitd.log\")\n }\n\n private var containerRootfsBlock: URL {\n self.path.appendingPathComponent(Self.containerRootFsBlockFilename)\n }\n\n private var containerRootfsConfig: URL {\n self.path.appendingPathComponent(Self.containerRootFsFilename)\n }\n\n public var containerRootfs: Filesystem {\n get throws {\n let data = try Data(contentsOf: containerRootfsConfig)\n let fs = try JSONDecoder().decode(Filesystem.self, from: data)\n return fs\n }\n }\n\n /// Return the initial filesystem for a sandbox.\n public var initialFilesystem: Filesystem {\n .block(\n format: \"ext4\",\n source: self.path.appendingPathComponent(Self.initfsFilename).path,\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n\n public var kernel: Kernel {\n get throws {\n try load(path: self.path.appendingPathComponent(Self.kernelFilename))\n }\n }\n\n public var configuration: ContainerConfiguration {\n get throws {\n try load(path: self.path.appendingPathComponent(Self.containerConfigFilename))\n }\n }\n}\n\nextension Bundle {\n public static func create(\n path: URL,\n initialFilesystem: Filesystem,\n kernel: Kernel,\n containerConfiguration: ContainerConfiguration? = nil\n ) throws -> Bundle {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n let kbin = path.appendingPathComponent(Self.kernelBinaryFilename)\n try FileManager.default.copyItem(at: kernel.path, to: kbin)\n var k = kernel\n k.path = kbin\n try write(path.appendingPathComponent(Self.kernelFilename), value: k)\n\n switch initialFilesystem.type {\n case .block(let fmt, _, _):\n guard fmt == \"ext4\" else {\n fatalError(\"ext4 is the only supported format for initial filesystem\")\n }\n // when saving the Initial Filesystem to the bundle\n // discard any filesystem information and just persist\n // the block into the Bundle.\n _ = try initialFilesystem.clone(to: path.appendingPathComponent(Self.initfsFilename).path)\n default:\n fatalError(\"invalid filesystem type for initial filesystem\")\n }\n let bundle = Bundle(path: path)\n if let containerConfiguration {\n try bundle.write(filename: Self.containerConfigFilename, value: containerConfiguration)\n }\n return bundle\n }\n}\n\nextension Bundle {\n /// Set the value of the configuration for the Bundle.\n public func set(configuration: ContainerConfiguration) throws {\n try write(filename: Self.containerConfigFilename, value: configuration)\n }\n\n /// Return the full filepath for a named resource in the Bundle.\n public func filePath(for name: String) -> URL {\n path.appendingPathComponent(name)\n }\n\n public func setContainerRootFs(cloning fs: Filesystem) throws {\n let cloned = try fs.clone(to: self.containerRootfsBlock.absolutePath())\n let fsData = try JSONEncoder().encode(cloned)\n try fsData.write(to: self.containerRootfsConfig)\n }\n\n /// Delete the bundle and all of the resources contained inside.\n public func delete() throws {\n try FileManager.default.removeItem(at: self.path)\n }\n\n public func write(filename: String, value: Encodable) throws {\n try Self.write(self.path.appendingPathComponent(filename), value: value)\n }\n\n private static func write(_ path: URL, value: Encodable) throws {\n let data = try JSONEncoder().encode(value)\n try data.write(to: path)\n }\n\n public func load(filename: String) throws -> T where T: Decodable {\n try load(path: self.path.appendingPathComponent(filename))\n }\n\n private func load(path: URL) throws -> T where T: Decodable {\n let data = try Data(contentsOf: path)\n return try JSONDecoder().decode(T.self, from: data)\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/AllocationOnlyVmnetNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\npublic actor AllocationOnlyVmnetNetwork: Network {\n private let log: Logger\n private var _state: NetworkState\n\n /// Configure a bridge network that allows external system access using\n /// network address translation.\n public init(\n configuration: NetworkConfiguration,\n log: Logger\n ) throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.unsupported, message: \"invalid network mode \\(configuration.mode)\")\n }\n\n guard configuration.subnet == nil else {\n throw ContainerizationError(.unsupported, message: \"subnet assignment is not yet implemented\")\n }\n\n self.log = log\n self._state = .created(configuration)\n }\n\n public var state: NetworkState {\n self._state\n }\n\n public nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws {\n try handler(nil)\n }\n\n public func start() async throws {\n guard case .created(let configuration) = _state else {\n throw ContainerizationError(.invalidState, message: \"cannot start network \\(_state.id) in \\(_state.state) state\")\n }\n var defaultSubnet = \"192.168.64.1/24\"\n\n log.info(\n \"starting allocation-only network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(NetworkMode.nat.rawValue)\",\n ]\n )\n\n if let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName) {\n // TODO: Make the suiteName a constant defined in ClientDefaults and use that.\n // This will need some re-working of dependencies between NetworkService and Client\n defaultSubnet = suite.string(forKey: \"network.subnet\") ?? defaultSubnet\n }\n\n let subnet = try CIDRAddress(defaultSubnet)\n let gateway = IPv4Address(fromValue: subnet.lower.value + 1)\n self._state = .running(configuration, NetworkStatus(address: subnet.description, gateway: gateway.description))\n log.info(\n \"started allocation-only network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n \"cidr\": \"\\(defaultSubnet)\",\n ]\n )\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\npublic actor NetworkService: Sendable {\n private let network: any Network\n private let log: Logger?\n private var allocator: AttachmentAllocator\n\n /// Set up a network service for the specified network.\n public init(\n network: any Network,\n log: Logger? = nil\n ) async throws {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let subnet = try CIDRAddress(status.address)\n\n let size = Int(subnet.upper.value - subnet.lower.value - 3)\n self.allocator = try AttachmentAllocator(lower: subnet.lower.value + 2, size: size)\n self.network = network\n self.log = log\n }\n\n @Sendable\n public func state(_ message: XPCMessage) async throws -> XPCMessage {\n let reply = message.reply()\n let state = await network.state\n try reply.setState(state)\n return reply\n }\n\n @Sendable\n public func allocate(_ message: XPCMessage) async throws -> XPCMessage {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let hostname = try message.hostname()\n let index = try await allocator.allocate(hostname: hostname)\n let subnet = try CIDRAddress(status.address)\n let ip = IPv4Address(fromValue: index)\n let attachment = Attachment(\n network: state.id,\n hostname: hostname,\n address: try CIDRAddress(ip, prefixLength: subnet.prefixLength).description,\n gateway: status.gateway\n )\n log?.info(\n \"allocated attachment\",\n metadata: [\n \"hostname\": \"\\(hostname)\",\n \"address\": \"\\(attachment.address)\",\n \"gateway\": \"\\(attachment.gateway)\",\n ])\n let reply = message.reply()\n try reply.setAttachment(attachment)\n try network.withAdditionalData {\n if let additionalData = $0 {\n try reply.setAdditionalData(additionalData.underlying)\n }\n }\n return reply\n }\n\n @Sendable\n public func deallocate(_ message: XPCMessage) async throws -> XPCMessage {\n let hostname = try message.hostname()\n try await allocator.deallocate(hostname: hostname)\n log?.info(\"released attachments\", metadata: [\"hostname\": \"\\(hostname)\"])\n return message.reply()\n }\n\n @Sendable\n public func lookup(_ message: XPCMessage) async throws -> XPCMessage {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let hostname = try message.hostname()\n let index = try await allocator.lookup(hostname: hostname)\n let reply = message.reply()\n guard let index else {\n return reply\n }\n\n let address = IPv4Address(fromValue: index)\n let subnet = try CIDRAddress(status.address)\n let attachment = Attachment(\n network: state.id,\n hostname: hostname,\n address: try CIDRAddress(address, prefixLength: subnet.prefixLength).description,\n gateway: status.gateway\n )\n log?.debug(\n \"lookup attachment\",\n metadata: [\n \"hostname\": \"\\(hostname)\",\n \"address\": \"\\(address)\",\n ])\n try reply.setAttachment(attachment)\n return reply\n }\n\n @Sendable\n public func disableAllocator(_ message: XPCMessage) async throws -> XPCMessage {\n let success = await allocator.disableAllocator()\n log?.info(\"attempted allocator disable\", metadata: [\"success\": \"\\(success)\"])\n let reply = message.reply()\n reply.setAllocatorDisabled(success)\n return reply\n }\n}\n\nextension XPCMessage {\n fileprivate func setAdditionalData(_ additionalData: xpc_object_t) throws {\n xpc_dictionary_set_value(self.underlying, NetworkKeys.additionalData.rawValue, additionalData)\n }\n\n fileprivate func setAllocatorDisabled(_ allocatorDisabled: Bool) {\n self.set(key: NetworkKeys.allocatorDisabled.rawValue, value: allocatorDisabled)\n }\n\n fileprivate func setAttachment(_ attachment: Attachment) throws {\n let data = try JSONEncoder().encode(attachment)\n self.set(key: NetworkKeys.attachment.rawValue, value: data)\n }\n\n fileprivate func setState(_ state: NetworkState) throws {\n let data = try JSONEncoder().encode(state)\n self.set(key: NetworkKeys.state.rawValue, value: data)\n }\n}\n"], ["/container/Sources/DNSServer/DNSServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\nimport NIOCore\nimport NIOPosix\n\n/// Provides a DNS server.\n/// - Parameters:\n/// - host: The host address on which to listen.\n/// - port: The port for the server to listen.\npublic struct DNSServer {\n public var handler: DNSHandler\n let log: Logger?\n\n public init(\n handler: DNSHandler,\n log: Logger? = nil\n ) {\n self.handler = handler\n self.log = log\n }\n\n public func run(host: String, port: Int) async throws {\n // TODO: TCP server\n let srv = try await DatagramBootstrap(group: NIOSingletons.posixEventLoopGroup)\n .channelOption(.socketOption(.so_reuseaddr), value: 1)\n .bind(host: host, port: port)\n .flatMapThrowing { channel in\n try NIOAsyncChannel(\n wrappingChannelSynchronously: channel,\n configuration: NIOAsyncChannel.Configuration(\n inboundType: AddressedEnvelope.self,\n outboundType: AddressedEnvelope.self\n )\n )\n }\n .get()\n\n try await srv.executeThenClose { inbound, outbound in\n for try await var packet in inbound {\n try await self.handle(outbound: outbound, packet: &packet)\n }\n }\n }\n\n public func run(socketPath: String) async throws {\n // TODO: TCP server\n let srv = try await DatagramBootstrap(group: NIOSingletons.posixEventLoopGroup)\n .bind(unixDomainSocketPath: socketPath, cleanupExistingSocketFile: true)\n .flatMapThrowing { channel in\n try NIOAsyncChannel(\n wrappingChannelSynchronously: channel,\n configuration: NIOAsyncChannel.Configuration(\n inboundType: AddressedEnvelope.self,\n outboundType: AddressedEnvelope.self\n )\n )\n }\n .get()\n\n try await srv.executeThenClose { inbound, outbound in\n for try await var packet in inbound {\n log?.debug(\"received packet from \\(packet.remoteAddress)\")\n try await self.handle(outbound: outbound, packet: &packet)\n log?.debug(\"sent packet\")\n }\n }\n }\n\n public func stop() async throws {}\n}\n"], ["/container/Sources/CLI/Container/ContainersCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct ContainersCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"containers\",\n abstract: \"Manage containers\",\n subcommands: [\n ContainerCreate.self,\n ContainerDelete.self,\n ContainerExec.self,\n ContainerInspect.self,\n ContainerKill.self,\n ContainerList.self,\n ContainerLogs.self,\n ContainerStart.self,\n ContainerStop.self,\n ],\n aliases: [\"container\", \"c\"]\n )\n }\n}\n"], ["/container/Sources/CLI/Registry/Logout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\n\nextension Application {\n struct Logout: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: \"Log out from a registry\")\n\n @Argument(help: \"Registry server name\")\n var registry: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let keychain = KeychainHelper(id: Constants.keychainID)\n let r = Reference.resolveDomain(domain: registry)\n try keychain.delete(domain: r)\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ContentServiceHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\n\npublic struct ContentServiceHarness: Sendable {\n private let log: Logging.Logger\n private let service: ContentStoreService\n\n public init(service: ContentStoreService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n public func get(_ message: XPCMessage) async throws -> XPCMessage {\n let d = message.string(key: .digest)\n guard let d else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n guard let path = try await service.get(digest: d) else {\n let err = ContainerizationError(.notFound, message: \"digest \\(d) not found\")\n let reply = message.reply()\n reply.set(error: err)\n return reply\n }\n let reply = message.reply()\n reply.set(key: .contentPath, value: path.path(percentEncoded: false))\n return reply\n }\n\n @Sendable\n public func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .digests)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n let digests = try JSONDecoder().decode([String].self, from: data)\n let (deleted, size) = try await self.service.delete(digests: digests)\n let d = try JSONEncoder().encode(deleted)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n reply.set(key: .size, value: size)\n return reply\n }\n\n @Sendable\n public func clean(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .digests)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n let digests = try JSONDecoder().decode([String].self, from: data)\n let (deleted, size) = try await self.service.delete(keeping: digests)\n let d = try JSONEncoder().encode(deleted)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n reply.set(key: .size, value: size)\n return reply\n }\n\n @Sendable\n public func newIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let session = try await self.service.newIngestSession()\n let id = session.id\n let dir = session.ingestDir\n let reply = message.reply()\n reply.set(key: .directory, value: dir.path(percentEncoded: false))\n reply.set(key: .ingestSessionId, value: id)\n return reply\n }\n\n @Sendable\n public func cancelIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .ingestSessionId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"missing ingest session id\")\n }\n try await self.service.cancelIngestSession(id)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func completeIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .ingestSessionId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"missing ingest session id\")\n }\n let ingested = try await self.service.completeIngestSession(id)\n let d = try JSONEncoder().encode(ingested)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n return reply\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientDefaults.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CVersion\nimport ContainerizationError\nimport Foundation\n\npublic enum ClientDefaults {\n private static let userDefaultDomain = \"com.apple.container.defaults\"\n\n public enum Keys: String {\n case defaultBuilderImage = \"image.builder\"\n case defaultDNSDomain = \"dns.domain\"\n case defaultRegistryDomain = \"registry.domain\"\n case defaultInitImage = \"image.init\"\n case defaultKernelURL = \"kernel.url\"\n case defaultKernelBinaryPath = \"kernel.binaryPath\"\n case buildRosetta = \"build.rosetta\"\n }\n\n public static func set(value: String, key: ClientDefaults.Keys) {\n udSuite.set(value, forKey: key.rawValue)\n }\n\n public static func unset(key: ClientDefaults.Keys) {\n udSuite.removeObject(forKey: key.rawValue)\n }\n\n public static func get(key: ClientDefaults.Keys) -> String {\n let current = udSuite.string(forKey: key.rawValue)\n return current ?? key.defaultValue\n }\n\n public static func getOptional(key: ClientDefaults.Keys) -> String? {\n udSuite.string(forKey: key.rawValue)\n }\n\n public static func setBool(value: Bool, key: ClientDefaults.Keys) {\n udSuite.set(value, forKey: key.rawValue)\n }\n\n public static func getBool(key: ClientDefaults.Keys) -> Bool? {\n guard udSuite.object(forKey: key.rawValue) != nil else { return nil }\n return udSuite.bool(forKey: key.rawValue)\n }\n\n private static var udSuite: UserDefaults {\n guard let ud = UserDefaults.init(suiteName: self.userDefaultDomain) else {\n fatalError(\"Failed to initialize UserDefaults for domain \\(self.userDefaultDomain)\")\n }\n return ud\n }\n}\n\nextension ClientDefaults.Keys {\n fileprivate var defaultValue: String {\n switch self {\n case .defaultKernelURL:\n return \"https://github.com/kata-containers/kata-containers/releases/download/3.17.0/kata-static-3.17.0-arm64.tar.xz\"\n case .defaultKernelBinaryPath:\n return \"opt/kata/share/kata-containers/vmlinux-6.12.28-153\"\n case .defaultBuilderImage:\n let tag = String(cString: get_container_builder_shim_version())\n return \"ghcr.io/apple/container-builder-shim/builder:\\(tag)\"\n case .defaultDNSDomain:\n return \"test\"\n case .defaultRegistryDomain:\n return \"docker.io\"\n case .defaultInitImage:\n let tag = String(cString: get_swift_containerization_version())\n guard tag != \"latest\" else {\n return \"vminit:latest\"\n }\n return \"ghcr.io/apple/containerization/vminit:\\(tag)\"\n case .buildRosetta:\n // This is a boolean key, not used with the string get() method\n return \"true\"\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemDNS.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct SystemDNS: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"dns\",\n abstract: \"Manage local DNS domains\",\n subcommands: [\n DNSCreate.self,\n DNSDelete.self,\n DNSList.self,\n DNSDefault.self,\n ]\n )\n }\n}\n"], ["/container/Sources/CLI/System/SystemCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct SystemCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"system\",\n abstract: \"Manage system components\",\n subcommands: [\n SystemDNS.self,\n SystemLogs.self,\n SystemStart.self,\n SystemStop.self,\n SystemStatus.self,\n SystemKernel.self,\n ],\n aliases: [\"s\"]\n )\n }\n}\n"], ["/container/Sources/ContainerClient/ContainerizationProgressAdapter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport TerminalProgress\n\npublic enum ContainerizationProgressAdapter: ProgressAdapter {\n public static func handler(from progressUpdate: ProgressUpdateHandler?) -> ProgressHandler? {\n guard let progressUpdate else {\n return nil\n }\n return { events in\n var updateEvents = [ProgressUpdateEvent]()\n for event in events {\n if event.event == \"add-items\" {\n if let items = event.value as? Int {\n updateEvents.append(.addItems(items))\n }\n } else if event.event == \"add-total-items\" {\n if let totalItems = event.value as? Int {\n updateEvents.append(.addTotalItems(totalItems))\n }\n } else if event.event == \"add-size\" {\n if let size = event.value as? Int64 {\n updateEvents.append(.addSize(size))\n }\n } else if event.event == \"add-total-size\" {\n if let totalSize = event.value as? Int64 {\n updateEvents.append(.addTotalSize(totalSize))\n }\n }\n }\n await progressUpdate(updateEvents)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/ProgressUpdateClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\n/// A client that can be used to receive progress updates from a service.\npublic actor ProgressUpdateClient {\n private var endpointConnection: xpc_connection_t?\n private var endpoint: xpc_endpoint_t?\n\n /// Creates a new client for receiving progress updates from a service.\n /// - Parameters:\n /// - progressUpdate: The handler to invoke when progress updates are received.\n /// - request: The XPC message to send the endpoint to connect to.\n public init(for progressUpdate: @escaping ProgressUpdateHandler, request: XPCMessage) async {\n createEndpoint(for: progressUpdate)\n setEndpoint(to: request)\n }\n\n /// Performs a connection setup for receiving progress updates.\n /// - Parameter progressUpdate: The handler to invoke when progress updates are received.\n private func createEndpoint(for progressUpdate: @escaping ProgressUpdateHandler) {\n let endpointConnection = xpc_connection_create(nil, nil)\n // Access to `reversedConnection` is protected by a lock\n nonisolated(unsafe) var reversedConnection: xpc_connection_t?\n let reversedConnectionLock = NSLock()\n xpc_connection_set_event_handler(endpointConnection) { connectionMessage in\n reversedConnectionLock.withLock {\n switch xpc_get_type(connectionMessage) {\n case XPC_TYPE_CONNECTION:\n reversedConnection = connectionMessage\n xpc_connection_set_event_handler(connectionMessage) { updateMessage in\n Self.handleProgressUpdate(updateMessage, progressUpdate: progressUpdate)\n }\n xpc_connection_activate(connectionMessage)\n case XPC_TYPE_ERROR:\n if let reversedConnectionUnwrapped = reversedConnection {\n xpc_connection_cancel(reversedConnectionUnwrapped)\n reversedConnection = nil\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(connectionMessage))\")\n }\n }\n }\n xpc_connection_activate(endpointConnection)\n\n self.endpointConnection = endpointConnection\n self.endpoint = xpc_endpoint_create(endpointConnection)\n }\n\n /// Performs a setup of the progress update endpoint.\n /// - Parameter request: The XPC message containing the endpoint to use.\n private func setEndpoint(to request: XPCMessage) {\n guard let endpoint else {\n return\n }\n request.set(key: .progressUpdateEndpoint, value: endpoint)\n }\n\n /// Performs cleanup of the created connection.\n public func finish() {\n if let endpointConnection {\n xpc_connection_cancel(endpointConnection)\n self.endpointConnection = nil\n }\n }\n\n private static func handleProgressUpdate(_ message: xpc_object_t, progressUpdate: @escaping ProgressUpdateHandler) {\n switch xpc_get_type(message) {\n case XPC_TYPE_DICTIONARY:\n let message = XPCMessage(object: message)\n handleProgressUpdate(message, progressUpdate: progressUpdate)\n case XPC_TYPE_ERROR:\n break\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(message))\")\n break\n }\n }\n\n private static func handleProgressUpdate(_ message: XPCMessage, progressUpdate: @escaping ProgressUpdateHandler) {\n var events = [ProgressUpdateEvent]()\n\n if let description = message.string(key: .progressUpdateSetDescription) {\n events.append(.setDescription(description))\n }\n if let subDescription = message.string(key: .progressUpdateSetSubDescription) {\n events.append(.setSubDescription(subDescription))\n }\n if let itemsName = message.string(key: .progressUpdateSetItemsName) {\n events.append(.setItemsName(itemsName))\n }\n var tasks = message.int(key: .progressUpdateAddTasks)\n if tasks != 0 {\n events.append(.addTasks(tasks))\n }\n tasks = message.int(key: .progressUpdateSetTasks)\n if tasks != 0 {\n events.append(.setTasks(tasks))\n }\n var totalTasks = message.int(key: .progressUpdateAddTotalTasks)\n if totalTasks != 0 {\n events.append(.addTotalTasks(totalTasks))\n }\n totalTasks = message.int(key: .progressUpdateSetTotalTasks)\n if totalTasks != 0 {\n events.append(.setTotalTasks(totalTasks))\n }\n var items = message.int(key: .progressUpdateAddItems)\n if items != 0 {\n events.append(.addItems(items))\n }\n items = message.int(key: .progressUpdateSetItems)\n if items != 0 {\n events.append(.setItems(items))\n }\n var totalItems = message.int(key: .progressUpdateAddTotalItems)\n if totalItems != 0 {\n events.append(.addTotalItems(totalItems))\n }\n totalItems = message.int(key: .progressUpdateSetTotalItems)\n if totalItems != 0 {\n events.append(.setTotalItems(totalItems))\n }\n var size = message.int64(key: .progressUpdateAddSize)\n if size != 0 {\n events.append(.addSize(size))\n }\n size = message.int64(key: .progressUpdateSetSize)\n if size != 0 {\n events.append(.setSize(size))\n }\n var totalSize = message.int64(key: .progressUpdateAddTotalSize)\n if totalSize != 0 {\n events.append(.addTotalSize(totalSize))\n }\n totalSize = message.int64(key: .progressUpdateSetTotalSize)\n if totalSize != 0 {\n events.append(.setTotalSize(totalSize))\n }\n\n Task {\n await progressUpdate(events)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/RequestScheme.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\n\n/// The URL scheme to be used for a HTTP request.\npublic enum RequestScheme: String, Sendable {\n case http = \"http\"\n case https = \"https\"\n\n case auto = \"auto\"\n\n public init(_ rawValue: String) throws {\n switch rawValue {\n case RequestScheme.http.rawValue:\n self = .http\n case RequestScheme.https.rawValue:\n self = .https\n case RequestScheme.auto.rawValue:\n self = .auto\n default:\n throw ContainerizationError(.invalidArgument, message: \"Unsupported scheme \\(rawValue)\")\n }\n }\n\n /// Returns the prescribed protocol to use while making a HTTP request to a webserver\n /// - Parameter host: The domain or IP address of the webserver\n /// - Returns: RequestScheme\n package func schemeFor(host: String) throws -> Self {\n guard host.count > 0 else {\n throw ContainerizationError(.invalidArgument, message: \"Host cannot be empty\")\n }\n switch self {\n case .http, .https:\n return self\n case .auto:\n return Self.isInternalHost(host: host) ? .http : .https\n }\n }\n\n /// Checks if the given `host` string is a private IP address\n /// or a domain typically reachable only on the local system.\n private static func isInternalHost(host: String) -> Bool {\n if host.hasPrefix(\"localhost\") || host.hasPrefix(\"127.\") {\n return true\n }\n if host.hasPrefix(\"192.168.\") || host.hasPrefix(\"10.\") {\n return true\n }\n let regex = \"(^172\\\\.1[6-9]\\\\.)|(^172\\\\.2[0-9]\\\\.)|(^172\\\\.3[0-1]\\\\.)\"\n if host.range(of: regex, options: .regularExpression) != nil {\n return true\n }\n let dnsDomain = ClientDefaults.get(key: .defaultDNSDomain)\n if host.hasSuffix(\".\\(dnsDomain)\") {\n return true\n }\n return false\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+Terminal.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nenum EscapeSequence {\n static let hideCursor = \"\\u{001B}[?25l\"\n static let showCursor = \"\\u{001B}[?25h\"\n static let moveUp = \"\\u{001B}[1A\"\n}\n\nextension ProgressBar {\n private var terminalWidth: Int {\n guard\n let terminalHandle = term,\n let terminal = try? Terminal(descriptor: terminalHandle.fileDescriptor)\n else {\n return 0\n }\n\n let terminalWidth = (try? Int(terminal.size.width)) ?? 0\n return terminalWidth\n }\n\n /// Clears the progress bar and resets the cursor.\n public func clearAndResetCursor() {\n clear()\n resetCursor()\n }\n\n /// Clears the progress bar.\n public func clear() {\n displayText(\"\")\n }\n\n /// Resets the cursor.\n public func resetCursor() {\n display(EscapeSequence.showCursor)\n }\n\n func display(_ text: String) {\n guard let term else {\n return\n }\n termQueue.sync {\n try? term.write(contentsOf: Data(text.utf8))\n try? term.synchronize()\n }\n }\n\n func displayText(_ text: String, terminating: String = \"\\r\") {\n var text = text\n\n // Clears previously printed characters if the new string is shorter.\n text += String(repeating: \" \", count: max(printedWidth - text.count, 0))\n printedWidth = text.count\n state.withLock {\n $0.output = text\n }\n\n // Clears previously printed lines.\n var lines = \"\"\n if terminating.hasSuffix(\"\\r\") && terminalWidth > 0 {\n let lineCount = (text.count - 1) / terminalWidth\n for _ in 0.. XPCMessage {\n let kernelFilePath = try message.kernelFilePath()\n let platform = try message.platform()\n\n guard let kernelTarUrl = try message.kernelTarURL() else {\n // We have been given a path to a kernel binary on disk\n guard let kernelFile = URL(string: kernelFilePath) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid kernel file path: \\(kernelFilePath)\")\n }\n try await self.service.installKernel(kernelFile: kernelFile, platform: platform)\n return message.reply()\n }\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await self.service.installKernelFrom(tar: kernelTarUrl, kernelFilePath: kernelFilePath, platform: platform, progressUpdate: progressUpdateService?.handler)\n return message.reply()\n }\n\n public func getDefaultKernel(_ message: XPCMessage) async throws -> XPCMessage {\n guard let platformData = message.dataNoCopy(key: .systemPlatform) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing SystemPlatform\")\n }\n let platform = try JSONDecoder().decode(SystemPlatform.self, from: platformData)\n let kernel = try await self.service.getDefaultKernel(platform: platform)\n let reply = message.reply()\n let data = try JSONEncoder().encode(kernel)\n reply.set(key: .kernel, value: data)\n return reply\n }\n}\n\nextension XPCMessage {\n fileprivate func platform() throws -> SystemPlatform {\n guard let platformData = self.dataNoCopy(key: .systemPlatform) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing SystemPlatform in XPC Message\")\n }\n let platform = try JSONDecoder().decode(SystemPlatform.self, from: platformData)\n return platform\n }\n\n fileprivate func kernelFilePath() throws -> String {\n guard let kernelFilePath = self.string(key: .kernelFilePath) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing kernel file path in XPC Message\")\n }\n return kernelFilePath\n }\n\n fileprivate func kernelTarURL() throws -> URL? {\n guard let kernelTarURLString = self.string(key: .kernelTarURL) else {\n return nil\n }\n guard let k = URL(string: kernelTarURLString) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse URL from \\(kernelTarURLString)\")\n }\n return k\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct NetworkCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"network\",\n abstract: \"Manage container networks\",\n subcommands: [\n NetworkCreate.self,\n NetworkDelete.self,\n NetworkList.self,\n NetworkInspect.self,\n ],\n aliases: [\"n\"]\n )\n }\n}\n"], ["/container/Sources/APIServer/Plugin/PluginsHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nstruct PluginsHarness {\n private let log: Logging.Logger\n private let service: PluginsService\n\n init(service: PluginsService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func load(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.load(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func get(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n let plugin = try await service.get(name: name)\n let data = try JSONEncoder().encode(plugin)\n\n let reply = message.reply()\n reply.set(key: .plugin, value: data)\n return reply\n }\n\n @Sendable\n func restart(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.restart(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func unload(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.unload(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let plugins = try await service.list()\n\n let data = try JSONEncoder().encode(plugins)\n\n let reply = message.reply()\n reply.set(key: .plugins, value: data)\n return reply\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport Foundation\n\n/// A client for interacting with a single network.\npublic struct NetworkClient: Sendable {\n // FIXME: need more flexibility than a hard-coded constant?\n static let label = \"com.apple.container.network.container-network-vmnet\"\n\n private var machServiceLabel: String {\n \"\\(Self.label).\\(id)\"\n }\n\n let id: String\n\n /// Create a client for a network.\n public init(id: String) {\n self.id = id\n }\n}\n\n// Runtime Methods\nextension NetworkClient {\n public func state() async throws -> NetworkState {\n let request = XPCMessage(route: NetworkRoutes.state.rawValue)\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n let state = try response.state()\n return state\n }\n\n public func allocate(hostname: String) async throws -> (attachment: Attachment, additionalData: XPCMessage?) {\n let request = XPCMessage(route: NetworkRoutes.allocate.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n let attachment = try response.attachment()\n let additionalData = response.additionalData()\n return (attachment, additionalData)\n }\n\n public func deallocate(hostname: String) async throws {\n let request = XPCMessage(route: NetworkRoutes.deallocate.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func lookup(hostname: String) async throws -> Attachment? {\n let request = XPCMessage(route: NetworkRoutes.lookup.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.dataNoCopy(key: NetworkKeys.attachment.rawValue).map {\n try JSONDecoder().decode(Attachment.self, from: $0)\n }\n }\n\n public func disableAllocator() async throws -> Bool {\n let request = XPCMessage(route: NetworkRoutes.disableAllocator.rawValue)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.allocatorDisabled()\n }\n\n private func createClient() -> XPCClient {\n XPCClient(service: machServiceLabel)\n }\n}\n\nextension XPCMessage {\n func additionalData() -> XPCMessage? {\n guard let additionalData = xpc_dictionary_get_dictionary(self.underlying, NetworkKeys.additionalData.rawValue) else {\n return nil\n }\n return XPCMessage(object: additionalData)\n }\n\n func allocatorDisabled() throws -> Bool {\n self.bool(key: NetworkKeys.allocatorDisabled.rawValue)\n }\n\n func attachment() throws -> Attachment {\n let data = self.dataNoCopy(key: NetworkKeys.attachment.rawValue)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No network attachment snapshot data in message\")\n }\n return try JSONDecoder().decode(Attachment.self, from: data)\n }\n\n func hostname() throws -> String {\n let hostname = self.string(key: NetworkKeys.hostname.rawValue)\n guard let hostname else {\n throw ContainerizationError(.invalidArgument, message: \"No hostname data in message\")\n }\n return hostname\n }\n\n func state() throws -> NetworkState {\n let data = self.dataNoCopy(key: NetworkKeys.state.rawValue)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No network snapshot data in message\")\n }\n return try JSONDecoder().decode(NetworkState.self, from: data)\n }\n}\n"], ["/container/Sources/APIServer/ContainerDNSHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\nimport DNSServer\n\n/// Handler that uses table lookup to resolve hostnames.\nstruct ContainerDNSHandler: DNSHandler {\n private let networkService: NetworksService\n private let ttl: UInt32\n\n public init(networkService: NetworksService, ttl: UInt32 = 5) {\n self.networkService = networkService\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n let record: ResourceRecord?\n switch question.type {\n case ResourceRecordType.host:\n record = try await answerHost(question: question)\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n\n guard let record else {\n return nil\n }\n\n return Message(\n id: query.id,\n type: .response,\n returnCode: .noError,\n questions: query.questions,\n answers: [record]\n )\n }\n\n private func answerHost(question: Question) async throws -> ResourceRecord? {\n guard let ipAllocation = try await networkService.lookup(hostname: question.name) else {\n return nil\n }\n\n let components = ipAllocation.address.split(separator: \"/\")\n guard !components.isEmpty else {\n throw DNSResolverError.serverError(\"Invalid IP format: empty address\")\n }\n\n let ipString = String(components[0])\n guard let ip = IPv4(ipString) else {\n throw DNSResolverError.serverError(\"Failed to parse IP address: \\(ipString)\")\n }\n\n return HostRecord(name: question.name, ttl: ttl, ip: ip)\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildAPI+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationOCI\n\npublic typealias IO = Com_Apple_Container_Build_V1_IO\npublic typealias InfoRequest = Com_Apple_Container_Build_V1_InfoRequest\npublic typealias InfoResponse = Com_Apple_Container_Build_V1_InfoResponse\npublic typealias ClientStream = Com_Apple_Container_Build_V1_ClientStream\npublic typealias ServerStream = Com_Apple_Container_Build_V1_ServerStream\npublic typealias ImageTransfer = Com_Apple_Container_Build_V1_ImageTransfer\npublic typealias BuildTransfer = Com_Apple_Container_Build_V1_BuildTransfer\npublic typealias BuilderClient = Com_Apple_Container_Build_V1_BuilderNIOClient\npublic typealias BuilderClientAsync = Com_Apple_Container_Build_V1_BuilderAsyncClient\npublic typealias BuilderClientProtocol = Com_Apple_Container_Build_V1_BuilderClientProtocol\npublic typealias BuilderClientAsyncProtocol = Com_Apple_Container_Build_V1_BuilderAsyncClient\n\nextension BuildTransfer {\n func stage() -> String? {\n let stage = self.metadata[\"stage\"]\n return stage == \"\" ? nil : stage\n }\n\n func method() -> String? {\n let method = self.metadata[\"method\"]\n return method == \"\" ? nil : method\n }\n\n func includePatterns() -> [String]? {\n guard let includePatternsString = self.metadata[\"include-patterns\"] else {\n return nil\n }\n return includePatternsString == \"\" ? nil : includePatternsString.components(separatedBy: \",\")\n }\n\n func followPaths() -> [String]? {\n guard let followPathString = self.metadata[\"followpaths\"] else {\n return nil\n }\n return followPathString == \"\" ? nil : followPathString.components(separatedBy: \",\")\n }\n\n func mode() -> String? {\n self.metadata[\"mode\"]\n }\n\n func size() -> Int? {\n guard let sizeStr = self.metadata[\"size\"] else {\n return nil\n }\n return sizeStr == \"\" ? nil : Int(sizeStr)\n }\n\n func offset() -> UInt64? {\n guard let offsetStr = self.metadata[\"offset\"] else {\n return nil\n }\n return offsetStr == \"\" ? nil : UInt64(offsetStr)\n }\n\n func len() -> Int? {\n guard let lenStr = self.metadata[\"length\"] else {\n return nil\n }\n return lenStr == \"\" ? nil : Int(lenStr)\n }\n}\n\nextension ImageTransfer {\n func stage() -> String? {\n self.metadata[\"stage\"]\n }\n\n func method() -> String? {\n self.metadata[\"method\"]\n }\n\n func ref() -> String? {\n self.metadata[\"ref\"]\n }\n\n func platform() throws -> Platform? {\n let metadata = self.metadata\n guard let platform = metadata[\"platform\"] else {\n return nil\n }\n return try Platform(from: platform)\n }\n\n func mode() -> String? {\n self.metadata[\"mode\"]\n }\n\n func size() -> Int? {\n let metadata = self.metadata\n guard let sizeStr = metadata[\"size\"] else {\n return nil\n }\n return Int(sizeStr)\n }\n\n func len() -> Int? {\n let metadata = self.metadata\n guard let lenStr = metadata[\"length\"] else {\n return nil\n }\n return Int(lenStr)\n }\n\n func offset() -> UInt64? {\n let metadata = self.metadata\n guard let offsetStr = metadata[\"offset\"] else {\n return nil\n }\n return UInt64(offsetStr)\n }\n}\n\nextension ServerStream {\n func getImageTransfer() -> ImageTransfer? {\n if case .imageTransfer(let v) = self.packetType {\n return v\n }\n return nil\n }\n\n func getBuildTransfer() -> BuildTransfer? {\n if case .buildTransfer(let v) = self.packetType {\n return v\n }\n return nil\n }\n\n func getIO() -> IO? {\n if case .io(let v) = self.packetType {\n return v\n }\n return nil\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A configuration for displaying a progress bar.\npublic struct ProgressConfig: Sendable {\n /// The file handle for progress updates.\n let terminal: FileHandle\n /// The initial description of the progress bar.\n let initialDescription: String\n /// The initial additional description of the progress bar.\n let initialSubDescription: String\n /// The initial items name (e.g., \"files\").\n let initialItemsName: String\n /// A flag indicating whether to show a spinner (e.g., \"⠋\").\n /// The spinner is hidden when a progress bar is shown.\n public let showSpinner: Bool\n /// A flag indicating whether to show tasks and total tasks (e.g., \"[1]\" or \"[1/3]\").\n public let showTasks: Bool\n /// A flag indicating whether to show the description (e.g., \"Downloading...\").\n public let showDescription: Bool\n /// A flag indicating whether to show a percentage (e.g., \"100%\").\n /// The percentage is hidden when no total size and total items are set.\n public let showPercent: Bool\n /// A flag indicating whether to show a progress bar (e.g., \"|███ |\").\n /// The progress bar is hidden when no total size and total items are set.\n public let showProgressBar: Bool\n /// A flag indicating whether to show items and total items (e.g., \"(22 it)\" or \"(22/22 it)\").\n public let showItems: Bool\n /// A flag indicating whether to show a size and a total size (e.g., \"(22 MB)\" or \"(22/22 MB)\").\n public let showSize: Bool\n /// A flag indicating whether to show a speed (e.g., \"(4.834 MB/s)\").\n /// The speed is combined with the size and total size (e.g., \"(22/22 MB, 4.834 MB/s)\").\n /// The speed is hidden when no total size is set.\n public let showSpeed: Bool\n /// A flag indicating whether to show the elapsed time (e.g., \"[4s]\").\n public let showTime: Bool\n /// The flag indicating whether to ignore small size values (less than 1 MB). For example, this may help to avoid reaching 100% after downloading metadata before downloading content.\n public let ignoreSmallSize: Bool\n /// The initial total tasks of the progress bar.\n let initialTotalTasks: Int?\n /// The initial total size of the progress bar.\n let initialTotalSize: Int64?\n /// The initial total items of the progress bar.\n let initialTotalItems: Int?\n /// The width of the progress bar in characters.\n public let width: Int\n /// The theme of the progress bar.\n public let theme: ProgressTheme\n /// The flag indicating whether to clear the progress bar before resetting the cursor.\n public let clearOnFinish: Bool\n /// The flag indicating whether to update the progress bar.\n public let disableProgressUpdates: Bool\n /// Creates a new instance of `ProgressConfig`.\n /// - Parameters:\n /// - terminal: The file handle for progress updates. The default value is `FileHandle.standardError`.\n /// - description: The initial description of the progress bar. The default value is `\"\"`.\n /// - subDescription: The initial additional description of the progress bar. The default value is `\"\"`.\n /// - itemsName: The initial items name. The default value is `\"it\"`.\n /// - showSpinner: A flag indicating whether to show a spinner. The default value is `true`.\n /// - showTasks: A flag indicating whether to show tasks and total tasks. The default value is `false`.\n /// - showDescription: A flag indicating whether to show the description. The default value is `true`.\n /// - showPercent: A flag indicating whether to show a percentage. The default value is `true`.\n /// - showProgressBar: A flag indicating whether to show a progress bar. The default value is `false`.\n /// - showItems: A flag indicating whether to show items and a total items. The default value is `false`.\n /// - showSize: A flag indicating whether to show a size and a total size. The default value is `true`.\n /// - showSpeed: A flag indicating whether to show a speed. The default value is `true`.\n /// - showTime: A flag indicating whether to show the elapsed time. The default value is `true`.\n /// - ignoreSmallSize: A flag indicating whether to ignore small size values. The default value is `false`.\n /// - totalTasks: The initial total tasks of the progress bar. The default value is `nil`.\n /// - totalItems: The initial total items of the progress bar. The default value is `nil`.\n /// - totalSize: The initial total size of the progress bar. The default value is `nil`.\n /// - width: The width of the progress bar in characters. The default value is `120`.\n /// - theme: The theme of the progress bar. The default value is `nil`.\n /// - clearOnFinish: The flag indicating whether to clear the progress bar before resetting the cursor. The default is `true`.\n /// - disableProgressUpdates: The flag indicating whether to update the progress bar. The default is `false`.\n public init(\n terminal: FileHandle = .standardError,\n description: String = \"\",\n subDescription: String = \"\",\n itemsName: String = \"it\",\n showSpinner: Bool = true,\n showTasks: Bool = false,\n showDescription: Bool = true,\n showPercent: Bool = true,\n showProgressBar: Bool = false,\n showItems: Bool = false,\n showSize: Bool = true,\n showSpeed: Bool = true,\n showTime: Bool = true,\n ignoreSmallSize: Bool = false,\n totalTasks: Int? = nil,\n totalItems: Int? = nil,\n totalSize: Int64? = nil,\n width: Int = 120,\n theme: ProgressTheme? = nil,\n clearOnFinish: Bool = true,\n disableProgressUpdates: Bool = false\n ) throws {\n if let totalTasks {\n guard totalTasks > 0 else {\n throw Error.invalid(\"totalTasks must be greater than zero\")\n }\n }\n if let totalItems {\n guard totalItems > 0 else {\n throw Error.invalid(\"totalItems must be greater than zero\")\n }\n }\n if let totalSize {\n guard totalSize > 0 else {\n throw Error.invalid(\"totalSize must be greater than zero\")\n }\n }\n\n self.terminal = terminal\n self.initialDescription = description\n self.initialSubDescription = subDescription\n self.initialItemsName = itemsName\n\n self.showSpinner = showSpinner\n self.showTasks = showTasks\n self.showDescription = showDescription\n self.showPercent = showPercent\n self.showProgressBar = showProgressBar\n self.showItems = showItems\n self.showSize = showSize\n self.showSpeed = showSpeed\n self.showTime = showTime\n\n self.ignoreSmallSize = ignoreSmallSize\n self.initialTotalTasks = totalTasks\n self.initialTotalItems = totalItems\n self.initialTotalSize = totalSize\n\n self.width = width\n self.theme = theme ?? DefaultProgressTheme()\n self.clearOnFinish = clearOnFinish\n self.disableProgressUpdates = disableProgressUpdates\n }\n}\n\nextension ProgressConfig {\n /// An enumeration of errors that can occur when creating a `ProgressConfig`.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalid(String)\n\n /// The description of the error.\n public var description: String {\n switch self {\n case .invalid(let reason):\n return \"Failed to validate config (\\(reason))\"\n }\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\nimport Foundation\n\n/// PluginConfig details all of the fields to describe and register a plugin.\n/// A plugin is registered by creating a subdirectory `/user-plugins`,\n/// where the name of the subdirectory is the name of the plugin, and then placing a\n/// file named `config.json` inside with the schema below.\n/// If `services` is filled in then there MUST be a binary named matching the plugin name\n/// in a `bin` subdirectory inside the same directory as the `config.json`.\n/// An example of a valid plugin directory structure would be\n/// $ tree foobar\n/// foobar\n/// ├── bin\n/// │ └── foobar\n/// └── config.json\npublic struct PluginConfig: Sendable, Codable {\n /// Categories of services that can be offered through plugins.\n public enum DaemonPluginType: String, Sendable, Codable {\n /// A runtime plugin provides an XPC API through which the lifecycle\n /// of a **single** container can be managed.\n /// A runtime daemon plugin would typically also have a counterpart\n /// CLI plugin which knows how to talk to the API exposed by the runtime plugin.\n /// The API server ensures that a single instance of the plugin is configured\n /// for a given container such that the client can communicate with it given an instance id.\n case runtime\n /// A network plugin provides an XPC API through which IP address allocations on a given\n /// network can be managed. The API server ensures that a single instance\n /// of this plugin is configured for a given network. Similar to the runtime plugin, it typically\n /// would be accompanied by a CLI plugin that knows how to communicate with the XPC API\n /// given an instance id.\n case network\n /// A core plugin provides an XPC API to manage a given type of resource.\n /// The API server ensures that there exist only a single running instance\n /// of this plugin type. A core plugin can be thought of a singleton whose lifecycle\n /// is tied to that of the API server. Core plugins can be used to expand the base functionality\n /// provided by the API server. As with the other plugin types, it maybe associated with a client\n /// side plugin that communicates with the XPC service exposed by the daemon plugin.\n case core\n /// Reserved for future use. Currently there is no difference between a core and auxiliary daemon plugin.\n case auxiliary\n }\n\n // An XPC service that the plugin publishes.\n public struct Service: Sendable, Codable {\n /// The type of the service the daemon is exposing.\n /// One plugin can expose multiple services of different types.\n ///\n /// The plugin MUST expose a MachService at\n /// `com.apple.container.{type}.{name}.[{id}]` for\n /// each service that it exposes.\n public let type: DaemonPluginType\n /// Optional description of this service.\n public let description: String?\n }\n\n /// Descriptor for the services that the plugin offers.\n public struct ServicesConfig: Sendable, Codable {\n /// Load the plugin into launchd when the API server starts.\n public let loadAtBoot: Bool\n /// Launch the plugin binary as soon as it loads into launchd.\n public let runAtLoad: Bool\n /// The service types that the plugin provides.\n public let services: [Service]\n /// An optional parameter that include any command line arguments\n /// that must be passed to the plugin binary when it is loaded.\n /// This parameter is used only when `servicesConfig.loadAtBoot` is `true`\n public let defaultArguments: [String]\n }\n\n /// Short description of the plugin surface. This will be displayed as the\n /// help-text for CLI plugins, and will be returned in API calls to view loaded\n /// plugins from the daemon.\n public let abstract: String\n\n /// Author of the plugin. This is solely metadata.\n public let author: String?\n\n /// Services configuration. Specify nil for a CLI plugin, and an empty array for\n /// that does not publish any XPC services.\n public let servicesConfig: ServicesConfig?\n}\n\nextension PluginConfig {\n public var isCLI: Bool { self.servicesConfig == nil }\n}\n\nextension PluginConfig {\n public init?(configURL: URL) throws {\n let fm = FileManager.default\n if !fm.fileExists(atPath: configURL.path) {\n return nil\n }\n\n guard let data = fm.contents(atPath: configURL.path) else {\n return nil\n }\n\n let decoder: JSONDecoder = JSONDecoder()\n self = try decoder.decode(PluginConfig.self, from: data)\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ContentStoreService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\npublic actor ContentStoreService {\n private let log: Logger\n private let contentStore: LocalContentStore\n private let root: URL\n\n public init(root: URL, log: Logger) throws {\n try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)\n self.root = root.appendingPathComponent(\"content\")\n self.contentStore = try LocalContentStore(path: self.root)\n self.log = log\n }\n\n public func get(digest: String) async throws -> URL? {\n self.log.trace(\"ContentStoreService: \\(#function) digest \\(digest)\")\n return try await self.contentStore.get(digest: digest)?.path\n }\n\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n self.log.debug(\"ContentStoreService: \\(#function) digests \\(digests)\")\n return try await self.contentStore.delete(digests: digests)\n }\n\n @discardableResult\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n self.log.debug(\"ContentStoreService: \\(#function) digests \\(keeping)\")\n return try await self.contentStore.delete(keeping: keeping)\n }\n\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n self.log.debug(\"ContentStoreService: \\(#function)\")\n return try await self.contentStore.newIngestSession()\n }\n\n public func completeIngestSession(_ id: String) async throws -> [String] {\n self.log.debug(\"ContentStoreService: \\(#function) id \\(id)\")\n return try await self.contentStore.completeIngestSession(id)\n }\n\n public func cancelIngestSession(_ id: String) async throws {\n self.log.debug(\"ContentStoreService: \\(#function) id \\(id)\")\n return try await self.contentStore.cancelIngestSession(id)\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\n\npublic struct ContainerConfiguration: Sendable, Codable {\n /// Identifier for the container.\n public var id: String\n /// Image used to create the container.\n public var image: ImageDescription\n /// External mounts to add to the container.\n public var mounts: [Filesystem] = []\n /// Ports to publish from container to host.\n public var publishedPorts: [PublishPort] = []\n /// Sockets to publish from container to host.\n public var publishedSockets: [PublishSocket] = []\n /// Key/Value labels for the container.\n public var labels: [String: String] = [:]\n /// System controls for the container.\n public var sysctls: [String: String] = [:]\n /// The networks the container will be added to.\n public var networks: [String] = []\n /// The DNS configuration for the container.\n public var dns: DNSConfiguration? = nil\n /// Whether to enable rosetta x86-64 translation for the container.\n public var rosetta: Bool = false\n /// The hostname for the container.\n public var hostname: String? = nil\n /// Initial or main process of the container.\n public var initProcess: ProcessConfiguration\n /// Platform for the container\n public var platform: ContainerizationOCI.Platform = .current\n /// Resource values for the container.\n public var resources: Resources = .init()\n /// Name of the runtime that supports the container\n public var runtimeHandler: String = \"container-runtime-linux\"\n\n enum CodingKeys: String, CodingKey {\n case id\n case image\n case mounts\n case publishedPorts\n case publishedSockets\n case labels\n case sysctls\n case networks\n case dns\n case rosetta\n case hostname\n case initProcess\n case platform\n case resources\n case runtimeHandler\n }\n\n /// Create a configuration from the supplied Decoder, initializing missing\n /// values where possible to reasonable defaults.\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n id = try container.decode(String.self, forKey: .id)\n image = try container.decode(ImageDescription.self, forKey: .image)\n mounts = try container.decodeIfPresent([Filesystem].self, forKey: .mounts) ?? []\n publishedPorts = try container.decodeIfPresent([PublishPort].self, forKey: .publishedPorts) ?? []\n publishedSockets = try container.decodeIfPresent([PublishSocket].self, forKey: .publishedSockets) ?? []\n labels = try container.decodeIfPresent([String: String].self, forKey: .labels) ?? [:]\n sysctls = try container.decodeIfPresent([String: String].self, forKey: .sysctls) ?? [:]\n networks = try container.decodeIfPresent([String].self, forKey: .networks) ?? []\n dns = try container.decodeIfPresent(DNSConfiguration.self, forKey: .dns)\n rosetta = try container.decodeIfPresent(Bool.self, forKey: .rosetta) ?? false\n hostname = try container.decodeIfPresent(String.self, forKey: .hostname)\n initProcess = try container.decode(ProcessConfiguration.self, forKey: .initProcess)\n platform = try container.decodeIfPresent(ContainerizationOCI.Platform.self, forKey: .platform) ?? .current\n resources = try container.decodeIfPresent(Resources.self, forKey: .resources) ?? .init()\n runtimeHandler = try container.decodeIfPresent(String.self, forKey: .runtimeHandler) ?? \"container-runtime-linux\"\n }\n\n public struct DNSConfiguration: Sendable, Codable {\n public static let defaultNameservers = [\"1.1.1.1\"]\n\n public let nameservers: [String]\n public let domain: String?\n public let searchDomains: [String]\n public let options: [String]\n\n public init(\n nameservers: [String] = defaultNameservers,\n domain: String? = nil,\n searchDomains: [String] = [],\n options: [String] = []\n ) {\n self.nameservers = nameservers\n self.domain = domain\n self.searchDomains = searchDomains\n self.options = options\n }\n }\n\n /// Resources like cpu, memory, and storage quota.\n public struct Resources: Sendable, Codable {\n /// Number of CPU cores allocated.\n public var cpus: Int = 4\n /// Memory in bytes allocated.\n public var memoryInBytes: UInt64 = 1024.mib()\n /// Storage quota/size in bytes.\n public var storage: UInt64?\n\n public init() {}\n }\n\n public init(\n id: String,\n image: ImageDescription,\n process: ProcessConfiguration\n ) {\n self.id = id\n self.image = image\n self.initProcess = process\n }\n}\n"], ["/container/Sources/CLI/Registry/RegistryCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct RegistryCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"registry\",\n abstract: \"Manage registry configurations\",\n subcommands: [\n Login.self,\n Logout.self,\n RegistryDefault.self,\n ],\n aliases: [\"r\"]\n )\n }\n}\n"], ["/container/Sources/CLI/Image/ImagesCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct ImagesCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"images\",\n abstract: \"Manage images\",\n subcommands: [\n ImageInspect.self,\n ImageList.self,\n ImageLoad.self,\n ImagePrune.self,\n ImagePull.self,\n ImagePush.self,\n ImageRemove.self,\n ImageSave.self,\n ImageTag.self,\n ],\n aliases: [\"image\", \"i\"]\n )\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+State.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension ProgressBar {\n /// A configuration struct for the progress bar.\n public struct State {\n /// A flag indicating whether the progress bar is finished.\n public var finished = false\n var iteration = 0\n private let speedInterval: DispatchTimeInterval = .seconds(1)\n\n var description: String\n var subDescription: String\n var itemsName: String\n\n var tasks: Int\n var totalTasks: Int?\n\n var items: Int\n var totalItems: Int?\n\n private var sizeUpdateTime: DispatchTime?\n private var sizeUpdateValue: Int64 = 0\n var size: Int64 {\n didSet {\n calculateSizeSpeed()\n }\n }\n var totalSize: Int64?\n private var sizeUpdateSpeed: String?\n var sizeSpeed: String? {\n guard sizeUpdateTime == nil || sizeUpdateTime! > .now() - speedInterval - speedInterval else {\n return Int64(0).formattedSizeSpeed(from: startTime)\n }\n return sizeUpdateSpeed\n }\n var averageSizeSpeed: String {\n size.formattedSizeSpeed(from: startTime)\n }\n\n var percent: String {\n var value = 0\n if let totalSize, totalSize > 0 {\n value = Int(size * 100 / totalSize)\n } else if let totalItems, totalItems > 0 {\n value = Int(items * 100 / totalItems)\n }\n value = min(value, 100)\n return \"\\(value)%\"\n }\n\n var startTime: DispatchTime\n var output = \"\"\n\n init(\n description: String = \"\", subDescription: String = \"\", itemsName: String = \"\", tasks: Int = 0, totalTasks: Int? = nil, items: Int = 0, totalItems: Int? = nil,\n size: Int64 = 0, totalSize: Int64? = nil, startTime: DispatchTime = .now()\n ) {\n self.description = description\n self.subDescription = subDescription\n self.itemsName = itemsName\n self.tasks = tasks\n self.totalTasks = totalTasks\n self.items = items\n self.totalItems = totalItems\n self.size = size\n self.totalSize = totalSize\n self.startTime = startTime\n }\n\n private mutating func calculateSizeSpeed() {\n if sizeUpdateTime == nil || sizeUpdateTime! < .now() - speedInterval {\n let partSize = size - sizeUpdateValue\n let partStartTime = sizeUpdateTime ?? startTime\n let partSizeSpeed = partSize.formattedSizeSpeed(from: partStartTime)\n self.sizeUpdateSpeed = partSizeSpeed\n\n sizeUpdateTime = .now()\n sizeUpdateValue = size\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/SignalThreshold.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\n\n// For a lot of programs, they don't install their own signal handlers for\n// SIGINT/SIGTERM which poses a somewhat fun problem for containers. Because\n// they're pid 1 (doesn't matter that it isn't in the \"root\" pid namespace)\n// the default actions for SIGINT and SIGTERM now are nops. So this type gives\n// us an opportunity to set a threshold for a certain number of signals received\n// so we can have an escape hatch for users to escape their horrific mistake\n// of cat'ing /dev/urandom by exit(1)'ing :)\npublic struct SignalThreshold {\n private let threshold: Int\n private let signals: [Int32]\n private var t: Task<(), Never>?\n\n public init(\n threshold: Int,\n signals: [Int32],\n ) {\n self.threshold = threshold\n self.signals = signals\n }\n\n // Start kicks off the signal watching. The passed in handler will\n // run only once upon passing the threshold number passed in the constructor.\n mutating public func start(handler: @Sendable @escaping () -> Void) {\n let signals = self.signals\n let threshold = self.threshold\n self.t = Task {\n var received = 0\n let signalHandler = AsyncSignalHandler.create(notify: signals)\n for await _ in signalHandler.signals {\n received += 1\n if received == threshold {\n handler()\n signalHandler.cancel()\n return\n }\n }\n }\n }\n\n public func stop() {\n self.t?.cancel()\n }\n}\n"], ["/container/Sources/CLI/System/SystemKernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct SystemKernel: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kernel\",\n abstract: \"Manage the default kernel configuration\",\n subcommands: [\n KernelSet.self\n ]\n )\n }\n}\n"], ["/container/Sources/ContainerBuild/Globber.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic class Globber {\n let input: URL\n var results: Set = .init()\n\n public init(_ input: URL) {\n self.input = input\n }\n\n public func match(_ pattern: String) throws {\n let adjustedPattern =\n pattern\n .replacingOccurrences(of: #\"^\\./(?=.)\"#, with: \"\", options: .regularExpression)\n .replacingOccurrences(of: \"^\\\\.[/]?$\", with: \"*\", options: .regularExpression)\n .replacingOccurrences(of: \"\\\\*{2,}[/]\", with: \"*/**/\", options: .regularExpression)\n .replacingOccurrences(of: \"[/]\\\\*{2,}([^/])\", with: \"/**/*$1\", options: .regularExpression)\n .replacingOccurrences(of: \"^\\\\*{2,}([^/])\", with: \"**/*$1\", options: .regularExpression)\n\n for child in input.children {\n try self.match(input: child, components: adjustedPattern.split(separator: \"/\").map(String.init))\n }\n }\n\n private func match(input: URL, components: [String]) throws {\n if components.isEmpty {\n var dir = input.standardizedFileURL\n\n while dir != self.input.standardizedFileURL {\n results.insert(dir)\n guard dir.pathComponents.count > 1 else { break }\n dir.deleteLastPathComponent()\n }\n return input.childrenRecursive.forEach { results.insert($0) }\n }\n\n let head = components.first ?? \"\"\n let tail = components.tail\n\n if head == \"**\" {\n var tail: [String] = tail\n while tail.first == \"**\" {\n tail = tail.tail\n }\n try self.match(input: input, components: tail)\n for child in input.children {\n try self.match(input: child, components: components)\n }\n return\n }\n\n if try glob(input.lastPathComponent, head) {\n try self.match(input: input, components: tail)\n\n for child in input.children where try glob(child.lastPathComponent, tail.first ?? \"\") {\n try self.match(input: child, components: tail)\n }\n return\n }\n }\n\n func glob(_ input: String, _ pattern: String) throws -> Bool {\n let regexPattern =\n \"^\"\n + NSRegularExpression.escapedPattern(for: pattern)\n .replacingOccurrences(of: \"\\\\*\", with: \"[^/]*\")\n .replacingOccurrences(of: \"\\\\?\", with: \"[^/]\")\n .replacingOccurrences(of: \"[\\\\^\", with: \"[^\")\n .replacingOccurrences(of: \"\\\\[\", with: \"[\")\n .replacingOccurrences(of: \"\\\\]\", with: \"]\") + \"$\"\n\n // validate the regex pattern created\n let _ = try Regex(regexPattern)\n return input.range(of: regexPattern, options: .regularExpression) != nil\n }\n}\n\nextension URL {\n var children: [URL] {\n\n (try? FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil))\n ?? []\n }\n\n var childrenRecursive: [URL] {\n var results: [URL] = []\n if let enumerator = FileManager.default.enumerator(\n at: self, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey])\n {\n while let child = enumerator.nextObject() as? URL {\n results.append(child)\n }\n }\n return [self] + results\n }\n}\n\nextension [String] {\n var tail: [String] {\n if self.count <= 1 {\n return []\n }\n return Array(self.dropFirst())\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/StandardQueryValidator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Pass standard queries to a delegate handler.\npublic struct StandardQueryValidator: DNSHandler {\n private let handler: DNSHandler\n\n /// Create the handler.\n /// - Parameter delegate: the handler that receives valid queries\n public init(handler: DNSHandler) {\n self.handler = handler\n }\n\n /// Ensures the query is valid before forwarding it to the delegate.\n /// - Parameter msg: the query message\n /// - Returns: the delegate response if the query is valid, and an\n /// error response otherwise\n public func answer(query: Message) async throws -> Message? {\n // Reject response messages.\n guard query.type == .query else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions\n )\n }\n\n // Standard DNS servers handle only query operations.\n guard query.operationCode == .query else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions\n )\n }\n\n // Standard DNS servers only handle messages with exactly one question.\n guard query.questions.count == 1 else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions\n )\n }\n\n return try await handler.answer(query: query)\n }\n}\n"], ["/container/Sources/CLI/Container/ProcessUtils.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n static func ensureRunning(container: ClientContainer) throws {\n if container.status != .running {\n throw ContainerizationError(.invalidState, message: \"container \\(container.id) is not running\")\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/LaunchPlist.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\n\npublic struct LaunchPlist: Encodable {\n public enum Domain: String, Codable {\n case Aqua\n case Background\n case System\n }\n\n public let label: String\n public let arguments: [String]\n\n public let environment: [String: String]?\n public let cwd: String?\n public let username: String?\n public let groupname: String?\n public let limitLoadToSessionType: [Domain]?\n public let runAtLoad: Bool?\n public let stdin: String?\n public let stdout: String?\n public let stderr: String?\n public let disabled: Bool?\n public let program: String?\n public let keepAlive: Bool?\n public let machServices: [String: Bool]?\n public let waitForDebugger: Bool?\n\n enum CodingKeys: String, CodingKey {\n case label = \"Label\"\n case arguments = \"ProgramArguments\"\n case environment = \"EnvironmentVariables\"\n case cwd = \"WorkingDirectory\"\n case username = \"UserName\"\n case groupname = \"GroupName\"\n case limitLoadToSessionType = \"LimitLoadToSessionType\"\n case runAtLoad = \"RunAtLoad\"\n case stdin = \"StandardInPath\"\n case stdout = \"StandardOutPath\"\n case stderr = \"StandardErrorPath\"\n case disabled = \"Disabled\"\n case program = \"Program\"\n case keepAlive = \"KeepAlive\"\n case machServices = \"MachServices\"\n case waitForDebugger = \"WaitForDebugger\"\n }\n\n public init(\n label: String,\n arguments: [String],\n environment: [String: String]? = nil,\n cwd: String? = nil,\n username: String? = nil,\n groupname: String? = nil,\n limitLoadToSessionType: [Domain]? = nil,\n runAtLoad: Bool? = nil,\n stdin: String? = nil,\n stdout: String? = nil,\n stderr: String? = nil,\n disabled: Bool? = nil,\n program: String? = nil,\n keepAlive: Bool? = nil,\n machServices: [String]? = nil,\n waitForDebugger: Bool? = nil\n ) {\n self.label = label\n self.arguments = arguments\n self.environment = environment\n self.cwd = cwd\n self.username = username\n self.groupname = groupname\n self.limitLoadToSessionType = limitLoadToSessionType\n self.runAtLoad = runAtLoad\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n self.disabled = disabled\n self.program = program\n self.keepAlive = keepAlive\n self.waitForDebugger = waitForDebugger\n if let services = machServices {\n var machServices: [String: Bool] = [:]\n for service in services {\n machServices[service] = true\n }\n self.machServices = machServices\n } else {\n self.machServices = nil\n }\n }\n}\n\nextension LaunchPlist {\n public func encode() throws -> Data {\n let enc = PropertyListEncoder()\n enc.outputFormat = .xml\n return try enc.encode(self)\n }\n}\n#endif\n"], ["/container/Sources/ContainerLog/OSLogHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\nimport Logging\nimport os\n\nimport struct Logging.Logger\n\npublic struct OSLogHandler: LogHandler {\n private let logger: os.Logger\n\n public var logLevel: Logger.Level = .info\n private var formattedMetadata: String?\n\n public var metadata = Logger.Metadata() {\n didSet {\n self.formattedMetadata = self.formatMetadata(self.metadata)\n }\n }\n\n public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {\n get {\n self.metadata[metadataKey]\n }\n set {\n self.metadata[metadataKey] = newValue\n }\n }\n\n public init(label: String, category: String) {\n self.logger = os.Logger(subsystem: label, category: category)\n }\n}\n\nextension OSLogHandler {\n public func log(\n level: Logger.Level,\n message: Logger.Message,\n metadata: Logger.Metadata?,\n source: String,\n file: String,\n function: String,\n line: UInt\n ) {\n var formattedMetadata = self.formattedMetadata\n if let metadataOverride = metadata, !metadataOverride.isEmpty {\n formattedMetadata = self.formatMetadata(\n self.metadata.merging(metadataOverride) {\n $1\n }\n )\n }\n\n var finalMessage = message.description\n if let formattedMetadata {\n finalMessage += \" \" + formattedMetadata\n }\n\n self.logger.log(\n level: level.toOSLogLevel(),\n \"\\(finalMessage, privacy: .public)\"\n )\n }\n\n private func formatMetadata(_ metadata: Logger.Metadata) -> String? {\n if metadata.isEmpty {\n return nil\n }\n return metadata.map {\n \"[\\($0)=\\($1)]\"\n }.joined(separator: \" \")\n }\n}\n\nextension Logger.Level {\n func toOSLogLevel() -> OSLogType {\n switch self {\n case .debug, .trace:\n return .debug\n case .info:\n return .info\n case .notice:\n return .default\n case .error, .warning:\n return .error\n case .critical:\n return .fault\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Measurement+Parse.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nprivate let units: [Character: UnitInformationStorage] = [\n \"b\": .bytes,\n \"k\": .kibibytes,\n \"m\": .mebibytes,\n \"g\": .gibibytes,\n \"t\": .tebibytes,\n \"p\": .pebibytes,\n]\n\nextension Measurement {\n public enum ParseError: Swift.Error, CustomStringConvertible {\n case invalidSize\n case invalidSymbol(String)\n\n public var description: String {\n switch self {\n case .invalidSize:\n return \"invalid size\"\n case .invalidSymbol(let symbol):\n return \"invalid symbol: \\(symbol)\"\n }\n }\n }\n\n /// parse the provided string into a measurement that is able to be converted to various byte sizes\n public static func parse(parsing: String) throws -> Measurement {\n let check = \"01234567890. \"\n let i = parsing.lastIndex {\n check.contains($0)\n }\n guard let i else {\n throw ParseError.invalidSize\n }\n let after = parsing.index(after: i)\n let rawValue = parsing[..(value: value, unit: unit)\n }\n\n static func parseUnit(_ unit: String) throws -> Character {\n let s = unit.dropFirst()\n switch s {\n case \"\", \"b\", \"ib\":\n return unit.first ?? \"b\"\n default:\n throw ParseError.invalidSymbol(unit)\n }\n }\n}\n"], ["/container/Sources/SocketForwarder/TCPForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\n\npublic struct TCPForwarder: SocketForwarder {\n private let proxyAddress: SocketAddress\n\n private let serverAddress: SocketAddress\n\n private let eventLoopGroup: any EventLoopGroup\n\n private let log: Logger?\n\n public init(\n proxyAddress: SocketAddress,\n serverAddress: SocketAddress,\n eventLoopGroup: any EventLoopGroup,\n log: Logger? = nil\n ) throws {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.log = log\n }\n\n public func run() throws -> EventLoopFuture {\n self.log?.trace(\"frontend - creating listener\")\n\n let bootstrap = ServerBootstrap(group: self.eventLoopGroup)\n .serverChannelOption(ChannelOptions.socket(.init(SOL_SOCKET), .init(SO_REUSEADDR)), value: 1)\n .childChannelOption(ChannelOptions.socket(.init(SOL_SOCKET), .init(SO_REUSEADDR)), value: 1)\n .childChannelInitializer { channel in\n channel.eventLoop.makeCompletedFuture {\n try channel.pipeline.syncOperations.addHandler(\n ConnectHandler(serverAddress: self.serverAddress, log: log)\n )\n }\n }\n\n return\n bootstrap\n .bind(to: self.proxyAddress)\n .flatMap { $0.eventLoop.makeSucceededFuture(SocketForwarderResult(channel: $0)) }\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.grpc.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n// DO NOT EDIT.\n// swift-format-ignore-file\n//\n// Generated by the protocol buffer compiler.\n// Source: Builder.proto\n//\nimport GRPC\nimport NIO\nimport NIOConcurrencyHelpers\nimport SwiftProtobuf\n\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// Usage: instantiate `Com_Apple_Container_Build_V1_BuilderClient`, then call methods of this protocol to make API calls.\npublic protocol Com_Apple_Container_Build_V1_BuilderClientProtocol: GRPCClient {\n var serviceName: String { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? { get }\n\n func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func performBuild(\n callOptions: CallOptions?,\n handler: @escaping (Com_Apple_Container_Build_V1_ServerStream) -> Void\n ) -> BidirectionalStreamingCall\n\n func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n}\n\nextension Com_Apple_Container_Build_V1_BuilderClientProtocol {\n public var serviceName: String {\n return \"com.apple.container.build.v1.Builder\"\n }\n\n /// Create a build request.\n ///\n /// - Parameters:\n /// - request: Request to send to CreateBuild.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n ///\n /// Callers should use the `send` method on the returned object to send messages\n /// to the server. The caller should send an `.end` after the final message has been sent.\n ///\n /// - Parameters:\n /// - callOptions: Call options.\n /// - handler: A closure called when each response is received from the server.\n /// - Returns: A `ClientStreamingCall` with futures for the metadata and status.\n public func performBuild(\n callOptions: CallOptions? = nil,\n handler: @escaping (Com_Apple_Container_Build_V1_ServerStream) -> Void\n ) -> BidirectionalStreamingCall {\n return self.makeBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n handler: handler\n )\n }\n\n /// Unary call to Info\n ///\n /// - Parameters:\n /// - request: Request to send to Info.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(*, deprecated)\nextension Com_Apple_Container_Build_V1_BuilderClient: @unchecked Sendable {}\n\n@available(*, deprecated, renamed: \"Com_Apple_Container_Build_V1_BuilderNIOClient\")\npublic final class Com_Apple_Container_Build_V1_BuilderClient: Com_Apple_Container_Build_V1_BuilderClientProtocol {\n private let lock = Lock()\n private var _defaultCallOptions: CallOptions\n private var _interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n public let channel: GRPCChannel\n public var defaultCallOptions: CallOptions {\n get { self.lock.withLock { return self._defaultCallOptions } }\n set { self.lock.withLockVoid { self._defaultCallOptions = newValue } }\n }\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? {\n get { self.lock.withLock { return self._interceptors } }\n set { self.lock.withLockVoid { self._interceptors = newValue } }\n }\n\n /// Creates a client for the com.apple.container.build.v1.Builder service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self._defaultCallOptions = defaultCallOptions\n self._interceptors = interceptors\n }\n}\n\npublic struct Com_Apple_Container_Build_V1_BuilderNIOClient: Com_Apple_Container_Build_V1_BuilderClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n\n /// Creates a client for the com.apple.container.build.v1.Builder service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol: GRPCClient {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? { get }\n\n func makeCreateBuildCall(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makePerformBuildCall(\n callOptions: CallOptions?\n ) -> GRPCAsyncBidirectionalStreamingCall\n\n func makeInfoCall(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Container_Build_V1_BuilderClientMetadata.serviceDescriptor\n }\n\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? {\n return nil\n }\n\n public func makeCreateBuildCall(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n public func makePerformBuildCall(\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncBidirectionalStreamingCall {\n return self.makeAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func makeInfoCall(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Container_Build_V1_CreateBuildResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n public func performBuild(\n _ requests: RequestStream,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncResponseStream where RequestStream: Sequence, RequestStream.Element == Com_Apple_Container_Build_V1_ClientStream {\n return self.performAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n requests: requests,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func performBuild(\n _ requests: RequestStream,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncResponseStream where RequestStream: AsyncSequence & Sendable, RequestStream.Element == Com_Apple_Container_Build_V1_ClientStream {\n return self.performAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n requests: requests,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Container_Build_V1_InfoResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic struct Com_Apple_Container_Build_V1_BuilderAsyncClient: Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\npublic protocol Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when invoking 'createBuild'.\n func makeCreateBuildInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'performBuild'.\n func makePerformBuildInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'info'.\n func makeInfoInterceptors() -> [ClientInterceptor]\n}\n\npublic enum Com_Apple_Container_Build_V1_BuilderClientMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"Builder\",\n fullName: \"com.apple.container.build.v1.Builder\",\n methods: [\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild,\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild,\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info,\n ]\n )\n\n public enum Methods {\n public static let createBuild = GRPCMethodDescriptor(\n name: \"CreateBuild\",\n path: \"/com.apple.container.build.v1.Builder/CreateBuild\",\n type: GRPCCallType.unary\n )\n\n public static let performBuild = GRPCMethodDescriptor(\n name: \"PerformBuild\",\n path: \"/com.apple.container.build.v1.Builder/PerformBuild\",\n type: GRPCCallType.bidirectionalStreaming\n )\n\n public static let info = GRPCMethodDescriptor(\n name: \"Info\",\n path: \"/com.apple.container.build.v1.Builder/Info\",\n type: GRPCCallType.unary\n )\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// To build a server, implement a class that conforms to this protocol.\npublic protocol Com_Apple_Container_Build_V1_BuilderProvider: CallHandlerProvider {\n var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? { get }\n\n /// Create a build request.\n func createBuild(request: Com_Apple_Container_Build_V1_CreateBuildRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n func performBuild(context: StreamingResponseCallContext) -> EventLoopFuture<(StreamEvent) -> Void>\n\n func info(request: Com_Apple_Container_Build_V1_InfoRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n}\n\nextension Com_Apple_Container_Build_V1_BuilderProvider {\n public var serviceName: Substring {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor.fullName[...]\n }\n\n /// Determines, calls and returns the appropriate request handler, depending on the request's method.\n /// Returns nil for methods not handled by this service.\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"CreateBuild\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? [],\n userFunction: self.createBuild(request:context:)\n )\n\n case \"PerformBuild\":\n return BidirectionalStreamingServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n observerFactory: self.performBuild(context:)\n )\n\n case \"Info\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeInfoInterceptors() ?? [],\n userFunction: self.info(request:context:)\n )\n\n default:\n return nil\n }\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// To implement a server, implement an object which conforms to this protocol.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Container_Build_V1_BuilderAsyncProvider: CallHandlerProvider, Sendable {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? { get }\n\n /// Create a build request.\n func createBuild(\n request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Container_Build_V1_CreateBuildResponse\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n func performBuild(\n requestStream: GRPCAsyncRequestStream,\n responseStream: GRPCAsyncResponseStreamWriter,\n context: GRPCAsyncServerCallContext\n ) async throws\n\n func info(\n request: Com_Apple_Container_Build_V1_InfoRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Container_Build_V1_InfoResponse\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncProvider {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor\n }\n\n public var serviceName: Substring {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor.fullName[...]\n }\n\n public var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? {\n return nil\n }\n\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"CreateBuild\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? [],\n wrapping: { try await self.createBuild(request: $0, context: $1) }\n )\n\n case \"PerformBuild\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n wrapping: { try await self.performBuild(requestStream: $0, responseStream: $1, context: $2) }\n )\n\n case \"Info\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeInfoInterceptors() ?? [],\n wrapping: { try await self.info(request: $0, context: $1) }\n )\n\n default:\n return nil\n }\n }\n}\n\npublic protocol Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when handling 'createBuild'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCreateBuildInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'performBuild'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makePerformBuildInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'info'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeInfoInterceptors() -> [ServerInterceptor]\n}\n\npublic enum Com_Apple_Container_Build_V1_BuilderServerMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"Builder\",\n fullName: \"com.apple.container.build.v1.Builder\",\n methods: [\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.createBuild,\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.performBuild,\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.info,\n ]\n )\n\n public enum Methods {\n public static let createBuild = GRPCMethodDescriptor(\n name: \"CreateBuild\",\n path: \"/com.apple.container.build.v1.Builder/CreateBuild\",\n type: GRPCCallType.unary\n )\n\n public static let performBuild = GRPCMethodDescriptor(\n name: \"PerformBuild\",\n path: \"/com.apple.container.build.v1.Builder/PerformBuild\",\n type: GRPCCallType.bidirectionalStreaming\n )\n\n public static let info = GRPCMethodDescriptor(\n name: \"Info\",\n path: \"/com.apple.container.build.v1.Builder/Info\",\n type: GRPCCallType.unary\n )\n }\n}\n"], ["/container/Sources/APIServer/Plugin/PluginsService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerPlugin\nimport Foundation\nimport Logging\n\nactor PluginsService {\n private let log: Logger\n private var loaded: [String: Plugin]\n private let pluginLoader: PluginLoader\n\n public init(pluginLoader: PluginLoader, log: Logger) {\n self.log = log\n self.loaded = [:]\n self.pluginLoader = pluginLoader\n }\n\n /// Load the specified plugins, or all plugins with services defined\n /// if none are explicitly specified.\n public func loadAll(\n _ plugins: [Plugin]? = nil,\n ) throws {\n let registerPlugins = plugins ?? pluginLoader.findPlugins()\n for plugin in registerPlugins {\n try pluginLoader.registerWithLaunchd(plugin: plugin)\n loaded[plugin.name] = plugin\n }\n }\n\n /// Stop the specified plugins, or all plugins with services defined\n /// if none are explicitly specified.\n public func stopAll(_ plugins: [Plugin]? = nil) throws {\n let deregisterPlugins = plugins ?? pluginLoader.findPlugins()\n for plugin in deregisterPlugins {\n try pluginLoader.deregisterWithLaunchd(plugin: plugin)\n self.loaded.removeValue(forKey: plugin.name)\n }\n }\n\n // MARK: XPC API surface.\n\n /// Load a single plugin, doing nothing if the plugin is already loaded.\n public func load(name: String) throws {\n guard self.loaded[name] == nil else {\n return\n }\n guard let plugin = pluginLoader.findPlugin(name: name) else {\n throw Error.pluginNotFound(name)\n }\n try pluginLoader.registerWithLaunchd(plugin: plugin)\n self.loaded[plugin.name] = plugin\n }\n\n /// Get information for a loaded plugin.\n public func get(name: String) throws -> Plugin {\n guard let plugin = loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n return plugin\n }\n\n /// Restart a loaded plugin.\n public func restart(name: String) throws {\n guard let plugin = self.loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n try ServiceManager.kickstart(fullServiceLabel: plugin.getLaunchdLabel())\n }\n\n /// Unload a loaded plugin.\n public func unload(name: String) throws {\n guard let plugin = self.loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n try pluginLoader.deregisterWithLaunchd(plugin: plugin)\n self.loaded.removeValue(forKey: plugin.name)\n }\n\n /// List all loaded plugins.\n public func list() throws -> [Plugin] {\n self.loaded.map { $0.value }\n }\n\n public enum Error: Swift.Error, CustomStringConvertible {\n case pluginNotFound(String)\n case pluginNotLoaded(String)\n\n public var description: String {\n switch self {\n case .pluginNotFound(let name):\n return \"plugin not found: \\(name)\"\n case .pluginNotLoaded(let name):\n return \"plugin not loaded: \\(name)\"\n }\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/AttachmentAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\n\nactor AttachmentAllocator {\n private let allocator: any AddressAllocator\n private var hostnames: [String: UInt32] = [:]\n\n init(lower: UInt32, size: Int) throws {\n allocator = try UInt32.rotatingAllocator(\n lower: lower,\n size: UInt32(size)\n )\n }\n\n /// Allocate a network address for a host.\n func allocate(hostname: String) async throws -> UInt32 {\n guard hostnames[hostname] == nil else {\n throw ContainerizationError(.exists, message: \"Hostname \\(hostname) already exists on the network\")\n }\n let index = try allocator.allocate()\n hostnames[hostname] = index\n\n return index\n }\n\n /// Free an allocated network address by hostname.\n func deallocate(hostname: String) async throws {\n if let index = hostnames.removeValue(forKey: hostname) {\n try allocator.release(index)\n }\n }\n\n /// If no addresses are allocated, prevent future allocations and return true.\n func disableAllocator() async -> Bool {\n allocator.disableAllocator()\n }\n\n /// Retrieve the allocator index for a hostname.\n func lookup(hostname: String) async throws -> UInt32? {\n hostnames[hostname]\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/NonisolatedInterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Logging\nimport Virtualization\nimport vmnet\n\n/// Interface strategy for containers that use macOS's custom network feature.\n@available(macOS 26, *)\nstruct NonisolatedInterfaceStrategy: InterfaceStrategy {\n private let log: Logger\n\n public init(log: Logger) {\n self.log = log\n }\n\n public func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) throws -> Interface {\n guard let additionalData else {\n throw ContainerizationError(.invalidState, message: \"network state does not contain custom network reference\")\n }\n\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let networkRef = vmnet_network_create_with_serialization(additionalData.underlying, &status) else {\n throw ContainerizationError(.invalidState, message: \"cannot deserialize custom network reference, status \\(status)\")\n }\n\n log.info(\"creating NATNetworkInterface with network reference\")\n let gateway = interfaceIndex == 0 ? attachment.gateway : nil\n return NATNetworkInterface(address: attachment.address, gateway: gateway, reference: networkRef)\n }\n}\n"], ["/container/Sources/ContainerClient/ProgressUpdateService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\n/// A service that sends progress updates to the client.\npublic actor ProgressUpdateService {\n private let endpointConnection: xpc_connection_t\n\n /// Creates a new instance for sending progress updates to the client.\n /// - Parameter message: The XPC message that contains the endpoint to connect to.\n public init?(message: XPCMessage) {\n guard let progressUpdateEndpoint = message.endpoint(key: .progressUpdateEndpoint) else {\n return nil\n }\n endpointConnection = xpc_connection_create_from_endpoint(progressUpdateEndpoint)\n xpc_connection_set_event_handler(endpointConnection) { _ in }\n // This connection will be closed by the client.\n xpc_connection_activate(endpointConnection)\n }\n\n /// Performs a progress update.\n /// - Parameter events: The events that represent the update.\n public func handler(_ events: [ProgressUpdateEvent]) async {\n let object = xpc_dictionary_create(nil, nil, 0)\n let replyMessage = XPCMessage(object: object)\n for event in events {\n switch event {\n case .setDescription(let description):\n replyMessage.set(key: .progressUpdateSetDescription, value: description)\n case .setSubDescription(let subDescription):\n replyMessage.set(key: .progressUpdateSetSubDescription, value: subDescription)\n case .setItemsName(let itemsName):\n replyMessage.set(key: .progressUpdateSetItemsName, value: itemsName)\n case .addTasks(let tasks):\n replyMessage.set(key: .progressUpdateAddTasks, value: tasks)\n case .setTasks(let tasks):\n replyMessage.set(key: .progressUpdateSetTasks, value: tasks)\n case .addTotalTasks(let totalTasks):\n replyMessage.set(key: .progressUpdateAddTotalTasks, value: totalTasks)\n case .setTotalTasks(let totalTasks):\n replyMessage.set(key: .progressUpdateSetTotalTasks, value: totalTasks)\n case .addSize(let size):\n replyMessage.set(key: .progressUpdateAddSize, value: size)\n case .setSize(let size):\n replyMessage.set(key: .progressUpdateSetSize, value: size)\n case .addTotalSize(let totalSize):\n replyMessage.set(key: .progressUpdateAddTotalSize, value: totalSize)\n case .setTotalSize(let totalSize):\n replyMessage.set(key: .progressUpdateSetTotalSize, value: totalSize)\n case .addItems(let items):\n replyMessage.set(key: .progressUpdateAddItems, value: items)\n case .setItems(let items):\n replyMessage.set(key: .progressUpdateSetItems, value: items)\n case .addTotalItems(let totalItems):\n replyMessage.set(key: .progressUpdateAddTotalItems, value: totalItems)\n case .setTotalItems(let totalItems):\n replyMessage.set(key: .progressUpdateSetTotalItems, value: totalItems)\n case .custom(_):\n // Unsupported progress update event in XPC communication.\n break\n }\n }\n xpc_connection_send_message(endpointConnection, replyMessage.underlying)\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+Add.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension ProgressBar {\n /// A handler function to update the progress bar.\n /// - Parameter events: The events to handle.\n public func handler(_ events: [ProgressUpdateEvent]) {\n for event in events {\n switch event {\n case .setDescription(let description):\n set(description: description)\n case .setSubDescription(let subDescription):\n set(subDescription: subDescription)\n case .setItemsName(let itemsName):\n set(itemsName: itemsName)\n case .addTasks(let tasks):\n add(tasks: tasks)\n case .setTasks(let tasks):\n set(tasks: tasks)\n case .addTotalTasks(let totalTasks):\n add(totalTasks: totalTasks)\n case .setTotalTasks(let totalTasks):\n set(totalTasks: totalTasks)\n case .addSize(let size):\n add(size: size)\n case .setSize(let size):\n set(size: size)\n case .addTotalSize(let totalSize):\n add(totalSize: totalSize)\n case .setTotalSize(let totalSize):\n set(totalSize: totalSize)\n case .addItems(let items):\n add(items: items)\n case .setItems(let items):\n set(items: items)\n case .addTotalItems(let totalItems):\n add(totalItems: totalItems)\n case .setTotalItems(let totalItems):\n set(totalItems: totalItems)\n case .custom:\n // Custom events are handled by the client.\n break\n }\n }\n }\n\n /// Performs a check to see if the progress bar should be finished.\n public func checkIfFinished() {\n let state = self.state.withLock { $0 }\n\n var finished = true\n var defined = false\n if let totalTasks = state.totalTasks, totalTasks > 0 {\n // For tasks, we're showing the current task rather than the number of completed tasks.\n finished = finished && state.tasks == totalTasks\n defined = true\n }\n if let totalItems = state.totalItems, totalItems > 0 {\n finished = finished && state.items == totalItems\n defined = true\n }\n if let totalSize = state.totalSize, totalSize > 0 {\n finished = finished && state.size == totalSize\n defined = true\n }\n if defined && finished {\n finish()\n }\n }\n\n /// Sets the current tasks.\n /// - Parameter newTasks: The current tasks to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(tasks newTasks: Int, render: Bool = true) {\n state.withLock { $0.tasks = newTasks }\n if render {\n self.render()\n }\n checkIfFinished()\n }\n\n /// Performs an addition to the current tasks.\n /// - Parameter delta: The tasks to add to the current tasks.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(tasks delta: Int, render: Bool = true) {\n state.withLock {\n let newTasks = $0.tasks + delta\n $0.tasks = newTasks\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total tasks.\n /// - Parameter newTotalTasks: The total tasks to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalTasks newTotalTasks: Int, render: Bool = true) {\n state.withLock { $0.totalTasks = newTotalTasks }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total tasks.\n /// - Parameter delta: The tasks to add to the total tasks.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalTasks delta: Int, render: Bool = true) {\n state.withLock {\n let totalTasks = $0.totalTasks ?? 0\n let newTotalTasks = totalTasks + delta\n $0.totalTasks = newTotalTasks\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the items name.\n /// - Parameter newItemsName: The current items to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(itemsName newItemsName: String, render: Bool = true) {\n state.withLock { $0.itemsName = newItemsName }\n if render {\n self.render()\n }\n }\n\n /// Sets the current items.\n /// - Parameter newItems: The current items to set.\n public func set(items newItems: Int, render: Bool = true) {\n state.withLock { $0.items = newItems }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the current items.\n /// - Parameter delta: The items to add to the current items.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(items delta: Int, render: Bool = true) {\n state.withLock {\n let newItems = $0.items + delta\n $0.items = newItems\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total items.\n /// - Parameter newTotalItems: The total items to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalItems newTotalItems: Int, render: Bool = true) {\n state.withLock { $0.totalItems = newTotalItems }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total items.\n /// - Parameter delta: The items to add to the total items.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalItems delta: Int, render: Bool = true) {\n state.withLock {\n let totalItems = $0.totalItems ?? 0\n let newTotalItems = totalItems + delta\n $0.totalItems = newTotalItems\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the current size.\n /// - Parameter newSize: The current size to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(size newSize: Int64, render: Bool = true) {\n state.withLock { $0.size = newSize }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the current size.\n /// - Parameter delta: The size to add to the current size.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(size delta: Int64, render: Bool = true) {\n state.withLock {\n let newSize = $0.size + delta\n $0.size = newSize\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total size.\n /// - Parameter newTotalSize: The total size to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalSize newTotalSize: Int64, render: Bool = true) {\n state.withLock { $0.totalSize = newTotalSize }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total size.\n /// - Parameter delta: The size to add to the total size.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalSize delta: Int64, render: Bool = true) {\n state.withLock {\n let totalSize = $0.totalSize ?? 0\n let newTotalSize = totalSize + delta\n $0.totalSize = newTotalSize\n }\n if render {\n self.render()\n }\n }\n}\n"], ["/container/Sources/ContainerClient/TableOutput.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct TableOutput {\n private let rows: [[String]]\n private let spacing: Int\n\n public init(\n rows: [[String]],\n spacing: Int = 2\n ) {\n self.rows = rows\n self.spacing = spacing\n }\n\n public func format() -> String {\n var output = \"\"\n let maxLengths = self.maxLength()\n\n for rowIndex in 0.. [Int: Int] {\n var output: [Int: Int] = [:]\n for row in self.rows {\n for (i, column) in row.enumerated() {\n let currentMax = output[i] ?? 0\n output[i] = (column.count > currentMax) ? column.count : currentMax\n }\n }\n return output\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientHealthCheck.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Foundation\n\npublic enum ClientHealthCheck {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n}\n\nextension ClientHealthCheck {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public static func ping(timeout: Duration? = .seconds(5)) async throws {\n let client = Self.newClient()\n let request = XPCMessage(route: .ping)\n try await client.send(request, responseTimeout: timeout)\n }\n}\n"], ["/container/Sources/SocketForwarder/GlueHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIOCore\n\nfinal class GlueHandler {\n\n private var partner: GlueHandler?\n\n private var context: ChannelHandlerContext?\n\n private var pendingRead: Bool = false\n\n private init() {}\n}\n\nextension GlueHandler {\n static func matchedPair() -> (GlueHandler, GlueHandler) {\n let first = GlueHandler()\n let second = GlueHandler()\n\n first.partner = second\n second.partner = first\n\n return (first, second)\n }\n}\n\nextension GlueHandler {\n private func partnerWrite(_ data: NIOAny) {\n self.context?.write(data, promise: nil)\n }\n\n private func partnerFlush() {\n self.context?.flush()\n }\n\n private func partnerWriteEOF() {\n self.context?.close(mode: .output, promise: nil)\n }\n\n private func partnerCloseFull() {\n self.context?.close(promise: nil)\n }\n\n private func partnerBecameWritable() {\n if self.pendingRead {\n self.pendingRead = false\n self.context?.read()\n }\n }\n\n private var partnerWritable: Bool {\n self.context?.channel.isWritable ?? false\n }\n}\n\nextension GlueHandler: ChannelDuplexHandler {\n typealias InboundIn = NIOAny\n typealias OutboundIn = NIOAny\n typealias OutboundOut = NIOAny\n\n func handlerAdded(context: ChannelHandlerContext) {\n self.context = context\n }\n\n func handlerRemoved(context: ChannelHandlerContext) {\n self.context = nil\n self.partner = nil\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n self.partner?.partnerWrite(data)\n }\n\n func channelReadComplete(context: ChannelHandlerContext) {\n self.partner?.partnerFlush()\n }\n\n func channelInactive(context: ChannelHandlerContext) {\n self.partner?.partnerCloseFull()\n }\n\n func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {\n if let event = event as? ChannelEvent, case .inputClosed = event {\n // We have read EOF.\n self.partner?.partnerWriteEOF()\n }\n }\n\n func errorCaught(context: ChannelHandlerContext, error: Error) {\n self.partner?.partnerCloseFull()\n }\n\n func channelWritabilityChanged(context: ChannelHandlerContext) {\n if context.channel.isWritable {\n self.partner?.partnerBecameWritable()\n }\n }\n\n func read(context: ChannelHandlerContext) {\n if let partner = self.partner, partner.partnerWritable {\n context.read()\n } else {\n self.pendingRead = true\n }\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/HostTableResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\n\n/// Handler that uses table lookup to resolve hostnames.\npublic struct HostTableResolver: DNSHandler {\n public let hosts4: [String: IPv4]\n private let ttl: UInt32\n\n public init(hosts4: [String: IPv4], ttl: UInt32 = 300) {\n self.hosts4 = hosts4\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n let record: ResourceRecord?\n switch question.type {\n case ResourceRecordType.host:\n record = answerHost(question: question)\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n\n guard let record else {\n return nil\n }\n\n return Message(\n id: query.id,\n type: .response,\n returnCode: .noError,\n questions: query.questions,\n answers: [record]\n )\n }\n\n private func answerHost(question: Question) -> ResourceRecord? {\n guard let ip = hosts4[question.name] else {\n return nil\n }\n\n return HostRecord(name: question.name, ttl: ttl, ip: ip)\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/NxDomainResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\n\n/// Handler that returns NXDOMAIN for all hostnames.\npublic struct NxDomainResolver: DNSHandler {\n private let ttl: UInt32\n\n public init(ttl: UInt32 = 300) {\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n switch question.type {\n case ResourceRecordType.host:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .nonExistentDomain,\n questions: query.questions,\n answers: []\n )\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressTaskCoordinator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that represents a task whose progress is being monitored.\npublic struct ProgressTask: Sendable, Equatable {\n private var id = UUID()\n private var coordinator: ProgressTaskCoordinator\n\n init(manager: ProgressTaskCoordinator) {\n self.coordinator = manager\n }\n\n static public func == (lhs: ProgressTask, rhs: ProgressTask) -> Bool {\n lhs.id == rhs.id\n }\n\n /// Returns `true` if this task is the currently active task, `false` otherwise.\n public func isCurrent() async -> Bool {\n guard let currentTask = await coordinator.currentTask else {\n return false\n }\n return currentTask == self\n }\n}\n\n/// A type that coordinates progress tasks to ignore updates from completed tasks.\npublic actor ProgressTaskCoordinator {\n var currentTask: ProgressTask?\n\n /// Creates an instance of `ProgressTaskCoordinator`.\n public init() {}\n\n /// Returns a new task that should be monitored for progress updates.\n public func startTask() -> ProgressTask {\n let newTask = ProgressTask(manager: self)\n currentTask = newTask\n return newTask\n }\n\n /// Performs cleanup when the monitored tasks complete.\n public func finish() {\n currentTask = nil\n }\n\n /// Returns a handler that updates the progress of a given task.\n /// - Parameters:\n /// - task: The task whose progress is being updated.\n /// - progressUpdate: The handler to invoke when progress updates are received.\n public static func handler(for task: ProgressTask, from progressUpdate: @escaping ProgressUpdateHandler) -> ProgressUpdateHandler {\n { events in\n // Ignore updates from completed tasks.\n if await task.isCurrent() {\n await progressUpdate(events)\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/Filesystem.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Options to pass to a mount call.\npublic typealias MountOptions = [String]\n\nextension MountOptions {\n /// Returns true if the Filesystem should be consumed as read-only.\n public var readonly: Bool {\n self.contains(\"ro\")\n }\n}\n\n/// A host filesystem that will be attached to the sandbox for use.\n///\n/// A filesystem will be mounted automatically when starting the sandbox\n/// or container.\npublic struct Filesystem: Sendable, Codable {\n /// Type of caching to perform at the host level.\n public enum CacheMode: Sendable, Codable {\n case on\n case off\n case auto\n }\n\n /// Sync mode to perform at the host level.\n public enum SyncMode: Sendable, Codable {\n case full\n case fsync\n case nosync\n }\n\n /// The type of filesystem attachment for the sandbox.\n public enum FSType: Sendable, Codable, Equatable {\n package enum VirtiofsType: String, Sendable, Codable, Equatable {\n // This is a virtiofs share for the rootfs of a sandbox.\n case rootfs\n // Data share. This is what all virtiofs shares for anything besides\n // the rootfs for a sandbox will be.\n case data\n }\n\n case block(format: String, cache: CacheMode, sync: SyncMode)\n case virtiofs\n case tmpfs\n }\n\n /// Type of the filesystem.\n public var type: FSType\n /// Source of the filesystem.\n public var source: String\n /// Destination where the filesystem should be mounted.\n public var destination: String\n /// Mount options applied when mounting the filesystem.\n public var options: MountOptions\n\n public init() {\n self.type = .tmpfs\n self.source = \"\"\n self.destination = \"\"\n self.options = []\n }\n\n public init(type: FSType, source: String, destination: String, options: MountOptions) {\n self.type = type\n self.source = source\n self.destination = destination\n self.options = options\n }\n\n /// A block based filesystem.\n public static func block(\n format: String, source: String, destination: String, options: MountOptions, cache: CacheMode = .auto,\n sync: SyncMode = .full\n ) -> Filesystem {\n .init(\n type: .block(format: format, cache: cache, sync: sync),\n source: URL(fileURLWithPath: source).absolutePath(),\n destination: destination,\n options: options\n )\n }\n\n /// A vritiofs backed filesystem providing a directory.\n public static func virtiofs(source: String, destination: String, options: MountOptions) -> Filesystem {\n .init(\n type: .virtiofs,\n source: URL(fileURLWithPath: source).absolutePath(),\n destination: destination,\n options: options\n )\n }\n\n public static func tmpfs(destination: String, options: MountOptions) -> Filesystem {\n .init(\n type: .tmpfs,\n source: \"tmpfs\",\n destination: destination,\n options: options\n )\n }\n\n /// Returns true if the Filesystem is backed by a block device.\n public var isBlock: Bool {\n switch type {\n case .block(_, _, _): true\n default: false\n }\n }\n\n /// Returns true if the Filesystem is backed by a in-memory mount type.\n public var isTmpfs: Bool {\n switch type {\n case .tmpfs: true\n default: false\n }\n }\n\n /// Returns true if the Filesystem is backed by virtioFS.\n public var isVirtiofs: Bool {\n switch type {\n case .virtiofs: true\n default: false\n }\n }\n\n /// Clone the Filesystem to the provided path.\n ///\n /// This uses `clonefile` to provide a copy-on-write copy of the Filesystem.\n public func clone(to: String) throws -> Self {\n let fm = FileManager.default\n let src = self.source\n try fm.copyItem(atPath: src, toPath: to)\n return .init(type: self.type, source: to, destination: self.destination, options: self.options)\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkState.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct NetworkStatus: Codable, Sendable {\n /// The address allocated for the network if no subnet was specified at\n /// creation time; otherwise, the subnet from the configuration.\n public let address: String\n /// The gateway IPv4 address.\n public let gateway: String\n\n public init(\n address: String,\n gateway: String\n ) {\n self.address = address\n self.gateway = gateway\n }\n\n}\n\n/// The configuration and runtime attributes for a network.\npublic enum NetworkState: Codable, Sendable {\n // The network has been configured.\n case created(NetworkConfiguration)\n // The network is running.\n case running(NetworkConfiguration, NetworkStatus)\n\n public var state: String {\n switch self {\n case .created: \"created\"\n case .running: \"running\"\n }\n }\n\n public var id: String {\n switch self {\n case .created(let configuration): configuration.id\n case .running(let configuration, _): configuration.id\n }\n }\n}\n"], ["/container/Sources/ContainerClient/String+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension String {\n public func fromISO8601DateString(to: String) -> String? {\n if let date = fromISO8601Date() {\n let dateformatTo = DateFormatter()\n dateformatTo.dateFormat = to\n return dateformatTo.string(from: date)\n }\n return nil\n }\n\n public func fromISO8601Date() -> Date? {\n let iso8601DateFormatter = ISO8601DateFormatter()\n iso8601DateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]\n return iso8601DateFormatter.date(from: self)\n }\n\n public func isAbsolutePath() -> Bool {\n self.starts(with: \"/\")\n }\n\n /// Trim all `char` characters from the left side of the string. Stops when encountering a character that\n /// doesn't match `char`.\n mutating public func trimLeft(char: Character) {\n if self.isEmpty {\n return\n }\n var trimTo = 0\n for c in self {\n if char != c {\n break\n }\n trimTo += 1\n }\n if trimTo != 0 {\n let index = self.index(self.startIndex, offsetBy: trimTo)\n self = String(self[index...])\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/TerminalCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct TerminalCommand: Codable {\n let commandType: String\n let code: String\n let rows: UInt16\n let cols: UInt16\n\n enum CodingKeys: String, CodingKey {\n case commandType = \"command_type\"\n case code\n case rows\n case cols\n }\n\n init(rows: UInt16, cols: UInt16) {\n self.commandType = \"terminal\"\n self.code = \"winch\"\n self.rows = rows\n self.cols = cols\n }\n\n init() {\n self.commandType = \"terminal\"\n self.code = \"ack\"\n self.rows = 0\n self.cols = 0\n }\n\n func json() throws -> String? {\n let encoder = JSONEncoder()\n let data = try encoder.encode(self)\n return data.base64EncodedString().trimmingCharacters(in: CharacterSet(charactersIn: \"=\"))\n }\n}\n"], ["/container/Sources/DNSServer/Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport DNS\nimport Foundation\n\npublic typealias Message = DNS.Message\npublic typealias ResourceRecord = DNS.ResourceRecord\npublic typealias HostRecord = DNS.HostRecord\npublic typealias IPv4 = DNS.IPv4\npublic typealias IPv6 = DNS.IPv6\npublic typealias ReturnCode = DNS.ReturnCode\n\npublic enum DNSResolverError: Swift.Error, CustomStringConvertible {\n case serverError(_ msg: String)\n case invalidHandlerSpec(_ spec: String)\n case unsupportedHandlerType(_ t: String)\n case invalidIP(_ v: String)\n case invalidHandlerOption(_ v: String)\n case handlerConfigError(_ msg: String)\n\n public var description: String {\n switch self {\n case .serverError(let msg):\n return \"server error: \\(msg)\"\n case .invalidHandlerSpec(let msg):\n return \"invalid handler spec: \\(msg)\"\n case .unsupportedHandlerType(let t):\n return \"unsupported handler type specified: \\(t)\"\n case .invalidIP(let ip):\n return \"invalid IP specified: \\(ip)\"\n case .invalidHandlerOption(let v):\n return \"invalid handler option specified: \\(v)\"\n case .handlerConfigError(let msg):\n return \"error configuring handler: \\(msg)\"\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/Int+Formatted.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Int {\n func formattedTime() -> String {\n let secondsInMinute = 60\n let secondsInHour = secondsInMinute * 60\n let secondsInDay = secondsInHour * 24\n\n let days = self / secondsInDay\n let hours = (self % secondsInDay) / secondsInHour\n let minutes = (self % secondsInHour) / secondsInMinute\n let seconds = self % secondsInMinute\n\n var components = [String]()\n if days > 0 {\n components.append(\"\\(days)d\")\n }\n if hours > 0 || days > 0 {\n components.append(\"\\(hours)h\")\n }\n if minutes > 0 || hours > 0 || days > 0 {\n components.append(\"\\(minutes)m\")\n }\n components.append(\"\\(seconds)s\")\n return components.joined(separator: \" \")\n }\n\n func formattedNumber() -> String {\n let formatter = NumberFormatter()\n formatter.numberStyle = .decimal\n guard let formattedNumber = formatter.string(from: NSNumber(value: self)) else {\n return \"\"\n }\n return formattedNumber\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ProcessConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Configuration data for an executable Process.\npublic struct ProcessConfiguration: Sendable, Codable {\n /// The on disk path to the executable binary.\n public var executable: String\n /// Arguments passed to the Process.\n public var arguments: [String]\n /// Environment variables for the Process.\n public var environment: [String]\n /// The current working directory (cwd) for the Process.\n public var workingDirectory: String\n /// A boolean value indicating if a Terminal or PTY device should\n /// be attached to the Process's Standard I/O.\n public var terminal: Bool\n /// The User a Process should execute under.\n public var user: User\n /// Supplemental groups for the Process.\n public var supplementalGroups: [UInt32]\n /// Rlimits for the Process.\n public var rlimits: [Rlimit]\n\n /// Rlimits for Processes.\n public struct Rlimit: Sendable, Codable {\n /// The Rlimit type of the Process.\n ///\n /// Values include standard Rlimit resource types, i.e. RLIMIT_NPROC, RLIMIT_NOFILE, ...\n public let limit: String\n /// The soft limit of the Process\n public let soft: UInt64\n /// The hard or max limit of the Process.\n public let hard: UInt64\n\n public init(limit: String, soft: UInt64, hard: UInt64) {\n self.limit = limit\n self.soft = soft\n self.hard = hard\n }\n }\n\n /// The User information for a Process.\n public enum User: Sendable, Codable, CustomStringConvertible {\n /// Given the raw user string of the form or or lookup the uid/gid within\n /// the container before setting it for the Process.\n case raw(userString: String)\n /// Set the provided uid/gid for the Process.\n case id(uid: UInt32, gid: UInt32)\n\n public var description: String {\n switch self {\n case .id(let uid, let gid):\n return \"\\(uid):\\(gid)\"\n case .raw(let name):\n return name\n }\n }\n }\n\n public init(\n executable: String,\n arguments: [String],\n environment: [String],\n workingDirectory: String = \"/\",\n terminal: Bool = false,\n user: User = .id(uid: 0, gid: 0),\n supplementalGroups: [UInt32] = [],\n rlimits: [Rlimit] = []\n ) {\n self.executable = executable\n self.arguments = arguments\n self.environment = environment\n self.workingDirectory = workingDirectory\n self.terminal = terminal\n self.user = user\n self.supplementalGroups = supplementalGroups\n self.rlimits = rlimits\n }\n}\n"], ["/container/Sources/SocketForwarder/SocketForwarderResult.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIO\n\npublic struct SocketForwarderResult: Sendable {\n private let channel: any Channel\n\n public init(channel: Channel) {\n self.channel = channel\n }\n\n public var proxyAddress: SocketAddress? { self.channel.localAddress }\n\n public func close() {\n self.channel.eventLoop.execute {\n _ = channel.close()\n }\n }\n\n public func wait() async throws {\n try await self.channel.closeFuture.get()\n }\n}\n"], ["/container/Sources/SocketForwarder/LRUCache.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nstruct KeyExistsError: Error {}\n\nclass LRUCache {\n private class Node {\n fileprivate var prev: Node?\n fileprivate var next: Node?\n fileprivate let key: K\n fileprivate let value: V\n\n init(key: K, value: V) {\n self.prev = nil\n self.next = nil\n self.key = key\n self.value = value\n }\n }\n\n private let size: UInt\n private var head: Node?\n private var tail: Node?\n private var members: [K: Node]\n\n init(size: UInt) {\n self.size = size\n self.head = nil\n self.tail = nil\n self.members = [:]\n }\n\n var count: Int { members.count }\n\n func get(_ key: K) -> V? {\n guard let node = members[key] else {\n return nil\n }\n listRemove(node: node)\n listInsert(node: node, after: tail)\n return node.value\n }\n\n func put(key: K, value: V) -> (K, V)? {\n let node = Node(key: key, value: value)\n var evicted: (K, V)? = nil\n\n if let existingNode = members[key] {\n // evict the replaced node\n listRemove(node: existingNode)\n evicted = (existingNode.key, existingNode.value)\n } else if self.count >= self.size {\n // evict the least recently used node\n evicted = evict()\n }\n\n // insert the new node and return any evicted node\n members[key] = node\n listInsert(node: node, after: tail)\n return evicted\n }\n\n private func evict() -> (K, V)? {\n guard let head else {\n return nil\n }\n let ret = (head.key, head.value)\n listRemove(node: head)\n members.removeValue(forKey: head.key)\n return ret\n }\n\n private func listRemove(node: Node) {\n if let prev = node.prev {\n prev.next = node.next\n } else {\n head = node.next\n }\n if let next = node.next {\n next.prev = node.prev\n } else {\n tail = node.prev\n }\n }\n\n private func listInsert(node: Node, after: Node?) {\n let before: Node?\n if let after {\n before = after.next\n after.next = node\n } else {\n before = head\n head = node\n }\n\n if let before {\n before.prev = node\n } else {\n tail = node\n }\n\n node.prev = after\n node.next = before\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/CompositeResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Delegates a query sequentially to handlers until one provides a response.\npublic struct CompositeResolver: DNSHandler {\n private let handlers: [DNSHandler]\n\n public init(handlers: [DNSHandler]) {\n self.handlers = handlers\n }\n\n public func answer(query: Message) async throws -> Message? {\n for handler in self.handlers {\n if let response = try await handler.answer(query: query) {\n return response\n }\n }\n\n return nil\n }\n}\n"], ["/container/Sources/ContainerClient/XPC+.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\n/// Keys for XPC fields.\npublic enum XPCKeys: String {\n /// Route key.\n case route\n /// Container array key.\n case containers\n /// ID key.\n case id\n // ID for a process.\n case processIdentifier\n /// Container configuration key.\n case containerConfig\n /// Container options key.\n case containerOptions\n /// Vsock port number key.\n case port\n /// Exit code for a process\n case exitCode\n /// An event that occurred in a container\n case containerEvent\n /// Error key.\n case error\n /// FD to a container resource key.\n case fd\n /// FDs pointing to container logs key.\n case logs\n /// Options for stopping a container key.\n case stopOptions\n /// Plugins\n case pluginName\n case plugins\n case plugin\n\n /// Health check request.\n case ping\n\n /// Process request keys.\n case signal\n case snapshot\n case stdin\n case stdout\n case stderr\n case status\n case width\n case height\n case processConfig\n\n /// Update progress\n case progressUpdateEndpoint\n case progressUpdateSetDescription\n case progressUpdateSetSubDescription\n case progressUpdateSetItemsName\n case progressUpdateAddTasks\n case progressUpdateSetTasks\n case progressUpdateAddTotalTasks\n case progressUpdateSetTotalTasks\n case progressUpdateAddItems\n case progressUpdateSetItems\n case progressUpdateAddTotalItems\n case progressUpdateSetTotalItems\n case progressUpdateAddSize\n case progressUpdateSetSize\n case progressUpdateAddTotalSize\n case progressUpdateSetTotalSize\n\n /// Network\n case networkId\n case networkConfig\n case networkState\n case networkStates\n\n /// Kernel\n case kernel\n case kernelTarURL\n case kernelFilePath\n case systemPlatform\n}\n\npublic enum XPCRoute: String {\n case listContainer\n case createContainer\n case deleteContainer\n case containerLogs\n case containerEvent\n\n case pluginLoad\n case pluginGet\n case pluginRestart\n case pluginUnload\n case pluginList\n\n case networkCreate\n case networkDelete\n case networkList\n\n case ping\n\n case installKernel\n case getDefaultKernel\n}\n\nextension XPCMessage {\n public init(route: XPCRoute) {\n self.init(route: route.rawValue)\n }\n\n public func data(key: XPCKeys) -> Data? {\n data(key: key.rawValue)\n }\n\n public func dataNoCopy(key: XPCKeys) -> Data? {\n dataNoCopy(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Data) {\n set(key: key.rawValue, value: value)\n }\n\n public func string(key: XPCKeys) -> String? {\n string(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: String) {\n set(key: key.rawValue, value: value)\n }\n\n public func bool(key: XPCKeys) -> Bool {\n bool(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Bool) {\n set(key: key.rawValue, value: value)\n }\n\n public func uint64(key: XPCKeys) -> UInt64 {\n uint64(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: UInt64) {\n set(key: key.rawValue, value: value)\n }\n\n public func int64(key: XPCKeys) -> Int64 {\n int64(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Int64) {\n set(key: key.rawValue, value: value)\n }\n\n public func int(key: XPCKeys) -> Int {\n Int(int64(key: key.rawValue))\n }\n\n public func set(key: XPCKeys, value: Int) {\n set(key: key.rawValue, value: Int64(value))\n }\n\n public func fileHandle(key: XPCKeys) -> FileHandle? {\n fileHandle(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: FileHandle) {\n set(key: key.rawValue, value: value)\n }\n\n public func fileHandles(key: XPCKeys) -> [FileHandle]? {\n fileHandles(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: [FileHandle]) throws {\n try set(key: key.rawValue, value: value)\n }\n\n public func endpoint(key: XPCKeys) -> xpc_endpoint_t? {\n endpoint(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: xpc_endpoint_t) {\n set(key: key.rawValue, value: value)\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerClient/Core/ContainerStopOptions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct ContainerStopOptions: Sendable, Codable {\n public let timeoutInSeconds: Int32\n public let signal: Int32\n\n public static let `default` = ContainerStopOptions(\n timeoutInSeconds: 5,\n signal: SIGTERM\n )\n\n public init(timeoutInSeconds: Int32, signal: Int32) {\n self.timeoutInSeconds = timeoutInSeconds\n self.signal = signal\n }\n}\n"], ["/container/Sources/ContainerPlugin/CommandLine+Executable.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension CommandLine {\n public static var executablePathUrl: URL {\n /// _NSGetExecutablePath with a zero-length buffer returns the needed buffer length\n var bufferSize: Int32 = 0\n var buffer = [CChar](repeating: 0, count: Int(bufferSize))\n _ = _NSGetExecutablePath(&buffer, &bufferSize)\n\n /// Create the buffer and get the path\n buffer = [CChar](repeating: 0, count: Int(bufferSize))\n guard _NSGetExecutablePath(&buffer, &bufferSize) == 0 else {\n fatalError(\"UNEXPECTED: failed to get executable path\")\n }\n\n /// Return the path with the executable file component removed the last component and\n let executablePath = String(cString: &buffer)\n return URL(filePath: executablePath)\n }\n}\n"], ["/container/Sources/TerminalProgress/Int64+Formatted.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Int64 {\n func formattedSize() -> String {\n let formattedSize = ByteCountFormatter.string(fromByteCount: self, countStyle: .binary)\n return formattedSize\n }\n\n func formattedSizeSpeed(from startTime: DispatchTime) -> String {\n let elapsedTimeNanoseconds = DispatchTime.now().uptimeNanoseconds - startTime.uptimeNanoseconds\n let elapsedTimeSeconds = Double(elapsedTimeNanoseconds) / 1_000_000_000\n guard elapsedTimeSeconds > 0 else {\n return \"0 B/s\"\n }\n\n let speed = Double(self) / elapsedTimeSeconds\n let formattedSpeed = ByteCountFormatter.string(fromByteCount: Int64(speed), countStyle: .binary)\n return \"\\(formattedSpeed)/s\"\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkMode.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Networking mode that applies to client containers.\npublic enum NetworkMode: String, Codable, Sendable {\n /// NAT networking mode.\n /// Containers do not have routable IPs, and the host performs network\n /// address translation to allow containers to reach external services.\n case nat = \"nat\"\n}\n\nextension NetworkMode {\n public init() {\n self = .nat\n }\n\n public init?(_ value: String) {\n switch value.lowercased() {\n case \"nat\": self = .nat\n default: return nil\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ImageDescription.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\n\n/// A type that represents an OCI image that can be used with sandboxes or containers.\npublic struct ImageDescription: Sendable, Codable {\n /// The public reference/name of the image.\n public let reference: String\n /// The descriptor of the image.\n public let descriptor: Descriptor\n\n public var digest: String { descriptor.digest }\n public var mediaType: String { descriptor.mediaType }\n\n public init(reference: String, descriptor: Descriptor) {\n self.reference = reference\n self.descriptor = descriptor\n }\n}\n"], ["/container/Sources/ContainerClient/SandboxRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum SandboxRoutes: String {\n /// Bootstrap the sandbox instance and create the init process.\n case bootstrap = \"com.apple.container.sandbox/bootstrap\"\n /// Create a process in the sandbox.\n case createProcess = \"com.apple.container.sandbox/createProcess\"\n /// Start a process in the sandbox.\n case start = \"com.apple.container.sandbox/start\"\n /// Stop the sandbox.\n case stop = \"com.apple.container.sandbox/stop\"\n /// Return the current state of the sandbox.\n case state = \"com.apple.container.sandbox/state\"\n /// Kill a process in the sandbox.\n case kill = \"com.apple.container.sandbox/kill\"\n /// Resize the pty of a process in the sandbox.\n case resize = \"com.apple.container.sandbox/resize\"\n /// Wait on a process in the sandbox.\n case wait = \"com.apple.container.sandbox/wait\"\n /// Execute a new process in the sandbox.\n case exec = \"com.apple.container.sandbox/exec\"\n /// Dial a vsock port in the sandbox.\n case dial = \"com.apple.container.sandbox/dial\"\n}\n"], ["/container/Sources/ContainerClient/Core/PublishPort.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The network protocols available for port forwarding.\npublic enum PublishProtocol: String, Sendable, Codable {\n case tcp = \"tcp\"\n case udp = \"udp\"\n\n /// Initialize a protocol with to default value, `.tcp`.\n public init() {\n self = .tcp\n }\n\n /// Initialize a protocol value from the provided string.\n public init?(_ value: String) {\n switch value.lowercased() {\n case \"tcp\": self = .tcp\n case \"udp\": self = .udp\n default: return nil\n }\n }\n}\n\n/// Specifies internet port forwarding from host to container.\npublic struct PublishPort: Sendable, Codable {\n /// The IP address of the proxy listener on the host\n public let hostAddress: String\n\n /// The port number of the proxy listener on the host\n public let hostPort: Int\n\n /// The port number of the container listener\n public let containerPort: Int\n\n /// The network protocol for the proxy\n public let proto: PublishProtocol\n\n /// Creates a new port forwarding specification.\n public init(hostAddress: String, hostPort: Int, containerPort: Int, proto: PublishProtocol) {\n self.hostAddress = hostAddress\n self.hostPort = hostPort\n self.containerPort = containerPort\n self.proto = proto\n }\n}\n"], ["/container/Sources/APIServer/HealthCheck/HealthCheckHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport Logging\n\nactor HealthCheckHarness {\n private let log: Logger\n\n public init(log: Logger) {\n self.log = log\n }\n\n @Sendable\n func ping(_ message: XPCMessage) async -> XPCMessage {\n message.reply()\n }\n}\n"], ["/container/Sources/TerminalProgress/StandardError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct StandardError {\n func write(_ string: String) {\n if let data = string.data(using: .utf8) {\n FileHandle.standardError.write(data)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerSnapshot.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\n\n/// A snapshot of a container along with its configuration\n/// and any runtime state information.\npublic struct ContainerSnapshot: Codable, Sendable {\n /// The configuration of the container.\n public let configuration: ContainerConfiguration\n /// The runtime status of the container.\n public let status: RuntimeStatus\n /// Network interfaces attached to the sandbox that are provided to the container.\n public let networks: [Attachment]\n\n public init(\n configuration: ContainerConfiguration,\n status: RuntimeStatus,\n networks: [Attachment]\n ) {\n self.configuration = configuration\n self.status = status\n self.networks = networks\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressTheme.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A theme for progress bar.\npublic protocol ProgressTheme: Sendable {\n /// The icons used to represent a spinner.\n var spinner: [String] { get }\n /// The icon used to represent a progress bar.\n var bar: String { get }\n /// The icon used to indicate that a progress bar finished.\n var done: String { get }\n}\n\npublic struct DefaultProgressTheme: ProgressTheme {\n public let spinner = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"]\n public let bar = \"█\"\n public let done = \"✔\"\n}\n\nextension ProgressTheme {\n func getSpinnerIcon(_ iteration: Int) -> String {\n spinner[iteration % spinner.count]\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/IsolatedInterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\n\n/// Isolated container network interface strategy. This strategy prohibits\n/// container to container networking, but it is the only approach that\n/// works for macOS Sequoia.\nstruct IsolatedInterfaceStrategy: InterfaceStrategy {\n public func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) -> Interface {\n let gateway = interfaceIndex == 0 ? attachment.gateway : nil\n return NATInterface(address: attachment.address, gateway: gateway)\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/UserDefaults+Container.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension UserDefaults {\n public static let appSuiteName = \"com.apple.container.defaults\"\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Configuration parameters for network creation.\npublic struct NetworkConfiguration: Codable, Sendable, Identifiable {\n /// A unique identifier for the network\n public let id: String\n\n /// The network type\n public let mode: NetworkMode\n\n /// The preferred CIDR address for the subnet, if specified\n public let subnet: String?\n\n /// Creates a network configuration\n public init(\n id: String,\n mode: NetworkMode,\n subnet: String? = nil\n ) {\n self.id = id\n self.mode = mode\n self.subnet = subnet\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/Network.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\n\n/// Defines common characteristics and operations for a network.\npublic protocol Network: Sendable {\n // Contains network attributes while the network is running\n var state: NetworkState { get async }\n\n // Use implementation-dependent network attributes\n nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws\n\n // Start the network\n func start() async throws\n}\n"], ["/container/Sources/ContainerClient/SandboxSnapshot.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\n\n/// A snapshot of a sandbox and its resources.\npublic struct SandboxSnapshot: Codable, Sendable {\n /// The runtime status of the sandbox.\n public let status: RuntimeStatus\n /// Network attachments for the sandbox.\n public let networks: [Attachment]\n /// Containers placed in the sandbox.\n public let containers: [ContainerSnapshot]\n\n public init(\n status: RuntimeStatus,\n networks: [Attachment],\n containers: [ContainerSnapshot]\n ) {\n self.status = status\n self.networks = networks\n self.containers = containers\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum NetworkRoutes: String {\n /// Return the current state of the network.\n case state = \"com.apple.container.network/state\"\n /// Allocates parameters for attaching a sandbox to the network.\n case allocate = \"com.apple.container.network/allocate\"\n /// Deallocates parameters for attaching a sandbox to the network.\n case deallocate = \"com.apple.container.network/deallocate\"\n /// Disables the allocator if no sandboxes are attached.\n case disableAllocator = \"com.apple.container.network/disableAllocator\"\n /// Retrieves the allocation for a hostname.\n case lookup = \"com.apple.container.network/lookup\"\n}\n"], ["/container/Sources/ContainerClient/Core/PublishSocket.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\n/// Represents a socket that should be published from container to host.\npublic struct PublishSocket: Sendable, Codable {\n /// The path to the socket in the container.\n public var containerPath: URL\n\n /// The path where the socket should appear on the host.\n public var hostPath: URL\n\n /// File permissions for the socket on the host.\n public var permissions: FilePermissions?\n\n public init(\n containerPath: URL,\n hostPath: URL,\n permissions: FilePermissions? = nil\n ) {\n self.containerPath = containerPath\n self.hostPath = hostPath\n self.permissions = permissions\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerCreateOptions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct ContainerCreateOptions: Codable, Sendable {\n public let autoRemove: Bool\n\n public init(autoRemove: Bool) {\n self.autoRemove = autoRemove\n }\n\n public static let `default` = ContainerCreateOptions(autoRemove: false)\n\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/ImageServiceXPCKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\n/// Keys for XPC fields.\npublic enum ImagesServiceXPCKeys: String {\n case fd\n /// FDs pointing to container logs key.\n case logs\n /// Path to a file on disk key.\n case filePath\n\n /// Images\n case imageReference\n case imageNewReference\n case imageDescription\n case imageDescriptions\n case filesystem\n case ociPlatform\n case insecureFlag\n case garbageCollect\n\n /// ContentStore\n case digest\n case digests\n case directory\n case contentPath\n case size\n case ingestSessionId\n}\n\nextension XPCMessage {\n public func set(key: ImagesServiceXPCKeys, value: String) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: UInt64) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: Data) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: Bool) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func string(key: ImagesServiceXPCKeys) -> String? {\n self.string(key: key.rawValue)\n }\n\n public func data(key: ImagesServiceXPCKeys) -> Data? {\n self.data(key: key.rawValue)\n }\n\n public func dataNoCopy(key: ImagesServiceXPCKeys) -> Data? {\n self.dataNoCopy(key: key.rawValue)\n }\n\n public func uint64(key: ImagesServiceXPCKeys) -> UInt64 {\n self.uint64(key: key.rawValue)\n }\n\n public func bool(key: ImagesServiceXPCKeys) -> Bool {\n self.bool(key: key.rawValue)\n }\n}\n\n#endif\n"], ["/container/Sources/Services/ContainerSandboxService/InterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\n\n/// A strategy for mapping network attachment information to a network interface.\npublic protocol InterfaceStrategy: Sendable {\n /// Map a client network attachment request to a network interface specification.\n ///\n /// - Parameters:\n /// - attachment: General attachment information that is common\n /// for all networks.\n /// - interfaceIndex: The zero-based index of the interface.\n /// - additionalData: If present, attachment information that is\n /// specific for the network to which the container will attach.\n ///\n /// - Returns: An XPC message with no parameters.\n func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) throws -> Interface\n}\n"], ["/container/Sources/ContainerClient/Arch.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum Arch: String {\n case arm64, amd64\n\n public static func hostArchitecture() -> Arch {\n #if arch(arm64)\n return .arm64\n #elseif arch(x86_64)\n return .amd64\n #endif\n }\n}\n"], ["/container/Sources/CLI/Codable+JSON.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\nextension [any Codable] {\n func jsonArray() throws -> String {\n \"[\\(try self.map { String(data: try JSONEncoder().encode($0), encoding: .utf8)! }.joined(separator: \",\"))]\"\n }\n}\n"], ["/container/Sources/ContainerClient/Core/Constants.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum Constants {\n public static let keychainID = \"com.apple.container\"\n}\n"], ["/container/Sources/ContainerClient/Array+Dedupe.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension Array where Element: Hashable {\n func dedupe() -> [Element] {\n var elems = Set()\n return filter { elems.insert($0).inserted }\n }\n}\n"], ["/container/Sources/ContainerClient/ContainerEvents.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\npublic enum ContainerEvent: Sendable, Codable {\n case containerStart(id: String)\n case containerExit(id: String, exitCode: Int64)\n}\n"], ["/container/Sources/TerminalProgress/ProgressUpdate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum ProgressUpdateEvent: Sendable {\n case setDescription(String)\n case setSubDescription(String)\n case setItemsName(String)\n case addTasks(Int)\n case setTasks(Int)\n case addTotalTasks(Int)\n case setTotalTasks(Int)\n case addItems(Int)\n case setItems(Int)\n case addTotalItems(Int)\n case setTotalItems(Int)\n case addSize(Int64)\n case setSize(Int64)\n case addTotalSize(Int64)\n case setTotalSize(Int64)\n case custom(String)\n}\n\npublic typealias ProgressUpdateHandler = @Sendable (_ events: [ProgressUpdateEvent]) async -> Void\n\npublic protocol ProgressAdapter {\n associatedtype T\n static func handler(from progressUpdate: ProgressUpdateHandler?) -> (@Sendable ([T]) async -> Void)?\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/ImageServiceXPCRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\npublic enum ImagesServiceXPCRoute: String {\n case imageList\n case imagePull\n case imagePush\n case imageTag\n case imageBuild\n case imageDelete\n case imageSave\n case imageLoad\n case imagePrune\n\n case contentGet\n case contentDelete\n case contentClean\n case contentIngestStart\n case contentIngestComplete\n case contentIngestCancel\n\n case imageUnpack\n case snapshotDelete\n case snapshotGet\n}\n\nextension XPCMessage {\n public init(route: ImagesServiceXPCRoute) {\n self.init(route: route.rawValue)\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerClient/Core/RuntimeStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Runtime status for a sandbox or container.\npublic enum RuntimeStatus: String, CaseIterable, Sendable, Codable {\n /// The object is in an unknown status.\n case unknown\n /// The object is currently stopped.\n case stopped\n /// The object is currently running.\n case running\n /// The object is currently stopping.\n case stopping\n}\n"], ["/container/Sources/Services/ContainerNetworkService/Attachment.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A snapshot of a network interface allocated to a sandbox.\npublic struct Attachment: Codable, Sendable {\n /// The network ID associated with the attachment.\n public let network: String\n /// The hostname associated with the attachment.\n public let hostname: String\n /// The subnet CIDR, where the address is the container interface IPv4 address.\n public let address: String\n /// The IPv4 gateway address.\n public let gateway: String\n\n public init(network: String, hostname: String, address: String, gateway: String) {\n self.network = network\n self.hostname = hostname\n self.address = address\n self.gateway = gateway\n }\n}\n"], ["/container/Sources/SocketForwarder/SocketForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIO\n\npublic protocol SocketForwarder: Sendable {\n func run() throws -> EventLoopFuture\n}\n"], ["/container/Sources/DNSServer/DNSHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Protocol for implementing custom DNS handlers.\npublic protocol DNSHandler {\n /// Attempt to answer a DNS query\n /// - Parameter query: the query message\n /// - Throws: a server failure occurred during the query\n /// - Returns: The response message for the query, or nil if the request\n /// is not within the scope of the handler.\n func answer(query: Message) async throws -> Message?\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum NetworkKeys: String {\n case additionalData\n case allocatorDisabled\n case attachment\n case hostname\n case network\n case state\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:21:52", "created_task_model": "DeepSeek-R1", "function_skeleton": "func run ( ) async throws { }", "code_description": "This code segment functions to: Terminate a running resource instance after verifying its existence and handle cases where the target resource cannot be located by suppressing specific error conditions while propagating others."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\n func run() async throws {\n let client = try ContainerClient(configuration: .default)\n try await client.stopBuilder()\n print(\"Builder stopped successfully\")\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 03-22-06"}, "editdistance_info": {"edit_distance": 24.6914, "calculate_time": "2025-08-21 03:22:06", "true_code_clean": "func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n try await container.stop()\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n print(\"builder is not running\")\n return\n }\n }\n throw error\n }\n }", "predict_code_clean": "func run() async throws {\n let client = try ContainerClient(configuration: .default)\n try await client.stopBuilder()\n print(\"Builder stopped successfully\")\n }"}} {"repo_name": "container", "file_name": "/container/Sources/Services/ContainerNetworkService/ReservedVmnetNetwork.swift", "inference_info": {"prefix_code": "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport Dispatch\nimport Foundation\nimport Logging\nimport SendableProperty\nimport SystemConfiguration\nimport XPC\nimport vmnet\n\n/// Creates a vmnet network with reservation APIs.\n@available(macOS 26, *)\npublic final class ReservedVmnetNetwork: Network {\n @SendablePropertyUnchecked\n private var _state: NetworkState\n private let log: Logger\n\n @SendableProperty\n private var network: vmnet_network_ref?\n @SendableProperty\n private var interface: interface_ref?\n private let networkLock = NSLock()\n\n /// Configure a bridge network that allows external system access using\n /// network address translation.\n ", "suffix_code": "\n\n public var state: NetworkState {\n get async { _state }\n }\n\n public nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws {\n try networkLock.withLock {\n try handler(network.map { try Self.serialize_network_ref(ref: $0) })\n }\n }\n\n public func start() async throws {\n guard case .created(let configuration) = _state else {\n throw ContainerizationError(.invalidArgument, message: \"cannot start network that is in \\(_state.state) state\")\n }\n\n try startNetwork(configuration: configuration, log: log)\n }\n\n private static func serialize_network_ref(ref: vmnet_network_ref) throws -> XPCMessage {\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let refObject = vmnet_network_copy_serialization(ref, &status) else {\n throw ContainerizationError(.invalidArgument, message: \"cannot serialize vmnet_network_ref to XPC object, status \\(status)\")\n }\n return XPCMessage(object: refObject)\n }\n\n private func startNetwork(configuration: NetworkConfiguration, log: Logger) throws {\n log.info(\n \"starting vmnet network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n ]\n )\n let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName)\n let subnetText = configuration.subnet ?? suite?.string(forKey: \"network.subnet\")\n\n // with the reservation API, subnet priority is CLI argument, UserDefault, auto\n let subnet = try subnetText.map { try CIDRAddress($0) }\n\n // set up the vmnet configuration\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let vmnetConfiguration = vmnet_network_configuration_create(vmnet.operating_modes_t.VMNET_SHARED_MODE, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet config with status \\(status)\")\n }\n\n vmnet_network_configuration_disable_dhcp(vmnetConfiguration)\n\n // set the subnet if the caller provided one\n if let subnet {\n let gateway = IPv4Address(fromValue: subnet.lower.value + 1)\n var gatewayAddr = in_addr()\n inet_pton(AF_INET, gateway.description, &gatewayAddr)\n let mask = IPv4Address(fromValue: subnet.prefixLength.prefixMask32)\n var maskAddr = in_addr()\n inet_pton(AF_INET, mask.description, &maskAddr)\n log.info(\n \"configuring vmnet subnet\",\n metadata: [\"cidr\": \"\\(subnet)\"]\n )\n let status = vmnet_network_configuration_set_ipv4_subnet(vmnetConfiguration, &gatewayAddr, &maskAddr)\n guard status == .VMNET_SUCCESS else {\n throw ContainerizationError(.internalError, message: \"failed to set subnet \\(subnet) for network \\(configuration.id)\")\n }\n }\n\n // reserve the network\n guard let network = vmnet_network_create(vmnetConfiguration, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet network with status \\(status)\")\n }\n self.network = network\n\n // retrieve the subnet since the caller may not have provided one\n var subnetAddr = in_addr()\n var maskAddr = in_addr()\n vmnet_network_get_ipv4_subnet(network, &subnetAddr, &maskAddr)\n let subnetValue = UInt32(bigEndian: subnetAddr.s_addr)\n let maskValue = UInt32(bigEndian: maskAddr.s_addr)\n let lower = IPv4Address(fromValue: subnetValue & maskValue)\n let upper = IPv4Address(fromValue: lower.value + ~maskValue)\n let runningSubnet = try CIDRAddress(lower: lower, upper: upper)\n let runningGateway = IPv4Address(fromValue: runningSubnet.lower.value + 1)\n self._state = .running(configuration, NetworkStatus(address: runningSubnet.description, gateway: runningGateway.description))\n log.info(\n \"started vmnet network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n \"cidr\": \"\\(runningSubnet)\",\n ]\n )\n }\n}\n", "middle_code": "public init(\n configuration: NetworkConfiguration,\n log: Logger\n ) throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.unsupported, message: \"invalid network mode \\(configuration.mode)\")\n }\n log.info(\"creating vmnet network\")\n self.log = log\n _state = .created(configuration)\n log.info(\"created vmnet network\")\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/container/Sources/Services/ContainerNetworkService/AllocationOnlyVmnetNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\npublic actor AllocationOnlyVmnetNetwork: Network {\n private let log: Logger\n private var _state: NetworkState\n\n /// Configure a bridge network that allows external system access using\n /// network address translation.\n public init(\n configuration: NetworkConfiguration,\n log: Logger\n ) throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.unsupported, message: \"invalid network mode \\(configuration.mode)\")\n }\n\n guard configuration.subnet == nil else {\n throw ContainerizationError(.unsupported, message: \"subnet assignment is not yet implemented\")\n }\n\n self.log = log\n self._state = .created(configuration)\n }\n\n public var state: NetworkState {\n self._state\n }\n\n public nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws {\n try handler(nil)\n }\n\n public func start() async throws {\n guard case .created(let configuration) = _state else {\n throw ContainerizationError(.invalidState, message: \"cannot start network \\(_state.id) in \\(_state.state) state\")\n }\n var defaultSubnet = \"192.168.64.1/24\"\n\n log.info(\n \"starting allocation-only network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(NetworkMode.nat.rawValue)\",\n ]\n )\n\n if let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName) {\n // TODO: Make the suiteName a constant defined in ClientDefaults and use that.\n // This will need some re-working of dependencies between NetworkService and Client\n defaultSubnet = suite.string(forKey: \"network.subnet\") ?? defaultSubnet\n }\n\n let subnet = try CIDRAddress(defaultSubnet)\n let gateway = IPv4Address(fromValue: subnet.lower.value + 1)\n self._state = .running(configuration, NetworkStatus(address: subnet.description, gateway: gateway.description))\n log.info(\n \"started allocation-only network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n \"cidr\": \"\\(defaultSubnet)\",\n ]\n )\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/NonisolatedInterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Logging\nimport Virtualization\nimport vmnet\n\n/// Interface strategy for containers that use macOS's custom network feature.\n@available(macOS 26, *)\nstruct NonisolatedInterfaceStrategy: InterfaceStrategy {\n private let log: Logger\n\n public init(log: Logger) {\n self.log = log\n }\n\n public func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) throws -> Interface {\n guard let additionalData else {\n throw ContainerizationError(.invalidState, message: \"network state does not contain custom network reference\")\n }\n\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let networkRef = vmnet_network_create_with_serialization(additionalData.underlying, &status) else {\n throw ContainerizationError(.invalidState, message: \"cannot deserialize custom network reference, status \\(status)\")\n }\n\n log.info(\"creating NATNetworkInterface with network reference\")\n let gateway = interfaceIndex == 0 ? attachment.gateway : nil\n return NATNetworkInterface(address: attachment.address, gateway: gateway, reference: networkRef)\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\npublic actor NetworkService: Sendable {\n private let network: any Network\n private let log: Logger?\n private var allocator: AttachmentAllocator\n\n /// Set up a network service for the specified network.\n public init(\n network: any Network,\n log: Logger? = nil\n ) async throws {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let subnet = try CIDRAddress(status.address)\n\n let size = Int(subnet.upper.value - subnet.lower.value - 3)\n self.allocator = try AttachmentAllocator(lower: subnet.lower.value + 2, size: size)\n self.network = network\n self.log = log\n }\n\n @Sendable\n public func state(_ message: XPCMessage) async throws -> XPCMessage {\n let reply = message.reply()\n let state = await network.state\n try reply.setState(state)\n return reply\n }\n\n @Sendable\n public func allocate(_ message: XPCMessage) async throws -> XPCMessage {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let hostname = try message.hostname()\n let index = try await allocator.allocate(hostname: hostname)\n let subnet = try CIDRAddress(status.address)\n let ip = IPv4Address(fromValue: index)\n let attachment = Attachment(\n network: state.id,\n hostname: hostname,\n address: try CIDRAddress(ip, prefixLength: subnet.prefixLength).description,\n gateway: status.gateway\n )\n log?.info(\n \"allocated attachment\",\n metadata: [\n \"hostname\": \"\\(hostname)\",\n \"address\": \"\\(attachment.address)\",\n \"gateway\": \"\\(attachment.gateway)\",\n ])\n let reply = message.reply()\n try reply.setAttachment(attachment)\n try network.withAdditionalData {\n if let additionalData = $0 {\n try reply.setAdditionalData(additionalData.underlying)\n }\n }\n return reply\n }\n\n @Sendable\n public func deallocate(_ message: XPCMessage) async throws -> XPCMessage {\n let hostname = try message.hostname()\n try await allocator.deallocate(hostname: hostname)\n log?.info(\"released attachments\", metadata: [\"hostname\": \"\\(hostname)\"])\n return message.reply()\n }\n\n @Sendable\n public func lookup(_ message: XPCMessage) async throws -> XPCMessage {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let hostname = try message.hostname()\n let index = try await allocator.lookup(hostname: hostname)\n let reply = message.reply()\n guard let index else {\n return reply\n }\n\n let address = IPv4Address(fromValue: index)\n let subnet = try CIDRAddress(status.address)\n let attachment = Attachment(\n network: state.id,\n hostname: hostname,\n address: try CIDRAddress(address, prefixLength: subnet.prefixLength).description,\n gateway: status.gateway\n )\n log?.debug(\n \"lookup attachment\",\n metadata: [\n \"hostname\": \"\\(hostname)\",\n \"address\": \"\\(address)\",\n ])\n try reply.setAttachment(attachment)\n return reply\n }\n\n @Sendable\n public func disableAllocator(_ message: XPCMessage) async throws -> XPCMessage {\n let success = await allocator.disableAllocator()\n log?.info(\"attempted allocator disable\", metadata: [\"success\": \"\\(success)\"])\n let reply = message.reply()\n reply.setAllocatorDisabled(success)\n return reply\n }\n}\n\nextension XPCMessage {\n fileprivate func setAdditionalData(_ additionalData: xpc_object_t) throws {\n xpc_dictionary_set_value(self.underlying, NetworkKeys.additionalData.rawValue, additionalData)\n }\n\n fileprivate func setAllocatorDisabled(_ allocatorDisabled: Bool) {\n self.set(key: NetworkKeys.allocatorDisabled.rawValue, value: allocatorDisabled)\n }\n\n fileprivate func setAttachment(_ attachment: Attachment) throws {\n let data = try JSONEncoder().encode(attachment)\n self.set(key: NetworkKeys.attachment.rawValue, value: data)\n }\n\n fileprivate func setState(_ state: NetworkState) throws {\n let data = try JSONEncoder().encode(state)\n self.set(key: NetworkKeys.state.rawValue, value: data)\n }\n}\n"], ["/container/Sources/APIServer/Networks/NetworksService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerPersistence\nimport ContainerPlugin\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor NetworksService {\n private let resourceRoot: URL\n // FIXME: remove qualifier once we can update Containerization dependency.\n private let store: ContainerPersistence.FilesystemEntityStore\n private let pluginLoader: PluginLoader\n private let log: Logger\n private let networkPlugin: Plugin\n\n private var networkStates = [String: NetworkState]()\n private var busyNetworks = Set()\n\n public init(pluginLoader: PluginLoader, resourceRoot: URL, log: Logger) async throws {\n try FileManager.default.createDirectory(at: resourceRoot, withIntermediateDirectories: true)\n self.resourceRoot = resourceRoot\n self.store = try FilesystemEntityStore(path: resourceRoot, type: \"network\", log: log)\n self.pluginLoader = pluginLoader\n self.log = log\n\n let networkPlugin =\n pluginLoader\n .findPlugins()\n .filter { $0.hasType(.network) }\n .first\n guard let networkPlugin else {\n throw ContainerizationError(.internalError, message: \"cannot find network plugin\")\n }\n self.networkPlugin = networkPlugin\n\n let configurations = try await store.list()\n for configuration in configurations {\n do {\n try await registerService(configuration: configuration)\n } catch {\n log.error(\n \"failed to start network\",\n metadata: [\n \"id\": \"\\(configuration.id)\"\n ])\n }\n\n let client = NetworkClient(id: configuration.id)\n let networkState = try await client.state()\n networkStates[configuration.id] = networkState\n guard case .running = networkState else {\n log.error(\n \"network failed to start\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"state\": \"\\(networkState.state)\",\n ])\n return\n }\n }\n }\n\n /// List all networks registered with the service.\n public func list() async throws -> [NetworkState] {\n log.info(\"network service: list\")\n return networkStates.reduce(into: [NetworkState]()) {\n $0.append($1.value)\n }\n }\n\n /// Create a new network from the provided configuration.\n public func create(configuration: NetworkConfiguration) async throws -> NetworkState {\n guard !busyNetworks.contains(configuration.id) else {\n throw ContainerizationError(.exists, message: \"network \\(configuration.id) has a pending operation\")\n }\n\n busyNetworks.insert(configuration.id)\n defer { busyNetworks.remove(configuration.id) }\n\n log.info(\n \"network service: create\",\n metadata: [\n \"id\": \"\\(configuration.id)\"\n ])\n\n // Ensure the network doesn't already exist.\n guard networkStates[configuration.id] == nil else {\n throw ContainerizationError(.exists, message: \"network \\(configuration.id) already exists\")\n }\n\n // Create and start the network.\n try await registerService(configuration: configuration)\n let client = NetworkClient(id: configuration.id)\n let networkState = try await client.state()\n networkStates[configuration.id] = networkState\n\n // Persist the configuration data.\n do {\n try await store.create(configuration)\n return networkState\n } catch {\n networkStates.removeValue(forKey: configuration.id)\n do {\n try pluginLoader.deregisterWithLaunchd(plugin: networkPlugin, instanceId: configuration.id)\n } catch {\n log.error(\n \"failed to deregister network service after failed creation\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"error\": \"\\(error.localizedDescription)\",\n ])\n }\n\n throw error\n }\n }\n\n /// Delete a network.\n public func delete(id: String) async throws {\n guard !busyNetworks.contains(id) else {\n throw ContainerizationError(.exists, message: \"network \\(id) has a pending operation\")\n }\n\n busyNetworks.insert(id)\n defer { busyNetworks.remove(id) }\n\n log.info(\n \"network service: delete\",\n metadata: [\n \"id\": \"\\(id)\"\n ])\n if id == ClientNetwork.defaultNetworkName {\n throw ContainerizationError(.invalidArgument, message: \"cannot delete system subnet \\(ClientNetwork.defaultNetworkName)\")\n }\n\n guard let networkState = networkStates[id] else {\n throw ContainerizationError(.notFound, message: \"no network for id \\(id)\")\n }\n\n guard case .running = networkState else {\n throw ContainerizationError(.invalidState, message: \"cannot delete subnet \\(id) in state \\(networkState.state)\")\n }\n\n let client = NetworkClient(id: id)\n guard try await client.disableAllocator() else {\n throw ContainerizationError(.invalidState, message: \"cannot delete subnet \\(id) with containers attached\")\n }\n\n defer { networkStates.removeValue(forKey: id) }\n do {\n try pluginLoader.deregisterWithLaunchd(plugin: networkPlugin, instanceId: id)\n } catch {\n log.error(\n \"failed to deregister network service after failed creation\",\n metadata: [\n \"id\": \"\\(id)\",\n \"error\": \"\\(error.localizedDescription)\",\n ])\n }\n\n do {\n try await store.delete(id)\n } catch {\n throw ContainerizationError(.notFound, message: error.localizedDescription)\n }\n }\n\n /// Perform a hostname lookup on all networks.\n public func lookup(hostname: String) async throws -> Attachment? {\n for id in networkStates.keys {\n let client = NetworkClient(id: id)\n guard let allocation = try await client.lookup(hostname: hostname) else {\n continue\n }\n return allocation\n }\n return nil\n }\n\n private func registerService(configuration: NetworkConfiguration) async throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported network mode \\(configuration.mode.rawValue)\")\n }\n\n guard let serviceIdentifier = networkPlugin.getMachService(instanceId: configuration.id, type: .network) else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported network mode \\(configuration.mode.rawValue)\")\n }\n var args = [\n \"start\",\n \"--id\",\n configuration.id,\n \"--service-identifier\",\n serviceIdentifier,\n ]\n\n if let subnet = (try configuration.subnet.map { try CIDRAddress($0) }) {\n var existingCidrs: [CIDRAddress] = []\n for networkState in networkStates.values {\n if case .running(_, let status) = networkState {\n existingCidrs.append(try CIDRAddress(status.address))\n }\n }\n let overlap = existingCidrs.first { $0.overlaps(cidr: subnet) }\n if let overlap {\n throw ContainerizationError(.exists, message: \"subnet \\(subnet) overlaps an existing network with subnet \\(overlap)\")\n }\n\n args += [\"--subnet\", subnet.description]\n }\n\n try await pluginLoader.registerWithLaunchd(\n plugin: networkPlugin,\n rootURL: store.entityUrl(configuration.id),\n args: args,\n instanceId: configuration.id\n )\n }\n}\n"], ["/container/Sources/Helpers/NetworkVmnet/NetworkVmnetHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\n@main\nstruct NetworkVmnetHelper: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"container-network-vmnet\",\n abstract: \"XPC service for managing a vmnet network\",\n version: releaseVersion(),\n subcommands: [\n Start.self\n ]\n )\n}\n\nextension NetworkVmnetHelper {\n struct Start: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Starts the network plugin\"\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .long, help: \"XPC service identifier\")\n var serviceIdentifier: String\n\n @Option(name: .shortAndLong, help: \"Network identifier\")\n var id: String\n\n @Option(name: .shortAndLong, help: \"CIDR address for the subnet\")\n var subnet: String?\n\n func run() async throws {\n let commandName = NetworkVmnetHelper._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n do {\n log.info(\"configuring XPC server\")\n let subnet = try self.subnet.map { try CIDRAddress($0) }\n let configuration = NetworkConfiguration(id: id, mode: .nat, subnet: subnet?.description)\n let network = try Self.createNetwork(configuration: configuration, log: log)\n try await network.start()\n let server = try await NetworkService(network: network, log: log)\n let xpc = XPCServer(\n identifier: serviceIdentifier,\n routes: [\n NetworkRoutes.state.rawValue: server.state,\n NetworkRoutes.allocate.rawValue: server.allocate,\n NetworkRoutes.deallocate.rawValue: server.deallocate,\n NetworkRoutes.lookup.rawValue: server.lookup,\n NetworkRoutes.disableAllocator.rawValue: server.disableAllocator,\n ],\n log: log\n )\n\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n NetworkVmnetHelper.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"NetworkVmnetHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n log[metadataKey: \"id\"] = \"\\(id)\"\n return log\n }\n\n private static func createNetwork(configuration: NetworkConfiguration, log: Logger) throws -> Network {\n guard #available(macOS 26, *) else {\n return try AllocationOnlyVmnetNetwork(configuration: configuration, log: log)\n }\n\n return try ReservedVmnetNetwork(configuration: configuration, log: log)\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/SandboxService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\nimport SocketForwarder\n\nimport struct ContainerizationOCI.Mount\nimport struct ContainerizationOCI.Process\n\n/// An XPC service that manages the lifecycle of a single VM-backed container.\npublic actor SandboxService {\n private let root: URL\n private let interfaceStrategy: InterfaceStrategy\n private var container: ContainerInfo?\n private let monitor: ExitMonitor\n private let eventLoopGroup: any EventLoopGroup\n private var waiters: [String: [CheckedContinuation]] = [:]\n private let lock: AsyncLock = AsyncLock()\n private let log: Logging.Logger\n private var state: State = .created\n private var processes: [String: ProcessInfo] = [:]\n private var socketForwarders: [SocketForwarderResult] = []\n\n /// Create an instance with a bundle that describes the container.\n ///\n /// - Parameters:\n /// - root: The file URL for the bundle root.\n /// - interfaceStrategy: The strategy for producing network interface\n /// objects for each network to which the container attaches.\n /// - log: The destination for log messages.\n public init(root: URL, interfaceStrategy: InterfaceStrategy, eventLoopGroup: any EventLoopGroup, log: Logger) {\n self.root = root\n self.interfaceStrategy = interfaceStrategy\n self.log = log\n self.monitor = ExitMonitor(log: log)\n self.eventLoopGroup = eventLoopGroup\n }\n\n /// Start the VM and the guest agent process for a container.\n ///\n /// - Parameters:\n /// - message: An XPC message with no parameters.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func bootstrap(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`bootstrap` xpc handler\")\n return try await self.lock.withLock { _ in\n guard await self.state == .created else {\n throw ContainerizationError(\n .invalidState,\n message: \"container expected to be in created state, got: \\(await self.state)\"\n )\n }\n\n let bundle = ContainerClient.Bundle(path: self.root)\n try bundle.createLogFile()\n\n let vmm = VZVirtualMachineManager(\n kernel: try bundle.kernel,\n initialFilesystem: bundle.initialFilesystem.asMount,\n bootlog: bundle.bootlog.path,\n logger: self.log\n )\n var config = try bundle.configuration\n let container = LinuxContainer(\n config.id,\n rootfs: try bundle.containerRootfs.asMount,\n vmm: vmm,\n logger: self.log\n )\n\n // dynamically configure the DNS nameserver from a network if no explicit configuration\n if let dns = config.dns, dns.nameservers.isEmpty {\n if let nameserver = try await self.getDefaultNameserver(networks: config.networks) {\n config.dns = ContainerConfiguration.DNSConfiguration(\n nameservers: [nameserver],\n domain: dns.domain,\n searchDomains: dns.searchDomains,\n options: dns.options\n )\n }\n }\n\n try await self.configureContainer(container: container, config: config)\n\n let fqdn: String\n if let hostname = config.hostname {\n if let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName),\n let dnsDomain = suite.string(forKey: \"dns.domain\"),\n !hostname.contains(\".\")\n {\n // TODO: Make the suiteName a constant defined in ClientDefaults and use that.\n // This will need some re-working of dependencies between SandboxService and Client\n fqdn = \"\\(hostname).\\(dnsDomain).\"\n } else {\n fqdn = \"\\(hostname).\"\n }\n } else {\n fqdn = config.id\n }\n\n var attachments: [Attachment] = []\n for index in 0.. XPCMessage {\n self.log.info(\"`start` xpc handler\")\n return try await self.lock.withLock { lock in\n let id = try message.id()\n let stdio = message.stdio()\n let containerInfo = try await self.getContainer()\n let containerId = containerInfo.container.id\n if id == containerId {\n try await self.startInitProcess(stdio: stdio, lock: lock)\n await self.setState(.running)\n try await self.sendContainerEvent(.containerStart(id: id))\n } else {\n try await self.startExecProcess(processId: id, stdio: stdio, lock: lock)\n }\n return message.reply()\n }\n }\n\n private func startInitProcess(stdio: [FileHandle?], lock: AsyncLock.Context) async throws {\n let info = try self.getContainer()\n let container = info.container\n let bundle = info.bundle\n let id = container.id\n guard self.state == .booted else {\n throw ContainerizationError(\n .invalidState,\n message: \"container expected to be in booted state, got: \\(self.state)\"\n )\n }\n let containerLog = try FileHandle(forWritingTo: bundle.containerLog)\n let config = info.config\n let stdout = {\n if let h = stdio[1] {\n return MultiWriter(handles: [h, containerLog])\n }\n return MultiWriter(handles: [containerLog])\n }()\n let stderr: MultiWriter? = {\n if !config.initProcess.terminal {\n if let h = stdio[2] {\n return MultiWriter(handles: [h, containerLog])\n }\n return MultiWriter(handles: [containerLog])\n }\n return nil\n }()\n if let h = stdio[0] {\n container.stdin = h\n }\n container.stdout = stdout\n if let stderr {\n container.stderr = stderr\n }\n self.setState(.starting)\n do {\n try await container.start()\n let waitFunc: ExitMonitor.WaitHandler = {\n let code = try await container.wait()\n if let out = stdio[1] {\n try self.closeHandle(out.fileDescriptor)\n }\n if let err = stdio[2] {\n try self.closeHandle(err.fileDescriptor)\n }\n return code\n }\n try await self.monitor.track(id: id, waitingOn: waitFunc)\n } catch {\n try? await self.cleanupContainer()\n self.setState(.created)\n try await self.sendContainerEvent(.containerExit(id: id, exitCode: -1))\n throw error\n }\n }\n\n private func startExecProcess(processId id: String, stdio: [FileHandle?], lock: AsyncLock.Context) async throws {\n let container = try self.getContainer().container\n guard let processInfo = self.processes[id] else {\n throw ContainerizationError(.notFound, message: \"Process with id \\(id)\")\n }\n let ociConfig = self.configureProcessConfig(config: processInfo.config)\n let stdin: ReaderStream? = {\n if let h = stdio[0] {\n return h\n }\n return nil\n }()\n let process = try await container.exec(\n id,\n configuration: ociConfig,\n stdin: stdin,\n stdout: stdio[1],\n stderr: stdio[2]\n )\n try self.setUnderlyingProcess(id, process)\n try await process.start()\n let waitFunc: ExitMonitor.WaitHandler = {\n let code = try await process.wait()\n if let out = stdio[1] {\n try self.closeHandle(out.fileDescriptor)\n }\n if let err = stdio[2] {\n try self.closeHandle(err.fileDescriptor)\n }\n return code\n }\n try await self.monitor.track(id: id, waitingOn: waitFunc)\n }\n\n private func startSocketForwarders(containerIpAddress: String, publishedPorts: [PublishPort]) async throws {\n var forwarders: [SocketForwarderResult] = []\n try await withThrowingTaskGroup(of: SocketForwarderResult.self) { group in\n for publishedPort in publishedPorts {\n let proxyAddress = try SocketAddress(ipAddress: publishedPort.hostAddress, port: Int(publishedPort.hostPort))\n let serverAddress = try SocketAddress(ipAddress: containerIpAddress, port: Int(publishedPort.containerPort))\n log.info(\n \"creating forwarder for\",\n metadata: [\n \"proxy\": \"\\(proxyAddress)\",\n \"server\": \"\\(serverAddress)\",\n \"protocol\": \"\\(publishedPort.proto)\",\n ])\n group.addTask {\n let forwarder: SocketForwarder\n switch publishedPort.proto {\n case .tcp:\n forwarder = try TCPForwarder(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: self.log\n )\n case .udp:\n forwarder = try UDPForwarder(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: self.log\n )\n }\n return try await forwarder.run().get()\n }\n }\n for try await result in group {\n forwarders.append(result)\n }\n }\n\n self.socketForwarders = forwarders\n }\n\n private func stopSocketForwarders() async {\n log.info(\"closing forwarders\")\n for forwarder in self.socketForwarders {\n forwarder.close()\n try? await forwarder.wait()\n }\n log.info(\"closed forwarders\")\n }\n\n /// Create a process inside the virtual machine for the container.\n ///\n /// Use this procedure to run ad hoc processes in the virtual\n /// machine (`container exec`).\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: A client identifier for the process.\n /// - processConfig: JSON serialization of the `ProcessConfiguration`\n /// containing the process attributes.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func createProcess(_ message: XPCMessage) async throws -> XPCMessage {\n log.info(\"`createProcess` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped(_), .starting, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot exec: container is not running\"\n )\n case .running, .booted:\n let id = try message.id()\n let config = try message.processConfig()\n await self.addNewProcess(id, config)\n try await self.monitor.registerProcess(\n id: id,\n onExit: { id, code in\n guard let process = await self.processes[id]?.process else {\n throw ContainerizationError(.invalidState, message: \"ProcessInfo missing for process \\(id)\")\n }\n for cc in await self.waiters[id] ?? [] {\n cc.resume(returning: code)\n }\n await self.removeWaiters(for: id)\n try await process.delete()\n try await self.setProcessState(id: id, state: .stopped(code))\n })\n return message.reply()\n }\n }\n }\n\n /// Return the state for the sandbox and its containers.\n ///\n /// - Parameters:\n /// - message: An XPC message with no parameters.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - snapshot: The JSON serialization of the `SandboxSnapshot`\n /// that contains the state information.\n @Sendable\n public func state(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`state` xpc handler\")\n var status: RuntimeStatus = .unknown\n var networks: [Attachment] = []\n var cs: ContainerSnapshot?\n\n switch state {\n case .created, .stopped(_), .starting, .booted:\n status = .stopped\n case .stopping:\n status = .stopping\n case .running:\n let ctr = try getContainer()\n\n status = .running\n networks = ctr.attachments\n cs = ContainerSnapshot(\n configuration: ctr.config,\n status: RuntimeStatus.running,\n networks: networks\n )\n }\n\n let reply = message.reply()\n try reply.setState(\n .init(\n status: status,\n networks: networks,\n containers: cs != nil ? [cs!] : []\n )\n )\n return reply\n }\n\n /// Stop the container workload, any ad hoc processes, and the underlying\n /// virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - stopOptions: JSON serialization of `ContainerStopOptions`\n /// that modify stop behavior.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func stop(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`stop` xpc handler\")\n let reply = try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .stopped(_), .created, .stopping:\n return message.reply()\n case .starting:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot stop: container is not running\"\n )\n case .running, .booted:\n let ctr = try await getContainer()\n let stopOptions = try message.stopOptions()\n do {\n try await gracefulStopContainer(\n ctr.container,\n stopOpts: stopOptions\n )\n } catch {\n log.notice(\"failed to stop sandbox gracefully: \\(error)\")\n }\n await setState(.stopping)\n return message.reply()\n }\n }\n do {\n try await cleanupContainer()\n } catch {\n self.log.error(\"failed to cleanup container: \\(error)\")\n }\n return reply\n }\n\n /// Signal a process running in the virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n /// - signal: The signal value.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func kill(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`kill` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped, .starting, .booted, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot kill: container is not running\"\n )\n case .running:\n let ctr = try await getContainer()\n let id = try message.id()\n if id != ctr.container.id {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) does not exist\")\n }\n\n guard let proc = processInfo.process else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not started\")\n }\n try await proc.kill(Int32(try message.signal()))\n return message.reply()\n }\n\n // TODO: fix underlying signal value to int64\n try await ctr.container.kill(Int32(try message.signal()))\n return message.reply()\n }\n }\n }\n\n /// Resize the terminal for a process.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n /// - width: The terminal width.\n /// - height: The terminal height.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func resize(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`resize` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped, .starting, .booted, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot resize: container is not running\"\n )\n case .running:\n let id = try message.id()\n let ctr = try await getContainer()\n let width = message.uint64(key: .width)\n let height = message.uint64(key: .height)\n if id != ctr.container.id {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) does not exist\")\n }\n\n guard let proc = processInfo.process else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not started\")\n }\n\n try await proc.resize(to: .init(width: UInt16(width), height: UInt16(height)))\n return message.reply()\n }\n\n try await ctr.container.resize(to: .init(width: UInt16(width), height: UInt16(height)))\n return message.reply()\n }\n }\n }\n\n /// Wait for a process.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - exitCode: The exit code for the process.\n @Sendable\n public func wait(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`wait` xpc handler\")\n guard let id = message.string(key: .id) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing id in wait xpc message\")\n }\n\n let cachedCode: Int32? = try await self.lock.withLock { _ in\n let ctrInfo = try await self.getContainer()\n let ctr = ctrInfo.container\n if id == ctr.id {\n switch await self.state {\n case .stopped(let code):\n return code\n default:\n break\n }\n } else {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.notFound, message: \"Process with id \\(id)\")\n }\n switch processInfo.state {\n case .stopped(let code):\n return code\n default:\n break\n }\n }\n return nil\n }\n if let cachedCode {\n let reply = message.reply()\n reply.set(key: .exitCode, value: Int64(cachedCode))\n return reply\n }\n\n let exitCode = await withCheckedContinuation { cc in\n // Is this safe since we are in an actor? :(\n self.addWaiter(id: id, cont: cc)\n }\n let reply = message.reply()\n reply.set(key: .exitCode, value: Int64(exitCode))\n return reply\n }\n\n /// Dial a vsock port on the virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - port: The port number.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - fd: The file descriptor for the vsock.\n @Sendable\n public func dial(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`dial` xpc handler\")\n switch self.state {\n case .starting, .created, .stopped, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot dial: container is not running\"\n )\n case .running, .booted:\n let port = message.uint64(key: .port)\n guard port > 0 else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"no vsock port supplied for dial\"\n )\n }\n\n let ctr = try getContainer()\n let fh = try await ctr.container.dialVsock(port: UInt32(port))\n\n let reply = message.reply()\n reply.set(key: .fd, value: fh)\n return reply\n }\n }\n\n private func onContainerExit(id: String, code: Int32) async throws {\n self.log.info(\"init process exited with: \\(code)\")\n\n try await self.lock.withLock { [self] _ in\n let ctrInfo = try await getContainer()\n let ctr = ctrInfo.container\n // Did someone explicitly call stop and we're already\n // cleaning up?\n switch await self.state {\n case .stopped(_):\n return\n default:\n break\n }\n\n do {\n try await ctr.stop()\n } catch {\n log.notice(\"failed to stop sandbox gracefully: \\(error)\")\n }\n\n do {\n try await cleanupContainer()\n } catch {\n self.log.error(\"failed to cleanup container: \\(error)\")\n }\n await setState(.stopped(code))\n let waiters = await self.waiters[id] ?? []\n for cc in waiters {\n cc.resume(returning: code)\n }\n await self.removeWaiters(for: id)\n try await self.sendContainerEvent(.containerExit(id: id, exitCode: Int64(code)))\n exit(code)\n }\n }\n\n private func configureContainer(container: LinuxContainer, config: ContainerConfiguration) throws {\n container.cpus = config.resources.cpus\n container.memoryInBytes = config.resources.memoryInBytes\n container.rosetta = config.rosetta\n container.sysctl = config.sysctls.reduce(into: [String: String]()) {\n $0[$1.key] = $1.value\n }\n\n for mount in config.mounts {\n if try mount.isSocket() {\n let socket = UnixSocketConfiguration(\n source: URL(filePath: mount.source),\n destination: URL(filePath: mount.destination)\n )\n container.sockets.append(socket)\n } else {\n container.mounts.append(mount.asMount)\n }\n }\n\n for publishedSocket in config.publishedSockets {\n let socketConfig = UnixSocketConfiguration(\n source: publishedSocket.containerPath,\n destination: publishedSocket.hostPath,\n permissions: publishedSocket.permissions,\n direction: .outOf\n )\n container.sockets.append(socketConfig)\n }\n\n container.hostname = config.hostname ?? config.id\n\n if let dns = config.dns {\n container.dns = DNS(\n nameservers: dns.nameservers, domain: dns.domain,\n searchDomains: dns.searchDomains, options: dns.options)\n }\n\n configureInitialProcess(container: container, process: config.initProcess)\n }\n\n private func getDefaultNameserver(networks: [String]) async throws -> String? {\n for network in networks {\n let client = NetworkClient(id: network)\n let state = try await client.state()\n guard case .running(_, let status) = state else {\n continue\n }\n return status.gateway\n }\n\n return nil\n }\n\n private func configureInitialProcess(container: LinuxContainer, process: ProcessConfiguration) {\n container.arguments = [process.executable] + process.arguments\n container.environment = modifyingEnvironment(process)\n container.terminal = process.terminal\n container.workingDirectory = process.workingDirectory\n container.rlimits = process.rlimits.map {\n .init(type: $0.limit, hard: $0.hard, soft: $0.soft)\n }\n switch process.user {\n case .raw(let name):\n container.user = .init(\n uid: 0,\n gid: 0,\n umask: nil,\n additionalGids: process.supplementalGroups,\n username: name\n )\n case .id(let uid, let gid):\n container.user = .init(\n uid: uid,\n gid: gid,\n umask: nil,\n additionalGids: process.supplementalGroups,\n username: \"\"\n )\n }\n }\n\n private nonisolated func configureProcessConfig(config: ProcessConfiguration) -> ContainerizationOCI.Process {\n var proc = ContainerizationOCI.Process()\n proc.args = [config.executable] + config.arguments\n proc.env = modifyingEnvironment(config)\n proc.terminal = config.terminal\n proc.cwd = config.workingDirectory\n proc.rlimits = config.rlimits.map {\n .init(type: $0.limit, hard: $0.hard, soft: $0.soft)\n }\n switch config.user {\n case .raw(let name):\n proc.user = .init(\n uid: 0,\n gid: 0,\n umask: nil,\n additionalGids: config.supplementalGroups,\n username: name\n )\n case .id(let uid, let gid):\n proc.user = .init(\n uid: uid,\n gid: gid,\n umask: nil,\n additionalGids: config.supplementalGroups,\n username: \"\"\n )\n }\n\n return proc\n }\n\n private nonisolated func closeHandle(_ handle: Int32) throws {\n guard close(handle) == 0 else {\n guard let errCode = POSIXErrorCode(rawValue: errno) else {\n fatalError(\"failed to convert errno to POSIXErrorCode\")\n }\n throw POSIXError(errCode)\n }\n }\n\n private nonisolated func modifyingEnvironment(_ config: ProcessConfiguration) -> [String] {\n guard config.terminal else {\n return config.environment\n }\n // Prepend the TERM env var. If the user has it specified our value will be overridden.\n return [\"TERM=xterm\"] + config.environment\n }\n\n private func getContainer() throws -> ContainerInfo {\n guard let container else {\n throw ContainerizationError(\n .invalidState,\n message: \"no container found\"\n )\n }\n return container\n }\n\n private func gracefulStopContainer(_ lc: LinuxContainer, stopOpts: ContainerStopOptions) async throws {\n // Try and gracefully shut down the process. Even if this succeeds we need to power off\n // the vm, but we should try this first always.\n do {\n try await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n try await lc.wait()\n }\n group.addTask {\n try await lc.kill(stopOpts.signal)\n try await Task.sleep(for: .seconds(stopOpts.timeoutInSeconds))\n try await lc.kill(SIGKILL)\n }\n try await group.next()\n group.cancelAll()\n }\n } catch {}\n // Now actually bring down the vm.\n try await lc.stop()\n }\n\n private func cleanupContainer() async throws {\n // Give back our lovely IP(s)\n await self.stopSocketForwarders()\n let containerInfo = try self.getContainer()\n for attachment in containerInfo.attachments {\n let client = NetworkClient(id: attachment.network)\n do {\n try await client.deallocate(hostname: attachment.hostname)\n } catch {\n self.log.error(\"failed to deallocate hostname \\(attachment.hostname) on network \\(attachment.network): \\(error)\")\n }\n }\n }\n\n private func sendContainerEvent(_ event: ContainerEvent) async throws {\n let serviceIdentifier = \"com.apple.container.apiserver\"\n let client = XPCClient(service: serviceIdentifier)\n let message = XPCMessage(route: .containerEvent)\n\n let data = try JSONEncoder().encode(event)\n message.set(key: .containerEvent, value: data)\n try await client.send(message)\n }\n\n}\n\nextension XPCMessage {\n fileprivate func signal() throws -> Int64 {\n self.int64(key: .signal)\n }\n\n fileprivate func stopOptions() throws -> ContainerStopOptions {\n guard let data = self.dataNoCopy(key: .stopOptions) else {\n throw ContainerizationError(.invalidArgument, message: \"empty StopOptions\")\n }\n return try JSONDecoder().decode(ContainerStopOptions.self, from: data)\n }\n\n fileprivate func setState(_ state: SandboxSnapshot) throws {\n let data = try JSONEncoder().encode(state)\n self.set(key: .snapshot, value: data)\n }\n\n fileprivate func stdio() -> [FileHandle?] {\n var handles = [FileHandle?](repeating: nil, count: 3)\n if let stdin = self.fileHandle(key: .stdin) {\n handles[0] = stdin\n }\n if let stdout = self.fileHandle(key: .stdout) {\n handles[1] = stdout\n }\n if let stderr = self.fileHandle(key: .stderr) {\n handles[2] = stderr\n }\n return handles\n }\n\n fileprivate func setFileHandle(_ handle: FileHandle) {\n self.set(key: .fd, value: handle)\n }\n\n fileprivate func processConfig() throws -> ProcessConfiguration {\n guard let data = self.dataNoCopy(key: .processConfig) else {\n throw ContainerizationError(.invalidArgument, message: \"empty process configuration\")\n }\n return try JSONDecoder().decode(ProcessConfiguration.self, from: data)\n }\n}\n\nextension ContainerClient.Bundle {\n /// The pathname for the workload log file.\n public var containerLog: URL {\n path.appendingPathComponent(\"stdio.log\")\n }\n\n func createLogFile() throws {\n // Create the log file we'll write stdio to.\n // O_TRUNC resolves a log delay issue on restarted containers by force-updating internal state\n let fd = Darwin.open(self.containerLog.path, O_CREAT | O_RDONLY | O_TRUNC, 0o644)\n guard fd > 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n close(fd)\n }\n}\n\nextension Filesystem {\n var asMount: Containerization.Mount {\n switch self.type {\n case .tmpfs:\n return .any(\n type: \"tmpfs\",\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n case .virtiofs:\n return .share(\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n case .block(let format, _, _):\n return .block(\n format: format,\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n }\n }\n\n func isSocket() throws -> Bool {\n if !self.isVirtiofs {\n return false\n }\n let info = try File.info(self.source)\n return info.isSocket\n }\n}\n\nstruct MultiWriter: Writer {\n let handles: [FileHandle]\n\n func write(_ data: Data) throws {\n for handle in self.handles {\n try handle.write(contentsOf: data)\n }\n }\n}\n\nextension FileHandle: @retroactive ReaderStream, @retroactive Writer {\n public func write(_ data: Data) throws {\n try self.write(contentsOf: data)\n }\n\n public func stream() -> AsyncStream {\n .init { cont in\n self.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n self.readabilityHandler = nil\n cont.finish()\n return\n }\n cont.yield(data)\n }\n }\n }\n}\n\n// MARK: State handler helpers\n\nextension SandboxService {\n private func addWaiter(id: String, cont: CheckedContinuation) {\n var current = self.waiters[id] ?? []\n current.append(cont)\n self.waiters[id] = current\n }\n\n private func removeWaiters(for id: String) {\n self.waiters[id] = []\n }\n\n private func setUnderlyingProcess(_ id: String, _ process: LinuxProcess) throws {\n guard var info = self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not found\")\n }\n info.process = process\n self.processes[id] = info\n }\n\n private func setProcessState(id: String, state: State) throws {\n guard var info = self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not found\")\n }\n info.state = state\n self.processes[id] = info\n }\n\n private func setContainer(_ info: ContainerInfo) {\n self.container = info\n }\n\n private func addNewProcess(_ id: String, _ config: ProcessConfiguration) {\n self.processes[id] = ProcessInfo(config: config, process: nil, state: .created)\n }\n\n private struct ProcessInfo {\n let config: ProcessConfiguration\n var process: LinuxProcess?\n var state: State\n }\n\n private struct ContainerInfo {\n let container: LinuxContainer\n let config: ContainerConfiguration\n let attachments: [Attachment]\n let bundle: ContainerClient.Bundle\n }\n\n public enum State: Sendable, Equatable {\n case created\n case booted\n case starting\n case running\n case stopping\n case stopped(Int32)\n }\n\n func setState(_ new: State) {\n self.state = new\n }\n}\n"], ["/container/Sources/APIServer/APIServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerPlugin\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport DNSServer\nimport Foundation\nimport Logging\n\n@main\nstruct APIServer: AsyncParsableCommand {\n static let listenAddress = \"127.0.0.1\"\n static let dnsPort = 2053\n\n static let configuration = CommandConfiguration(\n commandName: \"container-apiserver\",\n abstract: \"Container management API server\",\n version: releaseVersion()\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .shortAndLong, help: \"Daemon root directory\")\n var root = Self.appRoot.path\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n func run() async throws {\n let commandName = Self.configuration.commandName ?? \"container-apiserver\"\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n do {\n log.info(\"configuring XPC server\")\n let root = URL(filePath: root)\n var routes = [XPCRoute: XPCServer.RouteHandler]()\n let pluginLoader = try initializePluginLoader(log: log)\n try await initializePlugins(pluginLoader: pluginLoader, log: log, routes: &routes)\n try initializeContainerService(root: root, pluginLoader: pluginLoader, log: log, routes: &routes)\n let networkService = try await initializeNetworkService(\n root: root,\n pluginLoader: pluginLoader,\n log: log,\n routes: &routes\n )\n initializeHealthCheckService(log: log, routes: &routes)\n try initializeKernelService(log: log, routes: &routes)\n\n let server = XPCServer(\n identifier: \"com.apple.container.apiserver\",\n routes: routes.reduce(\n into: [String: XPCServer.RouteHandler](),\n {\n $0[$1.key.rawValue] = $1.value\n }), log: log)\n\n await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n log.info(\"starting XPC server\")\n try await server.listen()\n }\n // start up host table DNS\n group.addTask {\n let hostsResolver = ContainerDNSHandler(networkService: networkService)\n let nxDomainResolver = NxDomainResolver()\n let compositeResolver = CompositeResolver(handlers: [hostsResolver, nxDomainResolver])\n let hostsQueryValidator = StandardQueryValidator(handler: compositeResolver)\n let dnsServer: DNSServer = DNSServer(handler: hostsQueryValidator, log: log)\n log.info(\n \"starting DNS host query resolver\",\n metadata: [\n \"host\": \"\\(Self.listenAddress)\",\n \"port\": \"\\(Self.dnsPort)\",\n ]\n )\n try await dnsServer.run(host: Self.listenAddress, port: Self.dnsPort)\n }\n }\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n APIServer.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"APIServer\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n return log\n }\n\n private func initializePluginLoader(log: Logger) throws -> PluginLoader {\n let installRoot = CommandLine.executablePathUrl\n .deletingLastPathComponent()\n .appendingPathComponent(\"..\")\n .standardized\n let pluginsURL = PluginLoader.userPluginsDir(root: installRoot)\n var directoryExists: ObjCBool = false\n _ = FileManager.default.fileExists(atPath: pluginsURL.path, isDirectory: &directoryExists)\n let userPluginsURL = directoryExists.boolValue ? pluginsURL : nil\n\n // plugins built into the application installed as a macOS app bundle\n let appBundlePluginsURL = Bundle.main.resourceURL?.appending(path: \"plugins\")\n\n // plugins built into the application installed as a Unix-like application\n let installRootPluginsURL =\n installRoot\n .appendingPathComponent(\"libexec\")\n .appendingPathComponent(\"container\")\n .appendingPathComponent(\"plugins\")\n .standardized\n\n let pluginDirectories = [\n userPluginsURL,\n appBundlePluginsURL,\n installRootPluginsURL,\n ].compactMap { $0 }\n\n let pluginFactories: [PluginFactory] = [\n DefaultPluginFactory(),\n AppBundlePluginFactory(),\n ]\n\n log.info(\"PLUGINS: \\(pluginDirectories)\")\n let statePath = PluginLoader.defaultPluginResourcePath(root: Self.appRoot)\n try FileManager.default.createDirectory(at: statePath, withIntermediateDirectories: true)\n return PluginLoader(pluginDirectories: pluginDirectories, pluginFactories: pluginFactories, defaultResourcePath: statePath, log: log)\n }\n\n // First load all of the plugins we can find. Then just expose\n // the handlers for clients to do whatever they want.\n private func initializePlugins(\n pluginLoader: PluginLoader,\n log: Logger,\n routes: inout [XPCRoute: XPCServer.RouteHandler]\n ) async throws {\n let bootPlugins = pluginLoader.findPlugins().filter { $0.shouldBoot }\n\n let service = PluginsService(pluginLoader: pluginLoader, log: log)\n try await service.loadAll(bootPlugins)\n\n let harness = PluginsHarness(service: service, log: log)\n routes[XPCRoute.pluginGet] = harness.get\n routes[XPCRoute.pluginList] = harness.list\n routes[XPCRoute.pluginLoad] = harness.load\n routes[XPCRoute.pluginUnload] = harness.unload\n routes[XPCRoute.pluginRestart] = harness.restart\n }\n\n private func initializeHealthCheckService(log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) {\n let svc = HealthCheckHarness(log: log)\n routes[XPCRoute.ping] = svc.ping\n }\n\n private func initializeKernelService(log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) throws {\n let svc = try KernelService(log: log, appRoot: Self.appRoot)\n let harness = KernelHarness(service: svc, log: log)\n routes[XPCRoute.installKernel] = harness.install\n routes[XPCRoute.getDefaultKernel] = harness.getDefaultKernel\n }\n\n private func initializeContainerService(root: URL, pluginLoader: PluginLoader, log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) throws {\n let service = try ContainersService(\n root: root,\n pluginLoader: pluginLoader,\n log: log\n )\n let harness = ContainersHarness(service: service, log: log)\n\n routes[XPCRoute.listContainer] = harness.list\n routes[XPCRoute.createContainer] = harness.create\n routes[XPCRoute.deleteContainer] = harness.delete\n routes[XPCRoute.containerLogs] = harness.logs\n routes[XPCRoute.containerEvent] = harness.eventHandler\n }\n\n private func initializeNetworkService(\n root: URL,\n pluginLoader: PluginLoader,\n log: Logger,\n routes: inout [XPCRoute: XPCServer.RouteHandler]\n ) async throws -> NetworksService {\n let resourceRoot = root.appendingPathComponent(\"networks\")\n let service = try await NetworksService(\n pluginLoader: pluginLoader,\n resourceRoot: resourceRoot,\n log: log\n )\n\n let defaultNetwork = try await service.list()\n .filter { $0.id == ClientNetwork.defaultNetworkName }\n .first\n if defaultNetwork == nil {\n let config = NetworkConfiguration(id: ClientNetwork.defaultNetworkName, mode: .nat)\n _ = try await service.create(configuration: config)\n }\n\n let harness = NetworksHarness(service: service, log: log)\n\n routes[XPCRoute.networkCreate] = harness.create\n routes[XPCRoute.networkDelete] = harness.delete\n routes[XPCRoute.networkList] = harness.list\n return service\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/APIServer/Containers/ContainersService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CVersion\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerSandboxService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ContainersService {\n private static let machServicePrefix = \"com.apple.container\"\n private static let launchdDomainString = try! ServiceManager.getDomainString()\n\n private let log: Logger\n private let containerRoot: URL\n private let pluginLoader: PluginLoader\n private let runtimePlugins: [Plugin]\n\n private let lock = AsyncLock()\n private var containers: [String: Item]\n\n struct Item: Sendable {\n let bundle: ContainerClient.Bundle\n var state: State\n\n enum State: Sendable {\n case dead\n case alive(SandboxClient)\n case exited(Int32)\n\n func isDead() -> Bool {\n switch self {\n case .dead: return true\n default: return false\n }\n }\n }\n }\n\n public init(root: URL, pluginLoader: PluginLoader, log: Logger) throws {\n let containerRoot = root.appendingPathComponent(\"containers\")\n try FileManager.default.createDirectory(at: containerRoot, withIntermediateDirectories: true)\n self.containerRoot = containerRoot\n self.pluginLoader = pluginLoader\n self.log = log\n self.runtimePlugins = pluginLoader.findPlugins().filter { $0.hasType(.runtime) }\n self.containers = try Self.loadAtBoot(root: containerRoot, loader: pluginLoader, log: log)\n }\n\n static func loadAtBoot(root: URL, loader: PluginLoader, log: Logger) throws -> [String: Item] {\n var directories = try FileManager.default.contentsOfDirectory(\n at: root,\n includingPropertiesForKeys: [.isDirectoryKey]\n )\n directories = directories.filter {\n $0.isDirectory\n }\n\n let runtimePlugins = loader.findPlugins().filter { $0.hasType(.runtime) }\n var results = [String: Item]()\n for dir in directories {\n do {\n let bundle = ContainerClient.Bundle(path: dir)\n let config = try bundle.configuration\n results[config.id] = .init(bundle: bundle, state: .dead)\n let plugin = runtimePlugins.first { $0.name == config.runtimeHandler }\n guard let plugin else {\n throw ContainerizationError(.internalError, message: \"Failed to find runtime plugin \\(config.runtimeHandler)\")\n }\n try Self.registerService(plugin: plugin, loader: loader, configuration: config, path: dir)\n } catch {\n try? FileManager.default.removeItem(at: dir)\n log.warning(\"failed to load container bundle at \\(dir.path)\")\n }\n }\n return results\n }\n\n private func setContainer(_ id: String, _ item: Item, context: AsyncLock.Context) async {\n self.containers[id] = item\n }\n\n /// List all containers registered with the service.\n public func list() async throws -> [ContainerSnapshot] {\n self.log.debug(\"\\(#function)\")\n return await lock.withLock { context in\n var snapshots = [ContainerSnapshot]()\n\n for (id, item) in await self.containers {\n do {\n let result = try await item.asSnapshot()\n snapshots.append(result.0)\n } catch {\n self.log.error(\"unable to load bundle for \\(id) \\(error)\")\n }\n }\n return snapshots\n }\n }\n\n /// Create a new container from the provided id and configuration.\n public func create(configuration: ContainerConfiguration, kernel: Kernel, options: ContainerCreateOptions) async throws {\n self.log.debug(\"\\(#function)\")\n\n let runtimePlugin = self.runtimePlugins.filter {\n $0.name == configuration.runtimeHandler\n }.first\n guard let runtimePlugin else {\n throw ContainerizationError(.notFound, message: \"unable to locate runtime plugin \\(configuration.runtimeHandler)\")\n }\n\n let path = self.containerRoot.appendingPathComponent(configuration.id)\n let systemPlatform = kernel.platform\n let initFs = try await getInitBlock(for: systemPlatform.ociPlatform())\n\n let bundle = try ContainerClient.Bundle.create(\n path: path,\n initialFilesystem: initFs,\n kernel: kernel,\n containerConfiguration: configuration\n )\n do {\n let containerImage = ClientImage(description: configuration.image)\n let imageFs = try await containerImage.getCreateSnapshot(platform: configuration.platform)\n try bundle.setContainerRootFs(cloning: imageFs)\n try bundle.write(filename: \"options.json\", value: options)\n\n try Self.registerService(\n plugin: runtimePlugin,\n loader: self.pluginLoader,\n configuration: configuration,\n path: path\n )\n } catch {\n do {\n try bundle.delete()\n } catch {\n self.log.error(\"failed to delete bundle for container \\(configuration.id): \\(error)\")\n }\n throw error\n }\n self.containers[configuration.id] = Item(bundle: bundle, state: .dead)\n }\n\n private func getInitBlock(for platform: Platform) async throws -> Filesystem {\n let initImage = try await ClientImage.fetch(reference: ClientImage.initImageRef, platform: platform)\n var fs = try await initImage.getCreateSnapshot(platform: platform)\n fs.options = [\"ro\"]\n return fs\n }\n\n private static func registerService(\n plugin: Plugin,\n loader: PluginLoader,\n configuration: ContainerConfiguration,\n path: URL\n ) throws {\n let args = [\n \"--root\", path.path,\n \"--uuid\", configuration.id,\n \"--debug\",\n ]\n try loader.registerWithLaunchd(\n plugin: plugin,\n rootURL: path,\n args: args,\n instanceId: configuration.id\n )\n }\n\n private func get(id: String, context: AsyncLock.Context) throws -> Item {\n try self._get(id: id)\n }\n\n private func _get(id: String) throws -> Item {\n let item = self.containers[id]\n guard let item else {\n throw ContainerizationError(\n .notFound,\n message: \"container with ID \\(id) not found\"\n )\n }\n return item\n }\n\n /// Delete a container and its resources.\n public func delete(id: String) async throws {\n self.log.debug(\"\\(#function)\")\n let item = try self._get(id: id)\n switch item.state {\n case .alive(let client):\n let state = try await client.state()\n if state.status == .running || state.status == .stopping {\n throw ContainerizationError(\n .invalidState,\n message: \"container \\(id) is not yet stopped and can not be deleted\"\n )\n }\n try self._cleanup(id: id, item: item)\n case .dead, .exited(_):\n try self._cleanup(id: id, item: item)\n }\n }\n\n private static func fullLaunchdServiceLabel(runtimeName: String, instanceId: String) -> String {\n \"\\(Self.launchdDomainString)/\\(Self.machServicePrefix).\\(runtimeName).\\(instanceId)\"\n }\n\n private func _cleanup(id: String, item: Item) throws {\n self.log.debug(\"\\(#function)\")\n let config = try item.bundle.configuration\n let label = Self.fullLaunchdServiceLabel(runtimeName: config.runtimeHandler, instanceId: id)\n try ServiceManager.deregister(fullServiceLabel: label)\n try item.bundle.delete()\n self.containers.removeValue(forKey: id)\n }\n\n private func _shutdown(id: String, item: Item) throws {\n let config = try item.bundle.configuration\n let label = Self.fullLaunchdServiceLabel(runtimeName: config.runtimeHandler, instanceId: id)\n try ServiceManager.kill(fullServiceLabel: label)\n }\n\n private func cleanup(id: String, item: Item, context: AsyncLock.Context) async throws {\n try self._cleanup(id: id, item: item)\n }\n\n private func containerProcessExitHandler(_ id: String, _ exitCode: Int32, context: AsyncLock.Context) async {\n self.log.info(\"Handling container \\(id) exit. Code \\(exitCode)\")\n do {\n var item = try self.get(id: id, context: context)\n switch item.state {\n case .dead, .exited(_):\n break\n case .alive(_):\n item.state = .exited(exitCode)\n await self.setContainer(id, item, context: context)\n }\n let options: ContainerCreateOptions = try item.bundle.load(filename: \"options.json\")\n if options.autoRemove {\n try await self.cleanup(id: id, item: item, context: context)\n }\n } catch {\n self.log.error(\n \"Failed to handle container exit\",\n metadata: [\n \"id\": .string(id),\n \"error\": .string(String(describing: error)),\n ])\n }\n }\n\n private func containerStartHandler(_ id: String, context: AsyncLock.Context) async throws {\n self.log.debug(\"\\(#function)\")\n self.log.info(\"Handling container \\(id) Start.\")\n do {\n var item = try self.get(id: id, context: context)\n let configuration = try item.bundle.configuration\n let client = SandboxClient(id: configuration.id, runtime: configuration.runtimeHandler)\n item.state = .alive(client)\n await self.setContainer(id, item, context: context)\n } catch {\n self.log.error(\n \"Failed to handle container start\",\n metadata: [\n \"id\": .string(id),\n \"error\": .string(String(describing: error)),\n ])\n }\n }\n}\n\nextension ContainersService {\n public func handleContainerEvents(event: ContainerEvent) async throws {\n self.log.debug(\"\\(#function)\")\n try await self.lock.withLock { context in\n switch event {\n case .containerExit(let id, let code):\n await self.containerProcessExitHandler(id, Int32(code), context: context)\n case .containerStart(let id):\n try await self.containerStartHandler(id, context: context)\n }\n }\n }\n\n /// Stop all containers inside the sandbox, aborting any processes currently\n /// executing inside the container, before stopping the underlying sandbox.\n public func stop(id: String, options: ContainerStopOptions) async throws {\n self.log.debug(\"\\(#function)\")\n try await lock.withLock { context in\n let item = try await self.get(id: id, context: context)\n switch item.state {\n case .dead, .exited(_):\n return\n case .alive(let client):\n try await client.stop(options: options)\n }\n }\n }\n\n public func logs(id: String) async throws -> [FileHandle] {\n self.log.debug(\"\\(#function)\")\n // Logs doesn't care if the container is running or not, just that\n // the bundle is there, and that the files actually exist.\n do {\n let item = try self._get(id: id)\n return [\n try FileHandle(forReadingFrom: item.bundle.containerLog),\n try FileHandle(forReadingFrom: item.bundle.bootlog),\n ]\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to open container logs: \\(error)\"\n )\n }\n }\n}\n\nextension ContainersService.Item {\n func asSnapshot() async throws -> (ContainerSnapshot, RuntimeStatus) {\n let config = try self.bundle.configuration\n\n switch self.state {\n case .dead, .exited(_):\n return (\n .init(\n configuration: config,\n status: RuntimeStatus.stopped,\n networks: []\n ), .stopped\n )\n case .alive(let client):\n let state = try await client.state()\n return (\n .init(\n configuration: config,\n status: state.status,\n networks: state.networks\n ), state.status\n )\n }\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerBuild\nimport ContainerClient\nimport ContainerNetworkService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct BuilderStart: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"start\"\n config._superCommandName = \"builder\"\n config.abstract = \"Start builder\"\n config.usage = \"\\nbuilder start [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64 = 2\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n public var memory: String = \"2048MB\"\n\n func run() async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n totalTasks: 4\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n try await Self.start(cpus: self.cpus, memory: self.memory, progressUpdate: progress.handler)\n progress.finish()\n }\n\n static func start(cpus: Int64?, memory: String?, progressUpdate: @escaping ProgressUpdateHandler) async throws {\n await progressUpdate([\n .setDescription(\"Fetching BuildKit image\"),\n .setItemsName(\"blobs\"),\n ])\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n\n let builderImage: String = ClientDefaults.get(key: .defaultBuilderImage)\n let exportsMount: String = Application.appRoot.appendingPathComponent(\".build\").absolutePath()\n\n if !FileManager.default.fileExists(atPath: exportsMount) {\n try FileManager.default.createDirectory(\n atPath: exportsMount,\n withIntermediateDirectories: true,\n attributes: nil\n )\n }\n\n let builderPlatform = ContainerizationOCI.Platform(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n\n let existingContainer = try? await ClientContainer.get(id: \"buildkit\")\n if let existingContainer {\n let existingImage = existingContainer.configuration.image.reference\n let existingResources = existingContainer.configuration.resources\n\n // Check if we need to recreate the builder due to different image\n let imageChanged = existingImage != builderImage\n let cpuChanged = {\n if let cpus {\n if existingResources.cpus != cpus {\n return true\n }\n }\n return false\n }()\n let memChanged = try {\n if let memory {\n let memoryInBytes = try Parser.resources(cpus: nil, memory: memory).memoryInBytes\n if existingResources.memoryInBytes != memoryInBytes {\n return true\n }\n }\n return false\n }()\n\n switch existingContainer.status {\n case .running:\n guard imageChanged || cpuChanged || memChanged else {\n // If image, mem and cpu are the same, continue using the existing builder\n return\n }\n // If they changed, stop and delete the existing builder\n try await existingContainer.stop()\n try await existingContainer.delete()\n case .stopped:\n // If the builder is stopped and matches our requirements, start it\n // Otherwise, delete it and create a new one\n guard imageChanged || cpuChanged || memChanged else {\n try await existingContainer.startBuildKit(progressUpdate, nil)\n return\n }\n try await existingContainer.delete()\n case .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"builder is stopping, please wait until it is fully stopped before proceeding\"\n )\n case .unknown:\n break\n }\n }\n\n let shimArguments: [String] = [\n \"--debug\",\n \"--vsock\",\n ]\n\n let id = \"buildkit\"\n try ContainerClient.Utility.validEntityName(id)\n\n let processConfig = ProcessConfiguration(\n executable: \"/usr/local/bin/container-builder-shim\",\n arguments: shimArguments,\n environment: [],\n workingDirectory: \"/\",\n terminal: false,\n user: .id(uid: 0, gid: 0)\n )\n\n let resources = try Parser.resources(\n cpus: cpus,\n memory: memory\n )\n\n let image = try await ClientImage.fetch(\n reference: builderImage,\n platform: builderPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progressUpdate)\n )\n // Unpack fetched image before use\n await progressUpdate([\n .setDescription(\"Unpacking BuildKit image\"),\n .setItemsName(\"entries\"),\n ])\n\n let unpackTask = await taskManager.startTask()\n _ = try await image.getCreateSnapshot(\n platform: builderPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progressUpdate)\n )\n let imageConfig = ImageDescription(\n reference: builderImage,\n descriptor: image.descriptor\n )\n\n var config = ContainerConfiguration(id: id, image: imageConfig, process: processConfig)\n config.resources = resources\n config.mounts = [\n .init(\n type: .tmpfs,\n source: \"\",\n destination: \"/run\",\n options: []\n ),\n .init(\n type: .virtiofs,\n source: exportsMount,\n destination: \"/var/lib/container-builder-shim/exports\",\n options: []\n ),\n ]\n // Enable Rosetta only if the user didn't ask to disable it\n config.rosetta = ClientDefaults.getBool(key: .buildRosetta) ?? true\n\n let network = try await ClientNetwork.get(id: ClientNetwork.defaultNetworkName)\n guard case .running(_, let networkStatus) = network else {\n throw ContainerizationError(.invalidState, message: \"default network is not running\")\n }\n config.networks = [network.id]\n let subnet = try CIDRAddress(networkStatus.address)\n let nameserver = IPv4Address(fromValue: subnet.lower.value + 1).description\n let nameservers = [nameserver]\n config.dns = ContainerConfiguration.DNSConfiguration(nameservers: nameservers)\n\n let kernel = try await {\n await progressUpdate([\n .setDescription(\"Fetching kernel\"),\n .setItemsName(\"binary\"),\n ])\n\n let kernel = try await ClientKernel.getDefaultKernel(for: .current)\n return kernel\n }()\n\n await progressUpdate([\n .setDescription(\"Starting BuildKit container\")\n ])\n\n let container = try await ClientContainer.create(\n configuration: config,\n options: .default,\n kernel: kernel\n )\n\n try await container.startBuildKit(progressUpdate, taskManager)\n }\n }\n}\n\n// MARK: - ClientContainer Extension for BuildKit\n\nextension ClientContainer {\n /// Starts the BuildKit process within the container\n /// This method handles bootstrapping the container and starting the BuildKit process\n fileprivate func startBuildKit(_ progress: @escaping ProgressUpdateHandler, _ taskManager: ProgressTaskCoordinator? = nil) async throws {\n do {\n let io = try ProcessIO.create(\n tty: false,\n interactive: false,\n detach: true\n )\n defer { try? io.close() }\n let process = try await bootstrap()\n _ = try await process.start(io.stdio)\n await taskManager?.finish()\n try io.closeAfterStart()\n log.debug(\"starting BuildKit and BuildKit-shim\")\n } catch {\n try? await stop()\n try? await delete()\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to start BuildKit: \\(error)\")\n }\n }\n}\n"], ["/container/Sources/CLI/Application.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerPlugin\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport TerminalProgress\n\n// `log` is updated only once in the `validate()` method.\nnonisolated(unsafe) var log = {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"CLI\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n log.logLevel = .debug\n return log\n}()\n\n@main\nstruct Application: AsyncParsableCommand {\n @OptionGroup\n var global: Flags.Global\n\n static let configuration = CommandConfiguration(\n commandName: \"container\",\n abstract: \"A container platform for macOS\",\n version: releaseVersion(),\n subcommands: [\n DefaultCommand.self\n ],\n groupedSubcommands: [\n CommandGroup(\n name: \"Container\",\n subcommands: [\n ContainerCreate.self,\n ContainerDelete.self,\n ContainerExec.self,\n ContainerInspect.self,\n ContainerKill.self,\n ContainerList.self,\n ContainerLogs.self,\n ContainerRunCommand.self,\n ContainerStart.self,\n ContainerStop.self,\n ]\n ),\n CommandGroup(\n name: \"Image\",\n subcommands: [\n BuildCommand.self,\n ImagesCommand.self,\n RegistryCommand.self,\n ]\n ),\n CommandGroup(\n name: \"Other\",\n subcommands: Self.otherCommands()\n ),\n ],\n // Hidden command to handle plugins on unrecognized input.\n defaultSubcommand: DefaultCommand.self\n )\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n static let pluginLoader: PluginLoader = {\n let installRoot = CommandLine.executablePathUrl\n .deletingLastPathComponent()\n .appendingPathComponent(\"..\")\n .standardized\n let pluginsURL = PluginLoader.userPluginsDir(root: installRoot)\n var directoryExists: ObjCBool = false\n _ = FileManager.default.fileExists(atPath: pluginsURL.path, isDirectory: &directoryExists)\n let userPluginsURL = directoryExists.boolValue ? pluginsURL : nil\n\n // plugins built into the application installed as a macOS app bundle\n let appBundlePluginsURL = Bundle.main.resourceURL?.appending(path: \"plugins\")\n\n // plugins built into the application installed as a Unix-like application\n let installRootPluginsURL =\n installRoot\n .appendingPathComponent(\"libexec\")\n .appendingPathComponent(\"container\")\n .appendingPathComponent(\"plugins\")\n .standardized\n\n let pluginDirectories = [\n userPluginsURL,\n appBundlePluginsURL,\n installRootPluginsURL,\n ].compactMap { $0 }\n\n let pluginFactories = [\n DefaultPluginFactory()\n ]\n\n let statePath = PluginLoader.defaultPluginResourcePath(root: Self.appRoot)\n try! FileManager.default.createDirectory(at: statePath, withIntermediateDirectories: true)\n return PluginLoader(pluginDirectories: pluginDirectories, pluginFactories: pluginFactories, defaultResourcePath: statePath, log: log)\n }()\n\n public static func main() async throws {\n restoreCursorAtExit()\n\n #if DEBUG\n let warning = \"Running debug build. Performance may be degraded.\"\n let formattedWarning = \"\\u{001B}[33mWarning!\\u{001B}[0m \\(warning)\\n\"\n let warningData = Data(formattedWarning.utf8)\n FileHandle.standardError.write(warningData)\n #endif\n\n let fullArgs = CommandLine.arguments\n let args = Array(fullArgs.dropFirst())\n\n do {\n // container -> defaultHelpCommand\n var command = try Application.parseAsRoot(args)\n if var asyncCommand = command as? AsyncParsableCommand {\n try await asyncCommand.run()\n } else {\n try command.run()\n }\n } catch {\n // Regular ol `command` with no args will get caught by DefaultCommand. --help\n // on the root command will land here.\n let containsHelp = fullArgs.contains(\"-h\") || fullArgs.contains(\"--help\")\n if fullArgs.count <= 2 && containsHelp {\n Self.printModifiedHelpText()\n return\n }\n let errorAsString: String = String(describing: error)\n if errorAsString.contains(\"XPC connection error\") {\n let modifiedError = ContainerizationError(.interrupted, message: \"\\(error)\\nEnsure container system service has been started with `container system start`.\")\n Application.exit(withError: modifiedError)\n } else {\n Application.exit(withError: error)\n }\n }\n }\n\n static func handleProcess(io: ProcessIO, process: ClientProcess) async throws -> Int32 {\n let signals = AsyncSignalHandler.create(notify: Application.signalSet)\n return try await withThrowingTaskGroup(of: Int32?.self, returning: Int32.self) { group in\n let waitAdded = group.addTaskUnlessCancelled {\n let code = try await process.wait()\n try await io.wait()\n return code\n }\n\n guard waitAdded else {\n group.cancelAll()\n return -1\n }\n\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n\n if let current = io.console {\n let size = try current.size\n // It's supremely possible the process could've exited already. We shouldn't treat\n // this as fatal.\n try? await process.resize(size)\n _ = group.addTaskUnlessCancelled {\n let winchHandler = AsyncSignalHandler.create(notify: [SIGWINCH])\n for await _ in winchHandler.signals {\n do {\n try await process.resize(try current.size)\n } catch {\n log.error(\n \"failed to send terminal resize event\",\n metadata: [\n \"error\": \"\\(error)\"\n ]\n )\n }\n }\n return nil\n }\n } else {\n _ = group.addTaskUnlessCancelled {\n for await sig in signals.signals {\n do {\n try await process.kill(sig)\n } catch {\n log.error(\n \"failed to send signal\",\n metadata: [\n \"signal\": \"\\(sig)\",\n \"error\": \"\\(error)\",\n ]\n )\n }\n }\n return nil\n }\n }\n\n while true {\n let result = try await group.next()\n if result == nil {\n return -1\n }\n let status = result!\n if let status {\n group.cancelAll()\n return status\n }\n }\n return -1\n }\n }\n\n func validate() throws {\n // Not really a \"validation\", but a cheat to run this before\n // any of the commands do their business.\n let debugEnvVar = ProcessInfo.processInfo.environment[\"CONTAINER_DEBUG\"]\n if self.global.debug || debugEnvVar != nil {\n log.logLevel = .debug\n }\n // Ensure we're not running under Rosetta.\n if try isTranslated() {\n throw ValidationError(\n \"\"\"\n `container` is currently running under Rosetta Translation, which could be\n caused by your terminal application. Please ensure this is turned off.\n \"\"\"\n )\n }\n }\n\n private static func otherCommands() -> [any ParsableCommand.Type] {\n guard #available(macOS 26, *) else {\n return [\n BuilderCommand.self,\n SystemCommand.self,\n ]\n }\n\n return [\n BuilderCommand.self,\n NetworkCommand.self,\n SystemCommand.self,\n ]\n }\n\n private static func restoreCursorAtExit() {\n let signalHandler: @convention(c) (Int32) -> Void = { signal in\n let exitCode = ExitCode(signal + 128)\n Application.exit(withError: exitCode)\n }\n // Termination by Ctrl+C.\n signal(SIGINT, signalHandler)\n // Termination using `kill`.\n signal(SIGTERM, signalHandler)\n // Normal and explicit exit.\n atexit {\n if let progressConfig = try? ProgressConfig() {\n let progressBar = ProgressBar(config: progressConfig)\n progressBar.resetCursor()\n }\n }\n }\n}\n\nextension Application {\n // Because we support plugins, we need to modify the help text to display\n // any if we found some.\n static func printModifiedHelpText() {\n let altered = Self.pluginLoader.alterCLIHelpText(\n original: Application.helpMessage(for: Application.self)\n )\n print(altered)\n }\n\n enum ListFormat: String, CaseIterable, ExpressibleByArgument {\n case json\n case table\n }\n\n static let signalSet: [Int32] = [\n SIGTERM,\n SIGINT,\n SIGUSR1,\n SIGUSR2,\n SIGWINCH,\n ]\n\n func isTranslated() throws -> Bool {\n do {\n return try Sysctl.byName(\"sysctl.proc_translated\") == 1\n } catch let posixErr as POSIXError {\n if posixErr.code == .ENOENT {\n return false\n }\n throw posixErr\n }\n }\n\n private static func releaseVersion() -> String {\n var versionDetails: [String: String] = [\"build\": \"release\"]\n #if DEBUG\n versionDetails[\"build\"] = \"debug\"\n #endif\n let gitCommit = {\n let sha = get_git_commit().map { String(cString: $0) }\n guard let sha else {\n return \"unspecified\"\n }\n return String(sha.prefix(7))\n }()\n versionDetails[\"commit\"] = gitCommit\n let extras: String = versionDetails.map { \"\\($0): \\($1)\" }.sorted().joined(separator: \", \")\n\n let bundleVersion = (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String)\n let releaseVersion = bundleVersion ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n\n return \"container CLI version \\(releaseVersion) (\\(extras))\"\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport Foundation\n\n/// A client for interacting with a single network.\npublic struct NetworkClient: Sendable {\n // FIXME: need more flexibility than a hard-coded constant?\n static let label = \"com.apple.container.network.container-network-vmnet\"\n\n private var machServiceLabel: String {\n \"\\(Self.label).\\(id)\"\n }\n\n let id: String\n\n /// Create a client for a network.\n public init(id: String) {\n self.id = id\n }\n}\n\n// Runtime Methods\nextension NetworkClient {\n public func state() async throws -> NetworkState {\n let request = XPCMessage(route: NetworkRoutes.state.rawValue)\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n let state = try response.state()\n return state\n }\n\n public func allocate(hostname: String) async throws -> (attachment: Attachment, additionalData: XPCMessage?) {\n let request = XPCMessage(route: NetworkRoutes.allocate.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n let attachment = try response.attachment()\n let additionalData = response.additionalData()\n return (attachment, additionalData)\n }\n\n public func deallocate(hostname: String) async throws {\n let request = XPCMessage(route: NetworkRoutes.deallocate.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func lookup(hostname: String) async throws -> Attachment? {\n let request = XPCMessage(route: NetworkRoutes.lookup.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.dataNoCopy(key: NetworkKeys.attachment.rawValue).map {\n try JSONDecoder().decode(Attachment.self, from: $0)\n }\n }\n\n public func disableAllocator() async throws -> Bool {\n let request = XPCMessage(route: NetworkRoutes.disableAllocator.rawValue)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.allocatorDisabled()\n }\n\n private func createClient() -> XPCClient {\n XPCClient(service: machServiceLabel)\n }\n}\n\nextension XPCMessage {\n func additionalData() -> XPCMessage? {\n guard let additionalData = xpc_dictionary_get_dictionary(self.underlying, NetworkKeys.additionalData.rawValue) else {\n return nil\n }\n return XPCMessage(object: additionalData)\n }\n\n func allocatorDisabled() throws -> Bool {\n self.bool(key: NetworkKeys.allocatorDisabled.rawValue)\n }\n\n func attachment() throws -> Attachment {\n let data = self.dataNoCopy(key: NetworkKeys.attachment.rawValue)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No network attachment snapshot data in message\")\n }\n return try JSONDecoder().decode(Attachment.self, from: data)\n }\n\n func hostname() throws -> String {\n let hostname = self.string(key: NetworkKeys.hostname.rawValue)\n guard let hostname else {\n throw ContainerizationError(.invalidArgument, message: \"No hostname data in message\")\n }\n return hostname\n }\n\n func state() throws -> NetworkState {\n let data = self.dataNoCopy(key: NetworkKeys.state.rawValue)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No network snapshot data in message\")\n }\n return try JSONDecoder().decode(NetworkState.self, from: data)\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/RuntimeLinuxHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\nimport NIO\n\n@main\nstruct RuntimeLinuxHelper: AsyncParsableCommand {\n static let label = \"com.apple.container.runtime.container-runtime-linux\"\n\n static let configuration = CommandConfiguration(\n commandName: \"container-runtime-linux\",\n abstract: \"XPC Service for managing a Linux sandbox\",\n version: releaseVersion()\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .shortAndLong, help: \"Sandbox UUID\")\n var uuid: String\n\n @Option(name: .shortAndLong, help: \"Root directory for the sandbox\")\n var root: String\n\n var machServiceLabel: String {\n \"\\(Self.label).\\(uuid)\"\n }\n\n func run() async throws {\n let commandName = Self._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n do {\n try adjustLimits()\n signal(SIGPIPE, SIG_IGN)\n\n log.info(\"configuring XPC server\")\n let interfaceStrategy: any InterfaceStrategy\n if #available(macOS 26, *) {\n interfaceStrategy = NonisolatedInterfaceStrategy(log: log)\n } else {\n interfaceStrategy = IsolatedInterfaceStrategy()\n }\n let server = SandboxService(root: .init(fileURLWithPath: root), interfaceStrategy: interfaceStrategy, eventLoopGroup: eventLoopGroup, log: log)\n let xpc = XPCServer(\n identifier: machServiceLabel,\n routes: [\n SandboxRoutes.bootstrap.rawValue: server.bootstrap,\n SandboxRoutes.createProcess.rawValue: server.createProcess,\n SandboxRoutes.state.rawValue: server.state,\n SandboxRoutes.stop.rawValue: server.stop,\n SandboxRoutes.kill.rawValue: server.kill,\n SandboxRoutes.resize.rawValue: server.resize,\n SandboxRoutes.wait.rawValue: server.wait,\n SandboxRoutes.start.rawValue: server.startProcess,\n SandboxRoutes.dial.rawValue: server.dial,\n ],\n log: log\n )\n\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n try? await eventLoopGroup.shutdownGracefully()\n RuntimeLinuxHelper.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"RuntimeLinuxHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n log[metadataKey: \"uuid\"] = \"\\(uuid)\"\n return log\n }\n\n private func adjustLimits() throws {\n var limits = rlimit()\n guard getrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n limits.rlim_cur = 65536\n limits.rlim_max = 65536\n guard setrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct ClientContainer: Sendable, Codable {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n\n private var sandboxClient: SandboxClient {\n SandboxClient(id: configuration.id, runtime: configuration.runtimeHandler)\n }\n\n /// Identifier of the container.\n public var id: String {\n configuration.id\n }\n\n public let status: RuntimeStatus\n\n /// Configured platform for the container.\n public var platform: ContainerizationOCI.Platform {\n configuration.platform\n }\n\n /// Configuration for the container.\n public let configuration: ContainerConfiguration\n\n /// Network allocated to the container.\n public let networks: [Attachment]\n\n package init(configuration: ContainerConfiguration) {\n self.configuration = configuration\n self.status = .stopped\n self.networks = []\n }\n\n init(snapshot: ContainerSnapshot) {\n self.configuration = snapshot.configuration\n self.status = snapshot.status\n self.networks = snapshot.networks\n }\n\n public var initProcess: ClientProcess {\n ClientProcessImpl(containerId: self.id, client: self.sandboxClient)\n }\n}\n\nextension ClientContainer {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n @discardableResult\n private static func xpcSend(\n client: XPCClient,\n message: XPCMessage,\n timeout: Duration? = .seconds(15)\n ) async throws -> XPCMessage {\n try await client.send(message, responseTimeout: timeout)\n }\n\n public static func create(\n configuration: ContainerConfiguration,\n options: ContainerCreateOptions = .default,\n kernel: Kernel\n ) async throws -> ClientContainer {\n do {\n let client = Self.newClient()\n let request = XPCMessage(route: .createContainer)\n\n let data = try JSONEncoder().encode(configuration)\n let kdata = try JSONEncoder().encode(kernel)\n let odata = try JSONEncoder().encode(options)\n request.set(key: .containerConfig, value: data)\n request.set(key: .kernel, value: kdata)\n request.set(key: .containerOptions, value: odata)\n\n try await xpcSend(client: client, message: request)\n return ClientContainer(configuration: configuration)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to create container\",\n cause: error\n )\n }\n }\n\n public static func list() async throws -> [ClientContainer] {\n do {\n let client = Self.newClient()\n let request = XPCMessage(route: .listContainer)\n\n let response = try await xpcSend(\n client: client,\n message: request,\n timeout: .seconds(10)\n )\n let data = response.dataNoCopy(key: .containers)\n guard let data else {\n return []\n }\n let configs = try JSONDecoder().decode([ContainerSnapshot].self, from: data)\n return configs.map { ClientContainer(snapshot: $0) }\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to list containers\",\n cause: error\n )\n }\n }\n\n /// Get the container for the provided id.\n public static func get(id: String) async throws -> ClientContainer {\n let containers = try await list()\n guard let container = containers.first(where: { $0.id == id }) else {\n throw ContainerizationError(\n .notFound,\n message: \"get failed: container \\(id) not found\"\n )\n }\n return container\n }\n}\n\nextension ClientContainer {\n public func bootstrap() async throws -> ClientProcess {\n let client = self.sandboxClient\n try await client.bootstrap()\n return ClientProcessImpl(containerId: self.id, client: self.sandboxClient)\n }\n\n /// Stop the container and all processes currently executing inside.\n public func stop(opts: ContainerStopOptions = ContainerStopOptions.default) async throws {\n do {\n let client = self.sandboxClient\n try await client.stop(options: opts)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to stop container\",\n cause: error\n )\n }\n }\n\n /// Delete the container along with any resources.\n public func delete() async throws {\n do {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .deleteContainer)\n request.set(key: .id, value: self.id)\n try await client.send(request)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to delete container\",\n cause: error\n )\n }\n }\n}\n\nextension ClientContainer {\n /// Execute a new process inside a running container.\n public func createProcess(id: String, configuration: ProcessConfiguration) async throws -> ClientProcess {\n do {\n let client = self.sandboxClient\n try await client.createProcess(id, config: configuration)\n return ClientProcessImpl(containerId: self.id, processId: id, client: client)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to exec in container\",\n cause: error\n )\n }\n }\n\n /// Send or \"kill\" a signal to the initial process of the container.\n /// Kill does not wait for the process to exit, it only delivers the signal.\n public func kill(_ signal: Int32) async throws {\n do {\n let client = self.sandboxClient\n try await client.kill(self.id, signal: Int64(signal))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill container \\(self.id)\",\n cause: error\n )\n }\n }\n\n public func logs() async throws -> [FileHandle] {\n do {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .containerLogs)\n request.set(key: .id, value: self.id)\n\n let response = try await client.send(request)\n let fds = response.fileHandles(key: .logs)\n guard let fds else {\n throw ContainerizationError(\n .internalError,\n message: \"No log fds returned\"\n )\n }\n return fds\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get logs for container \\(self.id)\",\n cause: error\n )\n }\n }\n\n public func dial(_ port: UInt32) async throws -> FileHandle {\n do {\n let client = self.sandboxClient\n return try await client.dial(port)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to dial \\(port) in container \\(self.id)\",\n cause: error\n )\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ImageService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport Logging\nimport TerminalProgress\n\npublic actor ImagesService {\n public static let keychainID = \"com.apple.container\"\n\n private let log: Logger\n private let contentStore: ContentStore\n private let imageStore: ImageStore\n private let snapshotStore: SnapshotStore\n\n public init(contentStore: ContentStore, imageStore: ImageStore, snapshotStore: SnapshotStore, log: Logger) throws {\n self.contentStore = contentStore\n self.imageStore = imageStore\n self.snapshotStore = snapshotStore\n self.log = log\n }\n\n private func _list() async throws -> [Containerization.Image] {\n try await imageStore.list()\n }\n\n private func _get(_ reference: String) async throws -> Containerization.Image {\n try await imageStore.get(reference: reference)\n }\n\n private func _get(_ description: ImageDescription) async throws -> Containerization.Image {\n let exists = try await self._get(description.reference)\n guard exists.descriptor == description.descriptor else {\n throw ContainerizationError(.invalidState, message: \"Descriptor mismatch. Expected \\(description.descriptor), got \\(exists.descriptor)\")\n }\n return exists\n }\n\n public func list() async throws -> [ImageDescription] {\n self.log.info(\"ImagesService: \\(#function)\")\n return try await imageStore.list().map { $0.description.fromCZ }\n }\n\n public func pull(reference: String, platform: Platform?, insecure: Bool, progressUpdate: ProgressUpdateHandler?) async throws -> ImageDescription {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference), platform: \\(String(describing: platform)), insecure: \\(insecure)\")\n let img = try await Self.withAuthentication(ref: reference) { auth in\n try await self.imageStore.pull(\n reference: reference, platform: platform, insecure: insecure, auth: auth, progress: ContainerizationProgressAdapter.handler(from: progressUpdate))\n }\n guard let img else {\n throw ContainerizationError(.internalError, message: \"Failed to pull image \\(reference)\")\n }\n return img.description.fromCZ\n }\n\n public func push(reference: String, platform: Platform?, insecure: Bool, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference), platform: \\(String(describing: platform)), insecure: \\(insecure)\")\n try await Self.withAuthentication(ref: reference) { auth in\n try await self.imageStore.push(\n reference: reference, platform: platform, insecure: insecure, auth: auth, progress: ContainerizationProgressAdapter.handler(from: progressUpdate))\n }\n }\n\n public func tag(old: String, new: String) async throws -> ImageDescription {\n self.log.info(\"ImagesService: \\(#function) - old: \\(old), new: \\(new)\")\n let img = try await self.imageStore.tag(existing: old, new: new)\n return img.description.fromCZ\n }\n\n public func delete(reference: String, garbageCollect: Bool) async throws {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference)\")\n try await self.imageStore.delete(reference: reference, performCleanup: garbageCollect)\n }\n\n public func save(reference: String, out: URL, platform: Platform?) async throws {\n self.log.info(\"ImagesService: \\(#function) - reference: \\(reference) , platform: \\(String(describing: platform))\")\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try await self.imageStore.save(references: [reference], out: tempDir, platform: platform)\n let writer = try ArchiveWriter(format: .pax, filter: .none, file: out)\n try writer.archiveDirectory(tempDir)\n try writer.finishEncoding()\n }\n\n public func load(from tarFile: URL) async throws -> [ImageDescription] {\n self.log.info(\"ImagesService: \\(#function) from: \\(tarFile.absolutePath())\")\n let reader = try ArchiveReader(file: tarFile)\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try reader.extractContents(to: tempDir)\n let loaded = try await self.imageStore.load(from: tempDir)\n var images: [ImageDescription] = []\n for image in loaded {\n images.append(image.description.fromCZ)\n }\n return images\n }\n\n public func prune() async throws -> ([String], UInt64) {\n let images = try await self._list()\n let freedSnapshotBytes = try await self.snapshotStore.clean(keepingSnapshotsFor: images)\n let (deleted, freedContentBytes) = try await self.imageStore.prune()\n return (deleted, freedContentBytes + freedSnapshotBytes)\n }\n}\n\n// MARK: Image Snapshot Methods\n\nextension ImagesService {\n public func unpack(description: ImageDescription, platform: Platform?, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n try await self.snapshotStore.unpack(image: img, platform: platform, progressUpdate: progressUpdate)\n }\n\n public func deleteImageSnapshot(description: ImageDescription, platform: Platform?) async throws {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n try await self.snapshotStore.delete(for: img, platform: platform)\n }\n\n public func getImageSnapshot(description: ImageDescription, platform: Platform) async throws -> Filesystem {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n return try await self.snapshotStore.get(for: img, platform: platform)\n }\n}\n\n// MARK: Static Methods\n\nextension ImagesService {\n private static func withAuthentication(\n ref: String, _ body: @Sendable @escaping (_ auth: Authentication?) async throws -> T?\n ) async throws -> T? {\n var authentication: Authentication?\n let ref = try Reference.parse(ref)\n guard let host = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"No host specified in image reference: \\(ref)\")\n }\n authentication = Self.authenticationFromEnv(host: host)\n if let authentication {\n return try await body(authentication)\n }\n let keychain = KeychainHelper(id: Self.keychainID)\n do {\n authentication = try keychain.lookup(domain: host)\n } catch let err as KeychainHelper.Error {\n guard case .keyNotFound = err else {\n throw ContainerizationError(.internalError, message: \"Error querying keychain for \\(host)\", cause: err)\n }\n }\n do {\n return try await body(authentication)\n } catch let err as RegistryClient.Error {\n guard case .invalidStatus(_, let status, _) = err else {\n throw err\n }\n guard status == .unauthorized || status == .forbidden else {\n throw err\n }\n guard authentication != nil else {\n throw ContainerizationError(.internalError, message: \"\\(String(describing: err)). No credentials found for host \\(host)\")\n }\n throw err\n }\n }\n\n private static func authenticationFromEnv(host: String) -> Authentication? {\n let env = ProcessInfo.processInfo.environment\n guard env[\"CONTAINER_REGISTRY_HOST\"] == host else {\n return nil\n }\n guard let user = env[\"CONTAINER_REGISTRY_USER\"], let password = env[\"CONTAINER_REGISTRY_TOKEN\"] else {\n return nil\n }\n return BasicAuthentication(username: user, password: password)\n }\n}\n\nextension ImageDescription {\n public var toCZ: Containerization.Image.Description {\n .init(reference: self.reference, descriptor: self.descriptor)\n }\n}\n\nextension Containerization.Image.Description {\n public var fromCZ: ImageDescription {\n .init(\n reference: self.reference,\n descriptor: self.descriptor\n )\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Configuration parameters for network creation.\npublic struct NetworkConfiguration: Codable, Sendable, Identifiable {\n /// A unique identifier for the network\n public let id: String\n\n /// The network type\n public let mode: NetworkMode\n\n /// The preferred CIDR address for the subnet, if specified\n public let subnet: String?\n\n /// Creates a network configuration\n public init(\n id: String,\n mode: NetworkMode,\n subnet: String? = nil\n ) {\n self.id = id\n self.mode = mode\n self.subnet = subnet\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCMessage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\n\n/// A message that can be pass across application boundaries via XPC.\npublic struct XPCMessage: Sendable {\n /// Defined message key storing the route value.\n public static let routeKey = \"com.apple.container.xpc.route\"\n /// Defined message key storing the error value.\n public static let errorKey = \"com.apple.container.xpc.error\"\n\n // Access to `object` is protected by a lock\n private nonisolated(unsafe) let object: xpc_object_t\n private let lock = NSLock()\n private let isErr: Bool\n\n /// The underlying xpc object that the message wraps.\n public var underlying: xpc_object_t {\n lock.withLock {\n object\n }\n }\n public var isErrorType: Bool { isErr }\n\n public init(object: xpc_object_t) {\n self.object = object\n self.isErr = xpc_get_type(self.object) == XPC_TYPE_ERROR\n }\n\n public init(route: String) {\n self.object = xpc_dictionary_create_empty()\n self.isErr = false\n xpc_dictionary_set_string(self.object, Self.routeKey, route)\n }\n}\n\nextension XPCMessage {\n public static func == (lhs: XPCMessage, rhs: xpc_object_t) -> Bool {\n xpc_equal(lhs.underlying, rhs)\n }\n\n public func reply() -> XPCMessage {\n lock.withLock {\n XPCMessage(object: xpc_dictionary_create_reply(object)!)\n }\n }\n\n public func errorKeyDescription() -> String? {\n guard self.isErr,\n let xpcErr = lock.withLock({\n xpc_dictionary_get_string(\n self.object,\n XPC_ERROR_KEY_DESCRIPTION\n )\n })\n else {\n return nil\n }\n return String(cString: xpcErr)\n }\n\n public func error() throws {\n let data = data(key: Self.errorKey)\n if let data {\n let item = try? JSONDecoder().decode(ContainerXPCError.self, from: data)\n precondition(item != nil, \"expected to receive a ContainerXPCXPCError\")\n\n throw ContainerizationError(item!.code, message: item!.message)\n }\n }\n\n public func set(error: ContainerizationError) {\n var message = error.message\n if let cause = error.cause {\n message += \" (cause: \\\"\\(cause)\\\")\"\n }\n let serializableError = ContainerXPCError(code: error.code.description, message: message)\n let data = try? JSONEncoder().encode(serializableError)\n precondition(data != nil)\n\n set(key: Self.errorKey, value: data!)\n }\n}\n\nstruct ContainerXPCError: Codable {\n let code: String\n let message: String\n}\n\nextension XPCMessage {\n public func data(key: String) -> Data? {\n var length: Int = 0\n let bytes = lock.withLock {\n xpc_dictionary_get_data(self.object, key, &length)\n }\n\n guard let bytes else {\n return nil\n }\n\n return Data(bytes: bytes, count: length)\n }\n\n /// dataNoCopy is similar to data, except the data is not copied\n /// to a new buffer. What this means in practice is the second the\n /// underlying xpc_object_t gets released by ARC the data will be\n /// released as well. This variant should be used when you know the\n /// data will be used before the object has no more references.\n public func dataNoCopy(key: String) -> Data? {\n var length: Int = 0\n let bytes = lock.withLock {\n xpc_dictionary_get_data(self.object, key, &length)\n }\n\n guard let bytes else {\n return nil\n }\n\n return Data(\n bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes),\n count: length,\n deallocator: .none\n )\n }\n\n public func set(key: String, value: Data) {\n value.withUnsafeBytes { ptr in\n if let addr = ptr.baseAddress {\n lock.withLock {\n xpc_dictionary_set_data(self.object, key, addr, value.count)\n }\n }\n }\n }\n\n public func string(key: String) -> String? {\n let _id = lock.withLock {\n xpc_dictionary_get_string(self.object, key)\n }\n if let _id {\n return String(cString: _id)\n }\n return nil\n }\n\n public func set(key: String, value: String) {\n lock.withLock {\n xpc_dictionary_set_string(self.object, key, value)\n }\n }\n\n public func bool(key: String) -> Bool {\n lock.withLock {\n xpc_dictionary_get_bool(self.object, key)\n }\n }\n\n public func set(key: String, value: Bool) {\n lock.withLock {\n xpc_dictionary_set_bool(self.object, key, value)\n }\n }\n\n public func uint64(key: String) -> UInt64 {\n lock.withLock {\n xpc_dictionary_get_uint64(self.object, key)\n }\n }\n\n public func set(key: String, value: UInt64) {\n lock.withLock {\n xpc_dictionary_set_uint64(self.object, key, value)\n }\n }\n\n public func int64(key: String) -> Int64 {\n lock.withLock {\n xpc_dictionary_get_int64(self.object, key)\n }\n }\n\n public func set(key: String, value: Int64) {\n lock.withLock {\n xpc_dictionary_set_int64(self.object, key, value)\n }\n }\n\n public func fileHandle(key: String) -> FileHandle? {\n let fd = lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n if let fd {\n let fd2 = xpc_fd_dup(fd)\n return FileHandle(fileDescriptor: fd2, closeOnDealloc: false)\n }\n return nil\n }\n\n public func set(key: String, value: FileHandle) {\n let fd = xpc_fd_create(value.fileDescriptor)\n close(value.fileDescriptor)\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, fd)\n }\n }\n\n public func fileHandles(key: String) -> [FileHandle]? {\n let fds = lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n if let fds {\n let fd1 = xpc_array_dup_fd(fds, 0)\n let fd2 = xpc_array_dup_fd(fds, 1)\n if fd1 == -1 || fd2 == -1 {\n return nil\n }\n return [\n FileHandle(fileDescriptor: fd1, closeOnDealloc: false),\n FileHandle(fileDescriptor: fd2, closeOnDealloc: false),\n ]\n }\n return nil\n }\n\n public func set(key: String, value: [FileHandle]) throws {\n let fdArray = xpc_array_create(nil, 0)\n for fh in value {\n guard let xpcFd = xpc_fd_create(fh.fileDescriptor) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to create xpc fd for \\(fh.fileDescriptor)\"\n )\n }\n xpc_array_append_value(fdArray, xpcFd)\n close(fh.fileDescriptor)\n }\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, fdArray)\n }\n }\n\n public func endpoint(key: String) -> xpc_endpoint_t? {\n lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n }\n\n public func set(key: String, value: xpc_endpoint_t) {\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, value)\n }\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerClient/Core/ClientNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\npublic struct ClientNetwork {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n\n public static let defaultNetworkName = \"default\"\n}\n\nextension ClientNetwork {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n private static func xpcSend(\n client: XPCClient,\n message: XPCMessage,\n timeout: Duration? = .seconds(15)\n ) async throws -> XPCMessage {\n try await client.send(message, responseTimeout: timeout)\n }\n\n public static func create(configuration: NetworkConfiguration) async throws -> NetworkState {\n let client = Self.newClient()\n let request = XPCMessage(route: .networkCreate)\n request.set(key: .networkId, value: configuration.id)\n\n let data = try JSONEncoder().encode(configuration)\n request.set(key: .networkConfig, value: data)\n\n let response = try await xpcSend(client: client, message: request)\n let responseData = response.dataNoCopy(key: .networkState)\n guard let responseData else {\n throw ContainerizationError(.invalidArgument, message: \"network configuration not received\")\n }\n let state = try JSONDecoder().decode(NetworkState.self, from: responseData)\n return state\n }\n\n public static func list() async throws -> [NetworkState] {\n let client = Self.newClient()\n let request = XPCMessage(route: .networkList)\n\n let response = try await xpcSend(client: client, message: request, timeout: .seconds(1))\n let responseData = response.dataNoCopy(key: .networkStates)\n guard let responseData else {\n return []\n }\n let states = try JSONDecoder().decode([NetworkState].self, from: responseData)\n return states\n }\n\n /// Get the network for the provided id.\n public static func get(id: String) async throws -> NetworkState {\n let networks = try await list()\n guard let network = networks.first(where: { $0.id == id }) else {\n throw ContainerizationError(.notFound, message: \"network \\(id) not found\")\n }\n return network\n }\n\n /// Delete the network with the given id.\n public static func delete(id: String) async throws {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .networkDelete)\n request.set(key: .networkId, value: id)\n try await client.send(request)\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct NetworkDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete one or more networks\",\n aliases: [\"rm\"])\n\n @Flag(name: .shortAndLong, help: \"Remove all networks\")\n var all = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Network names\")\n var networkNames: [String] = []\n\n func validate() throws {\n if networkNames.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no networks specified and --all not supplied\")\n }\n if networkNames.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument,\n message: \"explicitly supplied network name(s) conflict with the --all flag\"\n )\n }\n }\n\n mutating func run() async throws {\n let uniqueNetworkNames = Set(networkNames)\n let networks: [NetworkState]\n\n if all {\n networks = try await ClientNetwork.list()\n } else {\n networks = try await ClientNetwork.list()\n .filter { c in\n uniqueNetworkNames.contains(c.id)\n }\n\n // If one of the networks requested isn't present lets throw. We don't need to do\n // this for --all as --all should be perfectly usable with no networks to remove,\n // otherwise it'd be quite clunky.\n if networks.count != uniqueNetworkNames.count {\n let missing = uniqueNetworkNames.filter { id in\n !networks.contains { n in\n n.id == id\n }\n }\n throw ContainerizationError(\n .notFound,\n message: \"failed to delete one or more networks: \\(missing)\"\n )\n }\n }\n\n if uniqueNetworkNames.contains(ClientNetwork.defaultNetworkName) {\n throw ContainerizationError(\n .invalidArgument,\n message: \"cannot delete the default network\"\n )\n }\n\n var failed = [String]()\n try await withThrowingTaskGroup(of: NetworkState?.self) { group in\n for network in networks {\n group.addTask {\n do {\n // delete atomically disables the IP allocator, then deletes\n // the allocator disable fails if any IPs are still in use\n try await ClientNetwork.delete(id: network.id)\n print(network.id)\n return nil\n } catch {\n log.error(\"failed to delete network \\(network.id): \\(error)\")\n return network\n }\n }\n }\n\n for try await network in group {\n guard let network else {\n continue\n }\n failed.append(network.id)\n }\n }\n\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"delete failed for one or more networks: \\(failed)\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Utility.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct Utility {\n private static let infraImages = [\n ClientDefaults.get(key: .defaultBuilderImage),\n ClientDefaults.get(key: .defaultInitImage),\n ]\n\n public static func createContainerID(name: String?) -> String {\n guard let name else {\n return UUID().uuidString.lowercased()\n }\n return name\n }\n\n public static func isInfraImage(name: String) -> Bool {\n for infraImage in infraImages {\n if name == infraImage {\n return true\n }\n }\n return false\n }\n\n public static func trimDigest(digest: String) -> String {\n var digest = digest\n digest.trimPrefix(\"sha256:\")\n if digest.count > 24 {\n digest = String(digest.prefix(24)) + \"...\"\n }\n return digest\n }\n\n public static func validEntityName(_ name: String) throws {\n let pattern = #\"^[a-zA-Z0-9][a-zA-Z0-9_.-]+$\"#\n let regex = try Regex(pattern)\n if try regex.firstMatch(in: name) == nil {\n throw ContainerizationError(.invalidArgument, message: \"invalid entity name \\(name)\")\n }\n }\n\n public static func containerConfigFromFlags(\n id: String,\n image: String,\n arguments: [String],\n process: Flags.Process,\n management: Flags.Management,\n resource: Flags.Resource,\n registry: Flags.Registry,\n progressUpdate: @escaping ProgressUpdateHandler\n ) async throws -> (ContainerConfiguration, Kernel) {\n let requestedPlatform = Parser.platform(os: management.os, arch: management.arch)\n let scheme = try RequestScheme(registry.scheme)\n\n await progressUpdate([\n .setDescription(\"Fetching image\"),\n .setItemsName(\"blobs\"),\n ])\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n let img = try await ClientImage.fetch(\n reference: image,\n platform: requestedPlatform,\n scheme: scheme,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progressUpdate)\n )\n\n // Unpack a fetched image before use\n await progressUpdate([\n .setDescription(\"Unpacking image\"),\n .setItemsName(\"entries\"),\n ])\n let unpackTask = await taskManager.startTask()\n try await img.getCreateSnapshot(\n platform: requestedPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progressUpdate))\n\n await progressUpdate([\n .setDescription(\"Fetching kernel\"),\n .setItemsName(\"binary\"),\n ])\n\n let kernel = try await self.getKernel(management: management)\n\n // Pull and unpack the initial filesystem\n await progressUpdate([\n .setDescription(\"Fetching init image\"),\n .setItemsName(\"blobs\"),\n ])\n let fetchInitTask = await taskManager.startTask()\n let initImage = try await ClientImage.fetch(\n reference: ClientImage.initImageRef, platform: .current, scheme: scheme,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchInitTask, from: progressUpdate))\n\n await progressUpdate([\n .setDescription(\"Unpacking init image\"),\n .setItemsName(\"entries\"),\n ])\n let unpackInitTask = await taskManager.startTask()\n _ = try await initImage.getCreateSnapshot(\n platform: .current,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackInitTask, from: progressUpdate))\n\n await taskManager.finish()\n\n let imageConfig = try await img.config(for: requestedPlatform).config\n let description = img.description\n let pc = try Parser.process(\n arguments: arguments,\n processFlags: process,\n managementFlags: management,\n config: imageConfig\n )\n\n var config = ContainerConfiguration(id: id, image: description, process: pc)\n config.platform = requestedPlatform\n config.hostname = id\n\n config.resources = try Parser.resources(\n cpus: resource.cpus,\n memory: resource.memory\n )\n\n let tmpfs = try Parser.tmpfsMounts(management.tmpFs)\n let volumes = try Parser.volumes(management.volumes)\n var mounts = try Parser.mounts(management.mounts)\n mounts.append(contentsOf: tmpfs)\n mounts.append(contentsOf: volumes)\n config.mounts = mounts\n\n if management.networks.isEmpty {\n config.networks = [ClientNetwork.defaultNetworkName]\n } else {\n // networks may only be specified for macOS 26+\n guard #available(macOS 26, *) else {\n throw ContainerizationError(.invalidArgument, message: \"non-default network configuration requires macOS 26 or newer\")\n }\n config.networks = management.networks\n }\n\n var networkStatuses: [NetworkStatus] = []\n for networkName in config.networks {\n let network: NetworkState = try await ClientNetwork.get(id: networkName)\n guard case .running(_, let networkStatus) = network else {\n throw ContainerizationError(.invalidState, message: \"network \\(networkName) is not running\")\n }\n networkStatuses.append(networkStatus)\n }\n\n if management.dnsDisabled {\n config.dns = nil\n } else {\n let domain = management.dnsDomain ?? ClientDefaults.getOptional(key: .defaultDNSDomain)\n config.dns = .init(\n nameservers: management.dnsNameservers,\n domain: domain,\n searchDomains: management.dnsSearchDomains,\n options: management.dnsOptions\n )\n }\n\n if Platform.current.architecture == \"arm64\" && requestedPlatform.architecture == \"amd64\" {\n config.rosetta = true\n }\n\n config.labels = try Parser.labels(management.labels)\n\n config.publishedPorts = try Parser.publishPorts(management.publishPorts)\n\n // Parse --publish-socket arguments and add to container configuration\n // to enable socket forwarding from container to host.\n config.publishedSockets = try Parser.publishSockets(management.publishSockets)\n\n return (config, kernel)\n }\n\n private static func getKernel(management: Flags.Management) async throws -> Kernel {\n // For the image itself we'll take the user input and try with it as we can do userspace\n // emulation for x86, but for the kernel we need it to match the hosts architecture.\n let s: SystemPlatform = .current\n if let userKernel = management.kernel {\n guard FileManager.default.fileExists(atPath: userKernel) else {\n throw ContainerizationError(.notFound, message: \"Kernel file not found at path \\(userKernel)\")\n }\n let p = URL(filePath: userKernel)\n return .init(path: p, platform: s)\n }\n return try await ClientKernel.getDefaultKernel(for: s)\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationExtras\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct NetworkList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List networks\",\n aliases: [\"ls\"])\n\n @Flag(name: .shortAndLong, help: \"Only output the network name\")\n var quiet = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let networks = try await ClientNetwork.list()\n try printNetworks(networks: networks, format: format)\n }\n\n private func createHeader() -> [[String]] {\n [[\"NETWORK\", \"STATE\", \"SUBNET\"]]\n }\n\n private func printNetworks(networks: [NetworkState], format: ListFormat) throws {\n if format == .json {\n let printables = networks.map {\n PrintableNetwork($0)\n }\n let data = try JSONEncoder().encode(printables)\n print(String(data: data, encoding: .utf8)!)\n\n return\n }\n\n if self.quiet {\n networks.forEach {\n print($0.id)\n }\n return\n }\n\n var rows = createHeader()\n for network in networks {\n rows.append(network.asRow)\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n }\n}\n\nextension NetworkState {\n var asRow: [String] {\n switch self {\n case .created(_):\n return [self.id, self.state, \"none\"]\n case .running(_, let status):\n return [self.id, self.state, status.address]\n }\n }\n}\n\nstruct PrintableNetwork: Codable {\n let id: String\n let state: String\n let config: NetworkConfiguration\n let status: NetworkStatus?\n\n init(_ network: NetworkState) {\n self.id = network.id\n self.state = network.state\n switch network {\n case .created(let config):\n self.config = config\n self.status = nil\n case .running(let config, let status):\n self.config = config\n self.status = status\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SendableProperty\nimport Synchronization\n\n/// A progress bar that updates itself as tasks are completed.\npublic final class ProgressBar: Sendable {\n let config: ProgressConfig\n let state: Mutex\n @SendableProperty\n var printedWidth = 0\n let term: FileHandle?\n let termQueue = DispatchQueue(label: \"com.apple.container.ProgressBar\")\n private let standardError = StandardError()\n\n /// Returns `true` if the progress bar has finished.\n public var isFinished: Bool {\n state.withLock { $0.finished }\n }\n\n /// Creates a new progress bar.\n /// - Parameter config: The configuration for the progress bar.\n public init(config: ProgressConfig) {\n self.config = config\n term = isatty(config.terminal.fileDescriptor) == 1 ? config.terminal : nil\n let state = State(\n description: config.initialDescription, itemsName: config.initialItemsName, totalTasks: config.initialTotalTasks,\n totalItems: config.initialTotalItems,\n totalSize: config.initialTotalSize)\n self.state = Mutex(state)\n display(EscapeSequence.hideCursor)\n }\n\n deinit {\n clear()\n }\n\n /// Allows resetting the progress state.\n public func reset() {\n state.withLock {\n $0 = State(description: config.initialDescription)\n }\n }\n\n /// Allows resetting the progress state of the current task.\n public func resetCurrentTask() {\n state.withLock {\n $0 = State(description: $0.description, itemsName: $0.itemsName, tasks: $0.tasks, totalTasks: $0.totalTasks, startTime: $0.startTime)\n }\n }\n\n private func printFullDescription() {\n let (description, subDescription) = state.withLock { ($0.description, $0.subDescription) }\n\n if subDescription != \"\" {\n standardError.write(\"\\(description) \\(subDescription)\")\n } else {\n standardError.write(description)\n }\n }\n\n /// Updates the description of the progress bar and increments the tasks by one.\n /// - Parameter description: The description of the action being performed.\n public func set(description: String) {\n resetCurrentTask()\n\n state.withLock {\n $0.description = description\n $0.subDescription = \"\"\n $0.tasks += 1\n }\n if config.disableProgressUpdates {\n printFullDescription()\n }\n }\n\n /// Updates the additional description of the progress bar.\n /// - Parameter subDescription: The additional description of the action being performed.\n public func set(subDescription: String) {\n resetCurrentTask()\n\n state.withLock { $0.subDescription = subDescription }\n if config.disableProgressUpdates {\n printFullDescription()\n }\n }\n\n private func start(intervalSeconds: TimeInterval) async {\n if config.disableProgressUpdates && !state.withLock({ $0.description.isEmpty }) {\n printFullDescription()\n }\n\n while !state.withLock({ $0.finished }) {\n let intervalNanoseconds = UInt64(intervalSeconds * 1_000_000_000)\n render()\n state.withLock { $0.iteration += 1 }\n if (try? await Task.sleep(nanoseconds: intervalNanoseconds)) == nil {\n return\n }\n }\n }\n\n /// Starts an animation of the progress bar.\n /// - Parameter intervalSeconds: The time interval between updates in seconds.\n public func start(intervalSeconds: TimeInterval = 0.04) {\n Task(priority: .utility) {\n await start(intervalSeconds: intervalSeconds)\n }\n }\n\n /// Finishes the progress bar.\n public func finish() {\n guard !state.withLock({ $0.finished }) else {\n return\n }\n\n state.withLock { $0.finished = true }\n\n // The last render.\n render(force: true)\n\n if !config.disableProgressUpdates && !config.clearOnFinish {\n displayText(state.withLock { $0.output }, terminating: \"\\n\")\n }\n\n if config.clearOnFinish {\n clearAndResetCursor()\n } else {\n resetCursor()\n }\n // Allow printed output to flush.\n usleep(100_000)\n }\n}\n\nextension ProgressBar {\n private func secondsSinceStart() -> Int {\n let timeDifferenceNanoseconds = DispatchTime.now().uptimeNanoseconds - state.withLock { $0.startTime.uptimeNanoseconds }\n let timeDifferenceSeconds = Int(floor(Double(timeDifferenceNanoseconds) / 1_000_000_000))\n return timeDifferenceSeconds\n }\n\n func render(force: Bool = false) {\n guard term != nil && !config.disableProgressUpdates && (force || !state.withLock { $0.finished }) else {\n return\n }\n let output = draw()\n displayText(output)\n }\n\n func draw() -> String {\n let state = self.state.withLock { $0 }\n\n var components = [String]()\n if config.showSpinner && !config.showProgressBar {\n if !state.finished {\n let spinnerIcon = config.theme.getSpinnerIcon(state.iteration)\n components.append(\"\\(spinnerIcon)\")\n } else {\n components.append(\"\\(config.theme.done)\")\n }\n }\n\n if config.showTasks, let totalTasks = state.totalTasks {\n let tasks = min(state.tasks, totalTasks)\n components.append(\"[\\(tasks)/\\(totalTasks)]\")\n }\n\n if config.showDescription && !state.description.isEmpty {\n components.append(\"\\(state.description)\")\n if !state.subDescription.isEmpty {\n components.append(\"\\(state.subDescription)\")\n }\n }\n\n let allowProgress = !config.ignoreSmallSize || state.totalSize == nil || state.totalSize! > Int64(1024 * 1024)\n\n let value = state.totalSize != nil ? state.size : Int64(state.items)\n let total = state.totalSize ?? Int64(state.totalItems ?? 0)\n\n if config.showPercent && total > 0 && allowProgress {\n components.append(\"\\(state.finished ? \"100%\" : state.percent)\")\n }\n\n if config.showProgressBar, total > 0, allowProgress {\n let usedWidth = components.joined(separator: \" \").count + 45 /* the maximum number of characters we may need */\n let remainingWidth = max(config.width - usedWidth, 1 /* the minimum width of a progress bar */)\n let barLength = state.finished ? remainingWidth : Int(Int64(remainingWidth) * value / total)\n let barPaddingLength = remainingWidth - barLength\n let bar = \"\\(String(repeating: config.theme.bar, count: barLength))\\(String(repeating: \" \", count: barPaddingLength))\"\n components.append(\"|\\(bar)|\")\n }\n\n var additionalComponents = [String]()\n\n if config.showItems, state.items > 0 {\n var itemsName = \"\"\n if !state.itemsName.isEmpty {\n itemsName = \" \\(state.itemsName)\"\n }\n if state.finished {\n if let totalItems = state.totalItems {\n additionalComponents.append(\"\\(totalItems.formattedNumber())\\(itemsName)\")\n }\n } else {\n if let totalItems = state.totalItems {\n additionalComponents.append(\"\\(state.items.formattedNumber()) of \\(totalItems.formattedNumber())\\(itemsName)\")\n } else {\n additionalComponents.append(\"\\(state.items.formattedNumber())\\(itemsName)\")\n }\n }\n }\n\n if state.size > 0 && allowProgress {\n if state.finished {\n if config.showSize {\n if let totalSize = state.totalSize {\n var formattedTotalSize = totalSize.formattedSize()\n formattedTotalSize = adjustFormattedSize(formattedTotalSize)\n additionalComponents.append(formattedTotalSize)\n }\n }\n } else {\n var formattedCombinedSize = \"\"\n if config.showSize {\n var formattedSize = state.size.formattedSize()\n formattedSize = adjustFormattedSize(formattedSize)\n if let totalSize = state.totalSize {\n var formattedTotalSize = totalSize.formattedSize()\n formattedTotalSize = adjustFormattedSize(formattedTotalSize)\n formattedCombinedSize = combineSize(size: formattedSize, totalSize: formattedTotalSize)\n } else {\n formattedCombinedSize = formattedSize\n }\n }\n\n var formattedSpeed = \"\"\n if config.showSpeed {\n formattedSpeed = \"\\(state.sizeSpeed ?? state.averageSizeSpeed)\"\n formattedSpeed = adjustFormattedSize(formattedSpeed)\n }\n\n if config.showSize && config.showSpeed {\n additionalComponents.append(formattedCombinedSize)\n additionalComponents.append(formattedSpeed)\n } else if config.showSize {\n additionalComponents.append(formattedCombinedSize)\n } else if config.showSpeed {\n additionalComponents.append(formattedSpeed)\n }\n }\n }\n\n if additionalComponents.count > 0 {\n let joinedAdditionalComponents = additionalComponents.joined(separator: \", \")\n components.append(\"(\\(joinedAdditionalComponents))\")\n }\n\n if config.showTime {\n let timeDifferenceSeconds = secondsSinceStart()\n let formattedTime = timeDifferenceSeconds.formattedTime()\n components.append(\"[\\(formattedTime)]\")\n }\n\n return components.joined(separator: \" \")\n }\n\n private func adjustFormattedSize(_ size: String) -> String {\n // Ensure we always have one digit after the decimal point to prevent flickering.\n let zero = Int64(0).formattedSize()\n guard !size.contains(\".\"), let first = size.first, first.isNumber || !size.contains(zero) else {\n return size\n }\n var size = size\n for unit in [\"MB\", \"GB\", \"TB\"] {\n size = size.replacingOccurrences(of: \" \\(unit)\", with: \".0 \\(unit)\")\n }\n return size\n }\n\n private func combineSize(size: String, totalSize: String) -> String {\n let sizeComponents = size.split(separator: \" \", maxSplits: 1)\n let totalSizeComponents = totalSize.split(separator: \" \", maxSplits: 1)\n guard sizeComponents.count == 2, totalSizeComponents.count == 2 else {\n return \"\\(size)/\\(totalSize)\"\n }\n let sizeNumber = sizeComponents[0]\n let sizeUnit = sizeComponents[1]\n let totalSizeNumber = totalSizeComponents[0]\n let totalSizeUnit = totalSizeComponents[1]\n guard sizeUnit == totalSizeUnit else {\n return \"\\(size)/\\(totalSize)\"\n }\n return \"\\(sizeNumber)/\\(totalSizeNumber) \\(totalSizeUnit)\"\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\nimport Logging\nimport os\nimport Synchronization\n\npublic struct XPCServer: Sendable {\n public typealias RouteHandler = @Sendable (XPCMessage) async throws -> XPCMessage\n\n private let routes: [String: RouteHandler]\n // Access to `connection` is protected by a lock\n private nonisolated(unsafe) let connection: xpc_connection_t\n private let lock = NSLock()\n\n let log: Logging.Logger\n\n public init(identifier: String, routes: [String: RouteHandler], log: Logging.Logger) {\n let connection = xpc_connection_create_mach_service(\n identifier,\n nil,\n UInt64(XPC_CONNECTION_MACH_SERVICE_LISTENER))\n\n self.routes = routes\n self.connection = connection\n self.log = log\n }\n\n public func listen() async throws {\n let connections = AsyncStream { cont in\n lock.withLock {\n xpc_connection_set_event_handler(self.connection) { object in\n switch xpc_get_type(object) {\n case XPC_TYPE_CONNECTION:\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n cont.yield(object)\n case XPC_TYPE_ERROR:\n if object.connectionError {\n cont.finish()\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(object))\")\n }\n }\n }\n }\n\n defer {\n lock.withLock {\n xpc_connection_cancel(self.connection)\n }\n }\n\n lock.withLock {\n xpc_connection_activate(self.connection)\n }\n try await withThrowingDiscardingTaskGroup { group in\n for await conn in connections {\n // `conn` isn't used concurrently.\n nonisolated(unsafe) let conn = conn\n let added = group.addTaskUnlessCancelled { @Sendable in\n try await self.handleClientConnection(connection: conn)\n xpc_connection_cancel(conn)\n }\n\n if !added {\n break\n }\n }\n\n group.cancelAll()\n }\n }\n\n func handleClientConnection(connection: xpc_connection_t) async throws {\n let replySent = Mutex(false)\n\n let objects = AsyncStream { cont in\n xpc_connection_set_event_handler(connection) { object in\n switch xpc_get_type(object) {\n case XPC_TYPE_DICTIONARY:\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n cont.yield(object)\n case XPC_TYPE_ERROR:\n if object.connectionError {\n cont.finish()\n }\n if !(replySent.withLock({ $0 }) && object.connectionClosed) {\n // When a xpc connection is closed, the framework sends a final XPC_ERROR_CONNECTION_INVALID message.\n // We can ignore this if we know we have already handled the request.\n self.log.error(\"xpc client handler connection error \\(object.errorDescription ?? \"no description\")\")\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(object))\")\n }\n }\n }\n defer {\n xpc_connection_cancel(connection)\n }\n\n xpc_connection_activate(connection)\n try await withThrowingDiscardingTaskGroup { group in\n // `connection` isn't used concurrently.\n nonisolated(unsafe) let connection = connection\n for await object in objects {\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n let added = group.addTaskUnlessCancelled { @Sendable in\n try await self.handleMessage(connection: connection, object: object)\n replySent.withLock { $0 = true }\n }\n if !added {\n break\n }\n }\n group.cancelAll()\n }\n }\n\n func handleMessage(connection: xpc_connection_t, object: xpc_object_t) async throws {\n guard let route = object.route else {\n log.error(\"empty route\")\n return\n }\n\n if let handler = routes[route] {\n let message = XPCMessage(object: object)\n do {\n let response = try await handler(message)\n xpc_connection_send_message(connection, response.underlying)\n } catch let error as ContainerizationError {\n let reply = message.reply()\n log.error(\"handler for \\(route) threw error \\(error)\")\n reply.set(error: error)\n xpc_connection_send_message(connection, reply.underlying)\n } catch {\n let reply = message.reply()\n log.error(\"handler for \\(route) threw error \\(error)\")\n let err = ContainerizationError(.unknown, message: String(describing: error))\n reply.set(error: err)\n xpc_connection_send_message(connection, reply.underlying)\n }\n }\n }\n}\n\nextension xpc_object_t {\n var route: String? {\n let croute = xpc_dictionary_get_string(self, XPCMessage.routeKey)\n guard let croute else {\n return nil\n }\n return String(cString: croute)\n }\n\n var connectionError: Bool {\n precondition(isError, \"Not an error\")\n return xpc_equal(self, XPC_ERROR_CONNECTION_INVALID) || xpc_equal(self, XPC_ERROR_CONNECTION_INTERRUPTED)\n }\n\n var connectionClosed: Bool {\n precondition(isError, \"Not an error\")\n return xpc_equal(self, XPC_ERROR_CONNECTION_INVALID)\n }\n\n var isError: Bool {\n xpc_get_type(self) == XPC_TYPE_ERROR\n }\n\n var errorDescription: String? {\n precondition(isError, \"Not an error\")\n let cstring = xpc_dictionary_get_string(self, XPC_ERROR_KEY_DESCRIPTION)\n guard let cstring else {\n return nil\n }\n return String(cString: cstring)\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerClient/Parser.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\npublic struct Parser {\n public static func memoryString(_ memory: String) throws -> Int64 {\n let ram = try Measurement.parse(parsing: memory)\n let mb = ram.converted(to: .mebibytes)\n return Int64(mb.value)\n }\n\n public static func user(\n user: String?, uid: UInt32?, gid: UInt32?,\n defaultUser: ProcessConfiguration.User = .id(uid: 0, gid: 0)\n ) -> (user: ProcessConfiguration.User, groups: [UInt32]) {\n\n var supplementalGroups: [UInt32] = []\n let user: ProcessConfiguration.User = {\n if let user = user, !user.isEmpty {\n return .raw(userString: user)\n }\n if let uid, let gid {\n return .id(uid: uid, gid: gid)\n }\n if uid == nil, gid == nil {\n // Neither uid nor gid is set. return the default user\n return defaultUser\n }\n // One of uid / gid is left unspecified. Set the user accordingly\n if let uid {\n return .raw(userString: \"\\(uid)\")\n }\n if let gid {\n supplementalGroups.append(gid)\n }\n return defaultUser\n }()\n return (user, supplementalGroups)\n }\n\n public static func platform(os: String, arch: String) -> ContainerizationOCI.Platform {\n .init(arch: arch, os: os)\n }\n\n public static func resources(cpus: Int64?, memory: String?) throws -> ContainerConfiguration.Resources {\n var resource = ContainerConfiguration.Resources()\n if let cpus {\n resource.cpus = Int(cpus)\n }\n if let memory {\n resource.memoryInBytes = try Parser.memoryString(memory).mib()\n }\n return resource\n }\n\n public static func allEnv(imageEnvs: [String], envFiles: [String], envs: [String]) throws -> [String] {\n var output: [String] = []\n output.append(contentsOf: Parser.env(envList: imageEnvs))\n for envFile in envFiles {\n let content = try Parser.envFile(path: envFile)\n output.append(contentsOf: content)\n }\n output.append(contentsOf: Parser.env(envList: envs))\n return output\n }\n\n static func envFile(path: String) throws -> [String] {\n guard FileManager.default.fileExists(atPath: path) else {\n throw ContainerizationError(.notFound, message: \"envfile at \\(path) not found\")\n }\n\n let data = try String(contentsOfFile: path, encoding: .utf8)\n let lines = data.components(separatedBy: .newlines)\n var envVars: [String] = []\n for line in lines {\n let line = line.trimmingCharacters(in: .whitespaces)\n if line.isEmpty {\n continue\n }\n if !line.hasPrefix(\"#\") {\n let keyVals = line.split(separator: \"=\")\n if keyVals.count != 2 {\n continue\n }\n let key = keyVals[0].trimmingCharacters(in: .whitespaces)\n let val = keyVals[1].trimmingCharacters(in: .whitespaces)\n if key.isEmpty || val.isEmpty {\n continue\n }\n envVars.append(\"\\(key)=\\(val)\")\n }\n }\n return envVars\n }\n\n static func env(envList: [String]) -> [String] {\n var envVar: [String] = []\n for env in envList {\n var env = env\n let parts = env.split(separator: \"=\", maxSplits: 2)\n if parts.count == 1 {\n guard let val = ProcessInfo.processInfo.environment[env] else {\n continue\n }\n env = \"\\(env)=\\(val)\"\n }\n envVar.append(env)\n }\n return envVar\n }\n\n static func labels(_ rawLabels: [String]) throws -> [String: String] {\n var result: [String: String] = [:]\n for label in rawLabels {\n if label.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"label cannot be an empty string\")\n }\n let parts = label.split(separator: \"=\", maxSplits: 2)\n switch parts.count {\n case 1:\n result[String(parts[0])] = \"\"\n case 2:\n result[String(parts[0])] = String(parts[1])\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid label format \\(label)\")\n }\n }\n return result\n }\n\n static func process(\n arguments: [String],\n processFlags: Flags.Process,\n managementFlags: Flags.Management,\n config: ContainerizationOCI.ImageConfig?\n ) throws -> ProcessConfiguration {\n\n let imageEnvVars = config?.env ?? []\n let envvars = try Parser.allEnv(imageEnvs: imageEnvVars, envFiles: processFlags.envFile, envs: processFlags.env)\n\n let workingDir: String = {\n if let cwd = processFlags.cwd {\n return cwd\n }\n if let cwd = config?.workingDir {\n return cwd\n }\n return \"/\"\n }()\n\n let processArguments: [String]? = {\n var result: [String] = []\n var hasEntrypointOverride: Bool = false\n // ensure the entrypoint is honored if it has been explicitly set by the user\n if let entrypoint = managementFlags.entryPoint, !entrypoint.isEmpty {\n result = [entrypoint]\n hasEntrypointOverride = true\n } else if let entrypoint = config?.entrypoint, !entrypoint.isEmpty {\n result = entrypoint\n }\n if !arguments.isEmpty {\n result.append(contentsOf: arguments)\n } else {\n if let cmd = config?.cmd, !hasEntrypointOverride, !cmd.isEmpty {\n result.append(contentsOf: cmd)\n }\n }\n return result.count > 0 ? result : nil\n }()\n\n guard let commandToRun = processArguments, commandToRun.count > 0 else {\n throw ContainerizationError(.invalidArgument, message: \"Command/Entrypoint not specified for container process\")\n }\n\n let defaultUser: ProcessConfiguration.User = {\n if let u = config?.user {\n return .raw(userString: u)\n }\n return .id(uid: 0, gid: 0)\n }()\n\n let (user, additionalGroups) = Parser.user(\n user: processFlags.user, uid: processFlags.uid,\n gid: processFlags.gid, defaultUser: defaultUser)\n\n return .init(\n executable: commandToRun.first!,\n arguments: [String](commandToRun.dropFirst()),\n environment: envvars,\n workingDirectory: workingDir,\n terminal: processFlags.tty,\n user: user,\n supplementalGroups: additionalGroups\n )\n }\n\n // MARK: Mounts\n\n static let mountTypes = [\n \"virtiofs\",\n \"bind\",\n \"tmpfs\",\n ]\n\n static let defaultDirectives = [\"type\": \"virtiofs\"]\n\n static func tmpfsMounts(_ mounts: [String]) throws -> [Filesystem] {\n var result: [Filesystem] = []\n let mounts = mounts.dedupe()\n for tmpfs in mounts {\n let fs = Filesystem.tmpfs(destination: tmpfs, options: [])\n try validateMount(fs)\n result.append(fs)\n }\n return result\n }\n\n static func mounts(_ rawMounts: [String]) throws -> [Filesystem] {\n var mounts: [Filesystem] = []\n let rawMounts = rawMounts.dedupe()\n for mount in rawMounts {\n let m = try Parser.mount(mount)\n try validateMount(m)\n mounts.append(m)\n }\n return mounts\n }\n\n static func mount(_ mount: String) throws -> Filesystem {\n let parts = mount.split(separator: \",\")\n if parts.count == 0 {\n throw ContainerizationError(.invalidArgument, message: \"invalid mount format: \\(mount)\")\n }\n var directives = defaultDirectives\n for part in parts {\n let keyVal = part.split(separator: \"=\", maxSplits: 2)\n var key = String(keyVal[0])\n var skipValue = false\n switch key {\n case \"type\", \"size\", \"mode\":\n break\n case \"source\", \"src\":\n key = \"source\"\n case \"destination\", \"dst\", \"target\":\n key = \"destination\"\n case \"readonly\", \"ro\":\n key = \"ro\"\n skipValue = true\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown directive \\(key) when parsing mount \\(mount)\")\n }\n var value = \"\"\n if !skipValue {\n if keyVal.count != 2 {\n throw ContainerizationError(.invalidArgument, message: \"invalid directive format missing value \\(part) in \\(mount)\")\n }\n value = String(keyVal[1])\n }\n directives[key] = value\n }\n\n var fs = Filesystem()\n for (key, val) in directives {\n var val = val\n let type = directives[\"type\"] ?? \"\"\n\n switch key {\n case \"type\":\n if val == \"bind\" {\n val = \"virtiofs\"\n }\n switch val {\n case \"virtiofs\":\n fs.type = Filesystem.FSType.virtiofs\n case \"tmpfs\":\n fs.type = Filesystem.FSType.tmpfs\n default:\n throw ContainerizationError(.invalidArgument, message: \"unsupported mount type \\(val)\")\n }\n\n case \"ro\":\n fs.options.append(\"ro\")\n case \"size\":\n if type != \"tmpfs\" {\n throw ContainerizationError(.invalidArgument, message: \"unsupported option size for \\(type) mount\")\n }\n var overflow: Bool\n var memory = try Parser.memoryString(val)\n (memory, overflow) = memory.multipliedReportingOverflow(by: 1024 * 1024)\n if overflow {\n throw ContainerizationError(.invalidArgument, message: \"overflow encountered when parsing memory string: \\(val)\")\n }\n let s = \"size=\\(memory)\"\n fs.options.append(s)\n case \"mode\":\n if type != \"tmpfs\" {\n throw ContainerizationError(.invalidArgument, message: \"unsupported option mode for \\(type) mount\")\n }\n let s = \"mode=\\(val)\"\n fs.options.append(s)\n case \"source\":\n let absPath = URL(filePath: val).absoluteURL.path\n switch type {\n case \"virtiofs\", \"bind\":\n fs.source = absPath\n case \"tmpfs\":\n throw ContainerizationError(.invalidArgument, message: \"cannot specify source for tmpfs mount\")\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown mount type \\(type)\")\n }\n case \"destination\":\n fs.destination = val\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown mount directive \\(key)\")\n }\n }\n return fs\n }\n\n static func volumes(_ rawVolumes: [String]) throws -> [Filesystem] {\n var mounts: [Filesystem] = []\n for volume in rawVolumes {\n let m = try Parser.volume(volume)\n try Parser.validateMount(m)\n mounts.append(m)\n }\n return mounts\n }\n\n private static func volume(_ volume: String) throws -> Filesystem {\n var vol = volume\n vol.trimLeft(char: \":\")\n\n let parts = vol.split(separator: \":\")\n switch parts.count {\n case 1:\n throw ContainerizationError(.invalidArgument, message: \"anonymous volumes are not supported\")\n case 2, 3:\n // Bind / volume mounts.\n let src = String(parts[0])\n let dst = String(parts[1])\n\n let abs = URL(filePath: src).absoluteURL.path\n if !FileManager.default.fileExists(atPath: abs) {\n throw ContainerizationError(.invalidArgument, message: \"named volumes are not supported\")\n }\n\n var fs = Filesystem.virtiofs(\n source: URL(fileURLWithPath: src).absolutePath(),\n destination: dst,\n options: []\n )\n if parts.count == 3 {\n fs.options = parts[2].split(separator: \",\").map { String($0) }\n }\n return fs\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid volume format \\(volume)\")\n }\n }\n\n static func validMountType(_ type: String) -> Bool {\n mountTypes.contains(type)\n }\n\n static func validateMount(_ mount: Filesystem) throws {\n if !mount.isTmpfs {\n if !mount.source.isAbsolutePath() {\n throw ContainerizationError(\n .invalidArgument, message: \"\\(mount.source) is not an absolute path on the host\")\n }\n if !FileManager.default.fileExists(atPath: mount.source) {\n throw ContainerizationError(.invalidArgument, message: \"file path '\\(mount.source)' does not exist\")\n }\n }\n\n if mount.destination.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"mount destination cannot be empty\")\n }\n }\n\n /// Parse --publish-port arguments into PublishPort objects\n /// The format of each argument is `[host-ip:]host-port:container-port[/protocol]`\n /// (e.g., \"127.0.0.1:8080:80/tcp\")\n ///\n /// - Parameter rawPublishPorts: Array of port arguments\n /// - Returns: Array of PublishPort objects\n /// - Throws: ContainerizationError if parsing fails\n static func publishPorts(_ rawPublishPorts: [String]) throws -> [PublishPort] {\n var sockets: [PublishPort] = []\n\n // Process each raw port string\n for socket in rawPublishPorts {\n let parsedSocket = try Parser.publishPort(socket)\n sockets.append(parsedSocket)\n }\n return sockets\n }\n\n // Parse a single `--publish-port` argument into a `PublishPort`.\n private static func publishPort(_ portText: String) throws -> PublishPort {\n let protoSplit = portText.split(separator: \"/\")\n let proto: PublishProtocol\n let addressAndPortText: String\n switch protoSplit.count {\n case 1:\n addressAndPortText = String(protoSplit[0])\n proto = .tcp\n case 2:\n addressAndPortText = String(protoSplit[0])\n let protoText = String(protoSplit[1])\n guard let parsedProto = PublishProtocol(protoText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish protocol: \\(protoText)\")\n }\n proto = parsedProto\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid publish value: \\(portText)\")\n }\n\n let hostAddress: String\n let hostPortText: String\n let containerPortText: String\n let parts = addressAndPortText.split(separator: \":\")\n switch parts.count {\n case 2:\n hostAddress = \"0.0.0.0\"\n hostPortText = String(parts[0])\n containerPortText = String(parts[1])\n case 3:\n hostAddress = String(parts[0])\n hostPortText = String(parts[1])\n containerPortText = String(parts[2])\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid publish address: \\(portText)\")\n }\n\n guard let hostPort = Int(hostPortText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish host port: \\(hostPortText)\")\n }\n\n guard let containerPort = Int(containerPortText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish container port: \\(containerPortText)\")\n }\n\n return PublishPort(\n hostAddress: hostAddress,\n hostPort: hostPort,\n containerPort: containerPort,\n proto: proto\n )\n }\n\n /// Parse --publish-socket arguments into PublishSocket objects\n /// The format of each argument is `host_path:container_path`\n /// (e.g., \"/tmp/docker.sock:/var/run/docker.sock\")\n ///\n /// - Parameter rawPublishSockets: Array of socket arguments\n /// - Returns: Array of PublishSocket objects\n /// - Throws: ContainerizationError if parsing fails or a path is invalid\n static func publishSockets(_ rawPublishSockets: [String]) throws -> [PublishSocket] {\n var sockets: [PublishSocket] = []\n\n // Process each raw socket string\n for socket in rawPublishSockets {\n let parsedSocket = try Parser.publishSocket(socket)\n sockets.append(parsedSocket)\n }\n return sockets\n }\n\n // Parse a single `--publish-socket`` argument into a `PublishSocket`.\n private static func publishSocket(_ socketText: String) throws -> PublishSocket {\n // Split by colon to two parts: [host_path, container_path]\n let parts = socketText.split(separator: \":\")\n\n switch parts.count {\n case 2:\n // Extract host and container paths\n let hostPath = String(parts[0])\n let containerPath = String(parts[1])\n\n // Validate paths are not empty\n if hostPath.isEmpty {\n throw ContainerizationError(\n .invalidArgument, message: \"host socket path cannot be empty\")\n }\n if containerPath.isEmpty {\n throw ContainerizationError(\n .invalidArgument, message: \"container socket path cannot be empty\")\n }\n\n // Ensure container path must start with /\n if !containerPath.hasPrefix(\"/\") {\n throw ContainerizationError(\n .invalidArgument,\n message: \"container socket path must be absolute: \\(containerPath)\")\n }\n\n // Convert host path to absolute path for consistency\n let hostURL = URL(fileURLWithPath: hostPath)\n let absoluteHostPath = hostURL.absoluteURL.path\n\n // Check if host socket already exists and might be in use\n if FileManager.default.fileExists(atPath: absoluteHostPath) {\n do {\n let attrs = try FileManager.default.attributesOfItem(atPath: absoluteHostPath)\n if let fileType = attrs[.type] as? FileAttributeType, fileType == .typeSocket {\n throw ContainerizationError(\n .invalidArgument,\n message: \"host socket \\(absoluteHostPath) already exists and may be in use\")\n }\n // If it exists but is not a socket, we can remove it and create socket\n try FileManager.default.removeItem(atPath: absoluteHostPath)\n } catch let error as ContainerizationError {\n throw error\n } catch {\n // For other file system errors, continue with creation\n }\n }\n\n // Create host directory if it doesn't exist\n let hostDir = hostURL.deletingLastPathComponent()\n if !FileManager.default.fileExists(atPath: hostDir.path) {\n try FileManager.default.createDirectory(\n at: hostDir, withIntermediateDirectories: true)\n }\n\n // Create and return PublishSocket object with validated paths\n return PublishSocket(\n containerPath: URL(fileURLWithPath: containerPath),\n hostPath: URL(fileURLWithPath: absoluteHostPath),\n permissions: nil\n )\n\n default:\n throw ContainerizationError(\n .invalidArgument,\n message:\n \"invalid publish-socket format \\(socketText). Expected: host_path:container_path\")\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkState.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct NetworkStatus: Codable, Sendable {\n /// The address allocated for the network if no subnet was specified at\n /// creation time; otherwise, the subnet from the configuration.\n public let address: String\n /// The gateway IPv4 address.\n public let gateway: String\n\n public init(\n address: String,\n gateway: String\n ) {\n self.address = address\n self.gateway = gateway\n }\n\n}\n\n/// The configuration and runtime attributes for a network.\npublic enum NetworkState: Codable, Sendable {\n // The network has been configured.\n case created(NetworkConfiguration)\n // The network is running.\n case running(NetworkConfiguration, NetworkStatus)\n\n public var state: String {\n switch self {\n case .created: \"created\"\n case .running: \"running\"\n }\n }\n\n public var id: String {\n switch self {\n case .created(let configuration): configuration.id\n case .running(let configuration, _): configuration.id\n }\n }\n}\n"], ["/container/Sources/APIServer/Networks/NetworksHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nstruct NetworksHarness: Sendable {\n let log: Logging.Logger\n let service: NetworksService\n\n init(service: NetworksService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let containers = try await service.list()\n let data = try JSONEncoder().encode(containers)\n\n let reply = message.reply()\n reply.set(key: .networkStates, value: data)\n return reply\n }\n\n @Sendable\n func create(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .networkConfig)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"network configuration cannot be empty\")\n }\n\n let config = try JSONDecoder().decode(NetworkConfiguration.self, from: data)\n let networkState = try await service.create(configuration: config)\n\n let networkData = try JSONEncoder().encode(networkState)\n\n let reply = message.reply()\n reply.set(key: .networkState, value: networkData)\n return reply\n }\n\n @Sendable\n func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .networkId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"id cannot be empty\")\n }\n try await service.delete(id: id)\n\n return message.reply()\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientImage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\n// MARK: ClientImage structure\n\npublic struct ClientImage: Sendable {\n private let contentStore: ContentStore = RemoteContentStoreClient()\n public let description: ImageDescription\n\n public var digest: String { description.digest }\n public var descriptor: Descriptor { description.descriptor }\n public var reference: String { description.reference }\n\n public init(description: ImageDescription) {\n self.description = description\n }\n\n /// Returns the underlying OCI index for the image.\n public func index() async throws -> Index {\n guard let content: Content = try await contentStore.get(digest: description.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(description.digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the manifest for the specified platform.\n public func manifest(for platform: Platform) async throws -> Manifest {\n let index = try await self.index()\n let desc = index.manifests.first { desc in\n desc.platform == platform\n }\n guard let desc else {\n throw ContainerizationError(.unsupported, message: \"Platform \\(platform.description)\")\n }\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the OCI config for the specified platform.\n public func config(for platform: Platform) async throws -> ContainerizationOCI.Image {\n let manifest = try await self.manifest(for: platform)\n let desc = manifest.config\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n return try content.decode()\n }\n}\n\n// MARK: ClientImage constants\n\nextension ClientImage {\n private static let serviceIdentifier = \"com.apple.container.core.container-core-images\"\n public static let initImageRef = ClientDefaults.get(key: .defaultInitImage)\n\n private static func newXPCClient() -> XPCClient {\n XPCClient(service: Self.serviceIdentifier)\n }\n\n private static func newRequest(_ route: ImagesServiceXPCRoute) -> XPCMessage {\n XPCMessage(route: route)\n }\n\n private static var defaultRegistryDomain: String {\n ClientDefaults.get(key: .defaultRegistryDomain)\n }\n}\n\n// MARK: Static methods\n\nextension ClientImage {\n private static let legacyDockerRegistryHost = \"docker.io\"\n private static let dockerRegistryHost = \"registry-1.docker.io\"\n private static let defaultDockerRegistryRepo = \"library\"\n\n public static func normalizeReference(_ ref: String) throws -> String {\n guard ref != Self.initImageRef else {\n // Don't modify the default init image reference.\n // This is to allow for easier local development against\n // an updated containerization.\n return ref\n }\n // Check if the input reference has a domain specified\n var updatedRawReference: String = ref\n let r = try Reference.parse(ref)\n if r.domain == nil {\n updatedRawReference = \"\\(Self.defaultRegistryDomain)/\\(ref)\"\n }\n\n let updatedReference = try Reference.parse(updatedRawReference)\n\n // Handle adding the :latest tag if it isn't specified,\n // as well as adding the \"library/\" repository if it isn't set only if the host is docker.io\n updatedReference.normalize()\n return updatedReference.description\n }\n\n public static func denormalizeReference(_ ref: String) throws -> String {\n var updatedRawReference: String = ref\n let r = try Reference.parse(ref)\n let defaultRegistry = Self.defaultRegistryDomain\n if r.domain == defaultRegistry {\n updatedRawReference = \"\\(r.path)\"\n if let tag = r.tag {\n updatedRawReference += \":\\(tag)\"\n } else if let digest = r.digest {\n updatedRawReference += \"@\\(digest)\"\n }\n if defaultRegistry == dockerRegistryHost || defaultRegistry == legacyDockerRegistryHost {\n updatedRawReference.trimPrefix(\"\\(defaultDockerRegistryRepo)/\")\n }\n }\n return updatedRawReference\n }\n\n public static func list() async throws -> [ClientImage] {\n let client = newXPCClient()\n let request = newRequest(.imageList)\n let response = try await client.send(request)\n\n let imageDescriptions = try response.imageDescriptions()\n return imageDescriptions.map { desc in\n ClientImage(description: desc)\n }\n }\n\n public static func get(names: [String]) async throws -> (images: [ClientImage], error: [String]) {\n let all = try await self.list()\n var errors: [String] = []\n var found: [ClientImage] = []\n for name in names {\n do {\n guard let img = try Self._search(reference: name, in: all) else {\n errors.append(name)\n continue\n }\n found.append(img)\n } catch {\n errors.append(name)\n }\n }\n return (found, errors)\n }\n\n public static func get(reference: String) async throws -> ClientImage {\n let all = try await self.list()\n guard let found = try self._search(reference: reference, in: all) else {\n throw ContainerizationError(.notFound, message: \"Image with reference \\(reference)\")\n }\n return found\n }\n\n private static func _search(reference: String, in all: [ClientImage]) throws -> ClientImage? {\n let locallyBuiltImage = try {\n // Check if we have an image whose index descriptor contains the image name\n // as an annotation. Prefer this in all cases, since these are locally built images.\n let r = try Reference.parse(reference)\n r.normalize()\n let withDefaultTag = r.description\n\n let localImageMatches = all.filter { $0.description.nameFromAnnotation() == withDefaultTag }\n guard localImageMatches.count > 1 else {\n return localImageMatches.first\n }\n // More than one image matched. Check against the tagged reference\n return localImageMatches.first { $0.reference == withDefaultTag }\n }()\n if let locallyBuiltImage {\n return locallyBuiltImage\n }\n // If we don't find a match, try matching `ImageDescription.name` against the given\n // input string, while also checking against its normalized form.\n // Return the first match.\n let normalizedReference = try Self.normalizeReference(reference)\n return all.first(where: { image in\n image.reference == reference || image.reference == normalizedReference\n })\n }\n\n public static func pull(reference: String, platform: Platform? = nil, scheme: RequestScheme = .auto, progressUpdate: ProgressUpdateHandler? = nil) async throws -> ClientImage {\n let client = newXPCClient()\n let request = newRequest(.imagePull)\n\n let reference = try self.normalizeReference(reference)\n guard let host = try Reference.parse(reference).domain else {\n throw ContainerizationError(.invalidArgument, message: \"Could not extract host from reference \\(reference)\")\n }\n\n request.set(key: .imageReference, value: reference)\n try request.set(platform: platform)\n\n let insecure = try scheme.schemeFor(host: host) == .http\n request.set(key: .insecureFlag, value: insecure)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n\n let response = try await client.send(request)\n let description = try response.imageDescription()\n let image = ClientImage(description: description)\n\n await progressUpdateClient?.finish()\n return image\n }\n\n public static func delete(reference: String, garbageCollect: Bool = false) async throws {\n let client = newXPCClient()\n let request = newRequest(.imageDelete)\n request.set(key: .imageReference, value: reference)\n request.set(key: .garbageCollect, value: garbageCollect)\n let _ = try await client.send(request)\n }\n\n public static func load(from tarFile: String) async throws -> [ClientImage] {\n let client = newXPCClient()\n let request = newRequest(.imageLoad)\n request.set(key: .filePath, value: tarFile)\n let reply = try await client.send(request)\n\n let loaded = try reply.imageDescriptions()\n return loaded.map { desc in\n ClientImage(description: desc)\n }\n }\n\n public static func pruneImages() async throws -> ([String], UInt64) {\n let client = newXPCClient()\n let request = newRequest(.imagePrune)\n let response = try await client.send(request)\n let digests = try response.digests()\n let size = response.uint64(key: .size)\n return (digests, size)\n }\n\n public static func fetch(reference: String, platform: Platform? = nil, scheme: RequestScheme = .auto, progressUpdate: ProgressUpdateHandler? = nil) async throws -> ClientImage\n {\n do {\n let match = try await self.get(reference: reference)\n if let platform {\n // The image exists, but we dont know if we have the right platform pulled\n // Check if we do, if not pull the requested platform\n _ = try await match.config(for: platform)\n }\n return match\n } catch let err as ContainerizationError {\n guard err.isCode(.notFound) else {\n throw err\n }\n return try await Self.pull(reference: reference, platform: platform, scheme: scheme, progressUpdate: progressUpdate)\n }\n }\n}\n\n// MARK: Instance methods\n\nextension ClientImage {\n public func push(platform: Platform? = nil, scheme: RequestScheme, progressUpdate: ProgressUpdateHandler?) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imagePush)\n\n guard let host = try Reference.parse(reference).domain else {\n throw ContainerizationError(.invalidArgument, message: \"Could not extract host from reference \\(reference)\")\n }\n request.set(key: .imageReference, value: reference)\n\n let insecure = try scheme.schemeFor(host: host) == .http\n request.set(key: .insecureFlag, value: insecure)\n\n try request.set(platform: platform)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n _ = try await client.send(request)\n await progressUpdateClient?.finish()\n }\n\n @discardableResult\n public func tag(new: String) async throws -> ClientImage {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageTag)\n request.set(key: .imageReference, value: self.description.reference)\n request.set(key: .imageNewReference, value: new)\n let reply = try await client.send(request)\n let description = try reply.imageDescription()\n return ClientImage(description: description)\n }\n\n // MARK: Snapshot Methods\n\n public func save(out: String, platform: Platform? = nil) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageSave)\n try request.set(description: self.description)\n request.set(key: .filePath, value: out)\n try request.set(platform: platform)\n let _ = try await client.send(request)\n }\n\n public func unpack(platform: Platform?, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageUnpack)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n\n try await client.send(request)\n\n await progressUpdateClient?.finish()\n }\n\n public func deleteSnapshot(platform: Platform?) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.snapshotDelete)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n try await client.send(request)\n }\n\n public func getSnapshot(platform: Platform) async throws -> Filesystem {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.snapshotGet)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n let response = try await client.send(request)\n let fs = try response.filesystem()\n return fs\n }\n\n @discardableResult\n public func getCreateSnapshot(platform: Platform, progressUpdate: ProgressUpdateHandler? = nil) async throws -> Filesystem {\n do {\n return try await self.getSnapshot(platform: platform)\n } catch let err as ContainerizationError {\n guard err.code == .notFound else {\n throw err\n }\n try await self.unpack(platform: platform, progressUpdate: progressUpdate)\n return try await self.getSnapshot(platform: platform)\n }\n }\n}\n\nextension XPCMessage {\n fileprivate func set(description: ImageDescription) throws {\n let descData = try JSONEncoder().encode(description)\n self.set(key: .imageDescription, value: descData)\n }\n\n fileprivate func set(descriptions: [ImageDescription]) throws {\n let descData = try JSONEncoder().encode(descriptions)\n self.set(key: .imageDescriptions, value: descData)\n }\n\n fileprivate func set(platform: Platform?) throws {\n guard let platform else {\n return\n }\n let platformData = try JSONEncoder().encode(platform)\n self.set(key: .ociPlatform, value: platformData)\n }\n\n fileprivate func imageDescription() throws -> ImageDescription {\n let responseData = self.dataNoCopy(key: .imageDescription)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"imageDescription not received\")\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: responseData)\n return description\n }\n\n fileprivate func imageDescriptions() throws -> [ImageDescription] {\n let responseData = self.dataNoCopy(key: .imageDescriptions)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"imageDescriptions not received\")\n }\n let descriptions = try JSONDecoder().decode([ImageDescription].self, from: responseData)\n return descriptions\n }\n\n fileprivate func filesystem() throws -> Filesystem {\n let responseData = self.dataNoCopy(key: .filesystem)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"filesystem not received\")\n }\n let fs = try JSONDecoder().decode(Filesystem.self, from: responseData)\n return fs\n }\n\n fileprivate func digests() throws -> [String] {\n let responseData = self.dataNoCopy(key: .digests)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"digests not received\")\n }\n let digests = try JSONDecoder().decode([String].self, from: responseData)\n return digests\n }\n}\n\nextension ImageDescription {\n fileprivate func nameFromAnnotation() -> String? {\n guard let annotations = self.descriptor.annotations else {\n return nil\n }\n guard let name = annotations[AnnotationKeys.containerizationImageName] else {\n return nil\n }\n return name\n }\n}\n"], ["/container/Sources/ContainerPersistence/EntityStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nlet metadataFilename: String = \"entity.json\"\n\npublic protocol EntityStore {\n associatedtype T: Codable & Identifiable & Sendable\n\n func list() async throws -> [T]\n func create(_ entity: T) async throws\n func retrieve(_ id: String) async throws -> T?\n func update(_ entity: T) async throws\n func upsert(_ entity: T) async throws\n func delete(_ id: String) async throws\n}\n\npublic actor FilesystemEntityStore: EntityStore where T: Codable & Identifiable & Sendable {\n typealias Index = [String: T]\n\n private let path: URL\n private let type: String\n private var index: Index\n private let log: Logger\n private let encoder = JSONEncoder()\n\n public init(path: URL, type: String, log: Logger) throws {\n self.path = path\n self.type = type\n self.log = log\n self.index = try Self.load(path: path, log: log)\n }\n\n public func list() async throws -> [T] {\n Array(index.values)\n }\n\n public func create(_ entity: T) async throws {\n let metadataUrl = metadataUrl(entity.id)\n guard !FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.exists, message: \"Entity \\(entity.id) already exist\")\n }\n\n try FileManager.default.createDirectory(at: entityUrl(entity.id), withIntermediateDirectories: true)\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func retrieve(_ id: String) throws -> T? {\n index[id]\n }\n\n public func update(_ entity: T) async throws {\n let metadataUrl: URL = metadataUrl(entity.id)\n guard FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.notFound, message: \"Entity \\(entity.id) not found\")\n }\n\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func upsert(_ entity: T) async throws {\n let metadataUrl: URL = metadataUrl(entity.id)\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func delete(_ id: String) async throws {\n let metadataUrl = entityUrl(id)\n guard FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.notFound, message: \"entity \\(id) not found\")\n }\n try FileManager.default.removeItem(at: metadataUrl)\n index.removeValue(forKey: id)\n }\n\n public func entityUrl(_ id: String) -> URL {\n path.appendingPathComponent(id)\n }\n\n private static func load(path: URL, log: Logger) throws -> Index {\n let directories = try FileManager.default.contentsOfDirectory(at: path, includingPropertiesForKeys: nil)\n var index: FilesystemEntityStore.Index = Index()\n let decoder = JSONDecoder()\n\n for entityUrl in directories {\n do {\n let metadataUrl = entityUrl.appendingPathComponent(metadataFilename)\n let data = try Data(contentsOf: metadataUrl)\n let entity = try decoder.decode(T.self, from: data)\n index[entity.id] = entity\n } catch {\n log.warning(\n \"failed to load entity, ignoring\",\n metadata: [\n \"path\": \"\\(entityUrl)\"\n ])\n }\n }\n\n return index\n }\n\n private func metadataUrl(_ id: String) -> URL {\n entityUrl(id).appendingPathComponent(metadataFilename)\n }\n}\n"], ["/container/Sources/CLI/BuildCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerBuild\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport NIO\nimport TerminalProgress\n\nextension Application {\n struct BuildCommand: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"build\"\n config.abstract = \"Build an image from a Dockerfile\"\n config._superCommandName = \"container\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64 = 2\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n var memory: String = \"2048MB\"\n\n @Option(name: .long, help: ArgumentHelp(\"Set build-time variables\", valueName: \"key=val\"))\n var buildArg: [String] = []\n\n @Argument(help: \"Build directory\")\n var contextDir: String = \".\"\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Path to Dockerfile\", valueName: \"path\"))\n var file: String = \"Dockerfile\"\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Set a label\", valueName: \"key=val\"))\n var label: [String] = []\n\n @Flag(name: .long, help: \"Do not use cache\")\n var noCache: Bool = false\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Output configuration for the build\", valueName: \"value\"))\n var output: [String] = {\n [\"type=oci\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Cache imports for the build\", valueName: \"value\", visibility: .hidden))\n var cacheIn: [String] = {\n []\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Cache exports for the build\", valueName: \"value\", visibility: .hidden))\n var cacheOut: [String] = {\n []\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"set the build architecture\", valueName: \"value\"))\n var arch: [String] = {\n [\"arm64\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"set the build os\", valueName: \"value\"))\n var os: [String] = {\n [\"linux\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Progress type - one of [auto|plain|tty]\", valueName: \"type\"))\n var progress: String = \"auto\"\n\n @Option(name: .long, help: ArgumentHelp(\"Builder-shim vsock port\", valueName: \"port\"))\n var vsockPort: UInt32 = 8088\n\n @Option(name: [.customShort(\"t\"), .customLong(\"tag\")], help: ArgumentHelp(\"Name for the built image\", valueName: \"name\"))\n var targetImageName: String = UUID().uuidString.lowercased()\n\n @Option(name: .long, help: ArgumentHelp(\"Set the target build stage\", valueName: \"stage\"))\n var target: String = \"\"\n\n @Flag(name: .shortAndLong, help: \"Suppress build output\")\n var quiet: Bool = false\n\n func run() async throws {\n do {\n let timeout: Duration = .seconds(300)\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Dialing builder\")\n\n let builder: Builder? = try await withThrowingTaskGroup(of: Builder.self) { group in\n defer {\n group.cancelAll()\n }\n\n group.addTask {\n while true {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n let fh = try await container.dial(self.vsockPort)\n\n let threadGroup: MultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n let b = try Builder(socket: fh, group: threadGroup)\n\n // If this call succeeds, then BuildKit is running.\n let _ = try await b.info()\n return b\n } catch {\n // If we get here, \"Dialing builder\" is shown for such a short period\n // of time that it's invisible to the user.\n progress.set(tasks: 0)\n progress.set(totalTasks: 3)\n\n try await BuilderStart.start(\n cpus: self.cpus,\n memory: self.memory,\n progressUpdate: progress.handler\n )\n\n // wait (seconds) for builder to start listening on vsock\n try await Task.sleep(for: .seconds(5))\n continue\n }\n }\n }\n\n group.addTask {\n try await Task.sleep(for: timeout)\n throw ValidationError(\n \"\"\"\n Timeout waiting for connection to builder\n \"\"\"\n )\n }\n\n return try await group.next()\n }\n\n guard let builder else {\n throw ValidationError(\"builder is not running\")\n }\n\n let dockerfile = try Data(contentsOf: URL(filePath: file))\n let exportPath = Application.appRoot.appendingPathComponent(\".build\")\n\n let buildID = UUID().uuidString\n let tempURL = exportPath.appendingPathComponent(buildID)\n try FileManager.default.createDirectory(at: tempURL, withIntermediateDirectories: true, attributes: nil)\n defer {\n try? FileManager.default.removeItem(at: tempURL)\n }\n\n let imageName: String = try {\n let parsedReference = try Reference.parse(targetImageName)\n parsedReference.normalize()\n return parsedReference.description\n }()\n\n var terminal: Terminal?\n switch self.progress {\n case \"tty\":\n terminal = try Terminal(descriptor: STDERR_FILENO)\n case \"auto\":\n terminal = try? Terminal(descriptor: STDERR_FILENO)\n case \"plain\":\n terminal = nil\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid progress mode \\(self.progress)\")\n }\n\n defer { terminal?.tryReset() }\n\n let exports: [Builder.BuildExport] = try output.map { output in\n var exp = try Builder.BuildExport(from: output)\n if exp.destination == nil {\n exp.destination = tempURL.appendingPathComponent(\"out.tar\")\n }\n return exp\n }\n\n try await withThrowingTaskGroup(of: Void.self) { [terminal] group in\n defer {\n group.cancelAll()\n }\n group.addTask {\n let handler = AsyncSignalHandler.create(notify: [SIGTERM, SIGINT, SIGUSR1, SIGUSR2])\n for await sig in handler.signals {\n throw ContainerizationError(.interrupted, message: \"exiting on signal \\(sig)\")\n }\n }\n let platforms: [Platform] = try {\n var results: [Platform] = []\n for o in self.os {\n for a in self.arch {\n guard let platform = try? Platform(from: \"\\(o)/\\(a)\") else {\n throw ValidationError(\"invalid os/architecture combination \\(o)/\\(a)\")\n }\n results.append(platform)\n }\n }\n return results\n }()\n group.addTask { [terminal] in\n let config = ContainerBuild.Builder.BuildConfig(\n buildID: buildID,\n contentStore: RemoteContentStoreClient(),\n buildArgs: buildArg,\n contextDir: contextDir,\n dockerfile: dockerfile,\n labels: label,\n noCache: noCache,\n platforms: platforms,\n terminal: terminal,\n tag: imageName,\n target: target,\n quiet: quiet,\n exports: exports,\n cacheIn: cacheIn,\n cacheOut: cacheOut\n )\n progress.finish()\n\n try await builder.build(config)\n }\n\n try await group.next()\n }\n\n let unpackProgressConfig = try ProgressConfig(\n description: \"Unpacking built image\",\n itemsName: \"entries\",\n showTasks: exports.count > 1,\n totalTasks: exports.count\n )\n let unpackProgress = ProgressBar(config: unpackProgressConfig)\n defer {\n unpackProgress.finish()\n }\n unpackProgress.start()\n\n var finalMessage = \"Successfully built \\(imageName)\"\n let taskManager = ProgressTaskCoordinator()\n // Currently, only a single export can be specified.\n for exp in exports {\n unpackProgress.add(tasks: 1)\n let unpackTask = await taskManager.startTask()\n switch exp.type {\n case \"oci\":\n try Task.checkCancellation()\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let loaded = try await ClientImage.load(from: dest.absolutePath())\n\n for image in loaded {\n try Task.checkCancellation()\n try await image.unpack(platform: nil, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: unpackProgress.handler))\n }\n case \"tar\":\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let tarURL = tempURL.appendingPathComponent(\"out.tar\")\n try FileManager.default.moveItem(at: tarURL, to: dest)\n finalMessage = \"Successfully exported to \\(dest.absolutePath())\"\n case \"local\":\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let localDir = tempURL.appendingPathComponent(\"local\")\n\n guard FileManager.default.fileExists(atPath: localDir.path) else {\n throw ContainerizationError(.invalidArgument, message: \"expected local output not found\")\n }\n try FileManager.default.copyItem(at: localDir, to: dest)\n finalMessage = \"Successfully exported to \\(dest.absolutePath())\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid exporter \\(exp.rawValue)\")\n }\n }\n await taskManager.finish()\n unpackProgress.finish()\n print(finalMessage)\n } catch {\n throw NSError(domain: \"Build\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"\\(error)\"])\n }\n }\n\n func validate() throws {\n guard FileManager.default.fileExists(atPath: file) else {\n throw ValidationError(\"Dockerfile does not exist at path: \\(file)\")\n }\n guard FileManager.default.fileExists(atPath: contextDir) else {\n throw ValidationError(\"context dir does not exist \\(contextDir)\")\n }\n guard let _ = try? Reference.parse(targetImageName) else {\n throw ValidationError(\"invalid reference \\(targetImageName)\")\n }\n }\n }\n}\n"], ["/container/Sources/Helpers/Images/ImagesHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerImagesService\nimport ContainerImagesServiceClient\nimport ContainerLog\nimport ContainerXPC\nimport Containerization\nimport Foundation\nimport Logging\n\n@main\nstruct ImagesHelper: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"container-core-images\",\n abstract: \"XPC service for managing OCI images\",\n version: releaseVersion(),\n subcommands: [\n Start.self\n ]\n )\n}\n\nextension ImagesHelper {\n struct Start: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Starts the image plugin\"\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .long, help: \"XPC service prefix\")\n var serviceIdentifier: String = \"com.apple.container.core.container-core-images\"\n\n @Option(name: .shortAndLong, help: \"Daemon root directory\")\n var root = Self.appRoot.path\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n private static let unpackStrategy = SnapshotStore.defaultUnpackStrategy\n\n func run() async throws {\n let commandName = ImagesHelper._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n do {\n log.info(\"configuring XPC server\")\n let root = URL(filePath: root)\n var routes = [String: XPCServer.RouteHandler]()\n try self.initializeContentService(root: root, log: log, routes: &routes)\n try self.initializeImagesService(root: root, log: log, routes: &routes)\n let xpc = XPCServer(\n identifier: serviceIdentifier,\n routes: routes,\n log: log\n )\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n ImagesHelper.exit(withError: error)\n }\n }\n\n private func initializeImagesService(root: URL, log: Logger, routes: inout [String: XPCServer.RouteHandler]) throws {\n let contentStore = RemoteContentStoreClient()\n let imageStore = try ImageStore(path: root, contentStore: contentStore)\n let snapshotStore = try SnapshotStore(path: root, unpackStrategy: Self.unpackStrategy, log: log)\n let service = try ImagesService(contentStore: contentStore, imageStore: imageStore, snapshotStore: snapshotStore, log: log)\n let harness = ImagesServiceHarness(service: service, log: log)\n\n routes[ImagesServiceXPCRoute.imagePull.rawValue] = harness.pull\n routes[ImagesServiceXPCRoute.imageList.rawValue] = harness.list\n routes[ImagesServiceXPCRoute.imageDelete.rawValue] = harness.delete\n routes[ImagesServiceXPCRoute.imageTag.rawValue] = harness.tag\n routes[ImagesServiceXPCRoute.imagePush.rawValue] = harness.push\n routes[ImagesServiceXPCRoute.imageSave.rawValue] = harness.save\n routes[ImagesServiceXPCRoute.imageLoad.rawValue] = harness.load\n routes[ImagesServiceXPCRoute.imageUnpack.rawValue] = harness.unpack\n routes[ImagesServiceXPCRoute.imagePrune.rawValue] = harness.prune\n routes[ImagesServiceXPCRoute.snapshotDelete.rawValue] = harness.deleteSnapshot\n routes[ImagesServiceXPCRoute.snapshotGet.rawValue] = harness.getSnapshot\n }\n\n private func initializeContentService(root: URL, log: Logger, routes: inout [String: XPCServer.RouteHandler]) throws {\n let service = try ContentStoreService(root: root, log: log)\n let harness = ContentServiceHarness(service: service, log: log)\n\n routes[ImagesServiceXPCRoute.contentClean.rawValue] = harness.clean\n routes[ImagesServiceXPCRoute.contentGet.rawValue] = harness.get\n routes[ImagesServiceXPCRoute.contentDelete.rawValue] = harness.delete\n routes[ImagesServiceXPCRoute.contentIngestStart.rawValue] = harness.newIngestSession\n routes[ImagesServiceXPCRoute.contentIngestCancel.rawValue] = harness.cancelIngestSession\n routes[ImagesServiceXPCRoute.contentIngestComplete.rawValue] = harness.completeIngestSession\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"ImagesHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n return log\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIO\nimport NIOHPACK\nimport NIOHTTP2\n\npublic struct Builder: Sendable {\n let client: BuilderClientProtocol\n let clientAsync: BuilderClientAsyncProtocol\n let group: EventLoopGroup\n let builderShimSocket: FileHandle\n let channel: GRPCChannel\n\n public init(socket: FileHandle, group: EventLoopGroup) throws {\n try socket.setSendBufSize(4 << 20)\n try socket.setRecvBufSize(2 << 20)\n var config = ClientConnection.Configuration.default(\n target: .connectedSocket(socket.fileDescriptor),\n eventLoopGroup: group\n )\n config.connectionIdleTimeout = TimeAmount(.seconds(600))\n config.connectionKeepalive = .init(\n interval: TimeAmount(.seconds(600)),\n timeout: TimeAmount(.seconds(500)),\n permitWithoutCalls: true\n )\n config.connectionBackoff = .init(\n initialBackoff: TimeInterval(1),\n maximumBackoff: TimeInterval(10)\n )\n config.callStartBehavior = .fastFailure\n config.httpMaxFrameSize = 8 << 10\n config.maximumReceiveMessageLength = 512 << 20\n config.httpTargetWindowSize = 16 << 10\n\n let channel = ClientConnection(configuration: config)\n self.channel = channel\n self.clientAsync = BuilderClientAsync(channel: channel)\n self.client = BuilderClient(channel: channel)\n self.group = group\n self.builderShimSocket = socket\n }\n\n public func info() throws -> InfoResponse {\n let resp = self.client.info(InfoRequest(), callOptions: CallOptions())\n return try resp.response.wait()\n }\n\n public func info() async throws -> InfoResponse {\n let opts = CallOptions(timeLimit: .timeout(.seconds(30)))\n return try await self.clientAsync.info(InfoRequest(), callOptions: opts)\n }\n\n // TODO\n // - Symlinks in build context dir\n // - cache-to, cache-from\n // - output (other than the default OCI image output, e.g., local, tar, Docker)\n public func build(_ config: BuildConfig) async throws {\n var continuation: AsyncStream.Continuation?\n let reqStream = AsyncStream { (cont: AsyncStream.Continuation) in\n continuation = cont\n }\n guard let continuation else {\n throw Error.invalidContinuation\n }\n\n defer {\n continuation.finish()\n }\n\n if let terminal = config.terminal {\n Task {\n let winchHandler = AsyncSignalHandler.create(notify: [SIGWINCH])\n let setWinch = { (rows: UInt16, cols: UInt16) in\n var winch = ClientStream()\n winch.command = .init()\n if let cmdString = try TerminalCommand(rows: rows, cols: cols).json() {\n winch.command.command = cmdString\n continuation.yield(winch)\n }\n }\n let size = try terminal.size\n var width = size.width\n var height = size.height\n try setWinch(height, width)\n\n for await _ in winchHandler.signals {\n let size = try terminal.size\n let cols = size.width\n let rows = size.height\n if cols != width || rows != height {\n width = cols\n height = rows\n try setWinch(height, width)\n }\n }\n }\n }\n\n let respStream = self.clientAsync.performBuild(reqStream, callOptions: try CallOptions(config))\n let pipeline = try await BuildPipeline(config)\n do {\n try await pipeline.run(sender: continuation, receiver: respStream)\n } catch Error.buildComplete {\n _ = channel.close()\n try await group.shutdownGracefully()\n return\n }\n }\n\n public struct BuildExport: Sendable {\n public let type: String\n public var destination: URL?\n public let additionalFields: [String: String]\n public let rawValue: String\n\n public init(type: String, destination: URL?, additionalFields: [String: String], rawValue: String) {\n self.type = type\n self.destination = destination\n self.additionalFields = additionalFields\n self.rawValue = rawValue\n }\n\n public init(from input: String) throws {\n var typeValue: String?\n var destinationValue: URL?\n var additionalFields: [String: String] = [:]\n\n let pairs = input.components(separatedBy: \",\")\n for pair in pairs {\n let parts = pair.components(separatedBy: \"=\")\n guard parts.count == 2 else { continue }\n\n let key = parts[0].trimmingCharacters(in: .whitespaces)\n let value = parts[1].trimmingCharacters(in: .whitespaces)\n\n switch key {\n case \"type\":\n typeValue = value\n case \"dest\":\n destinationValue = try Self.resolveDestination(dest: value)\n default:\n additionalFields[key] = value\n }\n }\n\n guard let type = typeValue else {\n throw Builder.Error.invalidExport(input, \"type field is required\")\n }\n\n switch type {\n case \"oci\":\n break\n case \"tar\":\n if destinationValue == nil {\n throw Builder.Error.invalidExport(input, \"dest field is required\")\n }\n case \"local\":\n if destinationValue == nil {\n throw Builder.Error.invalidExport(input, \"dest field is required\")\n }\n default:\n throw Builder.Error.invalidExport(input, \"unsupported output type\")\n }\n\n self.init(type: type, destination: destinationValue, additionalFields: additionalFields, rawValue: input)\n }\n\n public var stringValue: String {\n get throws {\n var components = [\"type=\\(type)\"]\n\n switch type {\n case \"oci\", \"tar\", \"local\":\n break // ignore destination\n default:\n throw Builder.Error.invalidExport(rawValue, \"unsupported output type\")\n }\n\n for (key, value) in additionalFields {\n components.append(\"\\(key)=\\(value)\")\n }\n\n return components.joined(separator: \",\")\n }\n }\n\n static func resolveDestination(dest: String) throws -> URL {\n let destination = URL(fileURLWithPath: dest)\n let fileManager = FileManager.default\n\n if fileManager.fileExists(atPath: destination.path) {\n let resourceValues = try destination.resourceValues(forKeys: [.isDirectoryKey])\n let isDir = resourceValues.isDirectory\n if isDir != nil && isDir == false {\n throw Builder.Error.invalidExport(dest, \"dest path already exists\")\n }\n\n var finalDestination = destination.appendingPathComponent(\"out.tar\")\n var index = 1\n while fileManager.fileExists(atPath: finalDestination.path) {\n let path = \"out.tar.\\(index)\"\n finalDestination = destination.appendingPathComponent(path)\n index += 1\n }\n return finalDestination\n } else {\n let parentDirectory = destination.deletingLastPathComponent()\n try? fileManager.createDirectory(at: parentDirectory, withIntermediateDirectories: true, attributes: nil)\n }\n\n return destination\n }\n }\n\n public struct BuildConfig: Sendable {\n public let buildID: String\n public let contentStore: ContentStore\n public let buildArgs: [String]\n public let contextDir: String\n public let dockerfile: Data\n public let labels: [String]\n public let noCache: Bool\n public let platforms: [Platform]\n public let terminal: Terminal?\n public let tag: String\n public let target: String\n public let quiet: Bool\n public let exports: [BuildExport]\n public let cacheIn: [String]\n public let cacheOut: [String]\n\n public init(\n buildID: String,\n contentStore: ContentStore,\n buildArgs: [String],\n contextDir: String,\n dockerfile: Data,\n labels: [String],\n noCache: Bool,\n platforms: [Platform],\n terminal: Terminal?,\n tag: String,\n target: String,\n quiet: Bool,\n exports: [BuildExport],\n cacheIn: [String],\n cacheOut: [String],\n ) {\n self.buildID = buildID\n self.contentStore = contentStore\n self.buildArgs = buildArgs\n self.contextDir = contextDir\n self.dockerfile = dockerfile\n self.labels = labels\n self.noCache = noCache\n self.platforms = platforms\n self.terminal = terminal\n self.tag = tag\n self.target = target\n self.quiet = quiet\n self.exports = exports\n self.cacheIn = cacheIn\n self.cacheOut = cacheOut\n }\n }\n}\n\nextension Builder {\n enum Error: Swift.Error, CustomStringConvertible {\n case invalidContinuation\n case buildComplete\n case invalidExport(String, String)\n\n var description: String {\n switch self {\n case .invalidContinuation:\n return \"continuation could not created\"\n case .buildComplete:\n return \"build completed\"\n case .invalidExport(let exp, let reason):\n return \"export entry \\(exp) is invalid: \\(reason)\"\n }\n }\n }\n}\n\nextension CallOptions {\n public init(_ config: Builder.BuildConfig) throws {\n var headers: [(String, String)] = [\n (\"build-id\", config.buildID),\n (\"context\", URL(filePath: config.contextDir).path(percentEncoded: false)),\n (\"dockerfile\", config.dockerfile.base64EncodedString()),\n (\"progress\", config.terminal != nil ? \"tty\" : \"plain\"),\n (\"tag\", config.tag),\n (\"target\", config.target),\n ]\n for platform in config.platforms {\n headers.append((\"platforms\", platform.description))\n }\n if config.noCache {\n headers.append((\"no-cache\", \"\"))\n }\n for label in config.labels {\n headers.append((\"labels\", label))\n }\n for buildArg in config.buildArgs {\n headers.append((\"build-args\", buildArg))\n }\n for output in config.exports {\n headers.append((\"outputs\", try output.stringValue))\n }\n for cacheIn in config.cacheIn {\n headers.append((\"cache-in\", cacheIn))\n }\n for cacheOut in config.cacheOut {\n headers.append((\"cache-out\", cacheOut))\n }\n\n self.init(\n customMetadata: HPACKHeaders(headers)\n )\n }\n}\n\nextension FileHandle {\n @discardableResult\n func setSendBufSize(_ bytes: Int) throws -> Int {\n try setSockOpt(\n level: SOL_SOCKET,\n name: SO_SNDBUF,\n value: bytes)\n return bytes\n }\n\n @discardableResult\n func setRecvBufSize(_ bytes: Int) throws -> Int {\n try setSockOpt(\n level: SOL_SOCKET,\n name: SO_RCVBUF,\n value: bytes)\n return bytes\n }\n\n private func setSockOpt(level: Int32, name: Int32, value: Int) throws {\n var v = Int32(value)\n let res = withUnsafePointer(to: &v) { ptr -> Int32 in\n ptr.withMemoryRebound(\n to: UInt8.self,\n capacity: MemoryLayout.size\n ) { raw in\n #if canImport(Darwin)\n return setsockopt(\n self.fileDescriptor,\n level, name,\n raw,\n socklen_t(MemoryLayout.size))\n #else\n fatalError(\"unsupported platform\")\n #endif\n }\n }\n if res == -1 {\n throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EPERM)\n }\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/ExitMonitor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\n/// Track when long running work exits, and notify the caller via a callback.\npublic actor ExitMonitor {\n /// A callback that receives the client identifier and exit code.\n public typealias ExitCallback = @Sendable (String, Int32) async throws -> Void\n\n /// A function that waits for work to complete, returning an exit code.\n public typealias WaitHandler = @Sendable () async throws -> Int32\n\n /// Create a new monitor.\n ///\n /// - Parameters:\n /// - log: The destination for log messages.\n public init(log: Logger? = nil) {\n self.log = log\n }\n\n private var exitCallbacks: [String: ExitCallback] = [:]\n private var runningTasks: [String: Task] = [:]\n private let log: Logger?\n\n /// Remove tracked work from the monitor.\n ///\n /// - Parameters:\n /// - id: The client identifier for the tracked work.\n public func stopTracking(id: String) async {\n if let task = self.runningTasks[id] {\n task.cancel()\n }\n exitCallbacks.removeValue(forKey: id)\n runningTasks.removeValue(forKey: id)\n }\n\n /// Register long running work so that the monitor invokes\n /// a callback when the work completes.\n ///\n /// - Parameters:\n /// - id: The client identifier for the work.\n /// - onExit: The callback to invoke when the work completes.\n public func registerProcess(id: String, onExit: @escaping ExitCallback) async throws {\n guard self.exitCallbacks[id] == nil else {\n throw ContainerizationError(.invalidState, message: \"ExitMonitor already setup for process \\(id)\")\n }\n self.exitCallbacks[id] = onExit\n }\n\n /// Await the completion of previously registered item of work.\n ///\n /// - Parameters:\n /// - id: The client identifier for the work.\n /// - waitingOn: A function that waits for the work to complete,\n /// and then returns an exit code.\n public func track(id: String, waitingOn: @escaping WaitHandler) async throws {\n guard let onExit = self.exitCallbacks[id] else {\n throw ContainerizationError(.invalidState, message: \"ExitMonitor not setup for process \\(id)\")\n }\n guard self.runningTasks[id] == nil else {\n throw ContainerizationError(.invalidState, message: \"Already have a running task tracking process \\(id)\")\n }\n self.runningTasks[id] = Task {\n do {\n let exitStatus = try await waitingOn()\n try await onExit(id, exitStatus)\n } catch {\n self.log?.error(\"WaitHandler for \\(id) threw error \\(String(describing: error))\")\n try? await onExit(id, -1)\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/HostDNSResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n/// Functions for managing local DNS domains for containers.\npublic struct HostDNSResolver {\n public static let defaultConfigPath = URL(filePath: \"/etc/resolver\")\n\n // prefix used to mark our files as /etc/resolver/{prefix}{domainName}\n private static let containerizationPrefix = \"containerization.\"\n\n private let configURL: URL\n\n public init(configURL: URL = Self.defaultConfigPath) {\n self.configURL = configURL\n }\n\n /// Creates a DNS resolver configuration file for domain resolved by the application.\n public func createDomain(name: String) throws {\n let path = self.configURL.appending(path: \"\\(Self.containerizationPrefix)\\(name)\").path\n let fm: FileManager = FileManager.default\n\n if fm.fileExists(atPath: self.configURL.path) {\n guard let isDir = try self.configURL.resourceValues(forKeys: [.isDirectoryKey]).isDirectory, isDir else {\n throw ContainerizationError(.invalidState, message: \"expected \\(self.configURL.path) to be a directory, but found a file\")\n }\n } else {\n try fm.createDirectory(at: self.configURL, withIntermediateDirectories: true)\n }\n\n guard !fm.fileExists(atPath: path) else {\n throw ContainerizationError(.exists, message: \"domain \\(name) already exists\")\n }\n\n let resolverText = \"\"\"\n domain \\(name)\n search \\(name)\n nameserver 127.0.0.1\n port 2053\n \"\"\"\n\n do {\n try resolverText.write(toFile: path, atomically: true, encoding: .utf8)\n } catch {\n throw ContainerizationError(.invalidState, message: \"failed to write resolver configuration for \\(name)\")\n }\n }\n\n /// Removes a DNS resolver configuration file for domain resolved by the application.\n public func deleteDomain(name: String) throws {\n let path = self.configURL.appending(path: \"\\(Self.containerizationPrefix)\\(name)\").path\n let fm = FileManager.default\n guard fm.fileExists(atPath: path) else {\n throw ContainerizationError(.notFound, message: \"domain \\(name) at \\(path) not found\")\n }\n\n do {\n try fm.removeItem(atPath: path)\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot delete domain (try sudo?)\")\n }\n }\n\n /// Lists application-created local DNS domains.\n public func listDomains() -> [String] {\n let fm: FileManager = FileManager.default\n guard\n let resolverPaths = try? fm.contentsOfDirectory(\n at: self.configURL,\n includingPropertiesForKeys: [.isDirectoryKey]\n )\n else {\n return []\n }\n\n return\n resolverPaths\n .filter { $0.lastPathComponent.starts(with: Self.containerizationPrefix) }\n .compactMap { try? getDomainFromResolver(url: $0) }\n .sorted()\n }\n\n /// Reinitializes the macOS DNS daemon.\n public static func reinitialize() throws {\n do {\n let kill = Foundation.Process()\n kill.executableURL = URL(fileURLWithPath: \"/usr/bin/killall\")\n kill.arguments = [\"-HUP\", \"mDNSResponder\"]\n\n let null = FileHandle.nullDevice\n kill.standardOutput = null\n kill.standardError = null\n\n try kill.run()\n kill.waitUntilExit()\n let status = kill.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(.internalError, message: \"mDNSResponder restart failed with status \\(status)\")\n }\n }\n }\n\n private func getDomainFromResolver(url: URL) throws -> String? {\n let text = try String(contentsOf: url, encoding: .utf8)\n for line in text.components(separatedBy: .newlines) {\n let trimmed = line.trimmingCharacters(in: .whitespaces)\n let components = trimmed.split(whereSeparator: { $0.isWhitespace })\n guard components.count == 2 else {\n continue\n }\n guard components[0] == \"domain\" else {\n continue\n }\n\n return String(components[1])\n }\n\n return nil\n }\n}\n"], ["/container/Sources/ContainerClient/SandboxClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport TerminalProgress\n\n/// A client for interacting with a single sandbox.\npublic struct SandboxClient: Sendable, Codable {\n static let label = \"com.apple.container.runtime\"\n\n public static func machServiceLabel(runtime: String, id: String) -> String {\n \"\\(Self.label).\\(runtime).\\(id)\"\n }\n\n private var machServiceLabel: String {\n Self.machServiceLabel(runtime: runtime, id: id)\n }\n\n let id: String\n let runtime: String\n\n /// Create a container.\n public init(id: String, runtime: String) {\n self.id = id\n self.runtime = runtime\n }\n}\n\n// Runtime Methods\nextension SandboxClient {\n public func bootstrap() async throws {\n let request = XPCMessage(route: SandboxRoutes.bootstrap.rawValue)\n let client = createClient()\n defer { client.close() }\n\n try await client.send(request)\n }\n\n public func state() async throws -> SandboxSnapshot {\n let request = XPCMessage(route: SandboxRoutes.state.rawValue)\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.sandboxSnapshot()\n }\n\n public func createProcess(_ id: String, config: ProcessConfiguration) async throws {\n let request = XPCMessage(route: SandboxRoutes.createProcess.rawValue)\n request.set(key: .id, value: id)\n let data = try JSONEncoder().encode(config)\n request.set(key: .processConfig, value: data)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func startProcess(_ id: String, stdio: [FileHandle?]) async throws {\n let request = XPCMessage(route: SandboxRoutes.start.rawValue)\n for (i, h) in stdio.enumerated() {\n let key: XPCKeys = {\n switch i {\n case 0: .stdin\n case 1: .stdout\n case 2: .stderr\n default:\n fatalError(\"invalid fd \\(i)\")\n }\n }()\n\n if let h {\n request.set(key: key, value: h)\n }\n }\n request.set(key: .id, value: id)\n\n let client = createClient()\n defer { client.close() }\n\n try await client.send(request)\n }\n\n public func stop(options: ContainerStopOptions) async throws {\n let request = XPCMessage(route: SandboxRoutes.stop.rawValue)\n\n let data = try JSONEncoder().encode(options)\n request.set(key: .stopOptions, value: data)\n\n let client = createClient()\n defer { client.close() }\n let responseTimeout = Duration(.seconds(Int64(options.timeoutInSeconds + 1)))\n try await client.send(request, responseTimeout: responseTimeout)\n }\n\n public func kill(_ id: String, signal: Int64) async throws {\n let request = XPCMessage(route: SandboxRoutes.kill.rawValue)\n request.set(key: .id, value: id)\n request.set(key: .signal, value: signal)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func resize(_ id: String, size: Terminal.Size) async throws {\n let request = XPCMessage(route: SandboxRoutes.resize.rawValue)\n request.set(key: .id, value: id)\n request.set(key: .width, value: UInt64(size.width))\n request.set(key: .height, value: UInt64(size.height))\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func wait(_ id: String) async throws -> Int32 {\n let request = XPCMessage(route: SandboxRoutes.wait.rawValue)\n request.set(key: .id, value: id)\n\n let client = createClient()\n defer { client.close() }\n let response = try await client.send(request)\n let code = response.int64(key: .exitCode)\n return Int32(code)\n }\n\n public func dial(_ port: UInt32) async throws -> FileHandle {\n let request = XPCMessage(route: SandboxRoutes.dial.rawValue)\n request.set(key: .port, value: UInt64(port))\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n guard let fh = response.fileHandle(key: .fd) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get fd for vsock port \\(port)\"\n )\n }\n return fh\n }\n\n private func createClient() -> XPCClient {\n XPCClient(service: machServiceLabel)\n }\n}\n\nextension XPCMessage {\n public func id() throws -> String {\n let id = self.string(key: .id)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"No id\")\n }\n return id\n }\n\n func sandboxSnapshot() throws -> SandboxSnapshot {\n let data = self.dataNoCopy(key: .snapshot)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No state data returned\")\n }\n return try JSONDecoder().decode(SandboxSnapshot.self, from: data)\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginLoader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\npublic struct PluginLoader: Sendable {\n // A path on disk managed by the PluginLoader, where it stores\n // runtime data for loaded plugins. This includes the launchd plists\n // and logs files.\n private let defaultPluginResourcePath: URL\n\n private let pluginDirectories: [URL]\n\n private let pluginFactories: [PluginFactory]\n\n private let log: Logger?\n\n public typealias PluginQualifier = ((Plugin) -> Bool)\n\n public init(pluginDirectories: [URL], pluginFactories: [PluginFactory], defaultResourcePath: URL, log: Logger? = nil) {\n self.pluginDirectories = pluginDirectories\n self.pluginFactories = pluginFactories\n self.log = log\n self.defaultPluginResourcePath = defaultResourcePath\n }\n\n static public func defaultPluginResourcePath(root: URL) -> URL {\n root.appending(path: \"plugin-state\")\n }\n\n static public func userPluginsDir(root: URL) -> URL {\n root\n .appending(path: \"libexec\")\n .appending(path: \"container-plugins\")\n .resolvingSymlinksInPath()\n }\n}\n\nextension PluginLoader {\n public func alterCLIHelpText(original: String) -> String {\n var plugins = findPlugins()\n plugins = plugins.filter { $0.config.isCLI }\n guard !plugins.isEmpty else {\n return original\n }\n\n var lines = original.split(separator: \"\\n\").map { String($0) }\n\n let sectionHeader = \"PLUGINS:\"\n lines.append(sectionHeader)\n\n for plugin in plugins {\n let helpText = plugin.helpText(padding: 24)\n lines.append(helpText)\n }\n\n return lines.joined(separator: \"\\n\")\n }\n\n public func findPlugins() -> [Plugin] {\n let fm = FileManager.default\n\n var pluginNames = Set()\n var plugins: [Plugin] = []\n\n for pluginDir in pluginDirectories {\n if !fm.fileExists(atPath: pluginDir.path) {\n continue\n }\n\n guard\n var dirs = try? fm.contentsOfDirectory(\n at: pluginDir,\n includingPropertiesForKeys: [.isDirectoryKey],\n options: .skipsHiddenFiles\n )\n else {\n continue\n }\n dirs = dirs.filter {\n $0.isDirectory\n }\n\n for installURL in dirs {\n do {\n guard\n let plugin = try\n (pluginFactories.compactMap {\n try $0.create(installURL: installURL)\n }.first)\n else {\n log?.warning(\n \"Not installing plugin with missing configuration\",\n metadata: [\n \"path\": \"\\(installURL.path)\"\n ]\n )\n continue\n }\n\n guard !pluginNames.contains(plugin.name) else {\n log?.warning(\n \"Not installing shadowed plugin\",\n metadata: [\n \"path\": \"\\(installURL.path)\",\n \"name\": \"\\(plugin.name)\",\n ])\n continue\n }\n\n plugins.append(plugin)\n pluginNames.insert(plugin.name)\n } catch {\n log?.warning(\n \"Not installing plugin with invalid configuration\",\n metadata: [\n \"path\": \"\\(installURL.path)\",\n \"error\": \"\\(error)\",\n ]\n )\n }\n }\n }\n\n return plugins\n }\n\n public func findPlugin(name: String, log: Logger? = nil) -> Plugin? {\n do {\n return\n try pluginDirectories\n .compactMap { installURL in\n try pluginFactories.compactMap { try $0.create(installURL: installURL.appending(path: name)) }.first\n }\n .first\n } catch {\n log?.warning(\n \"Not installing plugin with invalid configuration\",\n metadata: [\n \"name\": \"\\(name)\",\n \"error\": \"\\(error)\",\n ]\n )\n return nil\n }\n }\n}\n\nextension PluginLoader {\n public func registerWithLaunchd(\n plugin: Plugin,\n rootURL: URL? = nil,\n args: [String]? = nil,\n instanceId: String? = nil\n ) throws {\n // We only care about loading plugins that have a service\n // to expose; otherwise, they may just be CLI commands.\n guard let serviceConfig = plugin.config.servicesConfig else {\n return\n }\n\n let id = plugin.getLaunchdLabel(instanceId: instanceId)\n log?.info(\"Registering plugin\", metadata: [\"id\": \"\\(id)\"])\n let rootURL = rootURL ?? self.defaultPluginResourcePath.appending(path: plugin.name)\n try FileManager.default.createDirectory(at: rootURL, withIntermediateDirectories: true)\n let env = ProcessInfo.processInfo.environment.filter { key, _ in\n key.hasPrefix(\"CONTAINER_\")\n }\n let logUrl = rootURL.appendingPathComponent(\"service.log\")\n let plist = LaunchPlist(\n label: id,\n arguments: [plugin.binaryURL.path] + (args ?? serviceConfig.defaultArguments),\n environment: env,\n limitLoadToSessionType: [.Aqua, .Background, .System],\n runAtLoad: serviceConfig.runAtLoad,\n stdout: logUrl.path,\n stderr: logUrl.path,\n machServices: plugin.getMachServices(instanceId: instanceId)\n )\n\n let plistUrl = rootURL.appendingPathComponent(\"service.plist\")\n let data = try plist.encode()\n try data.write(to: plistUrl)\n try ServiceManager.register(plistPath: plistUrl.path)\n }\n\n public func deregisterWithLaunchd(plugin: Plugin, instanceId: String? = nil) throws {\n // We only care about loading plugins that have a service\n // to expose; otherwise, they may just be CLI commands.\n guard plugin.config.servicesConfig != nil else {\n return\n }\n let domain = try ServiceManager.getDomainString()\n let label = \"\\(domain)/\\(plugin.getLaunchdLabel(instanceId: instanceId))\"\n log?.info(\"Deregistering plugin\", metadata: [\"id\": \"\\(plugin.getLaunchdLabel())\"])\n try ServiceManager.deregister(fullServiceLabel: label)\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\n\npublic struct XPCClient: Sendable {\n private nonisolated(unsafe) let connection: xpc_connection_t\n private let q: DispatchQueue?\n private let service: String\n\n public init(service: String, queue: DispatchQueue? = nil) {\n let connection = xpc_connection_create_mach_service(service, queue, 0)\n self.connection = connection\n self.q = queue\n self.service = service\n\n xpc_connection_set_event_handler(connection) { _ in }\n xpc_connection_set_target_queue(connection, self.q)\n xpc_connection_activate(connection)\n }\n}\n\nextension XPCClient {\n /// Close the underlying XPC connection.\n public func close() {\n xpc_connection_cancel(connection)\n }\n\n /// Returns the pid of process to which we have a connection.\n /// Note: `xpc_connection_get_pid` returns 0 if no activity\n /// has taken place on the connection prior to it being called.\n public func remotePid() -> pid_t {\n xpc_connection_get_pid(self.connection)\n }\n\n /// Send the provided message to the service.\n @discardableResult\n public func send(_ message: XPCMessage, responseTimeout: Duration? = nil) async throws -> XPCMessage {\n try await withThrowingTaskGroup(of: XPCMessage.self, returning: XPCMessage.self) { group in\n if let responseTimeout {\n group.addTask {\n try await Task.sleep(for: responseTimeout)\n let route = message.string(key: XPCMessage.routeKey) ?? \"nil\"\n throw ContainerizationError(.internalError, message: \"XPC timeout for request to \\(self.service)/\\(route)\")\n }\n }\n\n group.addTask {\n try await withCheckedThrowingContinuation { cont in\n xpc_connection_send_message_with_reply(self.connection, message.underlying, nil) { reply in\n do {\n let message = try self.parseReply(reply)\n cont.resume(returning: message)\n } catch {\n cont.resume(throwing: error)\n }\n }\n }\n }\n\n let response = try await group.next()\n // once one task has finished, cancel the rest.\n group.cancelAll()\n // we don't really care about the second error here\n // as it's most likely a `CancellationError`.\n try? await group.waitForAll()\n\n guard let response else {\n throw ContainerizationError(.invalidState, message: \"failed to receive XPC response\")\n }\n return response\n }\n }\n\n private func parseReply(_ reply: xpc_object_t) throws -> XPCMessage {\n switch xpc_get_type(reply) {\n case XPC_TYPE_ERROR:\n var code = ContainerizationError.Code.invalidState\n if reply.connectionError {\n code = .interrupted\n }\n throw ContainerizationError(\n code,\n message: \"XPC connection error: \\(reply.errorDescription ?? \"unknown\")\"\n )\n case XPC_TYPE_DICTIONARY:\n let message = XPCMessage(object: reply)\n // check errors from our protocol\n try message.error()\n return message\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(reply))\")\n }\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerBuild/BuildFSSync.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport ContainerClient\nimport ContainerizationArchive\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\n\nactor BuildFSSync: BuildPipelineHandler {\n let contextDir: URL\n\n init(_ contextDir: URL) throws {\n guard FileManager.default.fileExists(atPath: contextDir.cleanPath) else {\n throw Error.contextNotFound(contextDir.cleanPath)\n }\n guard try contextDir.isDir() else {\n throw Error.contextIsNotDirectory(contextDir.cleanPath)\n }\n\n self.contextDir = contextDir\n }\n\n nonisolated func accept(_ packet: ServerStream) throws -> Bool {\n guard let buildTransfer = packet.getBuildTransfer() else {\n return false\n }\n guard buildTransfer.stage() == \"fssync\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let buildTransfer = packet.getBuildTransfer() else {\n throw Error.buildTransferMissing\n }\n guard let method = buildTransfer.method() else {\n throw Error.methodMissing\n }\n switch try FSSyncMethod(method) {\n case .read:\n try await self.read(sender, buildTransfer, packet.buildID)\n case .info:\n try await self.info(sender, buildTransfer, packet.buildID)\n case .walk:\n try await self.walk(sender, buildTransfer, packet.buildID)\n }\n }\n\n func read(_ sender: AsyncStream.Continuation, _ packet: BuildTransfer, _ buildID: String) async throws {\n let offset: UInt64 = packet.offset() ?? 0\n let size: Int = packet.len() ?? 0\n var path: URL\n if packet.source.hasPrefix(\"/\") {\n path = URL(fileURLWithPath: packet.source).standardizedFileURL\n } else {\n path =\n contextDir\n .appendingPathComponent(packet.source)\n .standardizedFileURL\n }\n if !FileManager.default.fileExists(atPath: path.cleanPath) {\n path = URL(filePath: self.contextDir.cleanPath)\n path.append(components: packet.source.cleanPathComponent)\n }\n let data = try {\n if try path.isDir() {\n return Data()\n }\n let file = try LocalContent(path: path.standardizedFileURL)\n return try file.data(offset: offset, length: size) ?? Data()\n }()\n\n let transfer = try path.buildTransfer(id: packet.id, contextDir: self.contextDir, complete: true, data: data)\n var response = ClientStream()\n response.buildID = buildID\n response.buildTransfer = transfer\n response.packetType = .buildTransfer(transfer)\n sender.yield(response)\n }\n\n func info(_ sender: AsyncStream.Continuation, _ packet: BuildTransfer, _ buildID: String) async throws {\n let path: URL\n if packet.source.hasPrefix(\"/\") {\n path = URL(fileURLWithPath: packet.source).standardizedFileURL\n } else {\n path =\n contextDir\n .appendingPathComponent(packet.source)\n .standardizedFileURL\n }\n let transfer = try path.buildTransfer(id: packet.id, contextDir: self.contextDir, complete: true)\n var response = ClientStream()\n response.buildID = buildID\n response.buildTransfer = transfer\n response.packetType = .buildTransfer(transfer)\n sender.yield(response)\n }\n\n private struct DirEntry: Hashable {\n let url: URL\n let isDirectory: Bool\n let relativePath: String\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(relativePath)\n }\n\n static func == (lhs: DirEntry, rhs: DirEntry) -> Bool {\n lhs.relativePath == rhs.relativePath\n }\n }\n\n func walk(\n _ sender: AsyncStream.Continuation,\n _ packet: BuildTransfer,\n _ buildID: String\n ) async throws {\n let wantsTar = packet.mode() == \"tar\"\n\n var entries: [String: Set] = [:]\n let followPaths: [String] = packet.followPaths() ?? []\n\n let followPathsWalked = try walk(root: self.contextDir, includePatterns: followPaths)\n for url in followPathsWalked {\n guard self.contextDir.absoluteURL.cleanPath != url.absoluteURL.cleanPath else {\n continue\n }\n guard self.contextDir.parentOf(url) else {\n continue\n }\n\n let relPath = try url.relativeChildPath(to: contextDir)\n let parentPath = try url.deletingLastPathComponent().relativeChildPath(to: contextDir)\n let entry = DirEntry(url: url, isDirectory: url.hasDirectoryPath, relativePath: relPath)\n entries[parentPath, default: []].insert(entry)\n\n if url.isSymlink {\n let target: URL = url.resolvingSymlinksInPath()\n if self.contextDir.parentOf(target) {\n let relPath = try target.relativeChildPath(to: self.contextDir)\n let entry = DirEntry(url: target, isDirectory: target.hasDirectoryPath, relativePath: relPath)\n let parentPath: String = try target.deletingLastPathComponent().relativeChildPath(to: self.contextDir)\n entries[parentPath, default: []].insert(entry)\n }\n }\n }\n\n var fileOrder = [String]()\n try processDirectory(\"\", inputEntries: entries, processedPaths: &fileOrder)\n\n if !wantsTar {\n let fileInfos = try fileOrder.map { rel -> FileInfo in\n try FileInfo(path: contextDir.appendingPathComponent(rel), contextDir: contextDir)\n }\n\n let data = try JSONEncoder().encode(fileInfos)\n let transfer = BuildTransfer(\n id: packet.id,\n source: packet.source,\n complete: true,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"json\",\n ],\n data: data\n )\n var resp = ClientStream()\n resp.buildID = buildID\n resp.buildTransfer = transfer\n resp.packetType = .buildTransfer(transfer)\n sender.yield(resp)\n return\n }\n\n let tarURL = URL.temporaryDirectory\n .appendingPathComponent(UUID().uuidString + \".tar\")\n\n defer { try? FileManager.default.removeItem(at: tarURL) }\n\n let writerCfg = ArchiveWriterConfiguration(\n format: .paxRestricted,\n filter: .none)\n\n try Archiver.compress(\n source: contextDir,\n destination: tarURL,\n writerConfiguration: writerCfg\n ) { url in\n guard let rel = try? url.relativeChildPath(to: contextDir) else {\n return nil\n }\n\n guard let parent = try? url.deletingLastPathComponent().relativeChildPath(to: self.contextDir) else {\n return nil\n }\n\n guard let items = entries[parent] else {\n return nil\n }\n\n let include = items.contains { item in\n item.relativePath == rel\n }\n\n guard include else {\n return nil\n }\n\n return Archiver.ArchiveEntryInfo(\n pathOnHost: url,\n pathInArchive: URL(fileURLWithPath: rel))\n }\n\n for try await chunk in try tarURL.bufferedCopyReader() {\n let part = BuildTransfer(\n id: packet.id,\n source: tarURL.path,\n complete: false,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"tar\",\n ],\n data: chunk\n )\n var resp = ClientStream()\n resp.buildID = buildID\n resp.buildTransfer = part\n resp.packetType = .buildTransfer(part)\n sender.yield(resp)\n }\n\n let done = BuildTransfer(\n id: packet.id,\n source: tarURL.path,\n complete: true,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"tar\",\n ],\n data: Data()\n )\n\n var finalResp = ClientStream()\n finalResp.buildID = buildID\n finalResp.buildTransfer = done\n finalResp.packetType = .buildTransfer(done)\n sender.yield(finalResp)\n }\n\n func walk(root: URL, includePatterns: [String]) throws -> [URL] {\n let globber = Globber(root)\n\n for p in includePatterns {\n try globber.match(p)\n }\n return Array(globber.results)\n }\n\n private func processDirectory(\n _ currentDir: String,\n inputEntries: [String: Set],\n processedPaths: inout [String]\n ) throws {\n guard let entries = inputEntries[currentDir] else {\n return\n }\n\n // Sort purely by lexicographical order of relativePath\n let sortedEntries = entries.sorted { $0.relativePath < $1.relativePath }\n\n for entry in sortedEntries {\n processedPaths.append(entry.relativePath)\n\n if entry.isDirectory {\n try processDirectory(\n entry.relativePath,\n inputEntries: inputEntries,\n processedPaths: &processedPaths\n )\n }\n }\n }\n\n struct FileInfo: Codable {\n let name: String\n let modTime: String\n let mode: UInt32\n let size: UInt64\n let isDir: Bool\n let uid: UInt32\n let gid: UInt32\n let target: String\n\n init(path: URL, contextDir: URL) throws {\n if path.isSymlink {\n let target: URL = path.resolvingSymlinksInPath()\n if contextDir.parentOf(target) {\n self.target = target.relativePathFrom(from: path)\n } else {\n self.target = target.cleanPath\n }\n } else {\n self.target = \"\"\n }\n\n self.name = try path.relativeChildPath(to: contextDir)\n self.modTime = try path.modTime()\n self.mode = try path.mode()\n self.size = try path.size()\n self.isDir = path.hasDirectoryPath\n self.uid = 0\n self.gid = 0\n }\n }\n\n enum FSSyncMethod: String {\n case read = \"Read\"\n case info = \"Info\"\n case walk = \"Walk\"\n\n init(_ method: String) throws {\n switch method {\n case \"Read\":\n self = .read\n case \"Info\":\n self = .info\n case \"Walk\":\n self = .walk\n default:\n throw Error.unknownMethod(method)\n }\n }\n }\n}\n\nextension BuildFSSync {\n enum Error: Swift.Error, CustomStringConvertible, Equatable {\n case buildTransferMissing\n case methodMissing\n case unknownMethod(String)\n case contextNotFound(String)\n case contextIsNotDirectory(String)\n case couldNotDetermineFileSize(String)\n case couldNotDetermineModTime(String)\n case couldNotDetermineFileMode(String)\n case invalidOffsetSizeForFile(String, UInt64, Int)\n case couldNotDetermineUID(String)\n case couldNotDetermineGID(String)\n case pathIsNotChild(String, String)\n\n var description: String {\n switch self {\n case .buildTransferMissing:\n return \"buildTransfer field missing in packet\"\n case .methodMissing:\n return \"method is missing in request\"\n case .unknownMethod(let m):\n return \"unknown content-store method \\(m)\"\n case .contextNotFound(let path):\n return \"context dir \\(path) not found\"\n case .contextIsNotDirectory(let path):\n return \"context \\(path) not a directory\"\n case .couldNotDetermineFileSize(let path):\n return \"could not determine size of file \\(path)\"\n case .couldNotDetermineModTime(let path):\n return \"could not determine last modified time of \\(path)\"\n case .couldNotDetermineFileMode(let path):\n return \"could not determine posix permissions (FileMode) of \\(path)\"\n case .invalidOffsetSizeForFile(let digest, let offset, let size):\n return \"invalid request for file: \\(digest) with offset: \\(offset) size: \\(size)\"\n case .couldNotDetermineUID(let path):\n return \"could not determine UID of file at path: \\(path)\"\n case .couldNotDetermineGID(let path):\n return \"could not determine GID of file at path: \\(path)\"\n case .pathIsNotChild(let path, let parent):\n return \"\\(path) is not a child of \\(parent)\"\n }\n }\n }\n}\n\nextension BuildTransfer {\n fileprivate init(id: String, source: String, complete: Bool, isDir: Bool, metadata: [String: String], data: Data? = nil) {\n self.init()\n self.id = id\n self.source = source\n self.direction = .outof\n self.complete = complete\n self.metadata = metadata\n self.isDirectory = isDir\n if let data {\n self.data = data\n }\n }\n}\n\nextension URL {\n fileprivate func size() throws -> UInt64 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let size = attrs[FileAttributeKey.size] as? UInt64 {\n return size\n }\n throw BuildFSSync.Error.couldNotDetermineFileSize(self.cleanPath)\n }\n\n fileprivate func modTime() throws -> String {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let date = attrs[FileAttributeKey.modificationDate] as? Date {\n return date.rfc3339()\n }\n throw BuildFSSync.Error.couldNotDetermineModTime(self.cleanPath)\n }\n\n fileprivate func isDir() throws -> Bool {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n guard let t = attrs[.type] as? FileAttributeType, t == .typeDirectory else {\n return false\n }\n return true\n }\n\n fileprivate func mode() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let mode = attrs[FileAttributeKey.posixPermissions] as? NSNumber {\n return mode.uint32Value\n }\n throw BuildFSSync.Error.couldNotDetermineFileMode(self.cleanPath)\n }\n\n fileprivate func uid() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let uid = attrs[.ownerAccountID] as? UInt32 {\n return uid\n }\n throw BuildFSSync.Error.couldNotDetermineUID(self.cleanPath)\n }\n\n fileprivate func gid() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let gid = attrs[.groupOwnerAccountID] as? UInt32 {\n return gid\n }\n throw BuildFSSync.Error.couldNotDetermineGID(self.cleanPath)\n }\n\n fileprivate func buildTransfer(\n id: String,\n contextDir: URL? = nil,\n complete: Bool = false,\n data: Data = Data()\n ) throws -> BuildTransfer {\n let p = try {\n if let contextDir { return try self.relativeChildPath(to: contextDir) }\n return self.cleanPath\n }()\n return BuildTransfer(\n id: id,\n source: String(p),\n complete: complete,\n isDir: try self.isDir(),\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": String(try self.mode()),\n \"size\": String(try self.size()),\n \"modified_at\": try self.modTime(),\n \"uid\": String(try self.uid()),\n \"gid\": String(try self.gid()),\n ],\n data: data\n )\n }\n}\n\nextension Date {\n fileprivate func rfc3339() -> String {\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"yyyy-MM-dd'T'HH:mm:ssZZZZZ\"\n dateFormatter.locale = Locale(identifier: \"en_US_POSIX\")\n dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // Adjust if necessary\n\n return dateFormatter.string(from: self)\n }\n}\n\nextension String {\n var cleanPathComponent: String {\n let trimmed = self.trimmingCharacters(in: CharacterSet(charactersIn: \"/\"))\n if let clean = trimmed.removingPercentEncoding {\n return clean\n }\n return trimmed\n }\n}\n"], ["/container/Sources/CLI/System/SystemStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nextension Application {\n struct SystemStop: AsyncParsableCommand {\n private static let stopTimeoutSeconds: Int32 = 5\n private static let shutdownTimeoutSeconds: Int32 = 20\n\n static let configuration = CommandConfiguration(\n commandName: \"stop\",\n abstract: \"Stop all `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Launchd prefix for `container` services\")\n var prefix: String = \"com.apple.container.\"\n\n func run() async throws {\n let log = Logger(\n label: \"com.apple.container.cli\",\n factory: { label in\n StreamLogHandler.standardOutput(label: label)\n }\n )\n\n let launchdDomainString = try ServiceManager.getDomainString()\n let fullLabel = \"\\(launchdDomainString)/\\(prefix)apiserver\"\n\n log.info(\"stopping containers\", metadata: [\"stopTimeoutSeconds\": \"\\(Self.stopTimeoutSeconds)\"])\n do {\n let containers = try await ClientContainer.list()\n let signal = try Signals.parseSignal(\"SIGTERM\")\n let opts = ContainerStopOptions(timeoutInSeconds: Self.stopTimeoutSeconds, signal: signal)\n let failed = try await ContainerStop.stopContainers(containers: containers, stopOptions: opts)\n if !failed.isEmpty {\n log.warning(\"some containers could not be stopped gracefully\", metadata: [\"ids\": \"\\(failed)\"])\n }\n\n } catch {\n log.warning(\"failed to stop all containers\", metadata: [\"error\": \"\\(error)\"])\n }\n\n log.info(\"waiting for containers to exit\")\n do {\n for _ in 0.. Unpacker?\n\n public static let defaultUnpackStrategy: UnpackStrategy = { image, platform in\n guard platform.os == \"linux\" else {\n return nil\n }\n var minBlockSize = 512.gib()\n if image.reference == ClientDefaults.get(key: .defaultInitImage) {\n minBlockSize = 512.mib()\n }\n return EXT4Unpacker(blockSizeInBytes: minBlockSize)\n }\n\n let path: URL\n let fm = FileManager.default\n let ingestDir: URL\n let unpackStrategy: UnpackStrategy\n let log: Logger?\n\n public init(path: URL, unpackStrategy: @escaping UnpackStrategy, log: Logger?) throws {\n let root = path.appendingPathComponent(\"snapshots\")\n self.path = root\n self.ingestDir = self.path.appendingPathComponent(Self.ingestDirName)\n self.unpackStrategy = unpackStrategy\n self.log = log\n try self.fm.createDirectory(at: root, withIntermediateDirectories: true)\n try self.fm.createDirectory(at: self.ingestDir, withIntermediateDirectories: true)\n }\n\n public func unpack(image: Containerization.Image, platform: Platform? = nil, progressUpdate: ProgressUpdateHandler?) async throws {\n var toUnpack: [Descriptor] = []\n if let platform {\n let desc = try await image.descriptor(for: platform)\n toUnpack = [desc]\n } else {\n toUnpack = try await image.unpackableDescriptors()\n }\n\n let taskManager = ProgressTaskCoordinator()\n var taskUpdateProgress: ProgressUpdateHandler?\n\n for desc in toUnpack {\n try Task.checkCancellation()\n let snapshotDir = self.snapshotDir(desc)\n guard !self.fm.fileExists(atPath: snapshotDir.absolutePath()) else {\n // We have already unpacked this image + platform. Skip\n continue\n }\n guard let platform = desc.platform else {\n throw ContainerizationError(.internalError, message: \"Missing platform for descriptor \\(desc.digest)\")\n }\n guard let unpacker = try await self.unpackStrategy(image, platform) else {\n self.log?.warning(\"Skipping unpack for \\(image.reference) for platform \\(platform.description). No unpacker configured.\")\n continue\n }\n let currentSubTask = await taskManager.startTask()\n if let progressUpdate {\n let _taskUpdateProgress = ProgressTaskCoordinator.handler(for: currentSubTask, from: progressUpdate)\n await _taskUpdateProgress([\n .setSubDescription(\"for platform \\(platform.description)\")\n ])\n taskUpdateProgress = _taskUpdateProgress\n }\n\n let tempDir = try self.tempUnpackDir()\n\n let tempSnapshotPath = tempDir.appendingPathComponent(Self.snapshotFileName, isDirectory: false)\n let infoPath = tempDir.appendingPathComponent(Self.snapshotInfoFileName, isDirectory: false)\n do {\n let progress = ContainerizationProgressAdapter.handler(from: taskUpdateProgress)\n let mount = try await unpacker.unpack(image, for: platform, at: tempSnapshotPath, progress: progress)\n let fs = Filesystem.block(\n format: mount.type,\n source: self.snapshotPath(desc).absolutePath(),\n destination: mount.destination,\n options: mount.options\n )\n let snapshotInfo = try JSONEncoder().encode(fs)\n self.fm.createFile(atPath: infoPath.absolutePath(), contents: snapshotInfo)\n } catch {\n try? self.fm.removeItem(at: tempDir)\n throw error\n }\n do {\n try fm.moveItem(at: tempDir, to: snapshotDir)\n } catch let err as NSError {\n guard err.code == NSFileWriteFileExistsError else {\n throw err\n }\n try? self.fm.removeItem(at: tempDir)\n }\n }\n await taskManager.finish()\n }\n\n public func delete(for image: Containerization.Image, platform: Platform? = nil) async throws {\n var toDelete: [Descriptor] = []\n if let platform {\n let desc = try await image.descriptor(for: platform)\n toDelete.append(desc)\n } else {\n toDelete = try await image.unpackableDescriptors()\n }\n for desc in toDelete {\n let p = self.snapshotDir(desc)\n guard self.fm.fileExists(atPath: p.absolutePath()) else {\n continue\n }\n try self.fm.removeItem(at: p)\n }\n }\n\n public func get(for image: Containerization.Image, platform: Platform) async throws -> Filesystem {\n let desc = try await image.descriptor(for: platform)\n let infoPath = snapshotInfoPath(desc)\n let fsPath = snapshotPath(desc)\n\n guard self.fm.fileExists(atPath: infoPath.absolutePath()),\n self.fm.fileExists(atPath: fsPath.absolutePath())\n else {\n throw ContainerizationError(.notFound, message: \"image snapshot for \\(image.reference) with platform \\(platform.description)\")\n }\n let decoder = JSONDecoder()\n let data = try Data(contentsOf: infoPath)\n let fs = try decoder.decode(Filesystem.self, from: data)\n return fs\n }\n\n public func clean(keepingSnapshotsFor images: [Containerization.Image] = []) async throws -> UInt64 {\n var toKeep: [String] = [Self.ingestDirName]\n for image in images {\n for manifest in try await image.index().manifests {\n guard let platform = manifest.platform else {\n continue\n }\n let desc = try await image.descriptor(for: platform)\n toKeep.append(desc.digest.trimmingDigestPrefix)\n }\n }\n let all = try self.fm.contentsOfDirectory(at: self.path, includingPropertiesForKeys: [.totalFileAllocatedSizeKey]).map {\n $0.lastPathComponent\n }\n let delete = Set(all).subtracting(Set(toKeep))\n var deletedBytes: UInt64 = 0\n for dir in delete {\n let unpackedPath = self.path.appending(path: dir, directoryHint: .isDirectory)\n guard self.fm.fileExists(atPath: unpackedPath.absolutePath()) else {\n continue\n }\n deletedBytes += (try? self.fm.directorySize(dir: unpackedPath)) ?? 0\n try self.fm.removeItem(at: unpackedPath)\n }\n return deletedBytes\n }\n\n private func snapshotDir(_ desc: Descriptor) -> URL {\n let p = self.path.appendingPathComponent(desc.digest.trimmingDigestPrefix, isDirectory: true)\n return p\n }\n\n private func snapshotPath(_ desc: Descriptor) -> URL {\n let p = self.snapshotDir(desc)\n .appendingPathComponent(Self.snapshotFileName, isDirectory: false)\n return p\n }\n\n private func snapshotInfoPath(_ desc: Descriptor) -> URL {\n let p = self.snapshotDir(desc)\n .appendingPathComponent(Self.snapshotInfoFileName, isDirectory: false)\n return p\n }\n\n private func tempUnpackDir() throws -> URL {\n let uniqueDirectoryURL = ingestDir.appendingPathComponent(UUID().uuidString, isDirectory: true)\n try self.fm.createDirectory(at: uniqueDirectoryURL, withIntermediateDirectories: true, attributes: nil)\n return uniqueDirectoryURL\n }\n}\n\nextension FileManager {\n fileprivate func directorySize(dir: URL) throws -> UInt64 {\n var size = 0\n let resourceKeys: [URLResourceKey] = [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey]\n let contents = try self.contentsOfDirectory(\n at: dir,\n includingPropertiesForKeys: resourceKeys)\n\n for p in contents {\n let val = try p.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey])\n size += val.totalFileAllocatedSize ?? val.fileAllocatedSize ?? 0\n }\n return UInt64(size)\n }\n}\n\nextension Containerization.Image {\n fileprivate func unpackableDescriptors() async throws -> [Descriptor] {\n let index = try await self.index()\n return index.manifests.filter { desc in\n guard desc.platform != nil else {\n return false\n }\n if let referenceType = desc.annotations?[\"vnd.docker.reference.type\"], referenceType == \"attestation-manifest\" {\n return false\n }\n return true\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/ServiceManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\npublic struct ServiceManager {\n private static func runLaunchctlCommand(args: [String]) throws -> Int32 {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = args\n\n let null = FileHandle.nullDevice\n launchctl.standardOutput = null\n launchctl.standardError = null\n\n try launchctl.run()\n launchctl.waitUntilExit()\n\n return launchctl.terminationStatus\n }\n\n /// Register a service by providing the path to a plist.\n public static func register(plistPath: String) throws {\n let domain = try Self.getDomainString()\n _ = try runLaunchctlCommand(args: [\"bootstrap\", domain, plistPath])\n }\n\n /// Deregister a service by a launchd label.\n public static func deregister(fullServiceLabel label: String) throws {\n _ = try runLaunchctlCommand(args: [\"bootout\", label])\n }\n\n /// Restart a service by a launchd label.\n public static func kickstart(fullServiceLabel label: String) throws {\n _ = try runLaunchctlCommand(args: [\"kickstart\", \"-k\", label])\n }\n\n /// Send a signal to a service by a launchd label.\n public static func kill(fullServiceLabel label: String, signal: Int32 = 15) throws {\n _ = try runLaunchctlCommand(args: [\"kill\", \"\\(signal)\", label])\n }\n\n /// Retrieve labels for all loaded launch units.\n public static func enumerate() throws -> [String] {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = [\"list\"]\n\n let stdoutPipe = Pipe()\n let stderrPipe = Pipe()\n launchctl.standardOutput = stdoutPipe\n launchctl.standardError = stderrPipe\n\n try launchctl.run()\n let outputData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()\n let stderrData = stderrPipe.fileHandleForReading.readDataToEndOfFile()\n launchctl.waitUntilExit()\n let status = launchctl.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(\n .internalError, message: \"Command `launchctl list` failed with status \\(status). Message: \\(String(data: stderrData, encoding: .utf8) ?? \"No error message\")\")\n }\n\n guard let outputText = String(data: outputData, encoding: .utf8) else {\n throw ContainerizationError(\n .internalError, message: \"Could not decode output of command `launchctl list`. Message: \\(String(data: stderrData, encoding: .utf8) ?? \"No error message\")\")\n }\n\n // The third field of each line of launchctl list output is the label\n return outputText.split { $0.isNewline }\n .map { String($0).split { $0.isWhitespace } }\n .filter { $0.count >= 3 }\n .map { String($0[2]) }\n }\n\n /// Check if a service has been registered or not.\n public static func isRegistered(fullServiceLabel label: String) throws -> Bool {\n let exitStatus = try runLaunchctlCommand(args: [\"list\", label])\n return exitStatus == 0\n }\n\n private static func getLaunchdSessionType() throws -> String {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = [\"managername\"]\n\n let null = FileHandle.nullDevice\n let stdoutPipe = Pipe()\n launchctl.standardOutput = stdoutPipe\n launchctl.standardError = null\n\n try launchctl.run()\n let outputData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()\n launchctl.waitUntilExit()\n let status = launchctl.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(.internalError, message: \"Command `launchctl managername` failed with status \\(status)\")\n }\n guard let outputText = String(data: outputData, encoding: .utf8) else {\n throw ContainerizationError(.internalError, message: \"Could not decode output of command `launchctl managername`\")\n }\n return outputText.trimmingCharacters(in: .whitespacesAndNewlines)\n }\n\n public static func getDomainString() throws -> String {\n let currentSessionType = try getLaunchdSessionType()\n switch currentSessionType {\n case LaunchPlist.Domain.System.rawValue:\n return LaunchPlist.Domain.System.rawValue.lowercased()\n case LaunchPlist.Domain.Background.rawValue:\n return \"user/\\(getuid())\"\n case LaunchPlist.Domain.Aqua.rawValue:\n return \"gui/\\(getuid())\"\n default:\n throw ContainerizationError(.internalError, message: \"Unsupported session type \\(currentSessionType)\")\n }\n }\n}\n"], ["/container/Sources/APIServer/Containers/ContainersHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nstruct ContainersHarness {\n let log: Logging.Logger\n let service: ContainersService\n\n init(service: ContainersService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let containers = try await service.list()\n let data = try JSONEncoder().encode(containers)\n\n let reply = message.reply()\n reply.set(key: .containers, value: data)\n return reply\n }\n\n @Sendable\n func create(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .containerConfig)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"container configuration cannot be empty\")\n }\n let kdata = message.dataNoCopy(key: .kernel)\n guard let kdata else {\n throw ContainerizationError(.invalidArgument, message: \"kernel cannot be empty\")\n }\n let odata = message.dataNoCopy(key: .containerOptions)\n var options: ContainerCreateOptions = .default\n if let odata {\n options = try JSONDecoder().decode(ContainerCreateOptions.self, from: odata)\n }\n let config = try JSONDecoder().decode(ContainerConfiguration.self, from: data)\n let kernel = try JSONDecoder().decode(Kernel.self, from: kdata)\n\n try await service.create(configuration: config, kernel: kernel, options: options)\n return message.reply()\n }\n\n @Sendable\n func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .id)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"id cannot be empty\")\n }\n try await service.delete(id: id)\n return message.reply()\n }\n\n @Sendable\n func logs(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .id)\n guard let id else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"id cannot be empty\"\n )\n }\n let fds = try await service.logs(id: id)\n let reply = message.reply()\n try reply.set(key: .logs, value: fds)\n return reply\n }\n\n @Sendable\n func eventHandler(_ message: XPCMessage) async throws -> XPCMessage {\n let event = try message.containerEvent()\n try await service.handleContainerEvents(event: event)\n return message.reply()\n }\n}\n\nextension XPCMessage {\n public func containerEvent() throws -> ContainerEvent {\n guard let data = self.dataNoCopy(key: .containerEvent) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing container event data\")\n }\n let event = try JSONDecoder().decode(ContainerEvent.self, from: data)\n return event\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct ContainerDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete one or more containers\",\n aliases: [\"rm\"])\n\n @Flag(name: .shortAndLong, help: \"Force the removal of one or more running containers\")\n var force = false\n\n @Flag(name: .shortAndLong, help: \"Remove all containers\")\n var all = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Container IDs/names\")\n var containerIDs: [String] = []\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument,\n message: \"explicitly supplied container ID(s) conflict with the --all flag\"\n )\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n var containers = [ClientContainer]()\n\n if all {\n containers = try await ClientContainer.list()\n } else {\n let ctrs = try await ClientContainer.list()\n containers = ctrs.filter { c in\n set.contains(c.id)\n }\n // If one of the containers requested isn't present, let's throw. We don't need to do\n // this for --all as --all should be perfectly usable with no containers to remove; otherwise,\n // it'd be quite clunky.\n if containers.count != set.count {\n let missing = set.filter { id in\n !containers.contains { c in\n c.id == id\n }\n }\n throw ContainerizationError(\n .notFound,\n message: \"failed to delete one or more containers: \\(missing)\"\n )\n }\n }\n\n var failed = [String]()\n let force = self.force\n let all = self.all\n try await withThrowingTaskGroup(of: ClientContainer?.self) { group in\n for container in containers {\n group.addTask {\n do {\n // First we need to find if the container supports auto-remove\n // and if so we need to skip deletion.\n if container.status == .running {\n if !force {\n // We don't want to error if the user just wants all containers deleted.\n // It's implied we'll skip containers we can't actually delete.\n if all {\n return nil\n }\n throw ContainerizationError(.invalidState, message: \"container is running\")\n }\n let stopOpts = ContainerStopOptions(\n timeoutInSeconds: 5,\n signal: SIGKILL\n )\n try await container.stop(opts: stopOpts)\n }\n try await container.delete()\n print(container.id)\n return nil\n } catch {\n log.error(\"failed to delete container \\(container.id): \\(error)\")\n return container\n }\n }\n }\n\n for try await ctr in group {\n guard let ctr else {\n continue\n }\n failed.append(ctr.id)\n }\n }\n\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"delete failed for one or more containers: \\(failed)\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.pb.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// DO NOT EDIT.\n// swift-format-ignore-file\n// swiftlint:disable all\n//\n// Generated by the Swift generator plugin for the protocol buffer compiler.\n// Source: Builder.proto\n//\n// For information on using the generated types, please see the documentation:\n// https://github.com/apple/swift-protobuf/\n\nimport Foundation\nimport SwiftProtobuf\n\n// If the compiler emits an error on this type, it is because this file\n// was generated by a version of the `protoc` Swift plug-in that is\n// incompatible with the version of SwiftProtobuf to which you are linking.\n// Please ensure that you are building against the same version of the API\n// that was used to generate this file.\nfileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {\n struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}\n typealias Version = _2\n}\n\npublic enum Com_Apple_Container_Build_V1_TransferDirection: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case into // = 0\n case outof // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .into\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .into\n case 1: self = .outof\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .into: return 0\n case .outof: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_TransferDirection] = [\n .into,\n .outof,\n ]\n\n}\n\n/// Standard input/output.\npublic enum Com_Apple_Container_Build_V1_Stdio: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case stdin // = 0\n case stdout // = 1\n case stderr // = 2\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .stdin\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .stdin\n case 1: self = .stdout\n case 2: self = .stderr\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .stdin: return 0\n case .stdout: return 1\n case .stderr: return 2\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_Stdio] = [\n .stdin,\n .stdout,\n .stderr,\n ]\n\n}\n\n/// Build error type.\npublic enum Com_Apple_Container_Build_V1_BuildErrorType: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case buildFailed // = 0\n case `internal` // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .buildFailed\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .buildFailed\n case 1: self = .internal\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .buildFailed: return 0\n case .internal: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_BuildErrorType] = [\n .buildFailed,\n .internal,\n ]\n\n}\n\npublic struct Com_Apple_Container_Build_V1_InfoRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_InfoResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_CreateBuildRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The name of the build stage.\n public var stageName: String = String()\n\n /// The tag of the image to be created.\n public var tag: String = String()\n\n /// Any additional metadata to be associated with the build.\n public var metadata: Dictionary = [:]\n\n /// Additional build arguments.\n public var buildArgs: [String] = []\n\n /// Enable debug logging.\n public var debug: Bool = false\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_CreateBuildResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String = String()\n\n /// Any additional metadata to be associated with the build.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_ClientStream: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String {\n get {return _storage._buildID}\n set {_uniqueStorage()._buildID = newValue}\n }\n\n /// The packet type.\n public var packetType: OneOf_PacketType? {\n get {return _storage._packetType}\n set {_uniqueStorage()._packetType = newValue}\n }\n\n public var signal: Com_Apple_Container_Build_V1_Signal {\n get {\n if case .signal(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_Signal()\n }\n set {_uniqueStorage()._packetType = .signal(newValue)}\n }\n\n public var command: Com_Apple_Container_Build_V1_Run {\n get {\n if case .command(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_Run()\n }\n set {_uniqueStorage()._packetType = .command(newValue)}\n }\n\n public var buildTransfer: Com_Apple_Container_Build_V1_BuildTransfer {\n get {\n if case .buildTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildTransfer()\n }\n set {_uniqueStorage()._packetType = .buildTransfer(newValue)}\n }\n\n public var imageTransfer: Com_Apple_Container_Build_V1_ImageTransfer {\n get {\n if case .imageTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_ImageTransfer()\n }\n set {_uniqueStorage()._packetType = .imageTransfer(newValue)}\n }\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n /// The packet type.\n public enum OneOf_PacketType: Equatable, Sendable {\n case signal(Com_Apple_Container_Build_V1_Signal)\n case command(Com_Apple_Container_Build_V1_Run)\n case buildTransfer(Com_Apple_Container_Build_V1_BuildTransfer)\n case imageTransfer(Com_Apple_Container_Build_V1_ImageTransfer)\n\n }\n\n public init() {}\n\n fileprivate var _storage = _StorageClass.defaultInstance\n}\n\npublic struct Com_Apple_Container_Build_V1_Signal: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A POSIX signal to send to the build process.\n /// Can be used for cancelling builds.\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_Run: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the execution.\n public var id: String = String()\n\n /// The type of command to execute.\n public var command: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_RunComplete: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the execution.\n public var id: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_BuildTransfer: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the transfer.\n public var id: String = String()\n\n /// The direction for transferring data (either to the server or from the\n /// server).\n public var direction: Com_Apple_Container_Build_V1_TransferDirection = .into\n\n /// The absolute path to the source from the server perspective.\n public var source: String {\n get {return _source ?? String()}\n set {_source = newValue}\n }\n /// Returns true if `source` has been explicitly set.\n public var hasSource: Bool {return self._source != nil}\n /// Clears the value of `source`. Subsequent reads from it will return its default value.\n public mutating func clearSource() {self._source = nil}\n\n /// The absolute path for the destination from the server perspective.\n public var destination: String {\n get {return _destination ?? String()}\n set {_destination = newValue}\n }\n /// Returns true if `destination` has been explicitly set.\n public var hasDestination: Bool {return self._destination != nil}\n /// Clears the value of `destination`. Subsequent reads from it will return its default value.\n public mutating func clearDestination() {self._destination = nil}\n\n /// The actual data bytes to be transferred.\n public var data: Data = Data()\n\n /// Signal to indicate that the transfer of data for the request has finished.\n public var complete: Bool = false\n\n /// Boolean to indicate if the content is a directory.\n public var isDirectory: Bool = false\n\n /// Metadata for the transfer.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _source: String? = nil\n fileprivate var _destination: String? = nil\n}\n\npublic struct Com_Apple_Container_Build_V1_ImageTransfer: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the transfer.\n public var id: String = String()\n\n /// The direction for transferring data (either to the server or from the\n /// server).\n public var direction: Com_Apple_Container_Build_V1_TransferDirection = .into\n\n /// The tag for the image.\n public var tag: String = String()\n\n /// The descriptor for the image content.\n public var descriptor: Com_Apple_Container_Build_V1_Descriptor {\n get {return _descriptor ?? Com_Apple_Container_Build_V1_Descriptor()}\n set {_descriptor = newValue}\n }\n /// Returns true if `descriptor` has been explicitly set.\n public var hasDescriptor: Bool {return self._descriptor != nil}\n /// Clears the value of `descriptor`. Subsequent reads from it will return its default value.\n public mutating func clearDescriptor() {self._descriptor = nil}\n\n /// The actual data bytes to be transferred.\n public var data: Data = Data()\n\n /// Signal to indicate that the transfer of data for the request has finished.\n public var complete: Bool = false\n\n /// Metadata for the image.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _descriptor: Com_Apple_Container_Build_V1_Descriptor? = nil\n}\n\npublic struct Com_Apple_Container_Build_V1_ServerStream: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String {\n get {return _storage._buildID}\n set {_uniqueStorage()._buildID = newValue}\n }\n\n /// The packet type.\n public var packetType: OneOf_PacketType? {\n get {return _storage._packetType}\n set {_uniqueStorage()._packetType = newValue}\n }\n\n public var io: Com_Apple_Container_Build_V1_IO {\n get {\n if case .io(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_IO()\n }\n set {_uniqueStorage()._packetType = .io(newValue)}\n }\n\n public var buildError: Com_Apple_Container_Build_V1_BuildError {\n get {\n if case .buildError(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildError()\n }\n set {_uniqueStorage()._packetType = .buildError(newValue)}\n }\n\n public var commandComplete: Com_Apple_Container_Build_V1_RunComplete {\n get {\n if case .commandComplete(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_RunComplete()\n }\n set {_uniqueStorage()._packetType = .commandComplete(newValue)}\n }\n\n public var buildTransfer: Com_Apple_Container_Build_V1_BuildTransfer {\n get {\n if case .buildTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildTransfer()\n }\n set {_uniqueStorage()._packetType = .buildTransfer(newValue)}\n }\n\n public var imageTransfer: Com_Apple_Container_Build_V1_ImageTransfer {\n get {\n if case .imageTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_ImageTransfer()\n }\n set {_uniqueStorage()._packetType = .imageTransfer(newValue)}\n }\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n /// The packet type.\n public enum OneOf_PacketType: Equatable, Sendable {\n case io(Com_Apple_Container_Build_V1_IO)\n case buildError(Com_Apple_Container_Build_V1_BuildError)\n case commandComplete(Com_Apple_Container_Build_V1_RunComplete)\n case buildTransfer(Com_Apple_Container_Build_V1_BuildTransfer)\n case imageTransfer(Com_Apple_Container_Build_V1_ImageTransfer)\n\n }\n\n public init() {}\n\n fileprivate var _storage = _StorageClass.defaultInstance\n}\n\npublic struct Com_Apple_Container_Build_V1_IO: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The type of IO.\n public var type: Com_Apple_Container_Build_V1_Stdio = .stdin\n\n /// The IO data bytes.\n public var data: Data = Data()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_BuildError: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The type of build error.\n public var type: Com_Apple_Container_Build_V1_BuildErrorType = .buildFailed\n\n /// Additional message for the build failure.\n public var message: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n/// OCI Platform metadata.\npublic struct Com_Apple_Container_Build_V1_Platform: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var architecture: String = String()\n\n public var os: String = String()\n\n public var osVersion: String = String()\n\n public var osFeatures: [String] = []\n\n public var variant: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n/// OCI Descriptor metadata.\npublic struct Com_Apple_Container_Build_V1_Descriptor: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var mediaType: String = String()\n\n public var digest: String = String()\n\n public var size: Int64 = 0\n\n public var urls: [String] = []\n\n public var annotations: Dictionary = [:]\n\n public var platform: Com_Apple_Container_Build_V1_Platform {\n get {return _platform ?? Com_Apple_Container_Build_V1_Platform()}\n set {_platform = newValue}\n }\n /// Returns true if `platform` has been explicitly set.\n public var hasPlatform: Bool {return self._platform != nil}\n /// Clears the value of `platform`. Subsequent reads from it will return its default value.\n public mutating func clearPlatform() {self._platform = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _platform: Com_Apple_Container_Build_V1_Platform? = nil\n}\n\n// MARK: - Code below here is support for the SwiftProtobuf runtime.\n\nfileprivate let _protobuf_package = \"com.apple.container.build.v1\"\n\nextension Com_Apple_Container_Build_V1_TransferDirection: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"INTO\"),\n 1: .same(proto: \"OUTOF\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_Stdio: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"STDIN\"),\n 1: .same(proto: \"STDOUT\"),\n 2: .same(proto: \"STDERR\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_BuildErrorType: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"BUILD_FAILED\"),\n 1: .same(proto: \"INTERNAL\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_InfoRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".InfoRequest\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_InfoRequest, rhs: Com_Apple_Container_Build_V1_InfoRequest) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_InfoResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".InfoResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_InfoResponse, rhs: Com_Apple_Container_Build_V1_InfoResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_CreateBuildRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateBuildRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"stage_name\"),\n 2: .same(proto: \"tag\"),\n 3: .same(proto: \"metadata\"),\n 4: .standard(proto: \"build_args\"),\n 5: .same(proto: \"debug\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.stageName) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.tag) }()\n case 3: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.buildArgs) }()\n case 5: try { try decoder.decodeSingularBoolField(value: &self.debug) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.stageName.isEmpty {\n try visitor.visitSingularStringField(value: self.stageName, fieldNumber: 1)\n }\n if !self.tag.isEmpty {\n try visitor.visitSingularStringField(value: self.tag, fieldNumber: 2)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 3)\n }\n if !self.buildArgs.isEmpty {\n try visitor.visitRepeatedStringField(value: self.buildArgs, fieldNumber: 4)\n }\n if self.debug != false {\n try visitor.visitSingularBoolField(value: self.debug, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_CreateBuildRequest, rhs: Com_Apple_Container_Build_V1_CreateBuildRequest) -> Bool {\n if lhs.stageName != rhs.stageName {return false}\n if lhs.tag != rhs.tag {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.buildArgs != rhs.buildArgs {return false}\n if lhs.debug != rhs.debug {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_CreateBuildResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateBuildResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.buildID) }()\n case 2: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.buildID.isEmpty {\n try visitor.visitSingularStringField(value: self.buildID, fieldNumber: 1)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_CreateBuildResponse, rhs: Com_Apple_Container_Build_V1_CreateBuildResponse) -> Bool {\n if lhs.buildID != rhs.buildID {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ClientStream: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ClientStream\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"signal\"),\n 3: .same(proto: \"command\"),\n 4: .standard(proto: \"build_transfer\"),\n 5: .standard(proto: \"image_transfer\"),\n ]\n\n fileprivate class _StorageClass {\n var _buildID: String = String()\n var _packetType: Com_Apple_Container_Build_V1_ClientStream.OneOf_PacketType?\n\n // This property is used as the initial default value for new instances of the type.\n // The type itself is protecting the reference to its storage via CoW semantics.\n // This will force a copy to be made of this reference when the first mutation occurs;\n // hence, it is safe to mark this as `nonisolated(unsafe)`.\n static nonisolated(unsafe) let defaultInstance = _StorageClass()\n\n private init() {}\n\n init(copying source: _StorageClass) {\n _buildID = source._buildID\n _packetType = source._packetType\n }\n }\n\n fileprivate mutating func _uniqueStorage() -> _StorageClass {\n if !isKnownUniquelyReferenced(&_storage) {\n _storage = _StorageClass(copying: _storage)\n }\n return _storage\n }\n\n public mutating func decodeMessage(decoder: inout D) throws {\n _ = _uniqueStorage()\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &_storage._buildID) }()\n case 2: try {\n var v: Com_Apple_Container_Build_V1_Signal?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .signal(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .signal(v)\n }\n }()\n case 3: try {\n var v: Com_Apple_Container_Build_V1_Run?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .command(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .command(v)\n }\n }()\n case 4: try {\n var v: Com_Apple_Container_Build_V1_BuildTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildTransfer(v)\n }\n }()\n case 5: try {\n var v: Com_Apple_Container_Build_V1_ImageTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .imageTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .imageTransfer(v)\n }\n }()\n default: break\n }\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !_storage._buildID.isEmpty {\n try visitor.visitSingularStringField(value: _storage._buildID, fieldNumber: 1)\n }\n switch _storage._packetType {\n case .signal?: try {\n guard case .signal(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 2)\n }()\n case .command?: try {\n guard case .command(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 3)\n }()\n case .buildTransfer?: try {\n guard case .buildTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n }()\n case .imageTransfer?: try {\n guard case .imageTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 5)\n }()\n case nil: break\n }\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ClientStream, rhs: Com_Apple_Container_Build_V1_ClientStream) -> Bool {\n if lhs._storage !== rhs._storage {\n let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in\n let _storage = _args.0\n let rhs_storage = _args.1\n if _storage._buildID != rhs_storage._buildID {return false}\n if _storage._packetType != rhs_storage._packetType {return false}\n return true\n }\n if !storagesAreEqual {return false}\n }\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Signal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Signal\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Signal, rhs: Com_Apple_Container_Build_V1_Signal) -> Bool {\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Run: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Run\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"command\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.command) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if !self.command.isEmpty {\n try visitor.visitSingularStringField(value: self.command, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Run, rhs: Com_Apple_Container_Build_V1_Run) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.command != rhs.command {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_RunComplete: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".RunComplete\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_RunComplete, rhs: Com_Apple_Container_Build_V1_RunComplete) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_BuildTransfer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".BuildTransfer\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"direction\"),\n 3: .same(proto: \"source\"),\n 4: .same(proto: \"destination\"),\n 5: .same(proto: \"data\"),\n 6: .same(proto: \"complete\"),\n 7: .standard(proto: \"is_directory\"),\n 8: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularEnumField(value: &self.direction) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._source) }()\n case 4: try { try decoder.decodeSingularStringField(value: &self._destination) }()\n case 5: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n case 6: try { try decoder.decodeSingularBoolField(value: &self.complete) }()\n case 7: try { try decoder.decodeSingularBoolField(value: &self.isDirectory) }()\n case 8: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.direction != .into {\n try visitor.visitSingularEnumField(value: self.direction, fieldNumber: 2)\n }\n try { if let v = self._source {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try { if let v = self._destination {\n try visitor.visitSingularStringField(value: v, fieldNumber: 4)\n } }()\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 5)\n }\n if self.complete != false {\n try visitor.visitSingularBoolField(value: self.complete, fieldNumber: 6)\n }\n if self.isDirectory != false {\n try visitor.visitSingularBoolField(value: self.isDirectory, fieldNumber: 7)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 8)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_BuildTransfer, rhs: Com_Apple_Container_Build_V1_BuildTransfer) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.direction != rhs.direction {return false}\n if lhs._source != rhs._source {return false}\n if lhs._destination != rhs._destination {return false}\n if lhs.data != rhs.data {return false}\n if lhs.complete != rhs.complete {return false}\n if lhs.isDirectory != rhs.isDirectory {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ImageTransfer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ImageTransfer\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"direction\"),\n 3: .same(proto: \"tag\"),\n 4: .same(proto: \"descriptor\"),\n 5: .same(proto: \"data\"),\n 6: .same(proto: \"complete\"),\n 7: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularEnumField(value: &self.direction) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.tag) }()\n case 4: try { try decoder.decodeSingularMessageField(value: &self._descriptor) }()\n case 5: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n case 6: try { try decoder.decodeSingularBoolField(value: &self.complete) }()\n case 7: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.direction != .into {\n try visitor.visitSingularEnumField(value: self.direction, fieldNumber: 2)\n }\n if !self.tag.isEmpty {\n try visitor.visitSingularStringField(value: self.tag, fieldNumber: 3)\n }\n try { if let v = self._descriptor {\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n } }()\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 5)\n }\n if self.complete != false {\n try visitor.visitSingularBoolField(value: self.complete, fieldNumber: 6)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 7)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ImageTransfer, rhs: Com_Apple_Container_Build_V1_ImageTransfer) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.direction != rhs.direction {return false}\n if lhs.tag != rhs.tag {return false}\n if lhs._descriptor != rhs._descriptor {return false}\n if lhs.data != rhs.data {return false}\n if lhs.complete != rhs.complete {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ServerStream: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ServerStream\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"io\"),\n 3: .standard(proto: \"build_error\"),\n 4: .standard(proto: \"command_complete\"),\n 5: .standard(proto: \"build_transfer\"),\n 6: .standard(proto: \"image_transfer\"),\n ]\n\n fileprivate class _StorageClass {\n var _buildID: String = String()\n var _packetType: Com_Apple_Container_Build_V1_ServerStream.OneOf_PacketType?\n\n // This property is used as the initial default value for new instances of the type.\n // The type itself is protecting the reference to its storage via CoW semantics.\n // This will force a copy to be made of this reference when the first mutation occurs;\n // hence, it is safe to mark this as `nonisolated(unsafe)`.\n static nonisolated(unsafe) let defaultInstance = _StorageClass()\n\n private init() {}\n\n init(copying source: _StorageClass) {\n _buildID = source._buildID\n _packetType = source._packetType\n }\n }\n\n fileprivate mutating func _uniqueStorage() -> _StorageClass {\n if !isKnownUniquelyReferenced(&_storage) {\n _storage = _StorageClass(copying: _storage)\n }\n return _storage\n }\n\n public mutating func decodeMessage(decoder: inout D) throws {\n _ = _uniqueStorage()\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &_storage._buildID) }()\n case 2: try {\n var v: Com_Apple_Container_Build_V1_IO?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .io(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .io(v)\n }\n }()\n case 3: try {\n var v: Com_Apple_Container_Build_V1_BuildError?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildError(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildError(v)\n }\n }()\n case 4: try {\n var v: Com_Apple_Container_Build_V1_RunComplete?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .commandComplete(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .commandComplete(v)\n }\n }()\n case 5: try {\n var v: Com_Apple_Container_Build_V1_BuildTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildTransfer(v)\n }\n }()\n case 6: try {\n var v: Com_Apple_Container_Build_V1_ImageTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .imageTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .imageTransfer(v)\n }\n }()\n default: break\n }\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !_storage._buildID.isEmpty {\n try visitor.visitSingularStringField(value: _storage._buildID, fieldNumber: 1)\n }\n switch _storage._packetType {\n case .io?: try {\n guard case .io(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 2)\n }()\n case .buildError?: try {\n guard case .buildError(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 3)\n }()\n case .commandComplete?: try {\n guard case .commandComplete(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n }()\n case .buildTransfer?: try {\n guard case .buildTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 5)\n }()\n case .imageTransfer?: try {\n guard case .imageTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 6)\n }()\n case nil: break\n }\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ServerStream, rhs: Com_Apple_Container_Build_V1_ServerStream) -> Bool {\n if lhs._storage !== rhs._storage {\n let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in\n let _storage = _args.0\n let rhs_storage = _args.1\n if _storage._buildID != rhs_storage._buildID {return false}\n if _storage._packetType != rhs_storage._packetType {return false}\n return true\n }\n if !storagesAreEqual {return false}\n }\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_IO: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IO\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"data\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularEnumField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.type != .stdin {\n try visitor.visitSingularEnumField(value: self.type, fieldNumber: 1)\n }\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_IO, rhs: Com_Apple_Container_Build_V1_IO) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.data != rhs.data {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_BuildError: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".BuildError\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"message\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularEnumField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.message) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.type != .buildFailed {\n try visitor.visitSingularEnumField(value: self.type, fieldNumber: 1)\n }\n if !self.message.isEmpty {\n try visitor.visitSingularStringField(value: self.message, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_BuildError, rhs: Com_Apple_Container_Build_V1_BuildError) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.message != rhs.message {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Platform: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Platform\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"architecture\"),\n 2: .same(proto: \"os\"),\n 3: .standard(proto: \"os_version\"),\n 4: .standard(proto: \"os_features\"),\n 5: .same(proto: \"variant\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.architecture) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.os) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.osVersion) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.osFeatures) }()\n case 5: try { try decoder.decodeSingularStringField(value: &self.variant) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.architecture.isEmpty {\n try visitor.visitSingularStringField(value: self.architecture, fieldNumber: 1)\n }\n if !self.os.isEmpty {\n try visitor.visitSingularStringField(value: self.os, fieldNumber: 2)\n }\n if !self.osVersion.isEmpty {\n try visitor.visitSingularStringField(value: self.osVersion, fieldNumber: 3)\n }\n if !self.osFeatures.isEmpty {\n try visitor.visitRepeatedStringField(value: self.osFeatures, fieldNumber: 4)\n }\n if !self.variant.isEmpty {\n try visitor.visitSingularStringField(value: self.variant, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Platform, rhs: Com_Apple_Container_Build_V1_Platform) -> Bool {\n if lhs.architecture != rhs.architecture {return false}\n if lhs.os != rhs.os {return false}\n if lhs.osVersion != rhs.osVersion {return false}\n if lhs.osFeatures != rhs.osFeatures {return false}\n if lhs.variant != rhs.variant {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Descriptor: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Descriptor\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"media_type\"),\n 2: .same(proto: \"digest\"),\n 3: .same(proto: \"size\"),\n 4: .same(proto: \"urls\"),\n 5: .same(proto: \"annotations\"),\n 6: .same(proto: \"platform\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.mediaType) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.digest) }()\n case 3: try { try decoder.decodeSingularInt64Field(value: &self.size) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.urls) }()\n case 5: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.annotations) }()\n case 6: try { try decoder.decodeSingularMessageField(value: &self._platform) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.mediaType.isEmpty {\n try visitor.visitSingularStringField(value: self.mediaType, fieldNumber: 1)\n }\n if !self.digest.isEmpty {\n try visitor.visitSingularStringField(value: self.digest, fieldNumber: 2)\n }\n if self.size != 0 {\n try visitor.visitSingularInt64Field(value: self.size, fieldNumber: 3)\n }\n if !self.urls.isEmpty {\n try visitor.visitRepeatedStringField(value: self.urls, fieldNumber: 4)\n }\n if !self.annotations.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.annotations, fieldNumber: 5)\n }\n try { if let v = self._platform {\n try visitor.visitSingularMessageField(value: v, fieldNumber: 6)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Descriptor, rhs: Com_Apple_Container_Build_V1_Descriptor) -> Bool {\n if lhs.mediaType != rhs.mediaType {return false}\n if lhs.digest != rhs.digest {return false}\n if lhs.size != rhs.size {return false}\n if lhs.urls != rhs.urls {return false}\n if lhs.annotations != rhs.annotations {return false}\n if lhs._platform != rhs._platform {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ImagesServiceHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\npublic struct ImagesServiceHarness: Sendable {\n let log: Logging.Logger\n let service: ImagesService\n\n public init(service: ImagesService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n public func pull(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let insecure = message.bool(key: .insecureFlag)\n\n let progressUpdateService = ProgressUpdateService(message: message)\n let imageDescription = try await service.pull(reference: ref, platform: platform, insecure: insecure, progressUpdate: progressUpdateService?.handler)\n\n let imageData = try JSONEncoder().encode(imageDescription)\n let reply = message.reply()\n reply.set(key: .imageDescription, value: imageData)\n return reply\n }\n\n @Sendable\n public func push(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let insecure = message.bool(key: .insecureFlag)\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await service.push(reference: ref, platform: platform, insecure: insecure, progressUpdate: progressUpdateService?.handler)\n\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func tag(_ message: XPCMessage) async throws -> XPCMessage {\n let old = message.string(key: .imageReference)\n guard let old else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let new = message.string(key: .imageNewReference)\n guard let new else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing new image reference\"\n )\n }\n let newDescription = try await service.tag(old: old, new: new)\n let descData = try JSONEncoder().encode(newDescription)\n let reply = message.reply()\n reply.set(key: .imageDescription, value: descData)\n return reply\n }\n\n @Sendable\n public func list(_ message: XPCMessage) async throws -> XPCMessage {\n let images = try await service.list()\n let imageData = try JSONEncoder().encode(images)\n let reply = message.reply()\n reply.set(key: .imageDescriptions, value: imageData)\n return reply\n }\n\n @Sendable\n public func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let garbageCollect = message.bool(key: .garbageCollect)\n try await self.service.delete(reference: ref, garbageCollect: garbageCollect)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func save(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .imageDescription)\n guard let data else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let imageDescription = try JSONDecoder().decode(ImageDescription.self, from: data)\n\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let out = message.string(key: .filePath)\n guard let out else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing output file path\"\n )\n }\n try await service.save(reference: imageDescription.reference, out: URL(filePath: out), platform: platform)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func load(_ message: XPCMessage) async throws -> XPCMessage {\n let input = message.string(key: .filePath)\n guard let input else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing input file path\"\n )\n }\n let images = try await service.load(from: URL(filePath: input))\n let data = try JSONEncoder().encode(images)\n let reply = message.reply()\n reply.set(key: .imageDescriptions, value: data)\n return reply\n }\n\n @Sendable\n public func prune(_ message: XPCMessage) async throws -> XPCMessage {\n let (deleted, size) = try await service.prune()\n let reply = message.reply()\n let data = try JSONEncoder().encode(deleted)\n reply.set(key: .digests, value: data)\n reply.set(key: .size, value: size)\n return reply\n }\n}\n\n// MARK: Image Snapshot Methods\n\nextension ImagesServiceHarness {\n @Sendable\n public func unpack(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing Image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n var platform: Platform?\n if let platformData = message.dataNoCopy(key: .ociPlatform) {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await self.service.unpack(description: description, platform: platform, progressUpdate: progressUpdateService?.handler)\n\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func deleteSnapshot(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform?\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n try await self.service.deleteImageSnapshot(description: description, platform: platform)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func getSnapshot(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n let platformData = message.dataNoCopy(key: .ociPlatform)\n guard let platformData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing OCI platform\"\n )\n }\n let platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n let fs = try await self.service.getImageSnapshot(description: description, platform: platform)\n let fsData = try JSONEncoder().encode(fs)\n let reply = message.reply()\n reply.set(key: .filesystem, value: fsData)\n return reply\n }\n}\n"], ["/container/Sources/CLI/RunCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Foundation\nimport NIOCore\nimport NIOPosix\nimport TerminalProgress\n\nextension Application {\n struct ContainerRunCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"run\",\n abstract: \"Run a container\")\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var resourceFlags: Flags.Resource\n\n @OptionGroup\n var managementFlags: Flags.Management\n\n @OptionGroup\n var registryFlags: Flags.Registry\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Argument(help: \"Image name\")\n var image: String\n\n @Argument(parsing: .captureForPassthrough, help: \"Container init process arguments\")\n var arguments: [String] = []\n\n func run() async throws {\n var exitCode: Int32 = 127\n let id = Utility.createContainerID(name: self.managementFlags.name)\n\n var progressConfig: ProgressConfig\n if progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 6\n )\n }\n\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n try Utility.validEntityName(id)\n\n // Check if container with id already exists.\n let existing = try? await ClientContainer.get(id: id)\n guard existing == nil else {\n throw ContainerizationError(\n .exists,\n message: \"container with id \\(id) already exists\"\n )\n }\n\n let ck = try await Utility.containerConfigFromFlags(\n id: id,\n image: image,\n arguments: arguments,\n process: processFlags,\n management: managementFlags,\n resource: resourceFlags,\n registry: registryFlags,\n progressUpdate: progress.handler\n )\n\n progress.set(description: \"Starting container\")\n\n let options = ContainerCreateOptions(autoRemove: managementFlags.remove)\n let container = try await ClientContainer.create(\n configuration: ck.0,\n options: options,\n kernel: ck.1\n )\n\n let detach = self.managementFlags.detach\n\n let process = try await container.bootstrap()\n progress.finish()\n\n do {\n let io = try ProcessIO.create(\n tty: self.processFlags.tty,\n interactive: self.processFlags.interactive,\n detach: detach\n )\n\n if !self.managementFlags.cidfile.isEmpty {\n let path = self.managementFlags.cidfile\n let data = id.data(using: .utf8)\n var attributes = [FileAttributeKey: Any]()\n attributes[.posixPermissions] = 0o644\n let success = FileManager.default.createFile(\n atPath: path,\n contents: data,\n attributes: attributes\n )\n guard success else {\n throw ContainerizationError(\n .internalError, message: \"failed to create cidfile at \\(path): \\(errno)\")\n }\n }\n\n if detach {\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n print(id)\n return\n }\n\n if !self.processFlags.tty {\n var handler = SignalThreshold(threshold: 3, signals: [SIGINT, SIGTERM])\n handler.start {\n print(\"Received 3 SIGINT/SIGTERM's, forcefully exiting.\")\n Darwin.exit(1)\n }\n }\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to run container: \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n\nstruct ProcessIO {\n let stdin: Pipe?\n let stdout: Pipe?\n let stderr: Pipe?\n var ioTracker: IoTracker?\n\n struct IoTracker {\n let stream: AsyncStream\n let cont: AsyncStream.Continuation\n let configuredStreams: Int\n }\n\n let stdio: [FileHandle?]\n\n let console: Terminal?\n\n func closeAfterStart() throws {\n try stdin?.fileHandleForReading.close()\n try stdout?.fileHandleForWriting.close()\n try stderr?.fileHandleForWriting.close()\n }\n\n func close() throws {\n try console?.reset()\n }\n\n static func create(tty: Bool, interactive: Bool, detach: Bool) throws -> ProcessIO {\n let current: Terminal? = try {\n if !tty || !interactive {\n return nil\n }\n let current = try Terminal.current\n try current.setraw()\n return current\n }()\n\n var stdio = [FileHandle?](repeating: nil, count: 3)\n\n let stdin: Pipe? = {\n if !interactive && !tty {\n return nil\n }\n return Pipe()\n }()\n\n if let stdin {\n if interactive {\n let pin = FileHandle.standardInput\n let stdinOSFile = OSFile(fd: pin.fileDescriptor)\n let pipeOSFile = OSFile(fd: stdin.fileHandleForWriting.fileDescriptor)\n try stdinOSFile.makeNonBlocking()\n nonisolated(unsafe) let buf = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n\n pin.readabilityHandler = { _ in\n Self.streamStdin(\n from: stdinOSFile,\n to: pipeOSFile,\n buffer: buf,\n ) {\n pin.readabilityHandler = nil\n buf.deallocate()\n try? stdin.fileHandleForWriting.close()\n }\n }\n }\n stdio[0] = stdin.fileHandleForReading\n }\n\n let stdout: Pipe? = {\n if detach {\n return nil\n }\n return Pipe()\n }()\n\n var configuredStreams = 0\n let (stream, cc) = AsyncStream.makeStream()\n if let stdout {\n configuredStreams += 1\n let pout: FileHandle = {\n if let current {\n return current.handle\n }\n return .standardOutput\n }()\n\n let rout = stdout.fileHandleForReading\n rout.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n rout.readabilityHandler = nil\n cc.yield()\n return\n }\n try! pout.write(contentsOf: data)\n }\n stdio[1] = stdout.fileHandleForWriting\n }\n\n let stderr: Pipe? = {\n if detach || tty {\n return nil\n }\n return Pipe()\n }()\n if let stderr {\n configuredStreams += 1\n let perr: FileHandle = .standardError\n let rerr = stderr.fileHandleForReading\n rerr.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n rerr.readabilityHandler = nil\n cc.yield()\n return\n }\n try! perr.write(contentsOf: data)\n }\n stdio[2] = stderr.fileHandleForWriting\n }\n\n var ioTracker: IoTracker? = nil\n if configuredStreams > 0 {\n ioTracker = .init(stream: stream, cont: cc, configuredStreams: configuredStreams)\n }\n\n return .init(\n stdin: stdin,\n stdout: stdout,\n stderr: stderr,\n ioTracker: ioTracker,\n stdio: stdio,\n console: current\n )\n }\n\n static func streamStdin(\n from: OSFile,\n to: OSFile,\n buffer: UnsafeMutableBufferPointer,\n onErrorOrEOF: () -> Void,\n ) {\n while true {\n let (bytesRead, action) = from.read(buffer)\n if bytesRead > 0 {\n let view = UnsafeMutableBufferPointer(\n start: buffer.baseAddress,\n count: bytesRead\n )\n\n let (bytesWritten, _) = to.write(view)\n if bytesWritten != bytesRead {\n onErrorOrEOF()\n return\n }\n }\n\n switch action {\n case .error(_), .eof, .brokenPipe:\n onErrorOrEOF()\n return\n case .again:\n return\n case .success:\n break\n }\n }\n }\n\n public func wait() async throws {\n guard let ioTracker = self.ioTracker else {\n return\n }\n do {\n try await Timeout.run(seconds: 3) {\n var counter = ioTracker.configuredStreams\n for await _ in ioTracker.stream {\n counter -= 1\n if counter == 0 {\n ioTracker.cont.finish()\n break\n }\n }\n }\n } catch {\n log.error(\"Timeout waiting for IO to complete : \\(error)\")\n throw error\n }\n }\n}\n\nstruct OSFile: Sendable {\n private let fd: Int32\n\n enum IOAction: Equatable {\n case eof\n case again\n case success\n case brokenPipe\n case error(_ errno: Int32)\n }\n\n init(fd: Int32) {\n self.fd = fd\n }\n\n init(handle: FileHandle) {\n self.fd = handle.fileDescriptor\n }\n\n func makeNonBlocking() throws {\n let flags = fcntl(fd, F_GETFL)\n guard flags != -1 else {\n throw POSIXError.fromErrno()\n }\n\n if fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1 {\n throw POSIXError.fromErrno()\n }\n }\n\n func write(_ buffer: UnsafeMutableBufferPointer) -> (wrote: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesWrote: Int = 0\n while true {\n let n = Darwin.write(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesWrote),\n buffer.count - bytesWrote\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesWrote, .again)\n }\n return (bytesWrote, .error(errno))\n }\n\n if n == 0 {\n return (bytesWrote, .brokenPipe)\n }\n\n bytesWrote += n\n if bytesWrote < buffer.count {\n continue\n }\n return (bytesWrote, .success)\n }\n }\n\n func read(_ buffer: UnsafeMutableBufferPointer) -> (read: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesRead: Int = 0\n while true {\n let n = Darwin.read(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesRead),\n buffer.count - bytesRead\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesRead, .again)\n }\n return (bytesRead, .error(errno))\n }\n\n if n == 0 {\n return (bytesRead, .eof)\n }\n\n bytesRead += n\n if bytesRead < buffer.count {\n continue\n }\n return (bytesRead, .success)\n }\n }\n}\n"], ["/container/Sources/SocketForwarder/UDPForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\nimport Synchronization\n\n// Proxy backend for a single client address (clientIP, clientPort).\nprivate final class UDPProxyBackend: ChannelInboundHandler, Sendable {\n typealias InboundIn = AddressedEnvelope\n typealias OutboundOut = AddressedEnvelope\n\n private struct State {\n var queuedPayloads: Deque\n var channel: (any Channel)?\n }\n\n private let clientAddress: SocketAddress\n private let serverAddress: SocketAddress\n private let frontendChannel: any Channel\n private let log: Logger?\n private let state: Mutex\n\n init(clientAddress: SocketAddress, serverAddress: SocketAddress, frontendChannel: any Channel, log: Logger? = nil) {\n self.clientAddress = clientAddress\n self.serverAddress = serverAddress\n self.frontendChannel = frontendChannel\n self.log = log\n let state = State(queuedPayloads: Deque(), channel: nil)\n self.state = Mutex(state)\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n // relay data from server to client.\n let inbound = self.unwrapInboundIn(data)\n let outbound = OutboundOut(remoteAddress: self.clientAddress, data: inbound.data)\n self.log?.trace(\"backend - writing datagram to client\")\n _ = self.frontendChannel.writeAndFlush(outbound)\n }\n\n func channelActive(context: ChannelHandlerContext) {\n state.withLock {\n if !$0.queuedPayloads.isEmpty {\n self.log?.trace(\"backend - writing \\($0.queuedPayloads.count) queued datagrams to server\")\n while let queuedData = $0.queuedPayloads.popFirst() {\n let outbound: UDPProxyBackend.OutboundOut = OutboundOut(remoteAddress: self.serverAddress, data: queuedData)\n _ = context.channel.writeAndFlush(outbound)\n }\n }\n $0.channel = context.channel\n }\n }\n\n func write(data: ByteBuffer) {\n // change package remote address from proxy server to real server\n state.withLock {\n if let channel = $0.channel {\n // channel has been initialized, so relay any queued packets, along with this one to outbound\n self.log?.trace(\"backend - writing datagram to server\")\n let outbound: UDPProxyBackend.OutboundOut = OutboundOut(remoteAddress: self.serverAddress, data: data)\n _ = channel.writeAndFlush(outbound)\n } else {\n // channel is initializing, queue\n self.log?.trace(\"backend - queuing datagram\")\n $0.queuedPayloads.append(data)\n }\n }\n }\n\n func close() {\n state.withLock {\n guard let channel = $0.channel else {\n self.log?.warning(\"backend - close on inactive channel\")\n return\n }\n _ = channel.close()\n }\n }\n}\n\nprivate struct ProxyContext {\n public let proxy: UDPProxyBackend\n public let closeFuture: EventLoopFuture\n}\n\nprivate final class UDPProxyFrontend: ChannelInboundHandler, Sendable {\n typealias InboundIn = AddressedEnvelope\n typealias OutboundOut = AddressedEnvelope\n private let maxProxies = UInt(256)\n\n private let proxyAddress: SocketAddress\n private let serverAddress: SocketAddress\n private let eventLoopGroup: any EventLoopGroup\n private let log: Logger?\n\n private let proxies: Mutex>\n\n init(proxyAddress: SocketAddress, serverAddress: SocketAddress, eventLoopGroup: any EventLoopGroup, log: Logger? = nil) {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.proxies = Mutex(LRUCache(size: maxProxies))\n self.log = log\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n let inbound = self.unwrapInboundIn(data)\n\n guard let clientIP = inbound.remoteAddress.ipAddress else {\n log?.error(\"frontend - no client IP address in inbound payload\")\n return\n }\n\n guard let clientPort = inbound.remoteAddress.port else {\n log?.error(\"frontend - no client port in inbound payload\")\n return\n }\n\n let key = \"\\(clientIP):\\(clientPort)\"\n do {\n try proxies.withLock {\n if let context = $0.get(key) {\n context.proxy.write(data: inbound.data)\n } else {\n self.log?.trace(\"frontend - creating backend\")\n let proxy = UDPProxyBackend(\n clientAddress: inbound.remoteAddress,\n serverAddress: self.serverAddress,\n frontendChannel: context.channel,\n log: log\n )\n let proxyAddress = try SocketAddress(ipAddress: \"0.0.0.0\", port: 0)\n let proxyToServerFuture = DatagramBootstrap(group: self.eventLoopGroup)\n .channelInitializer {\n self.log?.trace(\"frontend - initializing backend\")\n return $0.pipeline.addHandler(proxy)\n }\n .bind(to: proxyAddress)\n .flatMap { $0.closeFuture }\n let context = ProxyContext(proxy: proxy, closeFuture: proxyToServerFuture)\n if let (_, evictedContext) = $0.put(key: key, value: context) {\n self.log?.trace(\"frontend - closing evicted backend\")\n evictedContext.proxy.close()\n }\n\n proxy.write(data: inbound.data)\n }\n }\n } catch {\n log?.error(\"server handler - backend channel creation failed with error: \\(error)\")\n return\n }\n }\n}\n\npublic struct UDPForwarder: SocketForwarder {\n private let proxyAddress: SocketAddress\n\n private let serverAddress: SocketAddress\n\n private let eventLoopGroup: any EventLoopGroup\n\n private let log: Logger?\n\n public init(\n proxyAddress: SocketAddress,\n serverAddress: SocketAddress,\n eventLoopGroup: any EventLoopGroup,\n log: Logger? = nil\n ) throws {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.log = log\n }\n\n public func run() throws -> EventLoopFuture {\n self.log?.trace(\"frontend - creating channel\")\n let proxyToServerHandler = UDPProxyFrontend(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: log\n )\n let bootstrap = DatagramBootstrap(group: self.eventLoopGroup)\n .channelInitializer { serverChannel in\n self.log?.trace(\"frontend - initializing channel\")\n return serverChannel.pipeline.addHandler(proxyToServerHandler)\n }\n return\n bootstrap\n .bind(to: proxyAddress)\n .flatMap { $0.eventLoop.makeSucceededFuture(SocketForwarderResult(channel: $0)) }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct ContainerStop: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"stop\",\n abstract: \"Stop one or more running containers\")\n\n @Flag(name: .shortAndLong, help: \"Stop all running containers\")\n var all = false\n\n @Option(name: .shortAndLong, help: \"Signal to send the container(s)\")\n var signal: String = \"SIGTERM\"\n\n @Option(name: .shortAndLong, help: \"Seconds to wait before killing the container(s)\")\n var time: Int32 = 5\n\n @Argument\n var containerIDs: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument, message: \"explicitly supplied container IDs conflicts with the --all flag\")\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n var containers = [ClientContainer]()\n if self.all {\n containers = try await ClientContainer.list()\n } else {\n containers = try await ClientContainer.list().filter { c in\n set.contains(c.id)\n }\n }\n\n let opts = ContainerStopOptions(\n timeoutInSeconds: self.time,\n signal: try Signals.parseSignal(self.signal)\n )\n let failed = try await Self.stopContainers(containers: containers, stopOptions: opts)\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"stop failed for one or more containers \\(failed.joined(separator: \",\"))\")\n }\n }\n\n static func stopContainers(containers: [ClientContainer], stopOptions: ContainerStopOptions) async throws -> [String] {\n var failed: [String] = []\n try await withThrowingTaskGroup(of: ClientContainer?.self) { group in\n for container in containers {\n group.addTask {\n do {\n try await container.stop(opts: stopOptions)\n print(container.id)\n return nil\n } catch {\n log.error(\"failed to stop container \\(container.id): \\(error)\")\n return container\n }\n }\n }\n\n for try await ctr in group {\n guard let ctr else {\n continue\n }\n failed.append(ctr.id)\n }\n }\n\n return failed\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct SystemStart: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Start `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Path to the `container-apiserver` binary\")\n var path: String = Bundle.main.executablePath ?? \"\"\n\n @Flag(name: .long, help: \"Enable debug logging for the runtime daemon.\")\n var debug = false\n\n @Flag(\n name: .long, inversion: .prefixedEnableDisable,\n help: \"Specify whether the default kernel should be installed or not. The default behavior is to prompt the user for a response.\")\n var kernelInstall: Bool?\n\n func run() async throws {\n // Without the true path to the binary in the plist, `container-apiserver` won't launch properly.\n let executableUrl = URL(filePath: path)\n .resolvingSymlinksInPath()\n .deletingLastPathComponent()\n .appendingPathComponent(\"container-apiserver\")\n\n var args = [executableUrl.absolutePath()]\n if debug {\n args.append(\"--debug\")\n }\n\n let apiServerDataUrl = appRoot.appending(path: \"apiserver\")\n try! FileManager.default.createDirectory(at: apiServerDataUrl, withIntermediateDirectories: true)\n let env = ProcessInfo.processInfo.environment.filter { key, _ in\n key.hasPrefix(\"CONTAINER_\")\n }\n\n let logURL = apiServerDataUrl.appending(path: \"apiserver.log\")\n let plist = LaunchPlist(\n label: \"com.apple.container.apiserver\",\n arguments: args,\n environment: env,\n limitLoadToSessionType: [.Aqua, .Background, .System],\n runAtLoad: true,\n stdout: logURL.path,\n stderr: logURL.path,\n machServices: [\"com.apple.container.apiserver\"]\n )\n\n let plistURL = apiServerDataUrl.appending(path: \"apiserver.plist\")\n let data = try plist.encode()\n try data.write(to: plistURL)\n\n try ServiceManager.register(plistPath: plistURL.path)\n\n // Now ping our friendly daemon. Fail if we don't get a response.\n do {\n print(\"Verifying apiserver is running...\")\n try await ClientHealthCheck.ping(timeout: .seconds(10))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get a response from apiserver: \\(error)\"\n )\n }\n\n if await !initImageExists() {\n try? await installInitialFilesystem()\n }\n\n guard await !kernelExists() else {\n return\n }\n try await installDefaultKernel()\n }\n\n private func installInitialFilesystem() async throws {\n let dep = Dependencies.initFs\n let pullCommand = ImagePull(reference: dep.source)\n print(\"Installing base container filesystem...\")\n do {\n try await pullCommand.run()\n } catch {\n log.error(\"Failed to install base container filesystem: \\(error)\")\n }\n }\n\n private func installDefaultKernel() async throws {\n let kernelDependency = Dependencies.kernel\n let defaultKernelURL = kernelDependency.source\n let defaultKernelBinaryPath = ClientDefaults.get(key: .defaultKernelBinaryPath)\n\n var shouldInstallKernel = false\n if kernelInstall == nil {\n print(\"No default kernel configured.\")\n print(\"Install the recommended default kernel from [\\(kernelDependency.source)]? [Y/n]: \", terminator: \"\")\n guard let read = readLine(strippingNewline: true) else {\n throw ContainerizationError(.internalError, message: \"Failed to read user input\")\n }\n guard read.lowercased() == \"y\" || read.count == 0 else {\n print(\"Please use the `container system kernel set --recommended` command to configure the default kernel\")\n return\n }\n shouldInstallKernel = true\n } else {\n shouldInstallKernel = kernelInstall ?? false\n }\n guard shouldInstallKernel else {\n return\n }\n print(\"Installing kernel...\")\n try await KernelSet.downloadAndInstallWithProgressBar(tarRemoteURL: defaultKernelURL, kernelFilePath: defaultKernelBinaryPath)\n }\n\n private func initImageExists() async -> Bool {\n do {\n let img = try await ClientImage.get(reference: Dependencies.initFs.source)\n let _ = try await img.getSnapshot(platform: .current)\n return true\n } catch {\n return false\n }\n }\n\n private func kernelExists() async -> Bool {\n do {\n try await ClientKernel.getDefaultKernel(for: .current)\n return true\n } catch {\n return false\n }\n }\n }\n\n private enum Dependencies: String {\n case kernel\n case initFs\n\n var source: String {\n switch self {\n case .initFs:\n return ClientDefaults.get(key: .defaultInitImage)\n case .kernel:\n return ClientDefaults.get(key: .defaultKernelURL)\n }\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/RemoteContentStoreClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Crypto\nimport ContainerizationError\nimport Foundation\nimport ContainerizationOCI\nimport ContainerXPC\n\npublic struct RemoteContentStoreClient: ContentStore {\n private static let serviceIdentifier = \"com.apple.container.core.container-core-images\"\n private static let encoder = JSONEncoder()\n\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public init() {}\n\n private func _get(digest: String) async throws -> URL? {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentGet)\n request.set(key: .digest, value: digest)\n do {\n let response = try await client.send(request)\n guard let path = response.string(key: .contentPath) else {\n return nil\n }\n return URL(filePath: path)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return nil\n }\n throw error\n }\n }\n\n public func get(digest: String) async throws -> Content? {\n guard let url = try await self._get(digest: digest) else {\n return nil\n }\n return try LocalContent(path: url)\n }\n\n public func get(digest: String) async throws -> T? {\n guard let content: Content = try await self.get(digest: digest) else {\n return nil\n }\n return try content.decode()\n }\n\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentClean)\n\n let d = try Self.encoder.encode(keeping)\n request.set(key: .digests, value: d)\n let response = try await client.send(request)\n\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let deleted = try decoder.decode([String].self, from: data)\n let size = response.uint64(key: .size)\n return (deleted, size)\n }\n\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentDelete)\n\n let d = try Self.encoder.encode(digests)\n request.set(key: .digests, value: d)\n let response = try await client.send(request)\n\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let deleted = try decoder.decode([String].self, from: data)\n let size = response.uint64(key: .size)\n return (deleted, size)\n }\n\n @discardableResult\n public func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String] {\n let (id, tempPath) = try await self.newIngestSession()\n try await body(tempPath)\n return try await self.completeIngestSession(id)\n }\n\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestStart)\n let response = try await client.send(request)\n guard let id = response.string(key: .ingestSessionId) else {\n throw ContainerizationError.init(.internalError, message: \"failed create new ingest session\")\n }\n guard let dir = response.string(key: .directory) else {\n throw ContainerizationError.init(.internalError, message: \"failed create new ingest session\")\n }\n return (id, URL(filePath: dir))\n }\n\n @discardableResult\n public func completeIngestSession(_ id: String) async throws -> [String] {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestComplete)\n\n request.set(key: .ingestSessionId, value: id)\n\n let response = try await client.send(request)\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let ingested = try decoder.decode([String].self, from: data)\n return ingested\n }\n\n public func cancelIngestSession(_ id: String) async throws {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestCancel)\n request.set(key: .ingestSessionId, value: id)\n try await client.send(request)\n }\n}\n\n#endif\n"], ["/container/Sources/CLI/Builder/BuilderStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderStatus: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"status\"\n config._superCommandName = \"builder\"\n config.abstract = \"Print builder status\"\n config.usage = \"\\n\\t builder status [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Flag(name: .long, help: ArgumentHelp(\"Display detailed status in json format\"))\n var json: Bool = false\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n if json {\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.prettyPrinted, .sortedKeys]\n let jsonData = try encoder.encode(container)\n\n guard let jsonString = String(data: jsonData, encoding: .utf8) else {\n throw ContainerizationError(.internalError, message: \"failed to encode BuildKit container as json\")\n }\n print(jsonString)\n return\n }\n\n let image = container.configuration.image.reference\n let resources = container.configuration.resources\n let cpus = resources.cpus\n let memory = resources.memoryInBytes / (1024 * 1024) // bytes to MB\n let addr = \"\"\n\n print(\"ID IMAGE STATE ADDR CPUS MEMORY\")\n print(\"\\(container.id) \\(image) \\(container.status.rawValue.uppercased()) \\(addr) \\(cpus) \\(memory) MB\")\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n print(\"builder is not running\")\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/APIServer/Kernel/KernelHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nstruct KernelHarness {\n private let log: Logging.Logger\n private let service: KernelService\n\n init(service: KernelService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n public func install(_ message: XPCMessage) async throws -> XPCMessage {\n let kernelFilePath = try message.kernelFilePath()\n let platform = try message.platform()\n\n guard let kernelTarUrl = try message.kernelTarURL() else {\n // We have been given a path to a kernel binary on disk\n guard let kernelFile = URL(string: kernelFilePath) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid kernel file path: \\(kernelFilePath)\")\n }\n try await self.service.installKernel(kernelFile: kernelFile, platform: platform)\n return message.reply()\n }\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await self.service.installKernelFrom(tar: kernelTarUrl, kernelFilePath: kernelFilePath, platform: platform, progressUpdate: progressUpdateService?.handler)\n return message.reply()\n }\n\n public func getDefaultKernel(_ message: XPCMessage) async throws -> XPCMessage {\n guard let platformData = message.dataNoCopy(key: .systemPlatform) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing SystemPlatform\")\n }\n let platform = try JSONDecoder().decode(SystemPlatform.self, from: platformData)\n let kernel = try await self.service.getDefaultKernel(platform: platform)\n let reply = message.reply()\n let data = try JSONEncoder().encode(kernel)\n reply.set(key: .kernel, value: data)\n return reply\n }\n}\n\nextension XPCMessage {\n fileprivate func platform() throws -> SystemPlatform {\n guard let platformData = self.dataNoCopy(key: .systemPlatform) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing SystemPlatform in XPC Message\")\n }\n let platform = try JSONDecoder().decode(SystemPlatform.self, from: platformData)\n return platform\n }\n\n fileprivate func kernelFilePath() throws -> String {\n guard let kernelFilePath = self.string(key: .kernelFilePath) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing kernel file path in XPC Message\")\n }\n return kernelFilePath\n }\n\n fileprivate func kernelTarURL() throws -> URL? {\n guard let kernelTarURLString = self.string(key: .kernelTarURL) else {\n return nil\n }\n guard let k = URL(string: kernelTarURLString) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse URL from \\(kernelTarURLString)\")\n }\n return k\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/AttachmentAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\n\nactor AttachmentAllocator {\n private let allocator: any AddressAllocator\n private var hostnames: [String: UInt32] = [:]\n\n init(lower: UInt32, size: Int) throws {\n allocator = try UInt32.rotatingAllocator(\n lower: lower,\n size: UInt32(size)\n )\n }\n\n /// Allocate a network address for a host.\n func allocate(hostname: String) async throws -> UInt32 {\n guard hostnames[hostname] == nil else {\n throw ContainerizationError(.exists, message: \"Hostname \\(hostname) already exists on the network\")\n }\n let index = try allocator.allocate()\n hostnames[hostname] = index\n\n return index\n }\n\n /// Free an allocated network address by hostname.\n func deallocate(hostname: String) async throws {\n if let index = hostnames.removeValue(forKey: hostname) {\n try allocator.release(index)\n }\n }\n\n /// If no addresses are allocated, prevent future allocations and return true.\n func disableAllocator() async -> Bool {\n allocator.disableAllocator()\n }\n\n /// Retrieve the allocator index for a hostname.\n func lookup(hostname: String) async throws -> UInt32? {\n hostnames[hostname]\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerLogs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Darwin\nimport Dispatch\nimport Foundation\n\nextension Application {\n struct ContainerLogs: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"logs\",\n abstract: \"Fetch container stdio or boot logs\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Flag(name: .shortAndLong, help: \"Follow log output\")\n var follow: Bool = false\n\n @Flag(name: .long, help: \"Display the boot log for the container instead of stdio\")\n var boot: Bool = false\n\n @Option(name: [.customShort(\"n\")], help: \"Number of lines to show from the end of the logs. If not provided this will print all of the logs\")\n var numLines: Int?\n\n @Argument(help: \"Container to fetch logs for\")\n var container: String\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: container)\n let fhs = try await container.logs()\n let fileHandle = boot ? fhs[1] : fhs[0]\n\n try await Self.tail(\n fh: fileHandle,\n n: numLines,\n follow: follow\n )\n } catch {\n throw ContainerizationError(\n .invalidArgument,\n message: \"failed to fetch container logs for \\(container): \\(error)\"\n )\n }\n }\n\n private static func tail(\n fh: FileHandle,\n n: Int?,\n follow: Bool\n ) async throws {\n if let n {\n var buffer = Data()\n let size = try fh.seekToEnd()\n var offset = size\n var lines: [String] = []\n\n while offset > 0, lines.count < n {\n let readSize = min(1024, offset)\n offset -= readSize\n try fh.seek(toOffset: offset)\n\n let data = fh.readData(ofLength: Int(readSize))\n buffer.insert(contentsOf: data, at: 0)\n\n if let chunk = String(data: buffer, encoding: .utf8) {\n lines = chunk.components(separatedBy: .newlines)\n lines = lines.filter { !$0.isEmpty }\n }\n }\n\n lines = Array(lines.suffix(n))\n for line in lines {\n print(line)\n }\n } else {\n // Fast path if all they want is the full file.\n guard let data = try fh.readToEnd() else {\n // Seems you get nil if it's a zero byte read, or you\n // try and read from dev/null.\n return\n }\n guard let str = String(data: data, encoding: .utf8) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to convert container logs to utf8\"\n )\n }\n print(str.trimmingCharacters(in: .newlines))\n }\n\n fflush(stdout)\n if follow {\n setbuf(stdout, nil)\n try await Self.followFile(fh: fh)\n }\n }\n\n private static func followFile(fh: FileHandle) async throws {\n _ = try fh.seekToEnd()\n let stream = AsyncStream { cont in\n fh.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n // Triggers on container restart - can exit here as well\n do {\n _ = try fh.seekToEnd() // To continue streaming existing truncated log files\n } catch {\n fh.readabilityHandler = nil\n cont.finish()\n return\n }\n }\n if let str = String(data: data, encoding: .utf8), !str.isEmpty {\n var lines = str.components(separatedBy: .newlines)\n lines = lines.filter { !$0.isEmpty }\n for line in lines {\n cont.yield(line)\n }\n }\n }\n }\n\n for await line in stream {\n print(line)\n }\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ContentServiceHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\n\npublic struct ContentServiceHarness: Sendable {\n private let log: Logging.Logger\n private let service: ContentStoreService\n\n public init(service: ContentStoreService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n public func get(_ message: XPCMessage) async throws -> XPCMessage {\n let d = message.string(key: .digest)\n guard let d else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n guard let path = try await service.get(digest: d) else {\n let err = ContainerizationError(.notFound, message: \"digest \\(d) not found\")\n let reply = message.reply()\n reply.set(error: err)\n return reply\n }\n let reply = message.reply()\n reply.set(key: .contentPath, value: path.path(percentEncoded: false))\n return reply\n }\n\n @Sendable\n public func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .digests)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n let digests = try JSONDecoder().decode([String].self, from: data)\n let (deleted, size) = try await self.service.delete(digests: digests)\n let d = try JSONEncoder().encode(deleted)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n reply.set(key: .size, value: size)\n return reply\n }\n\n @Sendable\n public func clean(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .digests)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n let digests = try JSONDecoder().decode([String].self, from: data)\n let (deleted, size) = try await self.service.delete(keeping: digests)\n let d = try JSONEncoder().encode(deleted)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n reply.set(key: .size, value: size)\n return reply\n }\n\n @Sendable\n public func newIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let session = try await self.service.newIngestSession()\n let id = session.id\n let dir = session.ingestDir\n let reply = message.reply()\n reply.set(key: .directory, value: dir.path(percentEncoded: false))\n reply.set(key: .ingestSessionId, value: id)\n return reply\n }\n\n @Sendable\n public func cancelIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .ingestSessionId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"missing ingest session id\")\n }\n try await self.service.cancelIngestSession(id)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func completeIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .ingestSessionId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"missing ingest session id\")\n }\n let ingested = try await self.service.completeIngestSession(id)\n let d = try JSONEncoder().encode(ingested)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n return reply\n }\n}\n"], ["/container/Sources/APIServer/Kernel/KernelService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\nimport TerminalProgress\n\nactor KernelService {\n private static let defaultKernelNamePrefix: String = \"default.kernel-\"\n\n private let log: Logger\n private let kernelDirectory: URL\n\n public init(log: Logger, appRoot: URL) throws {\n self.log = log\n self.kernelDirectory = appRoot.appending(path: \"kernels\")\n try FileManager.default.createDirectory(at: self.kernelDirectory, withIntermediateDirectories: true)\n }\n\n /// Copies a kernel binary from a local path on disk into the managed kernels directory\n /// as the default kernel for the provided platform.\n public func installKernel(kernelFile url: URL, platform: SystemPlatform = .linuxArm) throws {\n self.log.info(\"KernelService: \\(#function) - kernelFile: \\(url), platform: \\(String(describing: platform))\")\n let kFile = url.resolvingSymlinksInPath()\n let destPath = self.kernelDirectory.appendingPathComponent(kFile.lastPathComponent)\n try FileManager.default.copyItem(at: kFile, to: destPath)\n try Task.checkCancellation()\n do {\n try self.setDefaultKernel(name: kFile.lastPathComponent, platform: platform)\n } catch {\n try? FileManager.default.removeItem(at: destPath)\n throw error\n }\n }\n\n /// Copies a kernel binary from inside of tar file into the managed kernels directory\n /// as the default kernel for the provided platform.\n /// The parameter `tar` maybe a location to a local file on disk, or a remote URL.\n public func installKernelFrom(tar: URL, kernelFilePath: String, platform: SystemPlatform, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"KernelService: \\(#function) - tar: \\(tar), kernelFilePath: \\(kernelFilePath), platform: \\(String(describing: platform))\")\n\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n\n await progressUpdate?([\n .setDescription(\"Downloading kernel\")\n ])\n let taskManager = ProgressTaskCoordinator()\n let downloadTask = await taskManager.startTask()\n var tarFile = tar\n if !FileManager.default.fileExists(atPath: tar.absoluteString) {\n self.log.debug(\"KernelService: Downloading \\(tar)\")\n tarFile = tempDir.appendingPathComponent(tar.lastPathComponent)\n var downloadProgressUpdate: ProgressUpdateHandler?\n if let progressUpdate {\n downloadProgressUpdate = ProgressTaskCoordinator.handler(for: downloadTask, from: progressUpdate)\n }\n try await FileDownloader.downloadFile(url: tar, to: tarFile, progressUpdate: downloadProgressUpdate)\n }\n await taskManager.finish()\n\n await progressUpdate?([\n .setDescription(\"Unpacking kernel\")\n ])\n let archiveReader = try ArchiveReader(file: tarFile)\n let kernelFile = try archiveReader.extractFile(from: kernelFilePath, to: tempDir)\n try self.installKernel(kernelFile: kernelFile, platform: platform)\n\n if !FileManager.default.fileExists(atPath: tar.absoluteString) {\n try FileManager.default.removeItem(at: tarFile)\n }\n }\n\n private func setDefaultKernel(name: String, platform: SystemPlatform) throws {\n self.log.info(\"KernelService: \\(#function) - name: \\(name), platform: \\(String(describing: platform))\")\n let kernelPath = self.kernelDirectory.appendingPathComponent(name)\n guard FileManager.default.fileExists(atPath: kernelPath.path) else {\n throw ContainerizationError(.notFound, message: \"Kernel not found at \\(kernelPath)\")\n }\n let name = \"\\(Self.defaultKernelNamePrefix)\\(platform.architecture)\"\n let defaultKernelPath = self.kernelDirectory.appendingPathComponent(name)\n try? FileManager.default.removeItem(at: defaultKernelPath)\n try FileManager.default.createSymbolicLink(at: defaultKernelPath, withDestinationURL: kernelPath)\n }\n\n public func getDefaultKernel(platform: SystemPlatform = .linuxArm) async throws -> Kernel {\n self.log.info(\"KernelService: \\(#function) - platform: \\(String(describing: platform))\")\n let name = \"\\(Self.defaultKernelNamePrefix)\\(platform.architecture)\"\n let defaultKernelPath = self.kernelDirectory.appendingPathComponent(name).resolvingSymlinksInPath()\n guard FileManager.default.fileExists(atPath: defaultKernelPath.path) else {\n throw ContainerizationError(.notFound, message: \"Default kernel not found at \\(defaultKernelPath)\")\n }\n return Kernel(path: defaultKernelPath, platform: platform)\n }\n}\n\nextension ArchiveReader {\n fileprivate func extractFile(from: String, to directory: URL) throws -> URL {\n let (_, data) = try self.extractFile(path: from)\n try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)\n let fileName = URL(filePath: from).lastPathComponent\n let fileURL = directory.appendingPathComponent(fileName)\n try data.write(to: fileURL, options: .atomic)\n return fileURL\n }\n}\n"], ["/container/Sources/APIServer/Plugin/PluginsHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nstruct PluginsHarness {\n private let log: Logging.Logger\n private let service: PluginsService\n\n init(service: PluginsService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func load(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.load(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func get(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n let plugin = try await service.get(name: name)\n let data = try JSONEncoder().encode(plugin)\n\n let reply = message.reply()\n reply.set(key: .plugin, value: data)\n return reply\n }\n\n @Sendable\n func restart(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.restart(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func unload(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.unload(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let plugins = try await service.list()\n\n let data = try JSONEncoder().encode(plugins)\n\n let reply = message.reply()\n reply.set(key: .plugins, value: data)\n return reply\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerKill.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Darwin\n\nextension Application {\n struct ContainerKill: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kill\",\n abstract: \"Kill one or more running containers\")\n\n @Option(name: .shortAndLong, help: \"Signal to send the container(s)\")\n var signal: String = \"KILL\"\n\n @Flag(name: .shortAndLong, help: \"Kill all running containers\")\n var all = false\n\n @Argument(help: \"Container IDs\")\n var containerIDs: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(.invalidArgument, message: \"explicitly supplied container IDs conflicts with the --all flag\")\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n\n var containers = try await ClientContainer.list().filter { c in\n c.status == .running\n }\n if !self.all {\n containers = containers.filter { c in\n set.contains(c.id)\n }\n }\n\n let signalNumber = try Signals.parseSignal(signal)\n\n var failed: [String] = []\n for container in containers {\n do {\n try await container.kill(signalNumber)\n print(container.id)\n } catch {\n log.error(\"failed to kill container \\(container.id): \\(error)\")\n failed.append(container.id)\n }\n }\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"kill failed for one or more containers\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Archiver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationArchive\nimport ContainerizationOS\nimport Foundation\n\npublic final class Archiver: Sendable {\n public struct ArchiveEntryInfo: Sendable {\n let pathOnHost: URL\n let pathInArchive: URL\n\n public init(pathOnHost: URL, pathInArchive: URL) {\n self.pathOnHost = pathOnHost\n self.pathInArchive = pathInArchive\n }\n }\n\n public static func compress(\n source: URL,\n destination: URL,\n followSymlinks: Bool = false,\n writerConfiguration: ArchiveWriterConfiguration = ArchiveWriterConfiguration(format: .paxRestricted, filter: .gzip),\n closure: (URL) -> ArchiveEntryInfo?\n ) throws {\n let source = source.standardizedFileURL\n let destination = destination.standardizedFileURL\n\n let fileManager = FileManager.default\n try? fileManager.removeItem(at: destination)\n\n do {\n let directory = destination.deletingLastPathComponent()\n try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)\n\n guard\n let enumerator = FileManager.default.enumerator(\n at: source,\n includingPropertiesForKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]\n )\n else {\n throw Error.fileDoesNotExist(source)\n }\n\n var entryInfo = [ArchiveEntryInfo]()\n if !source.isDirectory {\n if let info = closure(source) {\n entryInfo.append(info)\n }\n } else {\n while let url = enumerator.nextObject() as? URL {\n guard let info = closure(url) else {\n continue\n }\n entryInfo.append(info)\n }\n }\n\n let archiver = try ArchiveWriter(\n configuration: writerConfiguration\n )\n try archiver.open(file: destination)\n\n for info in entryInfo {\n guard let entry = try Self._createEntry(entryInfo: info) else {\n throw Error.failedToCreateEntry\n }\n try Self._compressFile(item: info.pathOnHost, entry: entry, archiver: archiver)\n }\n try archiver.finishEncoding()\n } catch {\n try? fileManager.removeItem(at: destination)\n throw error\n }\n }\n\n public static func uncompress(source: URL, destination: URL) throws {\n let source = source.standardizedFileURL\n let destination = destination.standardizedFileURL\n\n // TODO: ArchiveReader needs some enhancement to support buffered uncompression\n let reader = try ArchiveReader(\n format: .paxRestricted,\n filter: .gzip,\n file: source\n )\n\n for (entry, data) in reader {\n guard let path = entry.path else {\n continue\n }\n let uncompressPath = destination.appendingPathComponent(path)\n\n let fileManager = FileManager.default\n switch entry.fileType {\n case .blockSpecial, .characterSpecial, .socket:\n continue\n case .directory:\n try fileManager.createDirectory(\n at: uncompressPath,\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: entry.permissions\n ]\n )\n case .regular:\n try fileManager.createDirectory(\n at: uncompressPath.deletingLastPathComponent(),\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: 0o755\n ]\n )\n let success = fileManager.createFile(\n atPath: uncompressPath.path,\n contents: data,\n attributes: [\n FileAttributeKey.posixPermissions: entry.permissions\n ]\n )\n if !success {\n throw POSIXError.fromErrno()\n }\n try data.write(to: uncompressPath)\n case .symbolicLink:\n guard let target = entry.symlinkTarget else {\n continue\n }\n try fileManager.createDirectory(\n at: uncompressPath.deletingLastPathComponent(),\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: 0o755\n ]\n )\n try fileManager.createSymbolicLink(atPath: uncompressPath.path, withDestinationPath: target)\n continue\n default:\n continue\n }\n\n // FIXME: uid/gid for compress.\n try fileManager.setAttributes(\n [.posixPermissions: NSNumber(value: entry.permissions)],\n ofItemAtPath: uncompressPath.path\n )\n\n if let creationDate = entry.creationDate {\n try fileManager.setAttributes(\n [.creationDate: creationDate],\n ofItemAtPath: uncompressPath.path\n )\n }\n\n if let modificationDate = entry.modificationDate {\n try fileManager.setAttributes(\n [.modificationDate: modificationDate],\n ofItemAtPath: uncompressPath.path\n )\n }\n }\n }\n\n // MARK: private functions\n private static func _compressFile(item: URL, entry: WriteEntry, archiver: ArchiveWriter) throws {\n guard let stream = InputStream(url: item) else {\n return\n }\n\n let writer = archiver.makeTransactionWriter()\n\n let bufferSize = Int(1.mib())\n let readBuffer = UnsafeMutablePointer.allocate(capacity: bufferSize)\n\n stream.open()\n try writer.writeHeader(entry: entry)\n while true {\n let byteRead = stream.read(readBuffer, maxLength: bufferSize)\n if byteRead <= 0 {\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n try data.withUnsafeBytes { pointer in\n try writer.writeChunk(data: pointer)\n }\n }\n }\n stream.close()\n try writer.finish()\n }\n\n private static func _createEntry(entryInfo: ArchiveEntryInfo, pathPrefix: String = \"\") throws -> WriteEntry? {\n let entry = WriteEntry()\n let fileManager = FileManager.default\n let attributes = try fileManager.attributesOfItem(atPath: entryInfo.pathOnHost.path)\n\n if let fileType = attributes[.type] as? FileAttributeType {\n switch fileType {\n case .typeBlockSpecial, .typeCharacterSpecial, .typeSocket:\n return nil\n case .typeDirectory:\n entry.fileType = .directory\n case .typeRegular:\n entry.fileType = .regular\n case .typeSymbolicLink:\n entry.fileType = .symbolicLink\n let symlinkTarget = try fileManager.destinationOfSymbolicLink(atPath: entryInfo.pathOnHost.path)\n entry.symlinkTarget = symlinkTarget\n default:\n return nil\n }\n }\n if let posixPermissions = attributes[.posixPermissions] as? NSNumber {\n #if os(macOS)\n entry.permissions = posixPermissions.uint16Value\n #else\n entry.permissions = posixPermissions.uint32Value\n #endif\n }\n if let fileSize = attributes[.size] as? UInt64 {\n entry.size = Int64(fileSize)\n }\n if let uid = attributes[.ownerAccountID] as? NSNumber {\n entry.owner = uid.uint32Value\n }\n if let gid = attributes[.groupOwnerAccountID] as? NSNumber {\n entry.group = gid.uint32Value\n }\n if let creationDate = attributes[.creationDate] as? Date {\n entry.creationDate = creationDate\n }\n if let modificationDate = attributes[.modificationDate] as? Date {\n entry.modificationDate = modificationDate\n }\n\n let pathTrimmed = Self._trimPathPrefix(entryInfo.pathInArchive.relativePath, pathPrefix: pathPrefix)\n entry.path = pathTrimmed\n return entry\n }\n\n private static func _trimPathPrefix(_ path: String, pathPrefix: String) -> String {\n guard !path.isEmpty && !pathPrefix.isEmpty else {\n return path\n }\n\n let decodedPath = path.removingPercentEncoding ?? path\n\n guard decodedPath.hasPrefix(pathPrefix) else {\n return decodedPath\n }\n let trimmedPath = String(decodedPath.suffix(from: pathPrefix.endIndex))\n return trimmedPath\n }\n\n private static func _isSymbolicLink(_ path: URL) throws -> Bool {\n let resourceValues = try path.resourceValues(forKeys: [.isSymbolicLinkKey])\n if let isSymbolicLink = resourceValues.isSymbolicLink {\n if isSymbolicLink {\n return true\n }\n }\n return false\n }\n}\n\nextension Archiver {\n public enum Error: Swift.Error, CustomStringConvertible {\n case failedToCreateEntry\n case fileDoesNotExist(_ url: URL)\n\n public var description: String {\n switch self {\n case .failedToCreateEntry:\n return \"failed to create entry\"\n case .fileDoesNotExist(let url):\n return \"file \\(url.path) does not exist\"\n }\n }\n }\n}\n"], ["/container/Sources/CLI/System/Kernel/KernelSet.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct KernelSet: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default kernel\"\n )\n\n @Option(name: .customLong(\"binary\"), help: \"Path to the binary to set as the default kernel. If used with --tar, this points to a location inside the tar\")\n var binaryPath: String? = nil\n\n @Option(name: .customLong(\"tar\"), help: \"Filesystem path or remote URL to a tar ball that contains the kernel to use\")\n var tarPath: String? = nil\n\n @Option(name: .customLong(\"arch\"), help: \"The architecture of the kernel binary. One of (amd64, arm64)\")\n var architecture: String = ContainerizationOCI.Platform.current.architecture.description\n\n @Flag(name: .customLong(\"recommended\"), help: \"Download and install the recommended kernel as the default. This flag ignores any other arguments\")\n var recommended: Bool = false\n\n func run() async throws {\n if recommended {\n let url = ClientDefaults.get(key: .defaultKernelURL)\n let path = ClientDefaults.get(key: .defaultKernelBinaryPath)\n print(\"Installing the recommended kernel from \\(url)...\")\n try await Self.downloadAndInstallWithProgressBar(tarRemoteURL: url, kernelFilePath: path)\n return\n }\n guard tarPath != nil else {\n return try await self.setKernelFromBinary()\n }\n try await self.setKernelFromTar()\n }\n\n private func setKernelFromBinary() async throws {\n guard let binaryPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--binary'\")\n }\n let absolutePath = URL(fileURLWithPath: binaryPath, relativeTo: .currentDirectory()).absoluteURL.absoluteString\n let platform = try getSystemPlatform()\n try await ClientKernel.installKernel(kernelFilePath: absolutePath, platform: platform)\n }\n\n private func setKernelFromTar() async throws {\n guard let binaryPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--binary'\")\n }\n guard let tarPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--tar\")\n }\n let platform = try getSystemPlatform()\n let localTarPath = URL(fileURLWithPath: tarPath, relativeTo: .currentDirectory()).absoluteString\n let fm = FileManager.default\n if fm.fileExists(atPath: localTarPath) {\n try await ClientKernel.installKernelFromTar(tarFile: localTarPath, kernelFilePath: binaryPath, platform: platform)\n return\n }\n guard let remoteURL = URL(string: tarPath) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid remote URL '\\(tarPath)' for argument '--tar'. Missing protocol?\")\n }\n try await Self.downloadAndInstallWithProgressBar(tarRemoteURL: remoteURL.absoluteString, kernelFilePath: binaryPath, platform: platform)\n }\n\n private func getSystemPlatform() throws -> SystemPlatform {\n switch architecture {\n case \"arm64\":\n return .linuxArm\n case \"amd64\":\n return .linuxAmd\n default:\n throw ContainerizationError(.unsupported, message: \"Unsupported architecture \\(architecture)\")\n }\n }\n\n public static func downloadAndInstallWithProgressBar(tarRemoteURL: String, kernelFilePath: String, platform: SystemPlatform = .current) async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n totalTasks: 2\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n try await ClientKernel.installKernelFromTar(tarFile: tarRemoteURL, kernelFilePath: kernelFilePath, platform: platform, progressUpdate: progress.handler)\n progress.finish()\n }\n\n }\n}\n"], ["/container/Sources/CLI/Registry/Login.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Login: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: \"Login to a registry\"\n )\n\n @Option(name: .shortAndLong, help: \"Username\")\n var username: String = \"\"\n\n @Flag(help: \"Take the password from stdin\")\n var passwordStdin: Bool = false\n\n @Argument(help: \"Registry server name\")\n var server: String\n\n @OptionGroup\n var registry: Flags.Registry\n\n func run() async throws {\n var username = self.username\n var password = \"\"\n if passwordStdin {\n if username == \"\" {\n throw ContainerizationError(\n .invalidArgument, message: \"must provide --username with --password-stdin\")\n }\n guard let passwordData = try FileHandle.standardInput.readToEnd() else {\n throw ContainerizationError(.invalidArgument, message: \"failed to read password from stdin\")\n }\n password = String(decoding: passwordData, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)\n }\n let keychain = KeychainHelper(id: Constants.keychainID)\n if username == \"\" {\n username = try keychain.userPrompt(domain: server)\n }\n if password == \"\" {\n password = try keychain.passwordPrompt()\n print()\n }\n\n let server = Reference.resolveDomain(domain: server)\n let scheme = try RequestScheme(registry.scheme).schemeFor(host: server)\n let _url = \"\\(scheme)://\\(server)\"\n guard let url = URL(string: _url) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n guard let host = url.host else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid host \\(server)\")\n }\n\n let client = RegistryClient(\n host: host,\n scheme: scheme.rawValue,\n port: url.port,\n authentication: BasicAuthentication(username: username, password: password),\n retryOptions: .init(\n maxRetries: 10,\n retryInterval: 300_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n )\n try await client.ping()\n try keychain.save(domain: server, username: username, password: password)\n print(\"Login succeeded\")\n }\n }\n}\n"], ["/container/Sources/APIServer/Plugin/PluginsService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerPlugin\nimport Foundation\nimport Logging\n\nactor PluginsService {\n private let log: Logger\n private var loaded: [String: Plugin]\n private let pluginLoader: PluginLoader\n\n public init(pluginLoader: PluginLoader, log: Logger) {\n self.log = log\n self.loaded = [:]\n self.pluginLoader = pluginLoader\n }\n\n /// Load the specified plugins, or all plugins with services defined\n /// if none are explicitly specified.\n public func loadAll(\n _ plugins: [Plugin]? = nil,\n ) throws {\n let registerPlugins = plugins ?? pluginLoader.findPlugins()\n for plugin in registerPlugins {\n try pluginLoader.registerWithLaunchd(plugin: plugin)\n loaded[plugin.name] = plugin\n }\n }\n\n /// Stop the specified plugins, or all plugins with services defined\n /// if none are explicitly specified.\n public func stopAll(_ plugins: [Plugin]? = nil) throws {\n let deregisterPlugins = plugins ?? pluginLoader.findPlugins()\n for plugin in deregisterPlugins {\n try pluginLoader.deregisterWithLaunchd(plugin: plugin)\n self.loaded.removeValue(forKey: plugin.name)\n }\n }\n\n // MARK: XPC API surface.\n\n /// Load a single plugin, doing nothing if the plugin is already loaded.\n public func load(name: String) throws {\n guard self.loaded[name] == nil else {\n return\n }\n guard let plugin = pluginLoader.findPlugin(name: name) else {\n throw Error.pluginNotFound(name)\n }\n try pluginLoader.registerWithLaunchd(plugin: plugin)\n self.loaded[plugin.name] = plugin\n }\n\n /// Get information for a loaded plugin.\n public func get(name: String) throws -> Plugin {\n guard let plugin = loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n return plugin\n }\n\n /// Restart a loaded plugin.\n public func restart(name: String) throws {\n guard let plugin = self.loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n try ServiceManager.kickstart(fullServiceLabel: plugin.getLaunchdLabel())\n }\n\n /// Unload a loaded plugin.\n public func unload(name: String) throws {\n guard let plugin = self.loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n try pluginLoader.deregisterWithLaunchd(plugin: plugin)\n self.loaded.removeValue(forKey: plugin.name)\n }\n\n /// List all loaded plugins.\n public func list() throws -> [Plugin] {\n self.loaded.map { $0.value }\n }\n\n public enum Error: Swift.Error, CustomStringConvertible {\n case pluginNotFound(String)\n case pluginNotLoaded(String)\n\n public var description: String {\n switch self {\n case .pluginNotFound(let name):\n return \"plugin not found: \\(name)\"\n case .pluginNotLoaded(let name):\n return \"plugin not loaded: \\(name)\"\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationExtras\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ContainerList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List containers\",\n aliases: [\"ls\"])\n\n @Flag(name: .shortAndLong, help: \"Show stopped containers as well\")\n var all = false\n\n @Flag(name: .shortAndLong, help: \"Only output the container ID\")\n var quiet = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let containers = try await ClientContainer.list()\n try printContainers(containers: containers, format: format)\n }\n\n private func createHeader() -> [[String]] {\n [[\"ID\", \"IMAGE\", \"OS\", \"ARCH\", \"STATE\", \"ADDR\"]]\n }\n\n private func printContainers(containers: [ClientContainer], format: ListFormat) throws {\n if format == .json {\n let printables = containers.map {\n PrintableContainer($0)\n }\n let data = try JSONEncoder().encode(printables)\n print(String(data: data, encoding: .utf8)!)\n\n return\n }\n\n if self.quiet {\n containers.forEach {\n if !self.all && $0.status != .running {\n return\n }\n print($0.id)\n }\n return\n }\n\n var rows = createHeader()\n for container in containers {\n if !self.all && container.status != .running {\n continue\n }\n rows.append(container.asRow)\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n }\n}\n\nextension ClientContainer {\n var asRow: [String] {\n [\n self.id,\n self.configuration.image.reference,\n self.configuration.platform.os,\n self.configuration.platform.architecture,\n self.status.rawValue,\n self.networks.compactMap { try? CIDRAddress($0.address).address.description }.joined(separator: \",\"),\n ]\n }\n}\n\nstruct PrintableContainer: Codable {\n let status: RuntimeStatus\n let configuration: ContainerConfiguration\n let networks: [Attachment]\n\n init(_ container: ClientContainer) {\n self.status = container.status\n self.configuration = container.configuration\n self.networks = container.networks\n }\n}\n"], ["/container/Sources/CLI/Image/ImageRemove.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct RemoveImageOptions: ParsableArguments {\n @Flag(name: .shortAndLong, help: \"Remove all images\")\n var all: Bool = false\n\n @Argument\n var images: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n }\n\n struct RemoveImageImplementation {\n static func validate(options: RemoveImageOptions) throws {\n if options.images.count == 0 && !options.all {\n throw ContainerizationError(.invalidArgument, message: \"no image specified and --all not supplied\")\n }\n if options.images.count > 0 && options.all {\n throw ContainerizationError(.invalidArgument, message: \"explicitly supplied images conflict with the --all flag\")\n }\n }\n\n static func removeImage(options: RemoveImageOptions) async throws {\n let (found, notFound) = try await {\n if options.all {\n let found = try await ClientImage.list()\n let notFound: [String] = []\n return (found, notFound)\n }\n return try await ClientImage.get(names: options.images)\n }()\n var failures: [String] = notFound\n var didDeleteAnyImage = false\n for image in found {\n guard !Utility.isInfraImage(name: image.reference) else {\n continue\n }\n do {\n try await ClientImage.delete(reference: image.reference, garbageCollect: false)\n print(image.reference)\n didDeleteAnyImage = true\n } catch {\n log.error(\"failed to remove \\(image.reference): \\(error)\")\n failures.append(image.reference)\n }\n }\n let (_, size) = try await ClientImage.pruneImages()\n let formatter = ByteCountFormatter()\n let freed = formatter.string(fromByteCount: Int64(size))\n\n if didDeleteAnyImage {\n print(\"Reclaimed \\(freed) in disk space\")\n }\n if failures.count > 0 {\n throw ContainerizationError(.internalError, message: \"failed to delete one or more images: \\(failures)\")\n }\n }\n }\n\n struct ImageRemove: AsyncParsableCommand {\n @OptionGroup\n var options: RemoveImageOptions\n\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Remove one or more images\",\n aliases: [\"rm\"])\n\n func validate() throws {\n try RemoveImageImplementation.validate(options: options)\n }\n\n mutating func run() async throws {\n try await RemoveImageImplementation.removeImage(options: options)\n }\n }\n}\n"], ["/container/Sources/APIServer/ContainerDNSHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\nimport DNSServer\n\n/// Handler that uses table lookup to resolve hostnames.\nstruct ContainerDNSHandler: DNSHandler {\n private let networkService: NetworksService\n private let ttl: UInt32\n\n public init(networkService: NetworksService, ttl: UInt32 = 5) {\n self.networkService = networkService\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n let record: ResourceRecord?\n switch question.type {\n case ResourceRecordType.host:\n record = try await answerHost(question: question)\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n\n guard let record else {\n return nil\n }\n\n return Message(\n id: query.id,\n type: .response,\n returnCode: .noError,\n questions: query.questions,\n answers: [record]\n )\n }\n\n private func answerHost(question: Question) async throws -> ResourceRecord? {\n guard let ipAllocation = try await networkService.lookup(hostname: question.name) else {\n return nil\n }\n\n let components = ipAllocation.address.split(separator: \"/\")\n guard !components.isEmpty else {\n throw DNSResolverError.serverError(\"Invalid IP format: empty address\")\n }\n\n let ipString = String(components[0])\n guard let ip = IPv4(ipString) else {\n throw DNSResolverError.serverError(\"Failed to parse IP address: \\(ipString)\")\n }\n\n return HostRecord(name: question.name, ttl: ttl, ip: ip)\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientProcess.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport NIOCore\nimport NIOPosix\nimport TerminalProgress\n\n/// A protocol that defines the methods and data members available to a process\n/// started inside of a container.\npublic protocol ClientProcess: Sendable {\n /// Identifier for the process.\n var id: String { get }\n\n /// Start the underlying process inside of the container.\n func start(_ stdio: [FileHandle?]) async throws\n /// Send a terminal resize request to the process `id`.\n func resize(_ size: Terminal.Size) async throws\n /// Send or \"kill\" a signal to the process `id`.\n /// Kill does not wait for the process to exit, it only delivers the signal.\n func kill(_ signal: Int32) async throws\n /// Wait for the process `id` to complete and return its exit code.\n /// This method blocks until the process exits and the code is obtained.\n func wait() async throws -> Int32\n}\n\nstruct ClientProcessImpl: ClientProcess, Sendable {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n /// Identifier of the container.\n public let containerId: String\n\n private let client: SandboxClient\n\n /// Identifier of a process. That is running inside of a container.\n /// This field is nil if the process this objects refers to is the\n /// init process of the container.\n public let processId: String?\n\n public var id: String {\n processId ?? containerId\n }\n\n init(containerId: String, processId: String? = nil, client: SandboxClient) {\n self.containerId = containerId\n self.processId = processId\n self.client = client\n }\n\n /// Start the container and return the initial process.\n public func start(_ stdio: [FileHandle?]) async throws {\n do {\n let client = self.client\n try await client.startProcess(self.id, stdio: stdio)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to start container\",\n cause: error\n )\n }\n }\n\n public func kill(_ signal: Int32) async throws {\n do {\n\n let client = self.client\n try await client.kill(self.id, signal: Int64(signal))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill process\",\n cause: error\n )\n }\n }\n\n public func resize(_ size: ContainerizationOS.Terminal.Size) async throws {\n do {\n\n let client = self.client\n try await client.resize(self.id, size: size)\n\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to resize process\",\n cause: error\n )\n }\n }\n\n public func wait() async throws -> Int32 {\n do {\n let client = self.client\n return try await client.wait(self.id)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to wait on process\",\n cause: error\n )\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientKernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct ClientKernel {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n}\n\nextension ClientKernel {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public static func installKernel(kernelFilePath: String, platform: SystemPlatform) async throws {\n let client = newClient()\n let message = XPCMessage(route: .installKernel)\n\n message.set(key: .kernelFilePath, value: kernelFilePath)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n try await client.send(message)\n }\n\n public static func installKernelFromTar(tarFile: String, kernelFilePath: String, platform: SystemPlatform, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let client = newClient()\n let message = XPCMessage(route: .installKernel)\n\n message.set(key: .kernelTarURL, value: tarFile)\n message.set(key: .kernelFilePath, value: kernelFilePath)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: message)\n }\n\n try await client.send(message)\n await progressUpdateClient?.finish()\n }\n\n @discardableResult\n public static func getDefaultKernel(for platform: SystemPlatform) async throws -> Kernel {\n let client = newClient()\n let message = XPCMessage(route: .getDefaultKernel)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n do {\n let reply = try await client.send(message)\n guard let kData = reply.dataNoCopy(key: .kernel) else {\n throw ContainerizationError(.internalError, message: \"Missing kernel data from XPC response\")\n }\n\n let kernel = try JSONDecoder().decode(Kernel.self, from: kData)\n return kernel\n } catch let err as ContainerizationError {\n guard err.isCode(.notFound) else {\n throw err\n }\n throw ContainerizationError(\n .notFound, message: \"Default kernel not configured for architecture \\(platform.architecture). Please use the `container system kernel set` command to configure it\")\n }\n }\n}\n\nextension SystemPlatform {\n public static var current: SystemPlatform {\n switch Platform.current.architecture {\n case \"arm64\":\n return .linuxArm\n case \"amd64\":\n return .linuxAmd\n default:\n fatalError(\"Unknown architecture\")\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildRemoteContentProxy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\n\nstruct BuildRemoteContentProxy: BuildPipelineHandler {\n let local: ContentStore\n\n public init(_ contentStore: ContentStore) throws {\n self.local = contentStore\n }\n\n func accept(_ packet: ServerStream) throws -> Bool {\n guard let imageTransfer = packet.getImageTransfer() else {\n return false\n }\n guard imageTransfer.stage() == \"content-store\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let imageTransfer = packet.getImageTransfer() else {\n throw Error.imageTransferMissing\n }\n\n guard let method = imageTransfer.method() else {\n throw Error.methodMissing\n }\n\n switch try ContentStoreMethod(method) {\n case .info:\n try await self.info(sender, imageTransfer, packet.buildID)\n case .readerAt:\n try await self.readerAt(sender, imageTransfer, packet.buildID)\n default:\n throw Error.unknownMethod(method)\n }\n }\n\n func info(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer, _ buildID: String) async throws {\n let descriptor = try await local.get(digest: packet.tag)\n let size = try descriptor?.size()\n let transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.info.rawValue,\n size: size\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n }\n\n func readerAt(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer, _ buildID: String) async throws {\n let digest = packet.descriptor.digest\n let offset: UInt64 = packet.offset() ?? 0\n let size: Int = packet.len() ?? 0\n guard let descriptor = try await local.get(digest: digest) else {\n throw Error.contentMissing\n }\n if offset == 0 && size == 0 { // Metadata request\n var transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.readerAt.rawValue,\n size: descriptor.size(),\n data: Data()\n )\n transfer.complete = true\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n return\n }\n guard let data = try descriptor.data(offset: offset, length: size) else {\n throw Error.invalidOffsetSizeForContent(packet.descriptor.digest, offset, size)\n }\n\n let transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.readerAt.rawValue,\n size: UInt64(data.count),\n data: data\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n }\n\n func delete(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.delete)\"])\n }\n\n func update(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.update)\"])\n }\n\n func walk(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.walk)\"])\n }\n\n enum ContentStoreMethod: String {\n case info = \"/containerd.services.content.v1.Content/Info\"\n case readerAt = \"/containerd.services.content.v1.Content/ReaderAt\"\n case delete = \"/containerd.services.content.v1.Content/Delete\"\n case update = \"/containerd.services.content.v1.Content/Update\"\n case walk = \"/containerd.services.content.v1.Content/Walk\"\n\n init(_ method: String) throws {\n guard let value = ContentStoreMethod(rawValue: method) else {\n throw Error.unknownMethod(method)\n }\n self = value\n }\n }\n}\n\nextension ImageTransfer {\n fileprivate init(id: String, digest: String, method: String, size: UInt64? = nil, data: Data = Data()) throws {\n self.init()\n self.id = id\n self.tag = digest\n self.metadata = [\n \"os\": \"linux\",\n \"stage\": \"content-store\",\n \"method\": method,\n ]\n if let size {\n self.metadata[\"size\"] = String(size)\n }\n self.complete = true\n self.direction = .into\n self.data = data\n }\n}\n\nextension BuildRemoteContentProxy {\n enum Error: Swift.Error, CustomStringConvertible {\n case imageTransferMissing\n case methodMissing\n case contentMissing\n case unknownMethod(String)\n case invalidOffsetSizeForContent(String, UInt64, Int)\n\n var description: String {\n switch self {\n case .imageTransferMissing:\n return \"imageTransfer is missing\"\n case .methodMissing:\n return \"method is missing in request\"\n case .contentMissing:\n return \"content cannot be found\"\n case .unknownMethod(let m):\n return \"unknown content-store method \\(m)\"\n case .invalidOffsetSizeForContent(let digest, let offset, let size):\n return \"invalid request for content: \\(digest) with offset: \\(offset) size: \\(size)\"\n }\n }\n }\n\n}\n"], ["/container/Sources/DNSServer/DNSServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\nimport NIOCore\nimport NIOPosix\n\n/// Provides a DNS server.\n/// - Parameters:\n/// - host: The host address on which to listen.\n/// - port: The port for the server to listen.\npublic struct DNSServer {\n public var handler: DNSHandler\n let log: Logger?\n\n public init(\n handler: DNSHandler,\n log: Logger? = nil\n ) {\n self.handler = handler\n self.log = log\n }\n\n public func run(host: String, port: Int) async throws {\n // TODO: TCP server\n let srv = try await DatagramBootstrap(group: NIOSingletons.posixEventLoopGroup)\n .channelOption(.socketOption(.so_reuseaddr), value: 1)\n .bind(host: host, port: port)\n .flatMapThrowing { channel in\n try NIOAsyncChannel(\n wrappingChannelSynchronously: channel,\n configuration: NIOAsyncChannel.Configuration(\n inboundType: AddressedEnvelope.self,\n outboundType: AddressedEnvelope.self\n )\n )\n }\n .get()\n\n try await srv.executeThenClose { inbound, outbound in\n for try await var packet in inbound {\n try await self.handle(outbound: outbound, packet: &packet)\n }\n }\n }\n\n public func run(socketPath: String) async throws {\n // TODO: TCP server\n let srv = try await DatagramBootstrap(group: NIOSingletons.posixEventLoopGroup)\n .bind(unixDomainSocketPath: socketPath, cleanupExistingSocketFile: true)\n .flatMapThrowing { channel in\n try NIOAsyncChannel(\n wrappingChannelSynchronously: channel,\n configuration: NIOAsyncChannel.Configuration(\n inboundType: AddressedEnvelope.self,\n outboundType: AddressedEnvelope.self\n )\n )\n }\n .get()\n\n try await srv.executeThenClose { inbound, outbound in\n for try await var packet in inbound {\n log?.debug(\"received packet from \\(packet.remoteAddress)\")\n try await self.handle(outbound: outbound, packet: &packet)\n log?.debug(\"sent packet\")\n }\n }\n }\n\n public func stop() async throws {}\n}\n"], ["/container/Sources/CLI/Image/ImageList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ListImageOptions: ParsableArguments {\n @Flag(name: .shortAndLong, help: \"Only output the image name\")\n var quiet = false\n\n @Flag(name: .shortAndLong, help: \"Verbose output\")\n var verbose = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n }\n\n struct ListImageImplementation {\n static private func createHeader() -> [[String]] {\n [[\"NAME\", \"TAG\", \"DIGEST\"]]\n }\n\n static private func createVerboseHeader() -> [[String]] {\n [[\"NAME\", \"TAG\", \"INDEX DIGEST\", \"OS\", \"ARCH\", \"VARIANT\", \"SIZE\", \"CREATED\", \"MANIFEST DIGEST\"]]\n }\n\n static private func printImagesVerbose(images: [ClientImage]) async throws {\n\n var rows = createVerboseHeader()\n for image in images {\n let formatter = ByteCountFormatter()\n for descriptor in try await image.index().manifests {\n // Don't list attestation manifests\n if let referenceType = descriptor.annotations?[\"vnd.docker.reference.type\"],\n referenceType == \"attestation-manifest\"\n {\n continue\n }\n\n guard let platform = descriptor.platform else {\n continue\n }\n\n let os = platform.os\n let arch = platform.architecture\n let variant = platform.variant ?? \"\"\n\n var config: ContainerizationOCI.Image\n var manifest: ContainerizationOCI.Manifest\n do {\n config = try await image.config(for: platform)\n manifest = try await image.manifest(for: platform)\n } catch {\n continue\n }\n\n let created = config.created ?? \"\"\n let size = descriptor.size + manifest.config.size + manifest.layers.reduce(0, { (l, r) in l + r.size })\n let formattedSize = formatter.string(fromByteCount: size)\n\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n let reference = try ContainerizationOCI.Reference.parse(processedReferenceString)\n let row = [\n reference.name,\n reference.tag ?? \"\",\n Utility.trimDigest(digest: image.descriptor.digest),\n os,\n arch,\n variant,\n formattedSize,\n created,\n Utility.trimDigest(digest: descriptor.digest),\n ]\n rows.append(row)\n }\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n\n static private func printImages(images: [ClientImage], format: ListFormat, options: ListImageOptions) async throws {\n var images = images\n images.sort {\n $0.reference < $1.reference\n }\n\n if format == .json {\n let data = try JSONEncoder().encode(images.map { $0.description })\n print(String(data: data, encoding: .utf8)!)\n return\n }\n\n if options.quiet {\n try images.forEach { image in\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n print(processedReferenceString)\n }\n return\n }\n\n if options.verbose {\n try await Self.printImagesVerbose(images: images)\n return\n }\n\n var rows = createHeader()\n for image in images {\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n let reference = try ContainerizationOCI.Reference.parse(processedReferenceString)\n rows.append([\n reference.name,\n reference.tag ?? \"\",\n Utility.trimDigest(digest: image.descriptor.digest),\n ])\n }\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n\n static func validate(options: ListImageOptions) throws {\n if options.quiet && options.verbose {\n throw ContainerizationError(.invalidArgument, message: \"Cannot use flag --quite and --verbose together\")\n }\n let modifier = options.quiet || options.verbose\n if modifier && options.format == .json {\n throw ContainerizationError(.invalidArgument, message: \"Cannot use flag --quite or --verbose along with --format json\")\n }\n }\n\n static func listImages(options: ListImageOptions) async throws {\n let images = try await ClientImage.list().filter { img in\n !Utility.isInfraImage(name: img.reference)\n }\n try await printImages(images: images, format: options.format, options: options)\n }\n }\n\n struct ImageList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List images\",\n aliases: [\"ls\"])\n\n @OptionGroup\n var options: ListImageOptions\n\n mutating func run() async throws {\n try ListImageImplementation.validate(options: options)\n try await ListImageImplementation.listImages(options: options)\n }\n }\n}\n"], ["/container/Sources/CLI/Registry/RegistryDefault.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct RegistryDefault: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"default\",\n abstract: \"Manage the default image registry\",\n subcommands: [\n DefaultSetCommand.self,\n DefaultUnsetCommand.self,\n DefaultInspectCommand.self,\n ]\n )\n }\n\n struct DefaultSetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default registry\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @Argument\n var host: String\n\n func run() async throws {\n let scheme = try RequestScheme(registry.scheme).schemeFor(host: host)\n\n let _url = \"\\(scheme)://\\(host)\"\n guard let url = URL(string: _url), let domain = url.host() else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n let resolvedDomain = Reference.resolveDomain(domain: domain)\n let client = RegistryClient(host: resolvedDomain, scheme: scheme.rawValue, port: url.port)\n do {\n try await client.ping()\n } catch let err as RegistryClient.Error {\n switch err {\n case .invalidStatus(url: _, .unauthorized, _), .invalidStatus(url: _, .forbidden, _):\n break\n default:\n throw err\n }\n }\n ClientDefaults.set(value: host, key: .defaultRegistryDomain)\n print(\"Set default registry to \\(host)\")\n }\n }\n\n struct DefaultUnsetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"unset\",\n abstract: \"Unset the default registry\",\n aliases: [\"clear\"]\n )\n\n func run() async throws {\n ClientDefaults.unset(key: .defaultRegistryDomain)\n print(\"Unset the default registry domain\")\n }\n }\n\n struct DefaultInspectCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display the default registry domain\"\n )\n\n func run() async throws {\n print(ClientDefaults.get(key: .defaultRegistryDomain))\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/Attachment.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A snapshot of a network interface allocated to a sandbox.\npublic struct Attachment: Codable, Sendable {\n /// The network ID associated with the attachment.\n public let network: String\n /// The hostname associated with the attachment.\n public let hostname: String\n /// The subnet CIDR, where the address is the container interface IPv4 address.\n public let address: String\n /// The IPv4 gateway address.\n public let gateway: String\n\n public init(network: String, hostname: String, address: String, gateway: String) {\n self.network = network\n self.hostname = hostname\n self.address = address\n self.gateway = gateway\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildImageResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\nimport Logging\n\nstruct BuildImageResolver: BuildPipelineHandler {\n let contentStore: ContentStore\n\n public init(_ contentStore: ContentStore) throws {\n self.contentStore = contentStore\n }\n\n func accept(_ packet: ServerStream) throws -> Bool {\n guard let imageTransfer = packet.getImageTransfer() else {\n return false\n }\n guard imageTransfer.stage() == \"resolver\" else {\n return false\n }\n guard imageTransfer.method() == \"/resolve\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let imageTransfer = packet.getImageTransfer() else {\n throw Error.imageTransferMissing\n }\n guard let ref = imageTransfer.ref() else {\n throw Error.tagMissing\n }\n\n guard let platform = try imageTransfer.platform() else {\n throw Error.platformMissing\n }\n\n let img = try await {\n guard let img = try? await ClientImage.pull(reference: ref, platform: platform) else {\n return try await ClientImage.fetch(reference: ref, platform: platform)\n }\n return img\n }()\n\n let index: Index = try await img.index()\n let buildID = packet.buildID\n let platforms = index.manifests.compactMap { $0.platform }\n for pl in platforms {\n if pl == platform {\n let manifest = try await img.manifest(for: pl)\n guard let ociImage: ContainerizationOCI.Image = try await self.contentStore.get(digest: manifest.config.digest) else {\n continue\n }\n let enc = JSONEncoder()\n let data = try enc.encode(ociImage)\n let transfer = try ImageTransfer(\n id: imageTransfer.id,\n digest: img.descriptor.digest,\n ref: ref,\n platform: platform.description,\n data: data\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n return\n }\n }\n throw Error.unknownPlatformForImage(platform.description, ref)\n }\n}\n\nextension ImageTransfer {\n fileprivate init(id: String, digest: String, ref: String, platform: String, data: Data) throws {\n self.init()\n self.id = id\n self.tag = digest\n self.metadata = [\n \"os\": \"linux\",\n \"stage\": \"resolver\",\n \"method\": \"/resolve\",\n \"ref\": ref,\n \"platform\": platform,\n ]\n self.complete = true\n self.direction = .into\n self.data = data\n }\n}\n\nextension BuildImageResolver {\n enum Error: Swift.Error, CustomStringConvertible {\n case imageTransferMissing\n case tagMissing\n case platformMissing\n case imageNameMissing\n case imageTagMissing\n case imageNotFound\n case indexDigestMissing(String)\n case unknownRegistry(String)\n case digestIsNotIndex(String)\n case digestIsNotManifest(String)\n case unknownPlatformForImage(String, String)\n\n var description: String {\n switch self {\n case .imageTransferMissing:\n return \"imageTransfer is missing\"\n case .tagMissing:\n return \"tag parameter missing in metadata\"\n case .platformMissing:\n return \"platform parameter missing in metadata\"\n case .imageNameMissing:\n return \"image name missing in $ref parameter\"\n case .imageTagMissing:\n return \"image tag missing in $ref parameter\"\n case .imageNotFound:\n return \"image not found\"\n case .indexDigestMissing(let ref):\n return \"index digest is missing for image: \\(ref)\"\n case .unknownRegistry(let registry):\n return \"registry \\(registry) is unknown\"\n case .digestIsNotIndex(let digest):\n return \"digest \\(digest) is not a descriptor to an index\"\n case .digestIsNotManifest(let digest):\n return \"digest \\(digest) is not a descriptor to a manifest\"\n case .unknownPlatformForImage(let platform, let ref):\n return \"platform \\(platform) for image \\(ref) not found\"\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/Bundle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport Foundation\n\npublic struct Bundle: Sendable {\n private static let initfsFilename = \"initfs.ext4\"\n private static let kernelFilename = \"kernel.json\"\n private static let kernelBinaryFilename = \"kernel.bin\"\n private static let containerRootFsBlockFilename = \"rootfs.ext4\"\n private static let containerRootFsFilename = \"rootfs.json\"\n\n static let containerConfigFilename = \"config.json\"\n\n /// The path to the bundle.\n public let path: URL\n\n public init(path: URL) {\n self.path = path\n }\n\n public var bootlog: URL {\n self.path.appendingPathComponent(\"vminitd.log\")\n }\n\n private var containerRootfsBlock: URL {\n self.path.appendingPathComponent(Self.containerRootFsBlockFilename)\n }\n\n private var containerRootfsConfig: URL {\n self.path.appendingPathComponent(Self.containerRootFsFilename)\n }\n\n public var containerRootfs: Filesystem {\n get throws {\n let data = try Data(contentsOf: containerRootfsConfig)\n let fs = try JSONDecoder().decode(Filesystem.self, from: data)\n return fs\n }\n }\n\n /// Return the initial filesystem for a sandbox.\n public var initialFilesystem: Filesystem {\n .block(\n format: \"ext4\",\n source: self.path.appendingPathComponent(Self.initfsFilename).path,\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n\n public var kernel: Kernel {\n get throws {\n try load(path: self.path.appendingPathComponent(Self.kernelFilename))\n }\n }\n\n public var configuration: ContainerConfiguration {\n get throws {\n try load(path: self.path.appendingPathComponent(Self.containerConfigFilename))\n }\n }\n}\n\nextension Bundle {\n public static func create(\n path: URL,\n initialFilesystem: Filesystem,\n kernel: Kernel,\n containerConfiguration: ContainerConfiguration? = nil\n ) throws -> Bundle {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n let kbin = path.appendingPathComponent(Self.kernelBinaryFilename)\n try FileManager.default.copyItem(at: kernel.path, to: kbin)\n var k = kernel\n k.path = kbin\n try write(path.appendingPathComponent(Self.kernelFilename), value: k)\n\n switch initialFilesystem.type {\n case .block(let fmt, _, _):\n guard fmt == \"ext4\" else {\n fatalError(\"ext4 is the only supported format for initial filesystem\")\n }\n // when saving the Initial Filesystem to the bundle\n // discard any filesystem information and just persist\n // the block into the Bundle.\n _ = try initialFilesystem.clone(to: path.appendingPathComponent(Self.initfsFilename).path)\n default:\n fatalError(\"invalid filesystem type for initial filesystem\")\n }\n let bundle = Bundle(path: path)\n if let containerConfiguration {\n try bundle.write(filename: Self.containerConfigFilename, value: containerConfiguration)\n }\n return bundle\n }\n}\n\nextension Bundle {\n /// Set the value of the configuration for the Bundle.\n public func set(configuration: ContainerConfiguration) throws {\n try write(filename: Self.containerConfigFilename, value: configuration)\n }\n\n /// Return the full filepath for a named resource in the Bundle.\n public func filePath(for name: String) -> URL {\n path.appendingPathComponent(name)\n }\n\n public func setContainerRootFs(cloning fs: Filesystem) throws {\n let cloned = try fs.clone(to: self.containerRootfsBlock.absolutePath())\n let fsData = try JSONEncoder().encode(cloned)\n try fsData.write(to: self.containerRootfsConfig)\n }\n\n /// Delete the bundle and all of the resources contained inside.\n public func delete() throws {\n try FileManager.default.removeItem(at: self.path)\n }\n\n public func write(filename: String, value: Encodable) throws {\n try Self.write(self.path.appendingPathComponent(filename), value: value)\n }\n\n private static func write(_ path: URL, value: Encodable) throws {\n let data = try JSONEncoder().encode(value)\n try data.write(to: path)\n }\n\n public func load(filename: String) throws -> T where T: Decodable {\n try load(path: self.path.appendingPathComponent(filename))\n }\n\n private func load(path: URL) throws -> T where T: Decodable {\n let data = try Data(contentsOf: path)\n return try JSONDecoder().decode(T.self, from: data)\n }\n}\n"], ["/container/Sources/SocketForwarder/ConnectHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Logging\nimport NIOCore\nimport NIOPosix\n\nfinal class ConnectHandler {\n private var pendingBytes: [NIOAny]\n private let serverAddress: SocketAddress\n private var log: Logger? = nil\n\n init(serverAddress: SocketAddress, log: Logger?) {\n self.pendingBytes = []\n self.serverAddress = serverAddress\n self.log = log\n }\n}\n\nextension ConnectHandler: ChannelInboundHandler {\n typealias InboundIn = ByteBuffer\n typealias OutboundOut = ByteBuffer\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n if self.pendingBytes.isEmpty {\n self.connectToServer(context: context)\n }\n self.pendingBytes.append(data)\n }\n\n func handlerAdded(context: ChannelHandlerContext) {\n // Add logger metadata.\n self.log?[metadataKey: \"proxy\"] = \"\\(context.channel.localAddress?.description ?? \"none\")\"\n self.log?[metadataKey: \"server\"] = \"\\(context.channel.remoteAddress?.description ?? \"none\")\"\n }\n}\n\nextension ConnectHandler: RemovableChannelHandler {\n func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) {\n var didRead = false\n\n // We are being removed, and need to deliver any pending bytes we may have if we're upgrading.\n while self.pendingBytes.count > 0 {\n let data = self.pendingBytes.removeFirst()\n context.fireChannelRead(data)\n didRead = true\n }\n\n if didRead {\n context.fireChannelReadComplete()\n }\n\n self.log?.trace(\"backend - removing connect handler from pipeline\")\n context.leavePipeline(removalToken: removalToken)\n }\n}\n\nextension ConnectHandler {\n private func connectToServer(context: ChannelHandlerContext) {\n self.log?.trace(\"backend - connecting\")\n\n ClientBootstrap(group: context.eventLoop)\n .connect(to: serverAddress)\n .assumeIsolatedUnsafeUnchecked()\n .whenComplete { result in\n switch result {\n case .success(let channel):\n self.log?.trace(\"backend - connected\")\n self.glue(channel, context: context)\n case .failure(let error):\n self.log?.error(\"backend - connect failed: \\(error)\")\n context.close(promise: nil)\n context.fireErrorCaught(error)\n }\n }\n }\n\n private func glue(_ peerChannel: Channel, context: ChannelHandlerContext) {\n self.log?.trace(\"backend - gluing channels\")\n\n // Now we need to glue our channel and the peer channel together.\n let (localGlue, peerGlue) = GlueHandler.matchedPair()\n do {\n try context.channel.pipeline.syncOperations.addHandler(localGlue)\n try peerChannel.pipeline.syncOperations.addHandler(peerGlue)\n context.pipeline.syncOperations.removeHandler(self, promise: nil)\n } catch {\n // Close connected peer channel before closing our channel.\n peerChannel.close(mode: .all, promise: nil)\n context.close(promise: nil)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/XPC+.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\n/// Keys for XPC fields.\npublic enum XPCKeys: String {\n /// Route key.\n case route\n /// Container array key.\n case containers\n /// ID key.\n case id\n // ID for a process.\n case processIdentifier\n /// Container configuration key.\n case containerConfig\n /// Container options key.\n case containerOptions\n /// Vsock port number key.\n case port\n /// Exit code for a process\n case exitCode\n /// An event that occurred in a container\n case containerEvent\n /// Error key.\n case error\n /// FD to a container resource key.\n case fd\n /// FDs pointing to container logs key.\n case logs\n /// Options for stopping a container key.\n case stopOptions\n /// Plugins\n case pluginName\n case plugins\n case plugin\n\n /// Health check request.\n case ping\n\n /// Process request keys.\n case signal\n case snapshot\n case stdin\n case stdout\n case stderr\n case status\n case width\n case height\n case processConfig\n\n /// Update progress\n case progressUpdateEndpoint\n case progressUpdateSetDescription\n case progressUpdateSetSubDescription\n case progressUpdateSetItemsName\n case progressUpdateAddTasks\n case progressUpdateSetTasks\n case progressUpdateAddTotalTasks\n case progressUpdateSetTotalTasks\n case progressUpdateAddItems\n case progressUpdateSetItems\n case progressUpdateAddTotalItems\n case progressUpdateSetTotalItems\n case progressUpdateAddSize\n case progressUpdateSetSize\n case progressUpdateAddTotalSize\n case progressUpdateSetTotalSize\n\n /// Network\n case networkId\n case networkConfig\n case networkState\n case networkStates\n\n /// Kernel\n case kernel\n case kernelTarURL\n case kernelFilePath\n case systemPlatform\n}\n\npublic enum XPCRoute: String {\n case listContainer\n case createContainer\n case deleteContainer\n case containerLogs\n case containerEvent\n\n case pluginLoad\n case pluginGet\n case pluginRestart\n case pluginUnload\n case pluginList\n\n case networkCreate\n case networkDelete\n case networkList\n\n case ping\n\n case installKernel\n case getDefaultKernel\n}\n\nextension XPCMessage {\n public init(route: XPCRoute) {\n self.init(route: route.rawValue)\n }\n\n public func data(key: XPCKeys) -> Data? {\n data(key: key.rawValue)\n }\n\n public func dataNoCopy(key: XPCKeys) -> Data? {\n dataNoCopy(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Data) {\n set(key: key.rawValue, value: value)\n }\n\n public func string(key: XPCKeys) -> String? {\n string(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: String) {\n set(key: key.rawValue, value: value)\n }\n\n public func bool(key: XPCKeys) -> Bool {\n bool(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Bool) {\n set(key: key.rawValue, value: value)\n }\n\n public func uint64(key: XPCKeys) -> UInt64 {\n uint64(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: UInt64) {\n set(key: key.rawValue, value: value)\n }\n\n public func int64(key: XPCKeys) -> Int64 {\n int64(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Int64) {\n set(key: key.rawValue, value: value)\n }\n\n public func int(key: XPCKeys) -> Int {\n Int(int64(key: key.rawValue))\n }\n\n public func set(key: XPCKeys, value: Int) {\n set(key: key.rawValue, value: Int64(value))\n }\n\n public func fileHandle(key: XPCKeys) -> FileHandle? {\n fileHandle(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: FileHandle) {\n set(key: key.rawValue, value: value)\n }\n\n public func fileHandles(key: XPCKeys) -> [FileHandle]? {\n fileHandles(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: [FileHandle]) throws {\n try set(key: key.rawValue, value: value)\n }\n\n public func endpoint(key: XPCKeys) -> xpc_endpoint_t? {\n endpoint(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: xpc_endpoint_t) {\n set(key: key.rawValue, value: value)\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerBuild/Builder.grpc.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n// DO NOT EDIT.\n// swift-format-ignore-file\n//\n// Generated by the protocol buffer compiler.\n// Source: Builder.proto\n//\nimport GRPC\nimport NIO\nimport NIOConcurrencyHelpers\nimport SwiftProtobuf\n\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// Usage: instantiate `Com_Apple_Container_Build_V1_BuilderClient`, then call methods of this protocol to make API calls.\npublic protocol Com_Apple_Container_Build_V1_BuilderClientProtocol: GRPCClient {\n var serviceName: String { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? { get }\n\n func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func performBuild(\n callOptions: CallOptions?,\n handler: @escaping (Com_Apple_Container_Build_V1_ServerStream) -> Void\n ) -> BidirectionalStreamingCall\n\n func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n}\n\nextension Com_Apple_Container_Build_V1_BuilderClientProtocol {\n public var serviceName: String {\n return \"com.apple.container.build.v1.Builder\"\n }\n\n /// Create a build request.\n ///\n /// - Parameters:\n /// - request: Request to send to CreateBuild.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n ///\n /// Callers should use the `send` method on the returned object to send messages\n /// to the server. The caller should send an `.end` after the final message has been sent.\n ///\n /// - Parameters:\n /// - callOptions: Call options.\n /// - handler: A closure called when each response is received from the server.\n /// - Returns: A `ClientStreamingCall` with futures for the metadata and status.\n public func performBuild(\n callOptions: CallOptions? = nil,\n handler: @escaping (Com_Apple_Container_Build_V1_ServerStream) -> Void\n ) -> BidirectionalStreamingCall {\n return self.makeBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n handler: handler\n )\n }\n\n /// Unary call to Info\n ///\n /// - Parameters:\n /// - request: Request to send to Info.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(*, deprecated)\nextension Com_Apple_Container_Build_V1_BuilderClient: @unchecked Sendable {}\n\n@available(*, deprecated, renamed: \"Com_Apple_Container_Build_V1_BuilderNIOClient\")\npublic final class Com_Apple_Container_Build_V1_BuilderClient: Com_Apple_Container_Build_V1_BuilderClientProtocol {\n private let lock = Lock()\n private var _defaultCallOptions: CallOptions\n private var _interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n public let channel: GRPCChannel\n public var defaultCallOptions: CallOptions {\n get { self.lock.withLock { return self._defaultCallOptions } }\n set { self.lock.withLockVoid { self._defaultCallOptions = newValue } }\n }\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? {\n get { self.lock.withLock { return self._interceptors } }\n set { self.lock.withLockVoid { self._interceptors = newValue } }\n }\n\n /// Creates a client for the com.apple.container.build.v1.Builder service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self._defaultCallOptions = defaultCallOptions\n self._interceptors = interceptors\n }\n}\n\npublic struct Com_Apple_Container_Build_V1_BuilderNIOClient: Com_Apple_Container_Build_V1_BuilderClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n\n /// Creates a client for the com.apple.container.build.v1.Builder service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol: GRPCClient {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? { get }\n\n func makeCreateBuildCall(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makePerformBuildCall(\n callOptions: CallOptions?\n ) -> GRPCAsyncBidirectionalStreamingCall\n\n func makeInfoCall(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Container_Build_V1_BuilderClientMetadata.serviceDescriptor\n }\n\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? {\n return nil\n }\n\n public func makeCreateBuildCall(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n public func makePerformBuildCall(\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncBidirectionalStreamingCall {\n return self.makeAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func makeInfoCall(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Container_Build_V1_CreateBuildResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n public func performBuild(\n _ requests: RequestStream,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncResponseStream where RequestStream: Sequence, RequestStream.Element == Com_Apple_Container_Build_V1_ClientStream {\n return self.performAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n requests: requests,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func performBuild(\n _ requests: RequestStream,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncResponseStream where RequestStream: AsyncSequence & Sendable, RequestStream.Element == Com_Apple_Container_Build_V1_ClientStream {\n return self.performAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n requests: requests,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Container_Build_V1_InfoResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic struct Com_Apple_Container_Build_V1_BuilderAsyncClient: Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\npublic protocol Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when invoking 'createBuild'.\n func makeCreateBuildInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'performBuild'.\n func makePerformBuildInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'info'.\n func makeInfoInterceptors() -> [ClientInterceptor]\n}\n\npublic enum Com_Apple_Container_Build_V1_BuilderClientMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"Builder\",\n fullName: \"com.apple.container.build.v1.Builder\",\n methods: [\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild,\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild,\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info,\n ]\n )\n\n public enum Methods {\n public static let createBuild = GRPCMethodDescriptor(\n name: \"CreateBuild\",\n path: \"/com.apple.container.build.v1.Builder/CreateBuild\",\n type: GRPCCallType.unary\n )\n\n public static let performBuild = GRPCMethodDescriptor(\n name: \"PerformBuild\",\n path: \"/com.apple.container.build.v1.Builder/PerformBuild\",\n type: GRPCCallType.bidirectionalStreaming\n )\n\n public static let info = GRPCMethodDescriptor(\n name: \"Info\",\n path: \"/com.apple.container.build.v1.Builder/Info\",\n type: GRPCCallType.unary\n )\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// To build a server, implement a class that conforms to this protocol.\npublic protocol Com_Apple_Container_Build_V1_BuilderProvider: CallHandlerProvider {\n var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? { get }\n\n /// Create a build request.\n func createBuild(request: Com_Apple_Container_Build_V1_CreateBuildRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n func performBuild(context: StreamingResponseCallContext) -> EventLoopFuture<(StreamEvent) -> Void>\n\n func info(request: Com_Apple_Container_Build_V1_InfoRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n}\n\nextension Com_Apple_Container_Build_V1_BuilderProvider {\n public var serviceName: Substring {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor.fullName[...]\n }\n\n /// Determines, calls and returns the appropriate request handler, depending on the request's method.\n /// Returns nil for methods not handled by this service.\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"CreateBuild\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? [],\n userFunction: self.createBuild(request:context:)\n )\n\n case \"PerformBuild\":\n return BidirectionalStreamingServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n observerFactory: self.performBuild(context:)\n )\n\n case \"Info\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeInfoInterceptors() ?? [],\n userFunction: self.info(request:context:)\n )\n\n default:\n return nil\n }\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// To implement a server, implement an object which conforms to this protocol.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Container_Build_V1_BuilderAsyncProvider: CallHandlerProvider, Sendable {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? { get }\n\n /// Create a build request.\n func createBuild(\n request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Container_Build_V1_CreateBuildResponse\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n func performBuild(\n requestStream: GRPCAsyncRequestStream,\n responseStream: GRPCAsyncResponseStreamWriter,\n context: GRPCAsyncServerCallContext\n ) async throws\n\n func info(\n request: Com_Apple_Container_Build_V1_InfoRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Container_Build_V1_InfoResponse\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncProvider {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor\n }\n\n public var serviceName: Substring {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor.fullName[...]\n }\n\n public var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? {\n return nil\n }\n\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"CreateBuild\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? [],\n wrapping: { try await self.createBuild(request: $0, context: $1) }\n )\n\n case \"PerformBuild\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n wrapping: { try await self.performBuild(requestStream: $0, responseStream: $1, context: $2) }\n )\n\n case \"Info\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeInfoInterceptors() ?? [],\n wrapping: { try await self.info(request: $0, context: $1) }\n )\n\n default:\n return nil\n }\n }\n}\n\npublic protocol Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when handling 'createBuild'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCreateBuildInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'performBuild'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makePerformBuildInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'info'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeInfoInterceptors() -> [ServerInterceptor]\n}\n\npublic enum Com_Apple_Container_Build_V1_BuilderServerMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"Builder\",\n fullName: \"com.apple.container.build.v1.Builder\",\n methods: [\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.createBuild,\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.performBuild,\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.info,\n ]\n )\n\n public enum Methods {\n public static let createBuild = GRPCMethodDescriptor(\n name: \"CreateBuild\",\n path: \"/com.apple.container.build.v1.Builder/CreateBuild\",\n type: GRPCCallType.unary\n )\n\n public static let performBuild = GRPCMethodDescriptor(\n name: \"PerformBuild\",\n path: \"/com.apple.container.build.v1.Builder/PerformBuild\",\n type: GRPCCallType.bidirectionalStreaming\n )\n\n public static let info = GRPCMethodDescriptor(\n name: \"Info\",\n path: \"/com.apple.container.build.v1.Builder/Info\",\n type: GRPCCallType.unary\n )\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildPipelineHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport GRPC\nimport NIO\n\nprotocol BuildPipelineHandler: Sendable {\n func accept(_ packet: ServerStream) throws -> Bool\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws\n}\n\npublic actor BuildPipeline {\n let handlers: [BuildPipelineHandler]\n public init(_ config: Builder.BuildConfig) async throws {\n self.handlers =\n [\n try BuildFSSync(URL(filePath: config.contextDir)),\n try BuildRemoteContentProxy(config.contentStore),\n try BuildImageResolver(config.contentStore),\n try BuildStdio(quiet: config.quiet, output: config.terminal?.handle ?? FileHandle.standardError),\n ]\n }\n\n public func run(\n sender: AsyncStream.Continuation,\n receiver: GRPCAsyncResponseStream\n ) async throws {\n defer { sender.finish() }\n try await untilFirstError { group in\n for try await packet in receiver {\n try Task.checkCancellation()\n for handler in self.handlers {\n try Task.checkCancellation()\n guard try handler.accept(packet) else {\n continue\n }\n try Task.checkCancellation()\n try await handler.handle(sender, packet)\n break\n }\n }\n }\n }\n\n /// untilFirstError() throws when any one of its submitted tasks fail.\n /// This is useful for asynchronous packet processing scenarios which\n /// have the following 3 requirements:\n /// - the packet should be processed without blocking I/O\n /// - the packet stream is never-ending\n /// - when the first task fails, the error needs to be propagated to the caller\n ///\n /// Usage:\n ///\n /// ```\n /// try await untilFirstError { group in\n /// for try await packet in receiver {\n /// group.addTask {\n /// try await handler.handle(sender, packet)\n /// }\n /// }\n /// }\n /// ```\n ///\n ///\n /// WithThrowingTaskGroup cannot accomplish this because it\n /// doesn't provide a mechanism to exit when one of the tasks fail\n /// before all the tasks have been added. i.e. it is more suitable for\n /// tasks that are limited. Here's a sample code where withThrowingTaskGroup\n /// doesn't solve the problem:\n ///\n /// ```\n /// withThrowingTaskGroup { group in\n /// for try await packet in receiver {\n /// group.addTask {\n /// /* process packet */\n /// }\n /// } /* this loop blocks forever waiting for more packets */\n /// try await group.next() /* this never gets called */\n /// }\n /// ```\n /// The above closure never returns even when a handler encounters an error\n /// because the blocking operation `try await group.next()` cannot be\n /// called while iterating over the receiver stream.\n private func untilFirstError(body: @Sendable @escaping (UntilFirstError) async throws -> Void) async throws {\n let group = try await UntilFirstError()\n var taskContinuation: AsyncStream>.Continuation?\n let tasks = AsyncStream> { continuation in\n taskContinuation = continuation\n }\n guard let taskContinuation else {\n throw NSError(\n domain: \"untilFirstError\",\n code: 1,\n userInfo: [NSLocalizedDescriptionKey: \"Failed to initialize task continuation\"])\n }\n defer { taskContinuation.finish() }\n let stream = AsyncStream { continuation in\n let processTasks = Task {\n let taskStream = await group.tasks()\n defer {\n continuation.finish()\n }\n for await item in taskStream {\n try Task.checkCancellation()\n let addedTask = Task {\n try Task.checkCancellation()\n do {\n try await item()\n } catch {\n continuation.yield(error)\n await group.continuation?.finish()\n throw error\n }\n }\n taskContinuation.yield(addedTask)\n }\n }\n taskContinuation.yield(processTasks)\n\n let mainTask = Task { @Sendable in\n defer {\n continuation.finish()\n processTasks.cancel()\n taskContinuation.finish()\n }\n do {\n try Task.checkCancellation()\n try await body(group)\n } catch {\n continuation.yield(error)\n await group.continuation?.finish()\n throw error\n }\n }\n taskContinuation.yield(mainTask)\n }\n\n // when the first handler fails, cancel all tasks and throw error\n for await item in stream {\n try Task.checkCancellation()\n Task {\n for await task in tasks {\n task.cancel()\n }\n }\n throw item\n }\n // if none of the handlers fail, wait for all subtasks to complete\n for await task in tasks {\n try Task.checkCancellation()\n try await task.value\n }\n }\n\n private actor UntilFirstError {\n var stream: AsyncStream<@Sendable () async throws -> Void>?\n var continuation: AsyncStream<@Sendable () async throws -> Void>.Continuation?\n\n init() async throws {\n self.stream = AsyncStream { cont in\n self.continuation = cont\n }\n guard let _ = continuation else {\n throw NSError()\n }\n }\n\n func addTask(body: @Sendable @escaping () async throws -> Void) {\n if !Task.isCancelled {\n self.continuation?.yield(body)\n }\n }\n\n func tasks() -> AsyncStream<@Sendable () async throws -> Void> {\n self.stream!\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension String {\n fileprivate var fs_cleaned: String {\n var value = self\n\n if value.hasPrefix(\"file://\") {\n value.removeFirst(\"file://\".count)\n }\n\n if value.count > 1 && value.last == \"/\" {\n value.removeLast()\n }\n\n return value.removingPercentEncoding ?? value\n }\n\n fileprivate var fs_components: [String] {\n var parts: [String] = []\n for segment in self.split(separator: \"/\", omittingEmptySubsequences: true) {\n switch segment {\n case \".\":\n continue\n case \"..\":\n if !parts.isEmpty { parts.removeLast() }\n default:\n parts.append(String(segment))\n }\n }\n return parts\n }\n\n fileprivate var fs_isAbsolute: Bool { first == \"/\" }\n}\n\nextension URL {\n var cleanPath: String {\n self.path.fs_cleaned\n }\n\n func parentOf(_ url: URL) -> Bool {\n let parentPath = self.absoluteURL.cleanPath\n let childPath = url.absoluteURL.cleanPath\n\n guard parentPath.fs_isAbsolute else {\n return true\n }\n\n let parentParts = parentPath.fs_components\n let childParts = childPath.fs_components\n\n guard parentParts.count <= childParts.count else { return false }\n return zip(parentParts, childParts).allSatisfy { $0 == $1 }\n }\n\n func relativeChildPath(to context: URL) throws -> String {\n guard context.parentOf(self) else {\n throw BuildFSSync.Error.pathIsNotChild(cleanPath, context.cleanPath)\n }\n\n let ctxParts = context.cleanPath.fs_components\n let selfParts = cleanPath.fs_components\n\n return selfParts.dropFirst(ctxParts.count).joined(separator: \"/\")\n }\n\n func relativePathFrom(from base: URL) -> String {\n let destParts = cleanPath.fs_components\n let baseParts = base.cleanPath.fs_components\n\n let common = zip(destParts, baseParts).prefix { $0 == $1 }.count\n guard common > 0 else { return cleanPath }\n\n let ups = Array(repeating: \"..\", count: baseParts.count - common)\n let remainder = destParts.dropFirst(common)\n return (ups + remainder).joined(separator: \"/\")\n }\n\n func zeroCopyReader(\n chunk: Int = 1024 * 1024,\n buffer: AsyncStream.Continuation.BufferingPolicy = .unbounded\n ) throws -> AsyncStream {\n\n let path = self.cleanPath\n let fd = open(path, O_RDONLY | O_NONBLOCK)\n guard fd >= 0 else { throw POSIXError.fromErrno() }\n\n let channel = DispatchIO(\n type: .stream,\n fileDescriptor: fd,\n queue: .global(qos: .userInitiated)\n ) { errno in\n close(fd)\n }\n\n channel.setLimit(highWater: chunk)\n return AsyncStream(bufferingPolicy: buffer) { continuation in\n\n channel.read(\n offset: 0, length: Int.max,\n queue: .global(qos: .userInitiated)\n ) { done, ddata, err in\n if err != 0 {\n continuation.finish()\n return\n }\n\n if let ddata, ddata.count > -1 {\n let data = Data(ddata)\n\n switch continuation.yield(data) {\n case .terminated:\n channel.close(flags: .stop)\n default: break\n }\n }\n\n if done {\n channel.close(flags: .stop)\n continuation.finish()\n }\n }\n }\n }\n\n func bufferedCopyReader(chunkSize: Int = 4 * 1024 * 1024) throws -> BufferedCopyReader {\n try BufferedCopyReader(url: self, chunkSize: chunkSize)\n }\n}\n\n/// A synchronous buffered reader that reads one chunk at a time from a file\n/// Uses a configurable buffer size (default 4MB) and only reads when nextChunk() is called\n/// Implements AsyncSequence for use with `for await` loops\npublic final class BufferedCopyReader: AsyncSequence {\n public typealias Element = Data\n public typealias AsyncIterator = BufferedCopyReaderIterator\n\n private let inputStream: InputStream\n private let chunkSize: Int\n private var isFinished: Bool = false\n private let reusableBuffer: UnsafeMutablePointer\n\n /// Initialize a buffered copy reader for the given URL\n /// - Parameters:\n /// - url: The file URL to read from\n /// - chunkSize: Size of each chunk to read (default: 4MB)\n public init(url: URL, chunkSize: Int = 4 * 1024 * 1024) throws {\n guard let stream = InputStream(url: url) else {\n throw CocoaError(.fileReadNoSuchFile)\n }\n self.inputStream = stream\n self.chunkSize = chunkSize\n self.reusableBuffer = UnsafeMutablePointer.allocate(capacity: chunkSize)\n self.inputStream.open()\n }\n\n deinit {\n inputStream.close()\n reusableBuffer.deallocate()\n }\n\n /// Create an async iterator for this sequence\n public func makeAsyncIterator() -> BufferedCopyReaderIterator {\n BufferedCopyReaderIterator(reader: self)\n }\n\n /// Read the next chunk of data from the file\n /// - Returns: Data chunk, or nil if end of file reached\n /// - Throws: Any file reading errors\n public func nextChunk() throws -> Data? {\n guard !isFinished else { return nil }\n\n // Read directly into our reusable buffer\n let bytesRead = inputStream.read(reusableBuffer, maxLength: chunkSize)\n\n // Check for errors\n if bytesRead < 0 {\n if let error = inputStream.streamError {\n throw error\n }\n throw CocoaError(.fileReadUnknown)\n }\n\n // If we read no data, we've reached the end\n if bytesRead == 0 {\n isFinished = true\n return nil\n }\n\n // If we read less than the chunk size, this is the last chunk\n if bytesRead < chunkSize {\n isFinished = true\n }\n\n // Create Data object only with the bytes actually read\n return Data(bytes: reusableBuffer, count: bytesRead)\n }\n\n /// Check if the reader has finished reading the file\n public var hasFinished: Bool {\n isFinished\n }\n\n /// Reset the reader to the beginning of the file\n /// Note: InputStream doesn't support seeking, so this recreates the stream\n /// - Throws: Any file opening errors\n public func reset() throws {\n inputStream.close()\n // Note: InputStream doesn't provide a way to get the original URL,\n // so reset functionality is limited. Consider removing this method\n // or storing the original URL if reset is needed.\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Reset not supported with InputStream-based implementation\"\n ])\n }\n\n /// Get the current file offset\n /// Note: InputStream doesn't provide offset information\n /// - Returns: Current position in the file\n /// - Throws: Unsupported operation error\n public func currentOffset() throws -> UInt64 {\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Offset tracking not supported with InputStream-based implementation\"\n ])\n }\n\n /// Seek to a specific offset in the file\n /// Note: InputStream doesn't support seeking\n /// - Parameter offset: The byte offset to seek to\n /// - Throws: Unsupported operation error\n public func seek(to offset: UInt64) throws {\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Seeking not supported with InputStream-based implementation\"\n ])\n }\n\n /// Close the input stream explicitly (called automatically in deinit)\n public func close() {\n inputStream.close()\n isFinished = true\n }\n}\n\n/// AsyncIteratorProtocol implementation for BufferedCopyReader\npublic struct BufferedCopyReaderIterator: AsyncIteratorProtocol {\n public typealias Element = Data\n\n private let reader: BufferedCopyReader\n\n init(reader: BufferedCopyReader) {\n self.reader = reader\n }\n\n /// Get the next chunk of data asynchronously\n /// - Returns: Next data chunk, or nil when finished\n /// - Throws: Any file reading errors\n public mutating func next() async throws -> Data? {\n // Yield control to allow other tasks to run, then read synchronously\n await Task.yield()\n return try reader.nextChunk()\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerExec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct ContainerExec: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"exec\",\n abstract: \"Run a new command in a running container\")\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Running containers ID\")\n var containerID: String\n\n @Argument(parsing: .captureForPassthrough, help: \"New process arguments\")\n var arguments: [String]\n\n func run() async throws {\n var exitCode: Int32 = 127\n let container = try await ClientContainer.get(id: containerID)\n try ensureRunning(container: container)\n\n let stdin = self.processFlags.interactive\n let tty = self.processFlags.tty\n\n var config = container.configuration.initProcess\n config.executable = arguments.first!\n config.arguments = [String](self.arguments.dropFirst())\n config.terminal = tty\n config.environment.append(\n contentsOf: try Parser.allEnv(\n imageEnvs: [],\n envFiles: self.processFlags.envFile,\n envs: self.processFlags.env\n ))\n\n if let cwd = self.processFlags.cwd {\n config.workingDirectory = cwd\n }\n\n let defaultUser = config.user\n let (user, additionalGroups) = Parser.user(\n user: processFlags.user, uid: processFlags.uid,\n gid: processFlags.gid, defaultUser: defaultUser)\n config.user = user\n config.supplementalGroups.append(contentsOf: additionalGroups)\n\n do {\n let io = try ProcessIO.create(tty: tty, interactive: stdin, detach: false)\n\n if !self.processFlags.tty {\n var handler = SignalThreshold(threshold: 3, signals: [SIGINT, SIGTERM])\n handler.start {\n print(\"Received 3 SIGINT/SIGTERM's, forcefully exiting.\")\n Darwin.exit(1)\n }\n }\n\n let process = try await container.createProcess(\n id: UUID().uuidString.lowercased(),\n configuration: config)\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to exec process \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/RequestScheme.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\n\n/// The URL scheme to be used for a HTTP request.\npublic enum RequestScheme: String, Sendable {\n case http = \"http\"\n case https = \"https\"\n\n case auto = \"auto\"\n\n public init(_ rawValue: String) throws {\n switch rawValue {\n case RequestScheme.http.rawValue:\n self = .http\n case RequestScheme.https.rawValue:\n self = .https\n case RequestScheme.auto.rawValue:\n self = .auto\n default:\n throw ContainerizationError(.invalidArgument, message: \"Unsupported scheme \\(rawValue)\")\n }\n }\n\n /// Returns the prescribed protocol to use while making a HTTP request to a webserver\n /// - Parameter host: The domain or IP address of the webserver\n /// - Returns: RequestScheme\n package func schemeFor(host: String) throws -> Self {\n guard host.count > 0 else {\n throw ContainerizationError(.invalidArgument, message: \"Host cannot be empty\")\n }\n switch self {\n case .http, .https:\n return self\n case .auto:\n return Self.isInternalHost(host: host) ? .http : .https\n }\n }\n\n /// Checks if the given `host` string is a private IP address\n /// or a domain typically reachable only on the local system.\n private static func isInternalHost(host: String) -> Bool {\n if host.hasPrefix(\"localhost\") || host.hasPrefix(\"127.\") {\n return true\n }\n if host.hasPrefix(\"192.168.\") || host.hasPrefix(\"10.\") {\n return true\n }\n let regex = \"(^172\\\\.1[6-9]\\\\.)|(^172\\\\.2[0-9]\\\\.)|(^172\\\\.3[0-1]\\\\.)\"\n if host.range(of: regex, options: .regularExpression) != nil {\n return true\n }\n let dnsDomain = ClientDefaults.get(key: .defaultDNSDomain)\n if host.hasSuffix(\".\\(dnsDomain)\") {\n return true\n }\n return false\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct NetworkCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a new network\")\n\n @Argument(help: \"Network name\")\n var name: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let config = NetworkConfiguration(id: self.name, mode: .nat)\n let state = try await ClientNetwork.create(configuration: config)\n print(state.id)\n }\n }\n}\n"], ["/container/Sources/ContainerLog/OSLogHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\nimport Logging\nimport os\n\nimport struct Logging.Logger\n\npublic struct OSLogHandler: LogHandler {\n private let logger: os.Logger\n\n public var logLevel: Logger.Level = .info\n private var formattedMetadata: String?\n\n public var metadata = Logger.Metadata() {\n didSet {\n self.formattedMetadata = self.formatMetadata(self.metadata)\n }\n }\n\n public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {\n get {\n self.metadata[metadataKey]\n }\n set {\n self.metadata[metadataKey] = newValue\n }\n }\n\n public init(label: String, category: String) {\n self.logger = os.Logger(subsystem: label, category: category)\n }\n}\n\nextension OSLogHandler {\n public func log(\n level: Logger.Level,\n message: Logger.Message,\n metadata: Logger.Metadata?,\n source: String,\n file: String,\n function: String,\n line: UInt\n ) {\n var formattedMetadata = self.formattedMetadata\n if let metadataOverride = metadata, !metadataOverride.isEmpty {\n formattedMetadata = self.formatMetadata(\n self.metadata.merging(metadataOverride) {\n $1\n }\n )\n }\n\n var finalMessage = message.description\n if let formattedMetadata {\n finalMessage += \" \" + formattedMetadata\n }\n\n self.logger.log(\n level: level.toOSLogLevel(),\n \"\\(finalMessage, privacy: .public)\"\n )\n }\n\n private func formatMetadata(_ metadata: Logger.Metadata) -> String? {\n if metadata.isEmpty {\n return nil\n }\n return metadata.map {\n \"[\\($0)=\\($1)]\"\n }.joined(separator: \" \")\n }\n}\n\nextension Logger.Level {\n func toOSLogLevel() -> OSLogType {\n switch self {\n case .debug, .trace:\n return .debug\n case .info:\n return .info\n case .notice:\n return .default\n case .error, .warning:\n return .error\n case .critical:\n return .fault\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ContainerCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a new container\")\n\n @Argument(help: \"Image name\")\n var image: String\n\n @Argument(help: \"Container init process arguments\")\n var arguments: [String] = []\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var resourceFlags: Flags.Resource\n\n @OptionGroup\n var managementFlags: Flags.Management\n\n @OptionGroup\n var registryFlags: Flags.Registry\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 3\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let id = Utility.createContainerID(name: self.managementFlags.name)\n try Utility.validEntityName(id)\n\n let ck = try await Utility.containerConfigFromFlags(\n id: id,\n image: image,\n arguments: arguments,\n process: processFlags,\n management: managementFlags,\n resource: resourceFlags,\n registry: registryFlags,\n progressUpdate: progress.handler\n )\n\n let options = ContainerCreateOptions(autoRemove: managementFlags.remove)\n let container = try await ClientContainer.create(configuration: ck.0, options: options, kernel: ck.1)\n\n if !self.managementFlags.cidfile.isEmpty {\n let path = self.managementFlags.cidfile\n let data = container.id.data(using: .utf8)\n var attributes = [FileAttributeKey: Any]()\n attributes[.posixPermissions] = 0o644\n let success = FileManager.default.createFile(\n atPath: path,\n contents: data,\n attributes: attributes\n )\n guard success else {\n throw ContainerizationError(\n .internalError, message: \"failed to create cidfile at \\(path): \\(errno)\")\n }\n }\n progress.finish()\n\n print(container.id)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/ProgressUpdateService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\n/// A service that sends progress updates to the client.\npublic actor ProgressUpdateService {\n private let endpointConnection: xpc_connection_t\n\n /// Creates a new instance for sending progress updates to the client.\n /// - Parameter message: The XPC message that contains the endpoint to connect to.\n public init?(message: XPCMessage) {\n guard let progressUpdateEndpoint = message.endpoint(key: .progressUpdateEndpoint) else {\n return nil\n }\n endpointConnection = xpc_connection_create_from_endpoint(progressUpdateEndpoint)\n xpc_connection_set_event_handler(endpointConnection) { _ in }\n // This connection will be closed by the client.\n xpc_connection_activate(endpointConnection)\n }\n\n /// Performs a progress update.\n /// - Parameter events: The events that represent the update.\n public func handler(_ events: [ProgressUpdateEvent]) async {\n let object = xpc_dictionary_create(nil, nil, 0)\n let replyMessage = XPCMessage(object: object)\n for event in events {\n switch event {\n case .setDescription(let description):\n replyMessage.set(key: .progressUpdateSetDescription, value: description)\n case .setSubDescription(let subDescription):\n replyMessage.set(key: .progressUpdateSetSubDescription, value: subDescription)\n case .setItemsName(let itemsName):\n replyMessage.set(key: .progressUpdateSetItemsName, value: itemsName)\n case .addTasks(let tasks):\n replyMessage.set(key: .progressUpdateAddTasks, value: tasks)\n case .setTasks(let tasks):\n replyMessage.set(key: .progressUpdateSetTasks, value: tasks)\n case .addTotalTasks(let totalTasks):\n replyMessage.set(key: .progressUpdateAddTotalTasks, value: totalTasks)\n case .setTotalTasks(let totalTasks):\n replyMessage.set(key: .progressUpdateSetTotalTasks, value: totalTasks)\n case .addSize(let size):\n replyMessage.set(key: .progressUpdateAddSize, value: size)\n case .setSize(let size):\n replyMessage.set(key: .progressUpdateSetSize, value: size)\n case .addTotalSize(let totalSize):\n replyMessage.set(key: .progressUpdateAddTotalSize, value: totalSize)\n case .setTotalSize(let totalSize):\n replyMessage.set(key: .progressUpdateSetTotalSize, value: totalSize)\n case .addItems(let items):\n replyMessage.set(key: .progressUpdateAddItems, value: items)\n case .setItems(let items):\n replyMessage.set(key: .progressUpdateSetItems, value: items)\n case .addTotalItems(let totalItems):\n replyMessage.set(key: .progressUpdateAddTotalItems, value: totalItems)\n case .setTotalItems(let totalItems):\n replyMessage.set(key: .progressUpdateSetTotalItems, value: totalItems)\n case .custom(_):\n // Unsupported progress update event in XPC communication.\n break\n }\n }\n xpc_connection_send_message(endpointConnection, replyMessage.underlying)\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/Network.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\n\n/// Defines common characteristics and operations for a network.\npublic protocol Network: Sendable {\n // Contains network attributes while the network is running\n var state: NetworkState { get async }\n\n // Use implementation-dependent network attributes\n nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws\n\n // Start the network\n func start() async throws\n}\n"], ["/container/Sources/CLI/System/SystemStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nextension Application {\n struct SystemStatus: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"status\",\n abstract: \"Show the status of `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Launchd prefix for `container` services\")\n var prefix: String = \"com.apple.container.\"\n\n func run() async throws {\n let isRegistered = try ServiceManager.isRegistered(fullServiceLabel: \"\\(prefix)apiserver\")\n if !isRegistered {\n print(\"apiserver is not running and not registered with launchd\")\n Application.exit(withError: ExitCode(1))\n }\n\n // Now ping our friendly daemon. Fail after 10 seconds with no response.\n do {\n print(\"Verifying apiserver is running...\")\n try await ClientHealthCheck.ping(timeout: .seconds(10))\n print(\"apiserver is running\")\n } catch {\n print(\"apiserver is not running\")\n Application.exit(withError: ExitCode(1))\n }\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+State.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension ProgressBar {\n /// A configuration struct for the progress bar.\n public struct State {\n /// A flag indicating whether the progress bar is finished.\n public var finished = false\n var iteration = 0\n private let speedInterval: DispatchTimeInterval = .seconds(1)\n\n var description: String\n var subDescription: String\n var itemsName: String\n\n var tasks: Int\n var totalTasks: Int?\n\n var items: Int\n var totalItems: Int?\n\n private var sizeUpdateTime: DispatchTime?\n private var sizeUpdateValue: Int64 = 0\n var size: Int64 {\n didSet {\n calculateSizeSpeed()\n }\n }\n var totalSize: Int64?\n private var sizeUpdateSpeed: String?\n var sizeSpeed: String? {\n guard sizeUpdateTime == nil || sizeUpdateTime! > .now() - speedInterval - speedInterval else {\n return Int64(0).formattedSizeSpeed(from: startTime)\n }\n return sizeUpdateSpeed\n }\n var averageSizeSpeed: String {\n size.formattedSizeSpeed(from: startTime)\n }\n\n var percent: String {\n var value = 0\n if let totalSize, totalSize > 0 {\n value = Int(size * 100 / totalSize)\n } else if let totalItems, totalItems > 0 {\n value = Int(items * 100 / totalItems)\n }\n value = min(value, 100)\n return \"\\(value)%\"\n }\n\n var startTime: DispatchTime\n var output = \"\"\n\n init(\n description: String = \"\", subDescription: String = \"\", itemsName: String = \"\", tasks: Int = 0, totalTasks: Int? = nil, items: Int = 0, totalItems: Int? = nil,\n size: Int64 = 0, totalSize: Int64? = nil, startTime: DispatchTime = .now()\n ) {\n self.description = description\n self.subDescription = subDescription\n self.itemsName = itemsName\n self.tasks = tasks\n self.totalTasks = totalTasks\n self.items = items\n self.totalItems = totalItems\n self.size = size\n self.totalSize = totalSize\n self.startTime = startTime\n }\n\n private mutating func calculateSizeSpeed() {\n if sizeUpdateTime == nil || sizeUpdateTime! < .now() - speedInterval {\n let partSize = size - sizeUpdateValue\n let partStartTime = sizeUpdateTime ?? startTime\n let partSizeSpeed = partSize.formattedSizeSpeed(from: partStartTime)\n self.sizeUpdateSpeed = partSizeSpeed\n\n sizeUpdateTime = .now()\n sizeUpdateValue = size\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Measurement+Parse.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nprivate let units: [Character: UnitInformationStorage] = [\n \"b\": .bytes,\n \"k\": .kibibytes,\n \"m\": .mebibytes,\n \"g\": .gibibytes,\n \"t\": .tebibytes,\n \"p\": .pebibytes,\n]\n\nextension Measurement {\n public enum ParseError: Swift.Error, CustomStringConvertible {\n case invalidSize\n case invalidSymbol(String)\n\n public var description: String {\n switch self {\n case .invalidSize:\n return \"invalid size\"\n case .invalidSymbol(let symbol):\n return \"invalid symbol: \\(symbol)\"\n }\n }\n }\n\n /// parse the provided string into a measurement that is able to be converted to various byte sizes\n public static func parse(parsing: String) throws -> Measurement {\n let check = \"01234567890. \"\n let i = parsing.lastIndex {\n check.contains($0)\n }\n guard let i else {\n throw ParseError.invalidSize\n }\n let after = parsing.index(after: i)\n let rawValue = parsing[..(value: value, unit: unit)\n }\n\n static func parseUnit(_ unit: String) throws -> Character {\n let s = unit.dropFirst()\n switch s {\n case \"\", \"b\", \"ib\":\n return unit.first ?? \"b\"\n default:\n throw ParseError.invalidSymbol(unit)\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\nimport Foundation\n\n/// PluginConfig details all of the fields to describe and register a plugin.\n/// A plugin is registered by creating a subdirectory `/user-plugins`,\n/// where the name of the subdirectory is the name of the plugin, and then placing a\n/// file named `config.json` inside with the schema below.\n/// If `services` is filled in then there MUST be a binary named matching the plugin name\n/// in a `bin` subdirectory inside the same directory as the `config.json`.\n/// An example of a valid plugin directory structure would be\n/// $ tree foobar\n/// foobar\n/// ├── bin\n/// │ └── foobar\n/// └── config.json\npublic struct PluginConfig: Sendable, Codable {\n /// Categories of services that can be offered through plugins.\n public enum DaemonPluginType: String, Sendable, Codable {\n /// A runtime plugin provides an XPC API through which the lifecycle\n /// of a **single** container can be managed.\n /// A runtime daemon plugin would typically also have a counterpart\n /// CLI plugin which knows how to talk to the API exposed by the runtime plugin.\n /// The API server ensures that a single instance of the plugin is configured\n /// for a given container such that the client can communicate with it given an instance id.\n case runtime\n /// A network plugin provides an XPC API through which IP address allocations on a given\n /// network can be managed. The API server ensures that a single instance\n /// of this plugin is configured for a given network. Similar to the runtime plugin, it typically\n /// would be accompanied by a CLI plugin that knows how to communicate with the XPC API\n /// given an instance id.\n case network\n /// A core plugin provides an XPC API to manage a given type of resource.\n /// The API server ensures that there exist only a single running instance\n /// of this plugin type. A core plugin can be thought of a singleton whose lifecycle\n /// is tied to that of the API server. Core plugins can be used to expand the base functionality\n /// provided by the API server. As with the other plugin types, it maybe associated with a client\n /// side plugin that communicates with the XPC service exposed by the daemon plugin.\n case core\n /// Reserved for future use. Currently there is no difference between a core and auxiliary daemon plugin.\n case auxiliary\n }\n\n // An XPC service that the plugin publishes.\n public struct Service: Sendable, Codable {\n /// The type of the service the daemon is exposing.\n /// One plugin can expose multiple services of different types.\n ///\n /// The plugin MUST expose a MachService at\n /// `com.apple.container.{type}.{name}.[{id}]` for\n /// each service that it exposes.\n public let type: DaemonPluginType\n /// Optional description of this service.\n public let description: String?\n }\n\n /// Descriptor for the services that the plugin offers.\n public struct ServicesConfig: Sendable, Codable {\n /// Load the plugin into launchd when the API server starts.\n public let loadAtBoot: Bool\n /// Launch the plugin binary as soon as it loads into launchd.\n public let runAtLoad: Bool\n /// The service types that the plugin provides.\n public let services: [Service]\n /// An optional parameter that include any command line arguments\n /// that must be passed to the plugin binary when it is loaded.\n /// This parameter is used only when `servicesConfig.loadAtBoot` is `true`\n public let defaultArguments: [String]\n }\n\n /// Short description of the plugin surface. This will be displayed as the\n /// help-text for CLI plugins, and will be returned in API calls to view loaded\n /// plugins from the daemon.\n public let abstract: String\n\n /// Author of the plugin. This is solely metadata.\n public let author: String?\n\n /// Services configuration. Specify nil for a CLI plugin, and an empty array for\n /// that does not publish any XPC services.\n public let servicesConfig: ServicesConfig?\n}\n\nextension PluginConfig {\n public var isCLI: Bool { self.servicesConfig == nil }\n}\n\nextension PluginConfig {\n public init?(configURL: URL) throws {\n let fm = FileManager.default\n if !fm.fileExists(atPath: configURL.path) {\n return nil\n }\n\n guard let data = fm.contents(atPath: configURL.path) else {\n return nil\n }\n\n let decoder: JSONDecoder = JSONDecoder()\n self = try decoder.decode(PluginConfig.self, from: data)\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport TerminalProgress\n\nextension Application {\n struct ContainerStart: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Start a container\")\n\n @Flag(name: .shortAndLong, help: \"Attach STDOUT/STDERR\")\n var attach = false\n\n @Flag(name: .shortAndLong, help: \"Attach container's STDIN\")\n var interactive = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Container's ID\")\n var containerID: String\n\n func run() async throws {\n var exitCode: Int32 = 127\n\n let progressConfig = try ProgressConfig(\n description: \"Starting container\"\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let container = try await ClientContainer.get(id: containerID)\n let process = try await container.bootstrap()\n\n progress.set(description: \"Starting init process\")\n let detach = !self.attach && !self.interactive\n do {\n let io = try ProcessIO.create(\n tty: container.configuration.initProcess.terminal,\n interactive: self.interactive,\n detach: detach\n )\n progress.finish()\n if detach {\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n print(self.containerID)\n return\n }\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n try? await container.stop()\n\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to start container: \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientDefaults.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CVersion\nimport ContainerizationError\nimport Foundation\n\npublic enum ClientDefaults {\n private static let userDefaultDomain = \"com.apple.container.defaults\"\n\n public enum Keys: String {\n case defaultBuilderImage = \"image.builder\"\n case defaultDNSDomain = \"dns.domain\"\n case defaultRegistryDomain = \"registry.domain\"\n case defaultInitImage = \"image.init\"\n case defaultKernelURL = \"kernel.url\"\n case defaultKernelBinaryPath = \"kernel.binaryPath\"\n case buildRosetta = \"build.rosetta\"\n }\n\n public static func set(value: String, key: ClientDefaults.Keys) {\n udSuite.set(value, forKey: key.rawValue)\n }\n\n public static func unset(key: ClientDefaults.Keys) {\n udSuite.removeObject(forKey: key.rawValue)\n }\n\n public static func get(key: ClientDefaults.Keys) -> String {\n let current = udSuite.string(forKey: key.rawValue)\n return current ?? key.defaultValue\n }\n\n public static func getOptional(key: ClientDefaults.Keys) -> String? {\n udSuite.string(forKey: key.rawValue)\n }\n\n public static func setBool(value: Bool, key: ClientDefaults.Keys) {\n udSuite.set(value, forKey: key.rawValue)\n }\n\n public static func getBool(key: ClientDefaults.Keys) -> Bool? {\n guard udSuite.object(forKey: key.rawValue) != nil else { return nil }\n return udSuite.bool(forKey: key.rawValue)\n }\n\n private static var udSuite: UserDefaults {\n guard let ud = UserDefaults.init(suiteName: self.userDefaultDomain) else {\n fatalError(\"Failed to initialize UserDefaults for domain \\(self.userDefaultDomain)\")\n }\n return ud\n }\n}\n\nextension ClientDefaults.Keys {\n fileprivate var defaultValue: String {\n switch self {\n case .defaultKernelURL:\n return \"https://github.com/kata-containers/kata-containers/releases/download/3.17.0/kata-static-3.17.0-arm64.tar.xz\"\n case .defaultKernelBinaryPath:\n return \"opt/kata/share/kata-containers/vmlinux-6.12.28-153\"\n case .defaultBuilderImage:\n let tag = String(cString: get_container_builder_shim_version())\n return \"ghcr.io/apple/container-builder-shim/builder:\\(tag)\"\n case .defaultDNSDomain:\n return \"test\"\n case .defaultRegistryDomain:\n return \"docker.io\"\n case .defaultInitImage:\n let tag = String(cString: get_swift_containerization_version())\n guard tag != \"latest\" else {\n return \"vminit:latest\"\n }\n return \"ghcr.io/apple/containerization/vminit:\\(tag)\"\n case .buildRosetta:\n // This is a boolean key, not used with the string get() method\n return \"true\"\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemLogs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport OSLog\n\nextension Application {\n struct SystemLogs: AsyncParsableCommand {\n static let subsystem = \"com.apple.container\"\n\n static let configuration = CommandConfiguration(\n commandName: \"logs\",\n abstract: \"Fetch system logs for `container` services\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(\n name: .long,\n help: \"Fetch logs starting from the specified time period (minus the current time); supported formats: m, h, d\"\n )\n var last: String = \"5m\"\n\n @Flag(name: .shortAndLong, help: \"Follow log output\")\n var follow: Bool = false\n\n func run() async throws {\n let process = Process()\n let sigHandler = AsyncSignalHandler.create(notify: [SIGINT, SIGTERM])\n\n Task {\n for await _ in sigHandler.signals {\n process.terminate()\n Darwin.exit(0)\n }\n }\n\n do {\n var args = [\"log\"]\n args.append(self.follow ? \"stream\" : \"show\")\n args.append(contentsOf: [\"--info\", \"--debug\"])\n if !self.follow {\n args.append(contentsOf: [\"--last\", last])\n }\n args.append(contentsOf: [\"--predicate\", \"subsystem = 'com.apple.container'\"])\n\n process.launchPath = \"/usr/bin/env\"\n process.arguments = args\n\n process.standardOutput = FileHandle.standardOutput\n process.standardError = FileHandle.standardError\n\n try process.run()\n process.waitUntilExit()\n } catch {\n throw ContainerizationError(\n .invalidArgument,\n message: \"failed to system logs: \\(error)\"\n )\n }\n throw ArgumentParser.ExitCode(process.terminationStatus)\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/Plugin.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\n/// Value type that contains the plugin configuration, the parsed name of the\n/// plugin and whether a CLI surface for the plugin was found.\npublic struct Plugin: Sendable, Codable {\n private static let machServicePrefix = \"com.apple.container.\"\n\n /// Pathname to installation directory for plugins.\n public let binaryURL: URL\n\n /// Configuration for the plugin.\n public let config: PluginConfig\n\n public init(binaryURL: URL, config: PluginConfig) {\n self.binaryURL = binaryURL\n self.config = config\n }\n}\n\nextension Plugin {\n public var name: String { binaryURL.lastPathComponent }\n\n public var shouldBoot: Bool {\n guard let config = self.config.servicesConfig else {\n return false\n }\n\n return config.loadAtBoot\n }\n\n public func getLaunchdLabel(instanceId: String? = nil) -> String {\n // Use the plugin name for the launchd label.\n guard let instanceId else {\n return \"\\(Self.machServicePrefix)\\(self.name)\"\n }\n return \"\\(Self.machServicePrefix)\\(self.name).\\(instanceId)\"\n }\n\n public func getMachServices(instanceId: String? = nil) -> [String] {\n // Use the service type for the mach service.\n guard let config = self.config.servicesConfig else {\n return []\n }\n var services = [String]()\n for service in config.services {\n let serviceName: String\n if let instanceId {\n serviceName = \"\\(Self.machServicePrefix)\\(service.type.rawValue).\\(name).\\(instanceId)\"\n } else {\n serviceName = \"\\(Self.machServicePrefix)\\(service.type.rawValue).\\(name)\"\n }\n services.append(serviceName)\n }\n return services\n }\n\n public func getMachService(instanceId: String? = nil, type: PluginConfig.DaemonPluginType) -> String? {\n guard hasType(type) else {\n return nil\n }\n\n guard let instanceId else {\n return \"\\(Self.machServicePrefix)\\(type.rawValue).\\(name)\"\n }\n return \"\\(Self.machServicePrefix)\\(type.rawValue).\\(name).\\(instanceId)\"\n }\n\n public func hasType(_ type: PluginConfig.DaemonPluginType) -> Bool {\n guard let config = self.config.servicesConfig else {\n return false\n }\n\n guard !(config.services.filter { $0.type == type }.isEmpty) else {\n return false\n }\n\n return true\n }\n}\n\nextension Plugin {\n public func exec(args: [String]) throws {\n var args = args\n let executable = self.binaryURL.path\n args[0] = executable\n let argv = args.map { strdup($0) } + [nil]\n guard execvp(executable, argv) != -1 else {\n throw POSIXError.fromErrno()\n }\n fatalError(\"unreachable\")\n }\n\n func helpText(padding: Int) -> String {\n guard !self.name.isEmpty else {\n return \"\"\n }\n let namePadded = name.padding(toLength: padding, withPad: \" \", startingAt: 0)\n return \" \" + namePadded + self.config.abstract\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct DNSDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete a local DNS domain (must run as an administrator)\",\n aliases: [\"rm\"]\n )\n\n @Argument(help: \"the local domain name\")\n var domainName: String\n\n func run() async throws {\n let resolver = HostDNSResolver()\n do {\n try resolver.deleteDomain(name: domainName)\n print(domainName)\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot create domain (try sudo?)\")\n }\n\n do {\n try HostDNSResolver.reinitialize()\n } catch {\n throw ContainerizationError(.invalidState, message: \"mDNSResponder restart failed, run `sudo killall -HUP mDNSResponder` to deactivate domain\")\n }\n }\n }\n}\n"], ["/container/Sources/SocketForwarder/TCPForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\n\npublic struct TCPForwarder: SocketForwarder {\n private let proxyAddress: SocketAddress\n\n private let serverAddress: SocketAddress\n\n private let eventLoopGroup: any EventLoopGroup\n\n private let log: Logger?\n\n public init(\n proxyAddress: SocketAddress,\n serverAddress: SocketAddress,\n eventLoopGroup: any EventLoopGroup,\n log: Logger? = nil\n ) throws {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.log = log\n }\n\n public func run() throws -> EventLoopFuture {\n self.log?.trace(\"frontend - creating listener\")\n\n let bootstrap = ServerBootstrap(group: self.eventLoopGroup)\n .serverChannelOption(ChannelOptions.socket(.init(SOL_SOCKET), .init(SO_REUSEADDR)), value: 1)\n .childChannelOption(ChannelOptions.socket(.init(SOL_SOCKET), .init(SO_REUSEADDR)), value: 1)\n .childChannelInitializer { channel in\n channel.eventLoop.makeCompletedFuture {\n try channel.pipeline.syncOperations.addHandler(\n ConnectHandler(serverAddress: self.serverAddress, log: log)\n )\n }\n }\n\n return\n bootstrap\n .bind(to: self.proxyAddress)\n .flatMap { $0.eventLoop.makeSucceededFuture(SocketForwarderResult(channel: $0)) }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\n\npublic struct ContainerConfiguration: Sendable, Codable {\n /// Identifier for the container.\n public var id: String\n /// Image used to create the container.\n public var image: ImageDescription\n /// External mounts to add to the container.\n public var mounts: [Filesystem] = []\n /// Ports to publish from container to host.\n public var publishedPorts: [PublishPort] = []\n /// Sockets to publish from container to host.\n public var publishedSockets: [PublishSocket] = []\n /// Key/Value labels for the container.\n public var labels: [String: String] = [:]\n /// System controls for the container.\n public var sysctls: [String: String] = [:]\n /// The networks the container will be added to.\n public var networks: [String] = []\n /// The DNS configuration for the container.\n public var dns: DNSConfiguration? = nil\n /// Whether to enable rosetta x86-64 translation for the container.\n public var rosetta: Bool = false\n /// The hostname for the container.\n public var hostname: String? = nil\n /// Initial or main process of the container.\n public var initProcess: ProcessConfiguration\n /// Platform for the container\n public var platform: ContainerizationOCI.Platform = .current\n /// Resource values for the container.\n public var resources: Resources = .init()\n /// Name of the runtime that supports the container\n public var runtimeHandler: String = \"container-runtime-linux\"\n\n enum CodingKeys: String, CodingKey {\n case id\n case image\n case mounts\n case publishedPorts\n case publishedSockets\n case labels\n case sysctls\n case networks\n case dns\n case rosetta\n case hostname\n case initProcess\n case platform\n case resources\n case runtimeHandler\n }\n\n /// Create a configuration from the supplied Decoder, initializing missing\n /// values where possible to reasonable defaults.\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n id = try container.decode(String.self, forKey: .id)\n image = try container.decode(ImageDescription.self, forKey: .image)\n mounts = try container.decodeIfPresent([Filesystem].self, forKey: .mounts) ?? []\n publishedPorts = try container.decodeIfPresent([PublishPort].self, forKey: .publishedPorts) ?? []\n publishedSockets = try container.decodeIfPresent([PublishSocket].self, forKey: .publishedSockets) ?? []\n labels = try container.decodeIfPresent([String: String].self, forKey: .labels) ?? [:]\n sysctls = try container.decodeIfPresent([String: String].self, forKey: .sysctls) ?? [:]\n networks = try container.decodeIfPresent([String].self, forKey: .networks) ?? []\n dns = try container.decodeIfPresent(DNSConfiguration.self, forKey: .dns)\n rosetta = try container.decodeIfPresent(Bool.self, forKey: .rosetta) ?? false\n hostname = try container.decodeIfPresent(String.self, forKey: .hostname)\n initProcess = try container.decode(ProcessConfiguration.self, forKey: .initProcess)\n platform = try container.decodeIfPresent(ContainerizationOCI.Platform.self, forKey: .platform) ?? .current\n resources = try container.decodeIfPresent(Resources.self, forKey: .resources) ?? .init()\n runtimeHandler = try container.decodeIfPresent(String.self, forKey: .runtimeHandler) ?? \"container-runtime-linux\"\n }\n\n public struct DNSConfiguration: Sendable, Codable {\n public static let defaultNameservers = [\"1.1.1.1\"]\n\n public let nameservers: [String]\n public let domain: String?\n public let searchDomains: [String]\n public let options: [String]\n\n public init(\n nameservers: [String] = defaultNameservers,\n domain: String? = nil,\n searchDomains: [String] = [],\n options: [String] = []\n ) {\n self.nameservers = nameservers\n self.domain = domain\n self.searchDomains = searchDomains\n self.options = options\n }\n }\n\n /// Resources like cpu, memory, and storage quota.\n public struct Resources: Sendable, Codable {\n /// Number of CPU cores allocated.\n public var cpus: Int = 4\n /// Memory in bytes allocated.\n public var memoryInBytes: UInt64 = 1024.mib()\n /// Storage quota/size in bytes.\n public var storage: UInt64?\n\n public init() {}\n }\n\n public init(\n id: String,\n image: ImageDescription,\n process: ProcessConfiguration\n ) {\n self.id = id\n self.image = image\n self.initProcess = process\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderDelete: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"delete\"\n config._superCommandName = \"builder\"\n config.abstract = \"Delete builder\"\n config.usage = \"\\n\\t builder delete [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Flag(name: .shortAndLong, help: \"Force delete builder even if it is running\")\n var force = false\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n if container.status != .stopped {\n guard force else {\n throw ContainerizationError(.invalidState, message: \"BuildKit container is not stopped, use --force to override\")\n }\n try await container.stop()\n }\n try await container.delete()\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/DNSServer/DNSServer+Handle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport NIOCore\nimport NIOPosix\n\nextension DNSServer {\n /// Handles the DNS request.\n /// - Parameters:\n /// - outbound: The NIOAsyncChannelOutboundWriter for which to respond.\n /// - packet: The request packet.\n func handle(\n outbound: NIOAsyncChannelOutboundWriter>,\n packet: inout AddressedEnvelope\n ) async throws {\n let chunkSize = 512\n var data = Data()\n\n self.log?.debug(\"reading data\")\n while packet.data.readableBytes > 0 {\n if let chunk = packet.data.readBytes(length: min(chunkSize, packet.data.readableBytes)) {\n data.append(contentsOf: chunk)\n }\n }\n\n self.log?.debug(\"deserializing message\")\n let query = try Message(deserialize: data)\n self.log?.debug(\"processing query: \\(query.questions)\")\n\n // always send response\n let responseData: Data\n do {\n self.log?.debug(\"awaiting processing\")\n var response =\n try await handler.answer(query: query)\n ?? Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n\n // no responses\n if response.answers.isEmpty {\n response.returnCode = .nonExistentDomain\n }\n\n self.log?.debug(\"serializing response\")\n responseData = try response.serialize()\n } catch {\n self.log?.error(\"error processing message from \\(query): \\(error)\")\n let response = Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n responseData = try response.serialize()\n }\n\n self.log?.debug(\"sending response for \\(query.id)\")\n let rData = ByteBuffer(bytes: responseData)\n try? await outbound.write(AddressedEnvelope(remoteAddress: packet.remoteAddress, data: rData))\n\n self.log?.debug(\"processing done\")\n\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+Add.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension ProgressBar {\n /// A handler function to update the progress bar.\n /// - Parameter events: The events to handle.\n public func handler(_ events: [ProgressUpdateEvent]) {\n for event in events {\n switch event {\n case .setDescription(let description):\n set(description: description)\n case .setSubDescription(let subDescription):\n set(subDescription: subDescription)\n case .setItemsName(let itemsName):\n set(itemsName: itemsName)\n case .addTasks(let tasks):\n add(tasks: tasks)\n case .setTasks(let tasks):\n set(tasks: tasks)\n case .addTotalTasks(let totalTasks):\n add(totalTasks: totalTasks)\n case .setTotalTasks(let totalTasks):\n set(totalTasks: totalTasks)\n case .addSize(let size):\n add(size: size)\n case .setSize(let size):\n set(size: size)\n case .addTotalSize(let totalSize):\n add(totalSize: totalSize)\n case .setTotalSize(let totalSize):\n set(totalSize: totalSize)\n case .addItems(let items):\n add(items: items)\n case .setItems(let items):\n set(items: items)\n case .addTotalItems(let totalItems):\n add(totalItems: totalItems)\n case .setTotalItems(let totalItems):\n set(totalItems: totalItems)\n case .custom:\n // Custom events are handled by the client.\n break\n }\n }\n }\n\n /// Performs a check to see if the progress bar should be finished.\n public func checkIfFinished() {\n let state = self.state.withLock { $0 }\n\n var finished = true\n var defined = false\n if let totalTasks = state.totalTasks, totalTasks > 0 {\n // For tasks, we're showing the current task rather than the number of completed tasks.\n finished = finished && state.tasks == totalTasks\n defined = true\n }\n if let totalItems = state.totalItems, totalItems > 0 {\n finished = finished && state.items == totalItems\n defined = true\n }\n if let totalSize = state.totalSize, totalSize > 0 {\n finished = finished && state.size == totalSize\n defined = true\n }\n if defined && finished {\n finish()\n }\n }\n\n /// Sets the current tasks.\n /// - Parameter newTasks: The current tasks to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(tasks newTasks: Int, render: Bool = true) {\n state.withLock { $0.tasks = newTasks }\n if render {\n self.render()\n }\n checkIfFinished()\n }\n\n /// Performs an addition to the current tasks.\n /// - Parameter delta: The tasks to add to the current tasks.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(tasks delta: Int, render: Bool = true) {\n state.withLock {\n let newTasks = $0.tasks + delta\n $0.tasks = newTasks\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total tasks.\n /// - Parameter newTotalTasks: The total tasks to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalTasks newTotalTasks: Int, render: Bool = true) {\n state.withLock { $0.totalTasks = newTotalTasks }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total tasks.\n /// - Parameter delta: The tasks to add to the total tasks.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalTasks delta: Int, render: Bool = true) {\n state.withLock {\n let totalTasks = $0.totalTasks ?? 0\n let newTotalTasks = totalTasks + delta\n $0.totalTasks = newTotalTasks\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the items name.\n /// - Parameter newItemsName: The current items to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(itemsName newItemsName: String, render: Bool = true) {\n state.withLock { $0.itemsName = newItemsName }\n if render {\n self.render()\n }\n }\n\n /// Sets the current items.\n /// - Parameter newItems: The current items to set.\n public func set(items newItems: Int, render: Bool = true) {\n state.withLock { $0.items = newItems }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the current items.\n /// - Parameter delta: The items to add to the current items.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(items delta: Int, render: Bool = true) {\n state.withLock {\n let newItems = $0.items + delta\n $0.items = newItems\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total items.\n /// - Parameter newTotalItems: The total items to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalItems newTotalItems: Int, render: Bool = true) {\n state.withLock { $0.totalItems = newTotalItems }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total items.\n /// - Parameter delta: The items to add to the total items.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalItems delta: Int, render: Bool = true) {\n state.withLock {\n let totalItems = $0.totalItems ?? 0\n let newTotalItems = totalItems + delta\n $0.totalItems = newTotalItems\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the current size.\n /// - Parameter newSize: The current size to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(size newSize: Int64, render: Bool = true) {\n state.withLock { $0.size = newSize }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the current size.\n /// - Parameter delta: The size to add to the current size.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(size delta: Int64, render: Bool = true) {\n state.withLock {\n let newSize = $0.size + delta\n $0.size = newSize\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total size.\n /// - Parameter newTotalSize: The total size to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalSize newTotalSize: Int64, render: Bool = true) {\n state.withLock { $0.totalSize = newTotalSize }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total size.\n /// - Parameter delta: The size to add to the total size.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalSize delta: Int64, render: Bool = true) {\n state.withLock {\n let totalSize = $0.totalSize ?? 0\n let newTotalSize = totalSize + delta\n $0.totalSize = newTotalSize\n }\n if render {\n self.render()\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+Terminal.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nenum EscapeSequence {\n static let hideCursor = \"\\u{001B}[?25l\"\n static let showCursor = \"\\u{001B}[?25h\"\n static let moveUp = \"\\u{001B}[1A\"\n}\n\nextension ProgressBar {\n private var terminalWidth: Int {\n guard\n let terminalHandle = term,\n let terminal = try? Terminal(descriptor: terminalHandle.fileDescriptor)\n else {\n return 0\n }\n\n let terminalWidth = (try? Int(terminal.size.width)) ?? 0\n return terminalWidth\n }\n\n /// Clears the progress bar and resets the cursor.\n public func clearAndResetCursor() {\n clear()\n resetCursor()\n }\n\n /// Clears the progress bar.\n public func clear() {\n displayText(\"\")\n }\n\n /// Resets the cursor.\n public func resetCursor() {\n display(EscapeSequence.showCursor)\n }\n\n func display(_ text: String) {\n guard let term else {\n return\n }\n termQueue.sync {\n try? term.write(contentsOf: Data(text.utf8))\n try? term.synchronize()\n }\n }\n\n func displayText(_ text: String, terminating: String = \"\\r\") {\n var text = text\n\n // Clears previously printed characters if the new string is shorter.\n text += String(repeating: \" \", count: max(printedWidth - text.count, 0))\n printedWidth = text.count\n state.withLock {\n $0.output = text\n }\n\n // Clears previously printed lines.\n var lines = \"\"\n if terminating.hasSuffix(\"\\r\") && terminalWidth > 0 {\n let lineCount = (text.count - 1) / terminalWidth\n for _ in 0.. URL? {\n self.log.trace(\"ContentStoreService: \\(#function) digest \\(digest)\")\n return try await self.contentStore.get(digest: digest)?.path\n }\n\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n self.log.debug(\"ContentStoreService: \\(#function) digests \\(digests)\")\n return try await self.contentStore.delete(digests: digests)\n }\n\n @discardableResult\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n self.log.debug(\"ContentStoreService: \\(#function) digests \\(keeping)\")\n return try await self.contentStore.delete(keeping: keeping)\n }\n\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n self.log.debug(\"ContentStoreService: \\(#function)\")\n return try await self.contentStore.newIngestSession()\n }\n\n public func completeIngestSession(_ id: String) async throws -> [String] {\n self.log.debug(\"ContentStoreService: \\(#function) id \\(id)\")\n return try await self.contentStore.completeIngestSession(id)\n }\n\n public func cancelIngestSession(_ id: String) async throws {\n self.log.debug(\"ContentStoreService: \\(#function) id \\(id)\")\n return try await self.contentStore.cancelIngestSession(id)\n }\n}\n"], ["/container/Sources/ContainerClient/Flags.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationError\nimport Foundation\n\npublic struct Flags {\n public struct Global: ParsableArguments {\n public init() {}\n\n @Flag(name: .long, help: \"Enable debug output [environment: CONTAINER_DEBUG]\")\n public var debug = false\n }\n\n public struct Process: ParsableArguments {\n public init() {}\n\n @Option(\n name: [.customLong(\"cwd\"), .customShort(\"w\"), .customLong(\"workdir\")],\n help: \"Current working directory for the container\")\n public var cwd: String?\n\n @Option(name: [.customLong(\"env\"), .customShort(\"e\")], help: \"Set environment variables\")\n public var env: [String] = []\n\n @Option(name: .customLong(\"env-file\"), help: \"Read in a file of environment variables\")\n public var envFile: [String] = []\n\n @Option(name: .customLong(\"uid\"), help: \"Set the uid for the process\")\n public var uid: UInt32?\n\n @Option(name: .customLong(\"gid\"), help: \"Set the gid for the process\")\n public var gid: UInt32?\n\n @Flag(name: [.customLong(\"interactive\"), .customShort(\"i\")], help: \"Keep Stdin open even if not attached\")\n public var interactive = false\n\n @Flag(name: [.customLong(\"tty\"), .customShort(\"t\")], help: \"Open a tty with the process\")\n public var tty = false\n\n @Option(name: [.customLong(\"user\"), .customShort(\"u\")], help: \"Set the user for the process\")\n public var user: String?\n }\n\n public struct Resource: ParsableArguments {\n public init() {}\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64?\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n public var memory: String?\n }\n\n public struct Registry: ParsableArguments {\n public init() {}\n\n public init(scheme: String) {\n self.scheme = scheme\n }\n\n @Option(help: \"Scheme to use when connecting to the container registry. One of (http, https, auto)\")\n public var scheme: String = \"auto\"\n }\n\n public struct Management: ParsableArguments {\n public init() {}\n\n @Flag(name: [.customLong(\"detach\"), .short], help: \"Run the container and detach from the process\")\n public var detach = false\n\n @Option(name: .customLong(\"entrypoint\"), help: \"Override the entrypoint of the image\")\n public var entryPoint: String?\n\n @Option(name: .customLong(\"mount\"), help: \"Add a mount to the container (type=<>,source=<>,target=<>,readonly)\")\n public var mounts: [String] = []\n\n @Option(name: [.customLong(\"publish\"), .short], help: \"Publish a port from container to host (format: [host-ip:]host-port:container-port[/protocol])\")\n public var publishPorts: [String] = []\n\n @Option(name: .customLong(\"publish-socket\"), help: \"Publish a socket from container to host (format: host_path:container_path)\")\n public var publishSockets: [String] = []\n\n @Option(name: .customLong(\"tmpfs\"), help: \"Add a tmpfs mount to the container at the given path\")\n public var tmpFs: [String] = []\n\n @Option(name: .customLong(\"name\"), help: \"Assign a name to the container. If excluded will be a generated UUID\")\n public var name: String?\n\n @Flag(name: [.customLong(\"remove\"), .customLong(\"rm\")], help: \"Remove the container after it stops\")\n public var remove = false\n\n @Option(name: .customLong(\"os\"), help: \"Set OS if image can target multiple operating systems\")\n public var os = \"linux\"\n\n @Option(\n name: [.customLong(\"arch\"), .short], help: \"Set arch if image can target multiple architectures\")\n public var arch: String = Arch.hostArchitecture().rawValue\n\n @Option(name: [.customLong(\"volume\"), .short], help: \"Bind mount a volume into the container\")\n public var volumes: [String] = []\n\n @Option(\n name: [.customLong(\"kernel\"), .short], help: \"Set a custom kernel path\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n public var kernel: String?\n\n @Option(name: [.customLong(\"network\")], help: \"Attach the container to a network\")\n public var networks: [String] = []\n\n @Option(name: .customLong(\"cidfile\"), help: \"Write the container ID to the path provided\")\n public var cidfile = \"\"\n\n @Flag(name: [.customLong(\"no-dns\")], help: \"Do not configure DNS in the container\")\n public var dnsDisabled = false\n\n @Option(name: .customLong(\"dns\"), help: \"DNS nameserver IP address\")\n public var dnsNameservers: [String] = []\n\n @Option(name: .customLong(\"dns-domain\"), help: \"Default DNS domain\")\n public var dnsDomain: String? = nil\n\n @Option(name: .customLong(\"dns-search\"), help: \"DNS search domains\")\n public var dnsSearchDomains: [String] = []\n\n @Option(name: .customLong(\"dns-option\"), help: \"DNS options\")\n public var dnsOptions: [String] = []\n\n @Option(name: [.customLong(\"label\"), .short], help: \"Add a key=value label to the container\")\n public var labels: [String] = []\n }\n\n public struct Progress: ParsableArguments {\n public init() {}\n\n public init(disableProgressUpdates: Bool) {\n self.disableProgressUpdates = disableProgressUpdates\n }\n\n @Flag(name: .customLong(\"disable-progress-updates\"), help: \"Disable progress bar updates\")\n public var disableProgressUpdates = false\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildAPI+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationOCI\n\npublic typealias IO = Com_Apple_Container_Build_V1_IO\npublic typealias InfoRequest = Com_Apple_Container_Build_V1_InfoRequest\npublic typealias InfoResponse = Com_Apple_Container_Build_V1_InfoResponse\npublic typealias ClientStream = Com_Apple_Container_Build_V1_ClientStream\npublic typealias ServerStream = Com_Apple_Container_Build_V1_ServerStream\npublic typealias ImageTransfer = Com_Apple_Container_Build_V1_ImageTransfer\npublic typealias BuildTransfer = Com_Apple_Container_Build_V1_BuildTransfer\npublic typealias BuilderClient = Com_Apple_Container_Build_V1_BuilderNIOClient\npublic typealias BuilderClientAsync = Com_Apple_Container_Build_V1_BuilderAsyncClient\npublic typealias BuilderClientProtocol = Com_Apple_Container_Build_V1_BuilderClientProtocol\npublic typealias BuilderClientAsyncProtocol = Com_Apple_Container_Build_V1_BuilderAsyncClient\n\nextension BuildTransfer {\n func stage() -> String? {\n let stage = self.metadata[\"stage\"]\n return stage == \"\" ? nil : stage\n }\n\n func method() -> String? {\n let method = self.metadata[\"method\"]\n return method == \"\" ? nil : method\n }\n\n func includePatterns() -> [String]? {\n guard let includePatternsString = self.metadata[\"include-patterns\"] else {\n return nil\n }\n return includePatternsString == \"\" ? nil : includePatternsString.components(separatedBy: \",\")\n }\n\n func followPaths() -> [String]? {\n guard let followPathString = self.metadata[\"followpaths\"] else {\n return nil\n }\n return followPathString == \"\" ? nil : followPathString.components(separatedBy: \",\")\n }\n\n func mode() -> String? {\n self.metadata[\"mode\"]\n }\n\n func size() -> Int? {\n guard let sizeStr = self.metadata[\"size\"] else {\n return nil\n }\n return sizeStr == \"\" ? nil : Int(sizeStr)\n }\n\n func offset() -> UInt64? {\n guard let offsetStr = self.metadata[\"offset\"] else {\n return nil\n }\n return offsetStr == \"\" ? nil : UInt64(offsetStr)\n }\n\n func len() -> Int? {\n guard let lenStr = self.metadata[\"length\"] else {\n return nil\n }\n return lenStr == \"\" ? nil : Int(lenStr)\n }\n}\n\nextension ImageTransfer {\n func stage() -> String? {\n self.metadata[\"stage\"]\n }\n\n func method() -> String? {\n self.metadata[\"method\"]\n }\n\n func ref() -> String? {\n self.metadata[\"ref\"]\n }\n\n func platform() throws -> Platform? {\n let metadata = self.metadata\n guard let platform = metadata[\"platform\"] else {\n return nil\n }\n return try Platform(from: platform)\n }\n\n func mode() -> String? {\n self.metadata[\"mode\"]\n }\n\n func size() -> Int? {\n let metadata = self.metadata\n guard let sizeStr = metadata[\"size\"] else {\n return nil\n }\n return Int(sizeStr)\n }\n\n func len() -> Int? {\n let metadata = self.metadata\n guard let lenStr = metadata[\"length\"] else {\n return nil\n }\n return Int(lenStr)\n }\n\n func offset() -> UInt64? {\n let metadata = self.metadata\n guard let offsetStr = metadata[\"offset\"] else {\n return nil\n }\n return UInt64(offsetStr)\n }\n}\n\nextension ServerStream {\n func getImageTransfer() -> ImageTransfer? {\n if case .imageTransfer(let v) = self.packetType {\n return v\n }\n return nil\n }\n\n func getBuildTransfer() -> BuildTransfer? {\n if case .buildTransfer(let v) = self.packetType {\n return v\n }\n return nil\n }\n\n func getIO() -> IO? {\n if case .io(let v) = self.packetType {\n return v\n }\n return nil\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\n\nextension Application {\n struct DNSCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a local DNS domain for containers (must run as an administrator)\"\n )\n\n @Argument(help: \"the local domain name\")\n var domainName: String\n\n func run() async throws {\n let resolver: HostDNSResolver = HostDNSResolver()\n do {\n try resolver.createDomain(name: domainName)\n print(domainName)\n } catch let error as ContainerizationError {\n throw error\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot create domain (try sudo?)\")\n }\n\n do {\n try HostDNSResolver.reinitialize()\n } catch {\n throw ContainerizationError(.invalidState, message: \"mDNSResponder restart failed, run `sudo killall -HUP mDNSResponder` to deactivate domain\")\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePush.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport TerminalProgress\n\nextension Application {\n struct ImagePush: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"push\",\n abstract: \"Push an image\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Argument var reference: String\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let scheme = try RequestScheme(registry.scheme)\n let image = try await ClientImage.get(reference: reference)\n\n var progressConfig: ProgressConfig\n if progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n description: \"Pushing image \\(image.reference)\",\n itemsName: \"blobs\",\n showItems: true,\n showSpeed: false,\n ignoreSmallSize: true\n )\n }\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n _ = try await image.push(platform: p, scheme: scheme, progressUpdate: progress.handler)\n progress.finish()\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImageLoad.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ImageLoad: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"load\",\n abstract: \"Load images from an OCI compatible tar archive\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(\n name: .shortAndLong, help: \"Path to the tar archive to load images from\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var input: String\n\n func run() async throws {\n guard FileManager.default.fileExists(atPath: input) else {\n print(\"File does not exist \\(input)\")\n Application.exit(withError: ArgumentParser.ExitCode(1))\n }\n\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n totalTasks: 2\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Loading tar archive\")\n let loaded = try await ClientImage.load(from: input)\n\n let taskManager = ProgressTaskCoordinator()\n let unpackTask = await taskManager.startTask()\n progress.set(description: \"Unpacking image\")\n progress.set(itemsName: \"entries\")\n for image in loaded {\n try await image.unpack(platform: nil, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progress.handler))\n }\n await taskManager.finish()\n progress.finish()\n print(\"Loaded images:\")\n for image in loaded {\n print(image.reference)\n }\n }\n }\n}\n"], ["/container/Sources/APIServer/Kernel/FileDownloader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\ninternal struct FileDownloader {\n public static func downloadFile(url: URL, to destination: URL, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let request = try HTTPClient.Request(url: url)\n\n let delegate = try FileDownloadDelegate(\n path: destination.path(),\n reportHead: {\n let expectedSizeString = $0.headers[\"Content-Length\"].first ?? \"\"\n if let expectedSize = Int64(expectedSizeString) {\n if let progressUpdate {\n Task {\n await progressUpdate([\n .addTotalSize(expectedSize)\n ])\n }\n }\n }\n },\n reportProgress: {\n let receivedBytes = Int64($0.receivedBytes)\n if let progressUpdate {\n Task {\n await progressUpdate([\n .setSize(receivedBytes)\n ])\n }\n }\n })\n\n let client = FileDownloader.createClient()\n _ = try await client.execute(request: request, delegate: delegate).get()\n try await client.shutdown()\n }\n\n private static func createClient() -> HTTPClient {\n var httpConfiguration = HTTPClient.Configuration()\n let proxyConfig: HTTPClient.Configuration.Proxy? = {\n let proxyEnv = ProcessInfo.processInfo.environment[\"HTTP_PROXY\"]\n guard let proxyEnv else {\n return nil\n }\n guard let url = URL(string: proxyEnv), let host = url.host(), let port = url.port else {\n return nil\n }\n return .server(host: host, port: port)\n }()\n httpConfiguration.proxy = proxyConfig\n return HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration)\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/IsolatedInterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\n\n/// Isolated container network interface strategy. This strategy prohibits\n/// container to container networking, but it is the only approach that\n/// works for macOS Sequoia.\nstruct IsolatedInterfaceStrategy: InterfaceStrategy {\n public func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) -> Interface {\n let gateway = interfaceIndex == 0 ? attachment.gateway : nil\n return NATInterface(address: attachment.address, gateway: gateway)\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/HostTableResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\n\n/// Handler that uses table lookup to resolve hostnames.\npublic struct HostTableResolver: DNSHandler {\n public let hosts4: [String: IPv4]\n private let ttl: UInt32\n\n public init(hosts4: [String: IPv4], ttl: UInt32 = 300) {\n self.hosts4 = hosts4\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n let record: ResourceRecord?\n switch question.type {\n case ResourceRecordType.host:\n record = answerHost(question: question)\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n\n guard let record else {\n return nil\n }\n\n return Message(\n id: query.id,\n type: .response,\n returnCode: .noError,\n questions: query.questions,\n answers: [record]\n )\n }\n\n private func answerHost(question: Question) -> ResourceRecord? {\n guard let ip = hosts4[question.name] else {\n return nil\n }\n\n return HostRecord(name: question.name, ttl: ttl, ip: ip)\n }\n}\n"], ["/container/Sources/CLI/DefaultCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\n\nstruct DefaultCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: nil,\n shouldDisplay: false\n )\n\n @OptionGroup(visibility: .hidden)\n var global: Flags.Global\n\n @Argument(parsing: .captureForPassthrough)\n var remaining: [String] = []\n\n func run() async throws {\n // See if we have a possible plugin command.\n guard let command = remaining.first else {\n Application.printModifiedHelpText()\n return\n }\n\n // Check for edge cases and unknown options to match the behavior in the absence of plugins.\n if command.isEmpty {\n throw ValidationError(\"Unknown argument '\\(command)'\")\n } else if command.starts(with: \"-\") {\n throw ValidationError(\"Unknown option '\\(command)'\")\n }\n\n let pluginLoader = Application.pluginLoader\n guard let plugin = pluginLoader.findPlugin(name: command), plugin.config.isCLI else {\n throw ValidationError(\"failed to find plugin named container-\\(command)\")\n }\n // Exec performs execvp (with no fork).\n try plugin.exec(args: remaining)\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePull.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport TerminalProgress\n\nextension Application {\n struct ImagePull: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"pull\",\n abstract: \"Pull an image\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Argument var reference: String\n\n init() {}\n\n init(platform: String? = nil, scheme: String = \"auto\", reference: String, disableProgress: Bool = false) {\n self.global = Flags.Global()\n self.registry = Flags.Registry(scheme: scheme)\n self.progressFlags = Flags.Progress(disableProgressUpdates: disableProgress)\n self.platform = platform\n self.reference = reference\n }\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let scheme = try RequestScheme(registry.scheme)\n\n let processedReference = try ClientImage.normalizeReference(reference)\n\n var progressConfig: ProgressConfig\n if self.progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: self.progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 2\n )\n }\n\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Fetching image\")\n progress.set(itemsName: \"blobs\")\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n let image = try await ClientImage.pull(\n reference: processedReference, platform: p, scheme: scheme, progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progress.handler)\n )\n\n progress.set(description: \"Unpacking image\")\n progress.set(itemsName: \"entries\")\n let unpackTask = await taskManager.startTask()\n try await image.unpack(platform: p, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progress.handler))\n await taskManager.finish()\n progress.finish()\n }\n }\n}\n"], ["/container/Sources/ContainerClient/SignalThreshold.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\n\n// For a lot of programs, they don't install their own signal handlers for\n// SIGINT/SIGTERM which poses a somewhat fun problem for containers. Because\n// they're pid 1 (doesn't matter that it isn't in the \"root\" pid namespace)\n// the default actions for SIGINT and SIGTERM now are nops. So this type gives\n// us an opportunity to set a threshold for a certain number of signals received\n// so we can have an escape hatch for users to escape their horrific mistake\n// of cat'ing /dev/urandom by exit(1)'ing :)\npublic struct SignalThreshold {\n private let threshold: Int\n private let signals: [Int32]\n private var t: Task<(), Never>?\n\n public init(\n threshold: Int,\n signals: [Int32],\n ) {\n self.threshold = threshold\n self.signals = signals\n }\n\n // Start kicks off the signal watching. The passed in handler will\n // run only once upon passing the threshold number passed in the constructor.\n mutating public func start(handler: @Sendable @escaping () -> Void) {\n let signals = self.signals\n let threshold = self.threshold\n self.t = Task {\n var received = 0\n let signalHandler = AsyncSignalHandler.create(notify: signals)\n for await _ in signalHandler.signals {\n received += 1\n if received == threshold {\n handler()\n signalHandler.cancel()\n return\n }\n }\n }\n }\n\n public func stop() {\n self.t?.cancel()\n }\n}\n"], ["/container/Sources/CLI/Image/ImageSave.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ImageSave: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"save\",\n abstract: \"Save an image as an OCI compatible tar archive\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Option(\n name: .shortAndLong, help: \"Path to save the image tar archive\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var output: String\n\n @Argument var reference: String\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let progressConfig = try ProgressConfig(\n description: \"Saving image\"\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let image = try await ClientImage.get(reference: reference)\n try await image.save(out: output, platform: p)\n\n progress.finish()\n print(\"Image saved\")\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/Globber.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic class Globber {\n let input: URL\n var results: Set = .init()\n\n public init(_ input: URL) {\n self.input = input\n }\n\n public func match(_ pattern: String) throws {\n let adjustedPattern =\n pattern\n .replacingOccurrences(of: #\"^\\./(?=.)\"#, with: \"\", options: .regularExpression)\n .replacingOccurrences(of: \"^\\\\.[/]?$\", with: \"*\", options: .regularExpression)\n .replacingOccurrences(of: \"\\\\*{2,}[/]\", with: \"*/**/\", options: .regularExpression)\n .replacingOccurrences(of: \"[/]\\\\*{2,}([^/])\", with: \"/**/*$1\", options: .regularExpression)\n .replacingOccurrences(of: \"^\\\\*{2,}([^/])\", with: \"**/*$1\", options: .regularExpression)\n\n for child in input.children {\n try self.match(input: child, components: adjustedPattern.split(separator: \"/\").map(String.init))\n }\n }\n\n private func match(input: URL, components: [String]) throws {\n if components.isEmpty {\n var dir = input.standardizedFileURL\n\n while dir != self.input.standardizedFileURL {\n results.insert(dir)\n guard dir.pathComponents.count > 1 else { break }\n dir.deleteLastPathComponent()\n }\n return input.childrenRecursive.forEach { results.insert($0) }\n }\n\n let head = components.first ?? \"\"\n let tail = components.tail\n\n if head == \"**\" {\n var tail: [String] = tail\n while tail.first == \"**\" {\n tail = tail.tail\n }\n try self.match(input: input, components: tail)\n for child in input.children {\n try self.match(input: child, components: components)\n }\n return\n }\n\n if try glob(input.lastPathComponent, head) {\n try self.match(input: input, components: tail)\n\n for child in input.children where try glob(child.lastPathComponent, tail.first ?? \"\") {\n try self.match(input: child, components: tail)\n }\n return\n }\n }\n\n func glob(_ input: String, _ pattern: String) throws -> Bool {\n let regexPattern =\n \"^\"\n + NSRegularExpression.escapedPattern(for: pattern)\n .replacingOccurrences(of: \"\\\\*\", with: \"[^/]*\")\n .replacingOccurrences(of: \"\\\\?\", with: \"[^/]\")\n .replacingOccurrences(of: \"[\\\\^\", with: \"[^\")\n .replacingOccurrences(of: \"\\\\[\", with: \"[\")\n .replacingOccurrences(of: \"\\\\]\", with: \"]\") + \"$\"\n\n // validate the regex pattern created\n let _ = try Regex(regexPattern)\n return input.range(of: regexPattern, options: .regularExpression) != nil\n }\n}\n\nextension URL {\n var children: [URL] {\n\n (try? FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil))\n ?? []\n }\n\n var childrenRecursive: [URL] {\n var results: [URL] = []\n if let enumerator = FileManager.default.enumerator(\n at: self, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey])\n {\n while let child = enumerator.nextObject() as? URL {\n results.append(child)\n }\n }\n return [self] + results\n }\n}\n\nextension [String] {\n var tail: [String] {\n if self.count <= 1 {\n return []\n }\n return Array(self.dropFirst())\n }\n}\n"], ["/container/Sources/ContainerClient/Core/PublishPort.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The network protocols available for port forwarding.\npublic enum PublishProtocol: String, Sendable, Codable {\n case tcp = \"tcp\"\n case udp = \"udp\"\n\n /// Initialize a protocol with to default value, `.tcp`.\n public init() {\n self = .tcp\n }\n\n /// Initialize a protocol value from the provided string.\n public init?(_ value: String) {\n switch value.lowercased() {\n case \"tcp\": self = .tcp\n case \"udp\": self = .udp\n default: return nil\n }\n }\n}\n\n/// Specifies internet port forwarding from host to container.\npublic struct PublishPort: Sendable, Codable {\n /// The IP address of the proxy listener on the host\n public let hostAddress: String\n\n /// The port number of the proxy listener on the host\n public let hostPort: Int\n\n /// The port number of the container listener\n public let containerPort: Int\n\n /// The network protocol for the proxy\n public let proto: PublishProtocol\n\n /// Creates a new port forwarding specification.\n public init(hostAddress: String, hostPort: Int, containerPort: Int, proto: PublishProtocol) {\n self.hostAddress = hostAddress\n self.hostPort = hostPort\n self.containerPort = containerPort\n self.proto = proto\n }\n}\n"], ["/container/Sources/CLI/Image/ImageInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ImageInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more images\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Images to inspect\")\n var images: [String]\n\n func run() async throws {\n var printable = [any Codable]()\n let result = try await ClientImage.get(names: images)\n let notFound = result.error\n for image in result.images {\n guard !Utility.isInfraImage(name: image.reference) else {\n continue\n }\n printable.append(try await image.details())\n }\n if printable.count > 0 {\n print(try printable.jsonArray())\n }\n if notFound.count > 0 {\n throw ContainerizationError(.notFound, message: \"Images: \\(notFound.joined(separator: \"\\n\"))\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildStdio.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIO\n\nactor BuildStdio: BuildPipelineHandler {\n public let quiet: Bool\n public let handle: FileHandle\n\n init(quiet: Bool = false, output: FileHandle = FileHandle.standardError) throws {\n self.quiet = quiet\n self.handle = output\n }\n\n nonisolated func accept(_ packet: ServerStream) throws -> Bool {\n guard let _ = packet.getIO() else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard !quiet else {\n return\n }\n guard let io = packet.getIO() else {\n throw Error.ioMissing\n }\n if let cmdString = try TerminalCommand().json() {\n var response = ClientStream()\n response.buildID = packet.buildID\n response.command = .init()\n response.command.id = packet.buildID\n response.command.command = cmdString\n sender.yield(response)\n }\n handle.write(io.data)\n }\n}\n\nextension BuildStdio {\n enum Error: Swift.Error, CustomStringConvertible {\n case ioMissing\n case invalidContinuation\n var description: String {\n switch self {\n case .ioMissing:\n return \"io field missing in packet\"\n case .invalidContinuation:\n return \"continuation could not created\"\n }\n }\n }\n}\n"], ["/container/Sources/APIServer/HealthCheck/HealthCheckHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport Logging\n\nactor HealthCheckHarness {\n private let log: Logger\n\n public init(log: Logger) {\n self.log = log\n }\n\n @Sendable\n func ping(_ message: XPCMessage) async -> XPCMessage {\n message.reply()\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/InterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\n\n/// A strategy for mapping network attachment information to a network interface.\npublic protocol InterfaceStrategy: Sendable {\n /// Map a client network attachment request to a network interface specification.\n ///\n /// - Parameters:\n /// - attachment: General attachment information that is common\n /// for all networks.\n /// - interfaceIndex: The zero-based index of the interface.\n /// - additionalData: If present, attachment information that is\n /// specific for the network to which the container will attach.\n ///\n /// - Returns: An XPC message with no parameters.\n func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) throws -> Interface\n}\n"], ["/container/Sources/SocketForwarder/LRUCache.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nstruct KeyExistsError: Error {}\n\nclass LRUCache {\n private class Node {\n fileprivate var prev: Node?\n fileprivate var next: Node?\n fileprivate let key: K\n fileprivate let value: V\n\n init(key: K, value: V) {\n self.prev = nil\n self.next = nil\n self.key = key\n self.value = value\n }\n }\n\n private let size: UInt\n private var head: Node?\n private var tail: Node?\n private var members: [K: Node]\n\n init(size: UInt) {\n self.size = size\n self.head = nil\n self.tail = nil\n self.members = [:]\n }\n\n var count: Int { members.count }\n\n func get(_ key: K) -> V? {\n guard let node = members[key] else {\n return nil\n }\n listRemove(node: node)\n listInsert(node: node, after: tail)\n return node.value\n }\n\n func put(key: K, value: V) -> (K, V)? {\n let node = Node(key: key, value: value)\n var evicted: (K, V)? = nil\n\n if let existingNode = members[key] {\n // evict the replaced node\n listRemove(node: existingNode)\n evicted = (existingNode.key, existingNode.value)\n } else if self.count >= self.size {\n // evict the least recently used node\n evicted = evict()\n }\n\n // insert the new node and return any evicted node\n members[key] = node\n listInsert(node: node, after: tail)\n return evicted\n }\n\n private func evict() -> (K, V)? {\n guard let head else {\n return nil\n }\n let ret = (head.key, head.value)\n listRemove(node: head)\n members.removeValue(forKey: head.key)\n return ret\n }\n\n private func listRemove(node: Node) {\n if let prev = node.prev {\n prev.next = node.next\n } else {\n head = node.next\n }\n if let next = node.next {\n next.prev = node.prev\n } else {\n tail = node.prev\n }\n }\n\n private func listInsert(node: Node, after: Node?) {\n let before: Node?\n if let after {\n before = after.next\n after.next = node\n } else {\n before = head\n head = node\n }\n\n if let before {\n before.prev = node\n } else {\n tail = node\n }\n\n node.prev = after\n node.next = before\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/StandardQueryValidator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Pass standard queries to a delegate handler.\npublic struct StandardQueryValidator: DNSHandler {\n private let handler: DNSHandler\n\n /// Create the handler.\n /// - Parameter delegate: the handler that receives valid queries\n public init(handler: DNSHandler) {\n self.handler = handler\n }\n\n /// Ensures the query is valid before forwarding it to the delegate.\n /// - Parameter msg: the query message\n /// - Returns: the delegate response if the query is valid, and an\n /// error response otherwise\n public func answer(query: Message) async throws -> Message? {\n // Reject response messages.\n guard query.type == .query else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions\n )\n }\n\n // Standard DNS servers handle only query operations.\n guard query.operationCode == .query else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions\n )\n }\n\n // Standard DNS servers only handle messages with exactly one question.\n guard query.questions.count == 1 else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions\n )\n }\n\n return try await handler.answer(query: query)\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkMode.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Networking mode that applies to client containers.\npublic enum NetworkMode: String, Codable, Sendable {\n /// NAT networking mode.\n /// Containers do not have routable IPs, and the host performs network\n /// address translation to allow containers to reach external services.\n case nat = \"nat\"\n}\n\nextension NetworkMode {\n public init() {\n self = .nat\n }\n\n public init?(_ value: String) {\n switch value.lowercased() {\n case \"nat\": self = .nat\n default: return nil\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ProcessConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Configuration data for an executable Process.\npublic struct ProcessConfiguration: Sendable, Codable {\n /// The on disk path to the executable binary.\n public var executable: String\n /// Arguments passed to the Process.\n public var arguments: [String]\n /// Environment variables for the Process.\n public var environment: [String]\n /// The current working directory (cwd) for the Process.\n public var workingDirectory: String\n /// A boolean value indicating if a Terminal or PTY device should\n /// be attached to the Process's Standard I/O.\n public var terminal: Bool\n /// The User a Process should execute under.\n public var user: User\n /// Supplemental groups for the Process.\n public var supplementalGroups: [UInt32]\n /// Rlimits for the Process.\n public var rlimits: [Rlimit]\n\n /// Rlimits for Processes.\n public struct Rlimit: Sendable, Codable {\n /// The Rlimit type of the Process.\n ///\n /// Values include standard Rlimit resource types, i.e. RLIMIT_NPROC, RLIMIT_NOFILE, ...\n public let limit: String\n /// The soft limit of the Process\n public let soft: UInt64\n /// The hard or max limit of the Process.\n public let hard: UInt64\n\n public init(limit: String, soft: UInt64, hard: UInt64) {\n self.limit = limit\n self.soft = soft\n self.hard = hard\n }\n }\n\n /// The User information for a Process.\n public enum User: Sendable, Codable, CustomStringConvertible {\n /// Given the raw user string of the form or or lookup the uid/gid within\n /// the container before setting it for the Process.\n case raw(userString: String)\n /// Set the provided uid/gid for the Process.\n case id(uid: UInt32, gid: UInt32)\n\n public var description: String {\n switch self {\n case .id(let uid, let gid):\n return \"\\(uid):\\(gid)\"\n case .raw(let name):\n return name\n }\n }\n }\n\n public init(\n executable: String,\n arguments: [String],\n environment: [String],\n workingDirectory: String = \"/\",\n terminal: Bool = false,\n user: User = .id(uid: 0, gid: 0),\n supplementalGroups: [UInt32] = [],\n rlimits: [Rlimit] = []\n ) {\n self.executable = executable\n self.arguments = arguments\n self.environment = environment\n self.workingDirectory = workingDirectory\n self.terminal = terminal\n self.user = user\n self.supplementalGroups = supplementalGroups\n self.rlimits = rlimits\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderStop: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"stop\"\n config._superCommandName = \"builder\"\n config.abstract = \"Stop builder\"\n config.usage = \"\\n\\t builder stop\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n try await container.stop()\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n print(\"builder is not running\")\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A configuration for displaying a progress bar.\npublic struct ProgressConfig: Sendable {\n /// The file handle for progress updates.\n let terminal: FileHandle\n /// The initial description of the progress bar.\n let initialDescription: String\n /// The initial additional description of the progress bar.\n let initialSubDescription: String\n /// The initial items name (e.g., \"files\").\n let initialItemsName: String\n /// A flag indicating whether to show a spinner (e.g., \"⠋\").\n /// The spinner is hidden when a progress bar is shown.\n public let showSpinner: Bool\n /// A flag indicating whether to show tasks and total tasks (e.g., \"[1]\" or \"[1/3]\").\n public let showTasks: Bool\n /// A flag indicating whether to show the description (e.g., \"Downloading...\").\n public let showDescription: Bool\n /// A flag indicating whether to show a percentage (e.g., \"100%\").\n /// The percentage is hidden when no total size and total items are set.\n public let showPercent: Bool\n /// A flag indicating whether to show a progress bar (e.g., \"|███ |\").\n /// The progress bar is hidden when no total size and total items are set.\n public let showProgressBar: Bool\n /// A flag indicating whether to show items and total items (e.g., \"(22 it)\" or \"(22/22 it)\").\n public let showItems: Bool\n /// A flag indicating whether to show a size and a total size (e.g., \"(22 MB)\" or \"(22/22 MB)\").\n public let showSize: Bool\n /// A flag indicating whether to show a speed (e.g., \"(4.834 MB/s)\").\n /// The speed is combined with the size and total size (e.g., \"(22/22 MB, 4.834 MB/s)\").\n /// The speed is hidden when no total size is set.\n public let showSpeed: Bool\n /// A flag indicating whether to show the elapsed time (e.g., \"[4s]\").\n public let showTime: Bool\n /// The flag indicating whether to ignore small size values (less than 1 MB). For example, this may help to avoid reaching 100% after downloading metadata before downloading content.\n public let ignoreSmallSize: Bool\n /// The initial total tasks of the progress bar.\n let initialTotalTasks: Int?\n /// The initial total size of the progress bar.\n let initialTotalSize: Int64?\n /// The initial total items of the progress bar.\n let initialTotalItems: Int?\n /// The width of the progress bar in characters.\n public let width: Int\n /// The theme of the progress bar.\n public let theme: ProgressTheme\n /// The flag indicating whether to clear the progress bar before resetting the cursor.\n public let clearOnFinish: Bool\n /// The flag indicating whether to update the progress bar.\n public let disableProgressUpdates: Bool\n /// Creates a new instance of `ProgressConfig`.\n /// - Parameters:\n /// - terminal: The file handle for progress updates. The default value is `FileHandle.standardError`.\n /// - description: The initial description of the progress bar. The default value is `\"\"`.\n /// - subDescription: The initial additional description of the progress bar. The default value is `\"\"`.\n /// - itemsName: The initial items name. The default value is `\"it\"`.\n /// - showSpinner: A flag indicating whether to show a spinner. The default value is `true`.\n /// - showTasks: A flag indicating whether to show tasks and total tasks. The default value is `false`.\n /// - showDescription: A flag indicating whether to show the description. The default value is `true`.\n /// - showPercent: A flag indicating whether to show a percentage. The default value is `true`.\n /// - showProgressBar: A flag indicating whether to show a progress bar. The default value is `false`.\n /// - showItems: A flag indicating whether to show items and a total items. The default value is `false`.\n /// - showSize: A flag indicating whether to show a size and a total size. The default value is `true`.\n /// - showSpeed: A flag indicating whether to show a speed. The default value is `true`.\n /// - showTime: A flag indicating whether to show the elapsed time. The default value is `true`.\n /// - ignoreSmallSize: A flag indicating whether to ignore small size values. The default value is `false`.\n /// - totalTasks: The initial total tasks of the progress bar. The default value is `nil`.\n /// - totalItems: The initial total items of the progress bar. The default value is `nil`.\n /// - totalSize: The initial total size of the progress bar. The default value is `nil`.\n /// - width: The width of the progress bar in characters. The default value is `120`.\n /// - theme: The theme of the progress bar. The default value is `nil`.\n /// - clearOnFinish: The flag indicating whether to clear the progress bar before resetting the cursor. The default is `true`.\n /// - disableProgressUpdates: The flag indicating whether to update the progress bar. The default is `false`.\n public init(\n terminal: FileHandle = .standardError,\n description: String = \"\",\n subDescription: String = \"\",\n itemsName: String = \"it\",\n showSpinner: Bool = true,\n showTasks: Bool = false,\n showDescription: Bool = true,\n showPercent: Bool = true,\n showProgressBar: Bool = false,\n showItems: Bool = false,\n showSize: Bool = true,\n showSpeed: Bool = true,\n showTime: Bool = true,\n ignoreSmallSize: Bool = false,\n totalTasks: Int? = nil,\n totalItems: Int? = nil,\n totalSize: Int64? = nil,\n width: Int = 120,\n theme: ProgressTheme? = nil,\n clearOnFinish: Bool = true,\n disableProgressUpdates: Bool = false\n ) throws {\n if let totalTasks {\n guard totalTasks > 0 else {\n throw Error.invalid(\"totalTasks must be greater than zero\")\n }\n }\n if let totalItems {\n guard totalItems > 0 else {\n throw Error.invalid(\"totalItems must be greater than zero\")\n }\n }\n if let totalSize {\n guard totalSize > 0 else {\n throw Error.invalid(\"totalSize must be greater than zero\")\n }\n }\n\n self.terminal = terminal\n self.initialDescription = description\n self.initialSubDescription = subDescription\n self.initialItemsName = itemsName\n\n self.showSpinner = showSpinner\n self.showTasks = showTasks\n self.showDescription = showDescription\n self.showPercent = showPercent\n self.showProgressBar = showProgressBar\n self.showItems = showItems\n self.showSize = showSize\n self.showSpeed = showSpeed\n self.showTime = showTime\n\n self.ignoreSmallSize = ignoreSmallSize\n self.initialTotalTasks = totalTasks\n self.initialTotalItems = totalItems\n self.initialTotalSize = totalSize\n\n self.width = width\n self.theme = theme ?? DefaultProgressTheme()\n self.clearOnFinish = clearOnFinish\n self.disableProgressUpdates = disableProgressUpdates\n }\n}\n\nextension ProgressConfig {\n /// An enumeration of errors that can occur when creating a `ProgressConfig`.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalid(String)\n\n /// The description of the error.\n public var description: String {\n switch self {\n case .invalid(let reason):\n return \"Failed to validate config (\\(reason))\"\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/ContainerizationProgressAdapter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport TerminalProgress\n\npublic enum ContainerizationProgressAdapter: ProgressAdapter {\n public static func handler(from progressUpdate: ProgressUpdateHandler?) -> ProgressHandler? {\n guard let progressUpdate else {\n return nil\n }\n return { events in\n var updateEvents = [ProgressUpdateEvent]()\n for event in events {\n if event.event == \"add-items\" {\n if let items = event.value as? Int {\n updateEvents.append(.addItems(items))\n }\n } else if event.event == \"add-total-items\" {\n if let totalItems = event.value as? Int {\n updateEvents.append(.addTotalItems(totalItems))\n }\n } else if event.event == \"add-size\" {\n if let size = event.value as? Int64 {\n updateEvents.append(.addSize(size))\n }\n } else if event.event == \"add-total-size\" {\n if let totalSize = event.value as? Int64 {\n updateEvents.append(.addTotalSize(totalSize))\n }\n }\n }\n await progressUpdate(updateEvents)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ImageDetail.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationOCI\n\npublic struct ImageDetail: Codable {\n public let name: String\n public let index: Descriptor\n public let variants: [Variants]\n\n public struct Variants: Codable {\n public let platform: Platform\n public let config: ContainerizationOCI.Image\n public let size: Int64\n\n init(platform: Platform, size: Int64, config: ContainerizationOCI.Image) {\n self.platform = platform\n self.config = config\n self.size = size\n }\n }\n\n init(name: String, index: Descriptor, variants: [Variants]) {\n self.name = name\n self.index = index\n self.variants = variants\n }\n}\n\nextension ClientImage {\n public func details() async throws -> ImageDetail {\n let indexDescriptor = self.descriptor\n let reference = self.reference\n var variants: [ImageDetail.Variants] = []\n for desc in try await self.index().manifests {\n guard let platform = desc.platform else {\n continue\n }\n let config: ContainerizationOCI.Image\n let manifest: ContainerizationOCI.Manifest\n do {\n config = try await self.config(for: platform)\n manifest = try await self.manifest(for: platform)\n } catch {\n continue\n }\n let size = desc.size + manifest.config.size + manifest.layers.reduce(0, { (l, r) in l + r.size })\n variants.append(.init(platform: platform, size: size, config: config))\n }\n return ImageDetail(name: reference, index: indexDescriptor, variants: variants)\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressTaskCoordinator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that represents a task whose progress is being monitored.\npublic struct ProgressTask: Sendable, Equatable {\n private var id = UUID()\n private var coordinator: ProgressTaskCoordinator\n\n init(manager: ProgressTaskCoordinator) {\n self.coordinator = manager\n }\n\n static public func == (lhs: ProgressTask, rhs: ProgressTask) -> Bool {\n lhs.id == rhs.id\n }\n\n /// Returns `true` if this task is the currently active task, `false` otherwise.\n public func isCurrent() async -> Bool {\n guard let currentTask = await coordinator.currentTask else {\n return false\n }\n return currentTask == self\n }\n}\n\n/// A type that coordinates progress tasks to ignore updates from completed tasks.\npublic actor ProgressTaskCoordinator {\n var currentTask: ProgressTask?\n\n /// Creates an instance of `ProgressTaskCoordinator`.\n public init() {}\n\n /// Returns a new task that should be monitored for progress updates.\n public func startTask() -> ProgressTask {\n let newTask = ProgressTask(manager: self)\n currentTask = newTask\n return newTask\n }\n\n /// Performs cleanup when the monitored tasks complete.\n public func finish() {\n currentTask = nil\n }\n\n /// Returns a handler that updates the progress of a given task.\n /// - Parameters:\n /// - task: The task whose progress is being updated.\n /// - progressUpdate: The handler to invoke when progress updates are received.\n public static func handler(for task: ProgressTask, from progressUpdate: @escaping ProgressUpdateHandler) -> ProgressUpdateHandler {\n { events in\n // Ignore updates from completed tasks.\n if await task.isCurrent() {\n await progressUpdate(events)\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerSnapshot.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\n\n/// A snapshot of a container along with its configuration\n/// and any runtime state information.\npublic struct ContainerSnapshot: Codable, Sendable {\n /// The configuration of the container.\n public let configuration: ContainerConfiguration\n /// The runtime status of the container.\n public let status: RuntimeStatus\n /// Network interfaces attached to the sandbox that are provided to the container.\n public let networks: [Attachment]\n\n public init(\n configuration: ContainerConfiguration,\n status: RuntimeStatus,\n networks: [Attachment]\n ) {\n self.configuration = configuration\n self.status = status\n self.networks = networks\n }\n}\n"], ["/container/Sources/DNSServer/Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport DNS\nimport Foundation\n\npublic typealias Message = DNS.Message\npublic typealias ResourceRecord = DNS.ResourceRecord\npublic typealias HostRecord = DNS.HostRecord\npublic typealias IPv4 = DNS.IPv4\npublic typealias IPv6 = DNS.IPv6\npublic typealias ReturnCode = DNS.ReturnCode\n\npublic enum DNSResolverError: Swift.Error, CustomStringConvertible {\n case serverError(_ msg: String)\n case invalidHandlerSpec(_ spec: String)\n case unsupportedHandlerType(_ t: String)\n case invalidIP(_ v: String)\n case invalidHandlerOption(_ v: String)\n case handlerConfigError(_ msg: String)\n\n public var description: String {\n switch self {\n case .serverError(let msg):\n return \"server error: \\(msg)\"\n case .invalidHandlerSpec(let msg):\n return \"invalid handler spec: \\(msg)\"\n case .unsupportedHandlerType(let t):\n return \"unsupported handler type specified: \\(t)\"\n case .invalidIP(let ip):\n return \"invalid IP specified: \\(ip)\"\n case .invalidHandlerOption(let v):\n return \"invalid handler option specified: \\(v)\"\n case .handlerConfigError(let msg):\n return \"error configuring handler: \\(msg)\"\n }\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct NetworkInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more networks\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Networks to inspect\")\n var networks: [String]\n\n func run() async throws {\n let objects: [any Codable] = try await ClientNetwork.list().filter {\n networks.contains($0.id)\n }.map {\n PrintableNetwork($0)\n }\n print(try objects.jsonArray())\n }\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSDefault.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\n\nextension Application {\n struct DNSDefault: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"default\",\n abstract: \"Set or unset the default local DNS domain\",\n subcommands: [\n DefaultSetCommand.self,\n DefaultUnsetCommand.self,\n DefaultInspectCommand.self,\n ]\n )\n\n struct DefaultSetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default local DNS domain\"\n\n )\n\n @Argument(help: \"the default `--domain-name` to use for the `create` or `run` command\")\n var domainName: String\n\n func run() async throws {\n ClientDefaults.set(value: domainName, key: .defaultDNSDomain)\n print(domainName)\n }\n }\n\n struct DefaultUnsetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"unset\",\n abstract: \"Unset the default local DNS domain\",\n aliases: [\"clear\"]\n )\n\n func run() async throws {\n ClientDefaults.unset(key: .defaultDNSDomain)\n print(\"Unset the default local DNS domain\")\n }\n }\n\n struct DefaultInspectCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display the default local DNS domain\"\n )\n\n func run() async throws {\n print(ClientDefaults.getOptional(key: .defaultDNSDomain) ?? \"\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/CommandLine+Executable.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension CommandLine {\n public static var executablePathUrl: URL {\n /// _NSGetExecutablePath with a zero-length buffer returns the needed buffer length\n var bufferSize: Int32 = 0\n var buffer = [CChar](repeating: 0, count: Int(bufferSize))\n _ = _NSGetExecutablePath(&buffer, &bufferSize)\n\n /// Create the buffer and get the path\n buffer = [CChar](repeating: 0, count: Int(bufferSize))\n guard _NSGetExecutablePath(&buffer, &bufferSize) == 0 else {\n fatalError(\"UNEXPECTED: failed to get executable path\")\n }\n\n /// Return the path with the executable file component removed the last component and\n let executablePath = String(cString: &buffer)\n return URL(filePath: executablePath)\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginFactory.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\nprivate let configFilename: String = \"config.json\"\n\n/// Describes the configuration and binary file locations for a plugin.\npublic protocol PluginFactory: Sendable {\n /// Create a plugin conforming to the layout, if possible.\n func create(installURL: URL) throws -> Plugin?\n}\n\n/// Default layout which uses a Unix-like structure.\npublic struct DefaultPluginFactory: PluginFactory {\n public init() {}\n\n public func create(installURL: URL) throws -> Plugin? {\n let fm = FileManager.default\n\n let configURL = installURL.appending(path: configFilename)\n guard fm.fileExists(atPath: configURL.path) else {\n return nil\n }\n\n guard let config = try PluginConfig(configURL: configURL) else {\n return nil\n }\n\n let name = installURL.lastPathComponent\n let binaryURL = installURL.appending(path: \"bin\").appending(path: name)\n guard fm.fileExists(atPath: binaryURL.path) else {\n return nil\n }\n\n return Plugin(binaryURL: binaryURL, config: config)\n }\n}\n\n/// Layout which uses a macOS application bundle structure.\npublic struct AppBundlePluginFactory: PluginFactory {\n private static let appSuffix = \".app\"\n\n public init() {}\n\n public func create(installURL: URL) throws -> Plugin? {\n let fm = FileManager.default\n\n let configURL =\n installURL\n .appending(path: \"Contents\")\n .appending(path: \"Resources\")\n .appending(path: configFilename)\n guard fm.fileExists(atPath: configURL.path) else {\n return nil\n }\n\n guard let config = try PluginConfig(configURL: configURL) else {\n return nil\n }\n\n let appName = installURL.lastPathComponent\n guard appName.hasSuffix(Self.appSuffix) else {\n return nil\n }\n let name = String(appName.dropLast(Self.appSuffix.count))\n let binaryURL =\n installURL\n .appending(path: \"Contents\")\n .appending(path: \"MacOS\")\n .appending(path: name)\n guard fm.fileExists(atPath: binaryURL.path) else {\n return nil\n }\n\n return Plugin(binaryURL: binaryURL, config: config)\n }\n}\n"], ["/container/Sources/CLI/Container/ProcessUtils.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n static func ensureRunning(container: ClientContainer) throws {\n if container.status != .running {\n throw ContainerizationError(.invalidState, message: \"container \\(container.id) is not running\")\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/Filesystem.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Options to pass to a mount call.\npublic typealias MountOptions = [String]\n\nextension MountOptions {\n /// Returns true if the Filesystem should be consumed as read-only.\n public var readonly: Bool {\n self.contains(\"ro\")\n }\n}\n\n/// A host filesystem that will be attached to the sandbox for use.\n///\n/// A filesystem will be mounted automatically when starting the sandbox\n/// or container.\npublic struct Filesystem: Sendable, Codable {\n /// Type of caching to perform at the host level.\n public enum CacheMode: Sendable, Codable {\n case on\n case off\n case auto\n }\n\n /// Sync mode to perform at the host level.\n public enum SyncMode: Sendable, Codable {\n case full\n case fsync\n case nosync\n }\n\n /// The type of filesystem attachment for the sandbox.\n public enum FSType: Sendable, Codable, Equatable {\n package enum VirtiofsType: String, Sendable, Codable, Equatable {\n // This is a virtiofs share for the rootfs of a sandbox.\n case rootfs\n // Data share. This is what all virtiofs shares for anything besides\n // the rootfs for a sandbox will be.\n case data\n }\n\n case block(format: String, cache: CacheMode, sync: SyncMode)\n case virtiofs\n case tmpfs\n }\n\n /// Type of the filesystem.\n public var type: FSType\n /// Source of the filesystem.\n public var source: String\n /// Destination where the filesystem should be mounted.\n public var destination: String\n /// Mount options applied when mounting the filesystem.\n public var options: MountOptions\n\n public init() {\n self.type = .tmpfs\n self.source = \"\"\n self.destination = \"\"\n self.options = []\n }\n\n public init(type: FSType, source: String, destination: String, options: MountOptions) {\n self.type = type\n self.source = source\n self.destination = destination\n self.options = options\n }\n\n /// A block based filesystem.\n public static func block(\n format: String, source: String, destination: String, options: MountOptions, cache: CacheMode = .auto,\n sync: SyncMode = .full\n ) -> Filesystem {\n .init(\n type: .block(format: format, cache: cache, sync: sync),\n source: URL(fileURLWithPath: source).absolutePath(),\n destination: destination,\n options: options\n )\n }\n\n /// A vritiofs backed filesystem providing a directory.\n public static func virtiofs(source: String, destination: String, options: MountOptions) -> Filesystem {\n .init(\n type: .virtiofs,\n source: URL(fileURLWithPath: source).absolutePath(),\n destination: destination,\n options: options\n )\n }\n\n public static func tmpfs(destination: String, options: MountOptions) -> Filesystem {\n .init(\n type: .tmpfs,\n source: \"tmpfs\",\n destination: destination,\n options: options\n )\n }\n\n /// Returns true if the Filesystem is backed by a block device.\n public var isBlock: Bool {\n switch type {\n case .block(_, _, _): true\n default: false\n }\n }\n\n /// Returns true if the Filesystem is backed by a in-memory mount type.\n public var isTmpfs: Bool {\n switch type {\n case .tmpfs: true\n default: false\n }\n }\n\n /// Returns true if the Filesystem is backed by virtioFS.\n public var isVirtiofs: Bool {\n switch type {\n case .virtiofs: true\n default: false\n }\n }\n\n /// Clone the Filesystem to the provided path.\n ///\n /// This uses `clonefile` to provide a copy-on-write copy of the Filesystem.\n public func clone(to: String) throws -> Self {\n let fm = FileManager.default\n let src = self.source\n try fm.copyItem(atPath: src, toPath: to)\n return .init(type: self.type, source: to, destination: self.destination, options: self.options)\n }\n}\n"], ["/container/Sources/TerminalProgress/Int64+Formatted.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Int64 {\n func formattedSize() -> String {\n let formattedSize = ByteCountFormatter.string(fromByteCount: self, countStyle: .binary)\n return formattedSize\n }\n\n func formattedSizeSpeed(from startTime: DispatchTime) -> String {\n let elapsedTimeNanoseconds = DispatchTime.now().uptimeNanoseconds - startTime.uptimeNanoseconds\n let elapsedTimeSeconds = Double(elapsedTimeNanoseconds) / 1_000_000_000\n guard elapsedTimeSeconds > 0 else {\n return \"0 B/s\"\n }\n\n let speed = Double(self) / elapsedTimeSeconds\n let formattedSpeed = ByteCountFormatter.string(fromByteCount: Int64(speed), countStyle: .binary)\n return \"\\(formattedSpeed)/s\"\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePrune.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\n\nextension Application {\n struct ImagePrune: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"prune\",\n abstract: \"Remove unreferenced and dangling images\")\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let (_, size) = try await ClientImage.pruneImages()\n let formatter = ByteCountFormatter()\n let freed = formatter.string(fromByteCount: Int64(size))\n print(\"Cleaned unreferenced images and snapshots\")\n print(\"Reclaimed \\(freed) in disk space\")\n }\n }\n}\n"], ["/container/Sources/ContainerClient/TableOutput.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct TableOutput {\n private let rows: [[String]]\n private let spacing: Int\n\n public init(\n rows: [[String]],\n spacing: Int = 2\n ) {\n self.rows = rows\n self.spacing = spacing\n }\n\n public func format() -> String {\n var output = \"\"\n let maxLengths = self.maxLength()\n\n for rowIndex in 0.. [Int: Int] {\n var output: [Int: Int] = [:]\n for row in self.rows {\n for (i, column) in row.enumerated() {\n let currentMax = output[i] ?? 0\n output[i] = (column.count > currentMax) ? column.count : currentMax\n }\n }\n return output\n }\n}\n"], ["/container/Sources/CLI/Image/ImageTag.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\n\nextension Application {\n struct ImageTag: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"tag\",\n abstract: \"Tag an image\")\n\n @Argument(help: \"SOURCE_IMAGE[:TAG]\")\n var source: String\n\n @Argument(help: \"TARGET_IMAGE[:TAG]\")\n var target: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let existing = try await ClientImage.get(reference: source)\n let targetReference = try ClientImage.normalizeReference(target)\n try await existing.tag(new: targetReference)\n print(\"Image \\(source) tagged as \\(target)\")\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ContainerInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more containers\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Containers to inspect\")\n var containers: [String]\n\n func run() async throws {\n let objects: [any Codable] = try await ClientContainer.list().filter {\n containers.contains($0.id)\n }.map {\n PrintableContainer($0)\n }\n print(try objects.jsonArray())\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/ImageServiceXPCKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\n/// Keys for XPC fields.\npublic enum ImagesServiceXPCKeys: String {\n case fd\n /// FDs pointing to container logs key.\n case logs\n /// Path to a file on disk key.\n case filePath\n\n /// Images\n case imageReference\n case imageNewReference\n case imageDescription\n case imageDescriptions\n case filesystem\n case ociPlatform\n case insecureFlag\n case garbageCollect\n\n /// ContentStore\n case digest\n case digests\n case directory\n case contentPath\n case size\n case ingestSessionId\n}\n\nextension XPCMessage {\n public func set(key: ImagesServiceXPCKeys, value: String) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: UInt64) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: Data) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: Bool) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func string(key: ImagesServiceXPCKeys) -> String? {\n self.string(key: key.rawValue)\n }\n\n public func data(key: ImagesServiceXPCKeys) -> Data? {\n self.data(key: key.rawValue)\n }\n\n public func dataNoCopy(key: ImagesServiceXPCKeys) -> Data? {\n self.dataNoCopy(key: key.rawValue)\n }\n\n public func uint64(key: ImagesServiceXPCKeys) -> UInt64 {\n self.uint64(key: key.rawValue)\n }\n\n public func bool(key: ImagesServiceXPCKeys) -> Bool {\n self.bool(key: key.rawValue)\n }\n}\n\n#endif\n"], ["/container/Sources/SocketForwarder/GlueHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIOCore\n\nfinal class GlueHandler {\n\n private var partner: GlueHandler?\n\n private var context: ChannelHandlerContext?\n\n private var pendingRead: Bool = false\n\n private init() {}\n}\n\nextension GlueHandler {\n static func matchedPair() -> (GlueHandler, GlueHandler) {\n let first = GlueHandler()\n let second = GlueHandler()\n\n first.partner = second\n second.partner = first\n\n return (first, second)\n }\n}\n\nextension GlueHandler {\n private func partnerWrite(_ data: NIOAny) {\n self.context?.write(data, promise: nil)\n }\n\n private func partnerFlush() {\n self.context?.flush()\n }\n\n private func partnerWriteEOF() {\n self.context?.close(mode: .output, promise: nil)\n }\n\n private func partnerCloseFull() {\n self.context?.close(promise: nil)\n }\n\n private func partnerBecameWritable() {\n if self.pendingRead {\n self.pendingRead = false\n self.context?.read()\n }\n }\n\n private var partnerWritable: Bool {\n self.context?.channel.isWritable ?? false\n }\n}\n\nextension GlueHandler: ChannelDuplexHandler {\n typealias InboundIn = NIOAny\n typealias OutboundIn = NIOAny\n typealias OutboundOut = NIOAny\n\n func handlerAdded(context: ChannelHandlerContext) {\n self.context = context\n }\n\n func handlerRemoved(context: ChannelHandlerContext) {\n self.context = nil\n self.partner = nil\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n self.partner?.partnerWrite(data)\n }\n\n func channelReadComplete(context: ChannelHandlerContext) {\n self.partner?.partnerFlush()\n }\n\n func channelInactive(context: ChannelHandlerContext) {\n self.partner?.partnerCloseFull()\n }\n\n func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {\n if let event = event as? ChannelEvent, case .inputClosed = event {\n // We have read EOF.\n self.partner?.partnerWriteEOF()\n }\n }\n\n func errorCaught(context: ChannelHandlerContext, error: Error) {\n self.partner?.partnerCloseFull()\n }\n\n func channelWritabilityChanged(context: ChannelHandlerContext) {\n if context.channel.isWritable {\n self.partner?.partnerBecameWritable()\n }\n }\n\n func read(context: ChannelHandlerContext) {\n if let partner = self.partner, partner.partnerWritable {\n context.read()\n } else {\n self.pendingRead = true\n }\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/NxDomainResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\n\n/// Handler that returns NXDOMAIN for all hostnames.\npublic struct NxDomainResolver: DNSHandler {\n private let ttl: UInt32\n\n public init(ttl: UInt32 = 300) {\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n switch question.type {\n case ResourceRecordType.host:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .nonExistentDomain,\n questions: query.questions,\n answers: []\n )\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n }\n}\n"], ["/container/Sources/ContainerClient/SandboxSnapshot.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\n\n/// A snapshot of a sandbox and its resources.\npublic struct SandboxSnapshot: Codable, Sendable {\n /// The runtime status of the sandbox.\n public let status: RuntimeStatus\n /// Network attachments for the sandbox.\n public let networks: [Attachment]\n /// Containers placed in the sandbox.\n public let containers: [ContainerSnapshot]\n\n public init(\n status: RuntimeStatus,\n networks: [Attachment],\n containers: [ContainerSnapshot]\n ) {\n self.status = status\n self.networks = networks\n self.containers = containers\n }\n}\n"], ["/container/Sources/SocketForwarder/SocketForwarderResult.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIO\n\npublic struct SocketForwarderResult: Sendable {\n private let channel: any Channel\n\n public init(channel: Channel) {\n self.channel = channel\n }\n\n public var proxyAddress: SocketAddress? { self.channel.localAddress }\n\n public func close() {\n self.channel.eventLoop.execute {\n _ = channel.close()\n }\n }\n\n public func wait() async throws {\n try await self.channel.closeFuture.get()\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientHealthCheck.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Foundation\n\npublic enum ClientHealthCheck {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n}\n\nextension ClientHealthCheck {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public static func ping(timeout: Duration? = .seconds(5)) async throws {\n let client = Self.newClient()\n let request = XPCMessage(route: .ping)\n try await client.send(request, responseTimeout: timeout)\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressUpdate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum ProgressUpdateEvent: Sendable {\n case setDescription(String)\n case setSubDescription(String)\n case setItemsName(String)\n case addTasks(Int)\n case setTasks(Int)\n case addTotalTasks(Int)\n case setTotalTasks(Int)\n case addItems(Int)\n case setItems(Int)\n case addTotalItems(Int)\n case setTotalItems(Int)\n case addSize(Int64)\n case setSize(Int64)\n case addTotalSize(Int64)\n case setTotalSize(Int64)\n case custom(String)\n}\n\npublic typealias ProgressUpdateHandler = @Sendable (_ events: [ProgressUpdateEvent]) async -> Void\n\npublic protocol ProgressAdapter {\n associatedtype T\n static func handler(from progressUpdate: ProgressUpdateHandler?) -> (@Sendable ([T]) async -> Void)?\n}\n"], ["/container/Sources/ContainerClient/String+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension String {\n public func fromISO8601DateString(to: String) -> String? {\n if let date = fromISO8601Date() {\n let dateformatTo = DateFormatter()\n dateformatTo.dateFormat = to\n return dateformatTo.string(from: date)\n }\n return nil\n }\n\n public func fromISO8601Date() -> Date? {\n let iso8601DateFormatter = ISO8601DateFormatter()\n iso8601DateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]\n return iso8601DateFormatter.date(from: self)\n }\n\n public func isAbsolutePath() -> Bool {\n self.starts(with: \"/\")\n }\n\n /// Trim all `char` characters from the left side of the string. Stops when encountering a character that\n /// doesn't match `char`.\n mutating public func trimLeft(char: Character) {\n if self.isEmpty {\n return\n }\n var trimTo = 0\n for c in self {\n if char != c {\n break\n }\n trimTo += 1\n }\n if trimTo != 0 {\n let index = self.index(self.startIndex, offsetBy: trimTo)\n self = String(self[index...])\n }\n }\n}\n"], ["/container/Sources/CLI/Registry/Logout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\n\nextension Application {\n struct Logout: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: \"Log out from a registry\")\n\n @Argument(help: \"Registry server name\")\n var registry: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let keychain = KeychainHelper(id: Constants.keychainID)\n let r = Reference.resolveDomain(domain: registry)\n try keychain.delete(domain: r)\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemDNS.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct SystemDNS: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"dns\",\n abstract: \"Manage local DNS domains\",\n subcommands: [\n DNSCreate.self,\n DNSDelete.self,\n DNSList.self,\n DNSDefault.self,\n ]\n )\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct NetworkCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"network\",\n abstract: \"Manage container networks\",\n subcommands: [\n NetworkCreate.self,\n NetworkDelete.self,\n NetworkList.self,\n NetworkInspect.self,\n ],\n aliases: [\"n\"]\n )\n }\n}\n"], ["/container/Sources/ContainerPlugin/LaunchPlist.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\n\npublic struct LaunchPlist: Encodable {\n public enum Domain: String, Codable {\n case Aqua\n case Background\n case System\n }\n\n public let label: String\n public let arguments: [String]\n\n public let environment: [String: String]?\n public let cwd: String?\n public let username: String?\n public let groupname: String?\n public let limitLoadToSessionType: [Domain]?\n public let runAtLoad: Bool?\n public let stdin: String?\n public let stdout: String?\n public let stderr: String?\n public let disabled: Bool?\n public let program: String?\n public let keepAlive: Bool?\n public let machServices: [String: Bool]?\n public let waitForDebugger: Bool?\n\n enum CodingKeys: String, CodingKey {\n case label = \"Label\"\n case arguments = \"ProgramArguments\"\n case environment = \"EnvironmentVariables\"\n case cwd = \"WorkingDirectory\"\n case username = \"UserName\"\n case groupname = \"GroupName\"\n case limitLoadToSessionType = \"LimitLoadToSessionType\"\n case runAtLoad = \"RunAtLoad\"\n case stdin = \"StandardInPath\"\n case stdout = \"StandardOutPath\"\n case stderr = \"StandardErrorPath\"\n case disabled = \"Disabled\"\n case program = \"Program\"\n case keepAlive = \"KeepAlive\"\n case machServices = \"MachServices\"\n case waitForDebugger = \"WaitForDebugger\"\n }\n\n public init(\n label: String,\n arguments: [String],\n environment: [String: String]? = nil,\n cwd: String? = nil,\n username: String? = nil,\n groupname: String? = nil,\n limitLoadToSessionType: [Domain]? = nil,\n runAtLoad: Bool? = nil,\n stdin: String? = nil,\n stdout: String? = nil,\n stderr: String? = nil,\n disabled: Bool? = nil,\n program: String? = nil,\n keepAlive: Bool? = nil,\n machServices: [String]? = nil,\n waitForDebugger: Bool? = nil\n ) {\n self.label = label\n self.arguments = arguments\n self.environment = environment\n self.cwd = cwd\n self.username = username\n self.groupname = groupname\n self.limitLoadToSessionType = limitLoadToSessionType\n self.runAtLoad = runAtLoad\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n self.disabled = disabled\n self.program = program\n self.keepAlive = keepAlive\n self.waitForDebugger = waitForDebugger\n if let services = machServices {\n var machServices: [String: Bool] = [:]\n for service in services {\n machServices[service] = true\n }\n self.machServices = machServices\n } else {\n self.machServices = nil\n }\n }\n}\n\nextension LaunchPlist {\n public func encode() throws -> Data {\n let enc = PropertyListEncoder()\n enc.outputFormat = .xml\n return try enc.encode(self)\n }\n}\n#endif\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum NetworkRoutes: String {\n /// Return the current state of the network.\n case state = \"com.apple.container.network/state\"\n /// Allocates parameters for attaching a sandbox to the network.\n case allocate = \"com.apple.container.network/allocate\"\n /// Deallocates parameters for attaching a sandbox to the network.\n case deallocate = \"com.apple.container.network/deallocate\"\n /// Disables the allocator if no sandboxes are attached.\n case disableAllocator = \"com.apple.container.network/disableAllocator\"\n /// Retrieves the allocation for a hostname.\n case lookup = \"com.apple.container.network/lookup\"\n}\n"], ["/container/Sources/TerminalProgress/Int+Formatted.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Int {\n func formattedTime() -> String {\n let secondsInMinute = 60\n let secondsInHour = secondsInMinute * 60\n let secondsInDay = secondsInHour * 24\n\n let days = self / secondsInDay\n let hours = (self % secondsInDay) / secondsInHour\n let minutes = (self % secondsInHour) / secondsInMinute\n let seconds = self % secondsInMinute\n\n var components = [String]()\n if days > 0 {\n components.append(\"\\(days)d\")\n }\n if hours > 0 || days > 0 {\n components.append(\"\\(hours)h\")\n }\n if minutes > 0 || hours > 0 || days > 0 {\n components.append(\"\\(minutes)m\")\n }\n components.append(\"\\(seconds)s\")\n return components.joined(separator: \" \")\n }\n\n func formattedNumber() -> String {\n let formatter = NumberFormatter()\n formatter.numberStyle = .decimal\n guard let formattedNumber = formatter.string(from: NSNumber(value: self)) else {\n return \"\"\n }\n return formattedNumber\n }\n}\n"], ["/container/Sources/CLI/Registry/RegistryCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct RegistryCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"registry\",\n abstract: \"Manage registry configurations\",\n subcommands: [\n Login.self,\n Logout.self,\n RegistryDefault.self,\n ],\n aliases: [\"r\"]\n )\n }\n}\n"], ["/container/Sources/CLI/System/SystemCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct SystemCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"system\",\n abstract: \"Manage system components\",\n subcommands: [\n SystemDNS.self,\n SystemLogs.self,\n SystemStart.self,\n SystemStop.self,\n SystemStatus.self,\n SystemKernel.self,\n ],\n aliases: [\"s\"]\n )\n }\n}\n"], ["/container/Sources/CLI/Container/ContainersCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct ContainersCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"containers\",\n abstract: \"Manage containers\",\n subcommands: [\n ContainerCreate.self,\n ContainerDelete.self,\n ContainerExec.self,\n ContainerInspect.self,\n ContainerKill.self,\n ContainerList.self,\n ContainerLogs.self,\n ContainerStart.self,\n ContainerStop.self,\n ],\n aliases: [\"container\", \"c\"]\n )\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ImageDescription.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\n\n/// A type that represents an OCI image that can be used with sandboxes or containers.\npublic struct ImageDescription: Sendable, Codable {\n /// The public reference/name of the image.\n public let reference: String\n /// The descriptor of the image.\n public let descriptor: Descriptor\n\n public var digest: String { descriptor.digest }\n public var mediaType: String { descriptor.mediaType }\n\n public init(reference: String, descriptor: Descriptor) {\n self.reference = reference\n self.descriptor = descriptor\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/CompositeResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Delegates a query sequentially to handlers until one provides a response.\npublic struct CompositeResolver: DNSHandler {\n private let handlers: [DNSHandler]\n\n public init(handlers: [DNSHandler]) {\n self.handlers = handlers\n }\n\n public func answer(query: Message) async throws -> Message? {\n for handler in self.handlers {\n if let response = try await handler.answer(query: query) {\n return response\n }\n }\n\n return nil\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\n\nextension Application {\n struct DNSList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List local DNS domains\",\n aliases: [\"ls\"]\n )\n\n func run() async throws {\n let resolver: HostDNSResolver = HostDNSResolver()\n let domains = resolver.listDomains()\n print(domains.joined(separator: \"\\n\"))\n }\n\n }\n}\n"], ["/container/Sources/CLI/System/SystemKernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct SystemKernel: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kernel\",\n abstract: \"Manage the default kernel configuration\",\n subcommands: [\n KernelSet.self\n ]\n )\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/ImageServiceXPCRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\npublic enum ImagesServiceXPCRoute: String {\n case imageList\n case imagePull\n case imagePush\n case imageTag\n case imageBuild\n case imageDelete\n case imageSave\n case imageLoad\n case imagePrune\n\n case contentGet\n case contentDelete\n case contentClean\n case contentIngestStart\n case contentIngestComplete\n case contentIngestCancel\n\n case imageUnpack\n case snapshotDelete\n case snapshotGet\n}\n\nextension XPCMessage {\n public init(route: ImagesServiceXPCRoute) {\n self.init(route: route.rawValue)\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerBuild/TerminalCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct TerminalCommand: Codable {\n let commandType: String\n let code: String\n let rows: UInt16\n let cols: UInt16\n\n enum CodingKeys: String, CodingKey {\n case commandType = \"command_type\"\n case code\n case rows\n case cols\n }\n\n init(rows: UInt16, cols: UInt16) {\n self.commandType = \"terminal\"\n self.code = \"winch\"\n self.rows = rows\n self.cols = cols\n }\n\n init() {\n self.commandType = \"terminal\"\n self.code = \"ack\"\n self.rows = 0\n self.cols = 0\n }\n\n func json() throws -> String? {\n let encoder = JSONEncoder()\n let data = try encoder.encode(self)\n return data.base64EncodedString().trimmingCharacters(in: CharacterSet(charactersIn: \"=\"))\n }\n}\n"], ["/container/Sources/ContainerClient/Core/RuntimeStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Runtime status for a sandbox or container.\npublic enum RuntimeStatus: String, CaseIterable, Sendable, Codable {\n /// The object is in an unknown status.\n case unknown\n /// The object is currently stopped.\n case stopped\n /// The object is currently running.\n case running\n /// The object is currently stopping.\n case stopping\n}\n"], ["/container/Sources/CLI/Image/ImagesCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct ImagesCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"images\",\n abstract: \"Manage images\",\n subcommands: [\n ImageInspect.self,\n ImageList.self,\n ImageLoad.self,\n ImagePrune.self,\n ImagePull.self,\n ImagePush.self,\n ImageRemove.self,\n ImageSave.self,\n ImageTag.self,\n ],\n aliases: [\"image\", \"i\"]\n )\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum NetworkKeys: String {\n case additionalData\n case allocatorDisabled\n case attachment\n case hostname\n case network\n case state\n}\n"], ["/container/Sources/CLI/Builder/Builder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct BuilderCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"builder\",\n abstract: \"Manage an image builder instance\",\n subcommands: [\n BuilderStart.self,\n BuilderStatus.self,\n BuilderStop.self,\n BuilderDelete.self,\n ])\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressTheme.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A theme for progress bar.\npublic protocol ProgressTheme: Sendable {\n /// The icons used to represent a spinner.\n var spinner: [String] { get }\n /// The icon used to represent a progress bar.\n var bar: String { get }\n /// The icon used to indicate that a progress bar finished.\n var done: String { get }\n}\n\npublic struct DefaultProgressTheme: ProgressTheme {\n public let spinner = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"]\n public let bar = \"█\"\n public let done = \"✔\"\n}\n\nextension ProgressTheme {\n func getSpinnerIcon(_ iteration: Int) -> String {\n spinner[iteration % spinner.count]\n }\n}\n"], ["/container/Sources/ContainerClient/Arch.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum Arch: String {\n case arm64, amd64\n\n public static func hostArchitecture() -> Arch {\n #if arch(arm64)\n return .arm64\n #elseif arch(x86_64)\n return .amd64\n #endif\n }\n}\n"], ["/container/Sources/TerminalProgress/StandardError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct StandardError {\n func write(_ string: String) {\n if let data = string.data(using: .utf8) {\n FileHandle.standardError.write(data)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerStopOptions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct ContainerStopOptions: Sendable, Codable {\n public let timeoutInSeconds: Int32\n public let signal: Int32\n\n public static let `default` = ContainerStopOptions(\n timeoutInSeconds: 5,\n signal: SIGTERM\n )\n\n public init(timeoutInSeconds: Int32, signal: Int32) {\n self.timeoutInSeconds = timeoutInSeconds\n self.signal = signal\n }\n}\n"], ["/container/Sources/ContainerClient/Core/PublishSocket.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\n/// Represents a socket that should be published from container to host.\npublic struct PublishSocket: Sendable, Codable {\n /// The path to the socket in the container.\n public var containerPath: URL\n\n /// The path where the socket should appear on the host.\n public var hostPath: URL\n\n /// File permissions for the socket on the host.\n public var permissions: FilePermissions?\n\n public init(\n containerPath: URL,\n hostPath: URL,\n permissions: FilePermissions? = nil\n ) {\n self.containerPath = containerPath\n self.hostPath = hostPath\n self.permissions = permissions\n }\n}\n"], ["/container/Sources/ContainerClient/SandboxRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum SandboxRoutes: String {\n /// Bootstrap the sandbox instance and create the init process.\n case bootstrap = \"com.apple.container.sandbox/bootstrap\"\n /// Create a process in the sandbox.\n case createProcess = \"com.apple.container.sandbox/createProcess\"\n /// Start a process in the sandbox.\n case start = \"com.apple.container.sandbox/start\"\n /// Stop the sandbox.\n case stop = \"com.apple.container.sandbox/stop\"\n /// Return the current state of the sandbox.\n case state = \"com.apple.container.sandbox/state\"\n /// Kill a process in the sandbox.\n case kill = \"com.apple.container.sandbox/kill\"\n /// Resize the pty of a process in the sandbox.\n case resize = \"com.apple.container.sandbox/resize\"\n /// Wait on a process in the sandbox.\n case wait = \"com.apple.container.sandbox/wait\"\n /// Execute a new process in the sandbox.\n case exec = \"com.apple.container.sandbox/exec\"\n /// Dial a vsock port in the sandbox.\n case dial = \"com.apple.container.sandbox/dial\"\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerCreateOptions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct ContainerCreateOptions: Codable, Sendable {\n public let autoRemove: Bool\n\n public init(autoRemove: Bool) {\n self.autoRemove = autoRemove\n }\n\n public static let `default` = ContainerCreateOptions(autoRemove: false)\n\n}\n"], ["/container/Sources/CLI/Codable+JSON.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\nextension [any Codable] {\n func jsonArray() throws -> String {\n \"[\\(try self.map { String(data: try JSONEncoder().encode($0), encoding: .utf8)! }.joined(separator: \",\"))]\"\n }\n}\n"], ["/container/Sources/DNSServer/DNSHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Protocol for implementing custom DNS handlers.\npublic protocol DNSHandler {\n /// Attempt to answer a DNS query\n /// - Parameter query: the query message\n /// - Throws: a server failure occurred during the query\n /// - Returns: The response message for the query, or nil if the request\n /// is not within the scope of the handler.\n func answer(query: Message) async throws -> Message?\n}\n"], ["/container/Sources/ContainerClient/ContainerEvents.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\npublic enum ContainerEvent: Sendable, Codable {\n case containerStart(id: String)\n case containerExit(id: String, exitCode: Int64)\n}\n"], ["/container/Sources/Services/ContainerNetworkService/UserDefaults+Container.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension UserDefaults {\n public static let appSuiteName = \"com.apple.container.defaults\"\n}\n"], ["/container/Sources/ContainerClient/Array+Dedupe.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension Array where Element: Hashable {\n func dedupe() -> [Element] {\n var elems = Set()\n return filter { elems.insert($0).inserted }\n }\n}\n"], ["/container/Sources/SocketForwarder/SocketForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIO\n\npublic protocol SocketForwarder: Sendable {\n func run() throws -> EventLoopFuture\n}\n"], ["/container/Sources/ContainerClient/Core/Constants.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum Constants {\n public static let keychainID = \"com.apple.container\"\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:21:52", "created_task_model": "DeepSeek-R1", "function_skeleton": "public init ( configuration: NetworkConfiguration , log: Logger ) throws { }", "code_description": "This code segment functions to: Validate network configuration parameters during object initialization and establish the foundational state for a network resource with specific operational constraints."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\n public init(configuration: NetworkConfiguration, log: Logger) throws {\n self._state = .created(configuration)\n self.log = log\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 03-22-09"}, "editdistance_info": {"edit_distance": 25.9259, "calculate_time": "2025-08-21 03:22:09", "true_code_clean": "public init(\n configuration: NetworkConfiguration,\n log: Logger\n ) throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.unsupported, message: \"invalid network mode \\(configuration.mode)\")\n }\n log.info(\"creating vmnet network\")\n self.log = log\n _state = .created(configuration)\n log.info(\"created vmnet network\")\n }", "predict_code_clean": "public init(configuration: NetworkConfiguration, log: Logger) throws {\n self._state = .created(configuration)\n self.log = log\n }"}} {"repo_name": "container", "file_name": "/container/Sources/CLI/Network/NetworkDelete.swift", "inference_info": {"prefix_code": "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct NetworkDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete one or more networks\",\n aliases: [\"rm\"])\n\n @Flag(name: .shortAndLong, help: \"Remove all networks\")\n var all = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Network names\")\n var networkNames: [String] = []\n\n ", "suffix_code": "\n\n mutating func run() async throws {\n let uniqueNetworkNames = Set(networkNames)\n let networks: [NetworkState]\n\n if all {\n networks = try await ClientNetwork.list()\n } else {\n networks = try await ClientNetwork.list()\n .filter { c in\n uniqueNetworkNames.contains(c.id)\n }\n\n // If one of the networks requested isn't present lets throw. We don't need to do\n // this for --all as --all should be perfectly usable with no networks to remove,\n // otherwise it'd be quite clunky.\n if networks.count != uniqueNetworkNames.count {\n let missing = uniqueNetworkNames.filter { id in\n !networks.contains { n in\n n.id == id\n }\n }\n throw ContainerizationError(\n .notFound,\n message: \"failed to delete one or more networks: \\(missing)\"\n )\n }\n }\n\n if uniqueNetworkNames.contains(ClientNetwork.defaultNetworkName) {\n throw ContainerizationError(\n .invalidArgument,\n message: \"cannot delete the default network\"\n )\n }\n\n var failed = [String]()\n try await withThrowingTaskGroup(of: NetworkState?.self) { group in\n for network in networks {\n group.addTask {\n do {\n // delete atomically disables the IP allocator, then deletes\n // the allocator disable fails if any IPs are still in use\n try await ClientNetwork.delete(id: network.id)\n print(network.id)\n return nil\n } catch {\n log.error(\"failed to delete network \\(network.id): \\(error)\")\n return network\n }\n }\n }\n\n for try await network in group {\n guard let network else {\n continue\n }\n failed.append(network.id)\n }\n }\n\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"delete failed for one or more networks: \\(failed)\")\n }\n }\n }\n}\n", "middle_code": "func validate() throws {\n if networkNames.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no networks specified and --all not supplied\")\n }\n if networkNames.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument,\n message: \"explicitly supplied network name(s) conflict with the --all flag\"\n )\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/container/Sources/CLI/Container/ContainerDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct ContainerDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete one or more containers\",\n aliases: [\"rm\"])\n\n @Flag(name: .shortAndLong, help: \"Force the removal of one or more running containers\")\n var force = false\n\n @Flag(name: .shortAndLong, help: \"Remove all containers\")\n var all = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Container IDs/names\")\n var containerIDs: [String] = []\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument,\n message: \"explicitly supplied container ID(s) conflict with the --all flag\"\n )\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n var containers = [ClientContainer]()\n\n if all {\n containers = try await ClientContainer.list()\n } else {\n let ctrs = try await ClientContainer.list()\n containers = ctrs.filter { c in\n set.contains(c.id)\n }\n // If one of the containers requested isn't present, let's throw. We don't need to do\n // this for --all as --all should be perfectly usable with no containers to remove; otherwise,\n // it'd be quite clunky.\n if containers.count != set.count {\n let missing = set.filter { id in\n !containers.contains { c in\n c.id == id\n }\n }\n throw ContainerizationError(\n .notFound,\n message: \"failed to delete one or more containers: \\(missing)\"\n )\n }\n }\n\n var failed = [String]()\n let force = self.force\n let all = self.all\n try await withThrowingTaskGroup(of: ClientContainer?.self) { group in\n for container in containers {\n group.addTask {\n do {\n // First we need to find if the container supports auto-remove\n // and if so we need to skip deletion.\n if container.status == .running {\n if !force {\n // We don't want to error if the user just wants all containers deleted.\n // It's implied we'll skip containers we can't actually delete.\n if all {\n return nil\n }\n throw ContainerizationError(.invalidState, message: \"container is running\")\n }\n let stopOpts = ContainerStopOptions(\n timeoutInSeconds: 5,\n signal: SIGKILL\n )\n try await container.stop(opts: stopOpts)\n }\n try await container.delete()\n print(container.id)\n return nil\n } catch {\n log.error(\"failed to delete container \\(container.id): \\(error)\")\n return container\n }\n }\n }\n\n for try await ctr in group {\n guard let ctr else {\n continue\n }\n failed.append(ctr.id)\n }\n }\n\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"delete failed for one or more containers: \\(failed)\")\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct ContainerStop: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"stop\",\n abstract: \"Stop one or more running containers\")\n\n @Flag(name: .shortAndLong, help: \"Stop all running containers\")\n var all = false\n\n @Option(name: .shortAndLong, help: \"Signal to send the container(s)\")\n var signal: String = \"SIGTERM\"\n\n @Option(name: .shortAndLong, help: \"Seconds to wait before killing the container(s)\")\n var time: Int32 = 5\n\n @Argument\n var containerIDs: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument, message: \"explicitly supplied container IDs conflicts with the --all flag\")\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n var containers = [ClientContainer]()\n if self.all {\n containers = try await ClientContainer.list()\n } else {\n containers = try await ClientContainer.list().filter { c in\n set.contains(c.id)\n }\n }\n\n let opts = ContainerStopOptions(\n timeoutInSeconds: self.time,\n signal: try Signals.parseSignal(self.signal)\n )\n let failed = try await Self.stopContainers(containers: containers, stopOptions: opts)\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"stop failed for one or more containers \\(failed.joined(separator: \",\"))\")\n }\n }\n\n static func stopContainers(containers: [ClientContainer], stopOptions: ContainerStopOptions) async throws -> [String] {\n var failed: [String] = []\n try await withThrowingTaskGroup(of: ClientContainer?.self) { group in\n for container in containers {\n group.addTask {\n do {\n try await container.stop(opts: stopOptions)\n print(container.id)\n return nil\n } catch {\n log.error(\"failed to stop container \\(container.id): \\(error)\")\n return container\n }\n }\n }\n\n for try await ctr in group {\n guard let ctr else {\n continue\n }\n failed.append(ctr.id)\n }\n }\n\n return failed\n }\n }\n}\n"], ["/container/Sources/APIServer/Networks/NetworksService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerPersistence\nimport ContainerPlugin\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor NetworksService {\n private let resourceRoot: URL\n // FIXME: remove qualifier once we can update Containerization dependency.\n private let store: ContainerPersistence.FilesystemEntityStore\n private let pluginLoader: PluginLoader\n private let log: Logger\n private let networkPlugin: Plugin\n\n private var networkStates = [String: NetworkState]()\n private var busyNetworks = Set()\n\n public init(pluginLoader: PluginLoader, resourceRoot: URL, log: Logger) async throws {\n try FileManager.default.createDirectory(at: resourceRoot, withIntermediateDirectories: true)\n self.resourceRoot = resourceRoot\n self.store = try FilesystemEntityStore(path: resourceRoot, type: \"network\", log: log)\n self.pluginLoader = pluginLoader\n self.log = log\n\n let networkPlugin =\n pluginLoader\n .findPlugins()\n .filter { $0.hasType(.network) }\n .first\n guard let networkPlugin else {\n throw ContainerizationError(.internalError, message: \"cannot find network plugin\")\n }\n self.networkPlugin = networkPlugin\n\n let configurations = try await store.list()\n for configuration in configurations {\n do {\n try await registerService(configuration: configuration)\n } catch {\n log.error(\n \"failed to start network\",\n metadata: [\n \"id\": \"\\(configuration.id)\"\n ])\n }\n\n let client = NetworkClient(id: configuration.id)\n let networkState = try await client.state()\n networkStates[configuration.id] = networkState\n guard case .running = networkState else {\n log.error(\n \"network failed to start\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"state\": \"\\(networkState.state)\",\n ])\n return\n }\n }\n }\n\n /// List all networks registered with the service.\n public func list() async throws -> [NetworkState] {\n log.info(\"network service: list\")\n return networkStates.reduce(into: [NetworkState]()) {\n $0.append($1.value)\n }\n }\n\n /// Create a new network from the provided configuration.\n public func create(configuration: NetworkConfiguration) async throws -> NetworkState {\n guard !busyNetworks.contains(configuration.id) else {\n throw ContainerizationError(.exists, message: \"network \\(configuration.id) has a pending operation\")\n }\n\n busyNetworks.insert(configuration.id)\n defer { busyNetworks.remove(configuration.id) }\n\n log.info(\n \"network service: create\",\n metadata: [\n \"id\": \"\\(configuration.id)\"\n ])\n\n // Ensure the network doesn't already exist.\n guard networkStates[configuration.id] == nil else {\n throw ContainerizationError(.exists, message: \"network \\(configuration.id) already exists\")\n }\n\n // Create and start the network.\n try await registerService(configuration: configuration)\n let client = NetworkClient(id: configuration.id)\n let networkState = try await client.state()\n networkStates[configuration.id] = networkState\n\n // Persist the configuration data.\n do {\n try await store.create(configuration)\n return networkState\n } catch {\n networkStates.removeValue(forKey: configuration.id)\n do {\n try pluginLoader.deregisterWithLaunchd(plugin: networkPlugin, instanceId: configuration.id)\n } catch {\n log.error(\n \"failed to deregister network service after failed creation\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"error\": \"\\(error.localizedDescription)\",\n ])\n }\n\n throw error\n }\n }\n\n /// Delete a network.\n public func delete(id: String) async throws {\n guard !busyNetworks.contains(id) else {\n throw ContainerizationError(.exists, message: \"network \\(id) has a pending operation\")\n }\n\n busyNetworks.insert(id)\n defer { busyNetworks.remove(id) }\n\n log.info(\n \"network service: delete\",\n metadata: [\n \"id\": \"\\(id)\"\n ])\n if id == ClientNetwork.defaultNetworkName {\n throw ContainerizationError(.invalidArgument, message: \"cannot delete system subnet \\(ClientNetwork.defaultNetworkName)\")\n }\n\n guard let networkState = networkStates[id] else {\n throw ContainerizationError(.notFound, message: \"no network for id \\(id)\")\n }\n\n guard case .running = networkState else {\n throw ContainerizationError(.invalidState, message: \"cannot delete subnet \\(id) in state \\(networkState.state)\")\n }\n\n let client = NetworkClient(id: id)\n guard try await client.disableAllocator() else {\n throw ContainerizationError(.invalidState, message: \"cannot delete subnet \\(id) with containers attached\")\n }\n\n defer { networkStates.removeValue(forKey: id) }\n do {\n try pluginLoader.deregisterWithLaunchd(plugin: networkPlugin, instanceId: id)\n } catch {\n log.error(\n \"failed to deregister network service after failed creation\",\n metadata: [\n \"id\": \"\\(id)\",\n \"error\": \"\\(error.localizedDescription)\",\n ])\n }\n\n do {\n try await store.delete(id)\n } catch {\n throw ContainerizationError(.notFound, message: error.localizedDescription)\n }\n }\n\n /// Perform a hostname lookup on all networks.\n public func lookup(hostname: String) async throws -> Attachment? {\n for id in networkStates.keys {\n let client = NetworkClient(id: id)\n guard let allocation = try await client.lookup(hostname: hostname) else {\n continue\n }\n return allocation\n }\n return nil\n }\n\n private func registerService(configuration: NetworkConfiguration) async throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported network mode \\(configuration.mode.rawValue)\")\n }\n\n guard let serviceIdentifier = networkPlugin.getMachService(instanceId: configuration.id, type: .network) else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported network mode \\(configuration.mode.rawValue)\")\n }\n var args = [\n \"start\",\n \"--id\",\n configuration.id,\n \"--service-identifier\",\n serviceIdentifier,\n ]\n\n if let subnet = (try configuration.subnet.map { try CIDRAddress($0) }) {\n var existingCidrs: [CIDRAddress] = []\n for networkState in networkStates.values {\n if case .running(_, let status) = networkState {\n existingCidrs.append(try CIDRAddress(status.address))\n }\n }\n let overlap = existingCidrs.first { $0.overlaps(cidr: subnet) }\n if let overlap {\n throw ContainerizationError(.exists, message: \"subnet \\(subnet) overlaps an existing network with subnet \\(overlap)\")\n }\n\n args += [\"--subnet\", subnet.description]\n }\n\n try await pluginLoader.registerWithLaunchd(\n plugin: networkPlugin,\n rootURL: store.entityUrl(configuration.id),\n args: args,\n instanceId: configuration.id\n )\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerKill.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Darwin\n\nextension Application {\n struct ContainerKill: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kill\",\n abstract: \"Kill one or more running containers\")\n\n @Option(name: .shortAndLong, help: \"Signal to send the container(s)\")\n var signal: String = \"KILL\"\n\n @Flag(name: .shortAndLong, help: \"Kill all running containers\")\n var all = false\n\n @Argument(help: \"Container IDs\")\n var containerIDs: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(.invalidArgument, message: \"explicitly supplied container IDs conflicts with the --all flag\")\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n\n var containers = try await ClientContainer.list().filter { c in\n c.status == .running\n }\n if !self.all {\n containers = containers.filter { c in\n set.contains(c.id)\n }\n }\n\n let signalNumber = try Signals.parseSignal(signal)\n\n var failed: [String] = []\n for container in containers {\n do {\n try await container.kill(signalNumber)\n print(container.id)\n } catch {\n log.error(\"failed to kill container \\(container.id): \\(error)\")\n failed.append(container.id)\n }\n }\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"kill failed for one or more containers\")\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImageRemove.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct RemoveImageOptions: ParsableArguments {\n @Flag(name: .shortAndLong, help: \"Remove all images\")\n var all: Bool = false\n\n @Argument\n var images: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n }\n\n struct RemoveImageImplementation {\n static func validate(options: RemoveImageOptions) throws {\n if options.images.count == 0 && !options.all {\n throw ContainerizationError(.invalidArgument, message: \"no image specified and --all not supplied\")\n }\n if options.images.count > 0 && options.all {\n throw ContainerizationError(.invalidArgument, message: \"explicitly supplied images conflict with the --all flag\")\n }\n }\n\n static func removeImage(options: RemoveImageOptions) async throws {\n let (found, notFound) = try await {\n if options.all {\n let found = try await ClientImage.list()\n let notFound: [String] = []\n return (found, notFound)\n }\n return try await ClientImage.get(names: options.images)\n }()\n var failures: [String] = notFound\n var didDeleteAnyImage = false\n for image in found {\n guard !Utility.isInfraImage(name: image.reference) else {\n continue\n }\n do {\n try await ClientImage.delete(reference: image.reference, garbageCollect: false)\n print(image.reference)\n didDeleteAnyImage = true\n } catch {\n log.error(\"failed to remove \\(image.reference): \\(error)\")\n failures.append(image.reference)\n }\n }\n let (_, size) = try await ClientImage.pruneImages()\n let formatter = ByteCountFormatter()\n let freed = formatter.string(fromByteCount: Int64(size))\n\n if didDeleteAnyImage {\n print(\"Reclaimed \\(freed) in disk space\")\n }\n if failures.count > 0 {\n throw ContainerizationError(.internalError, message: \"failed to delete one or more images: \\(failures)\")\n }\n }\n }\n\n struct ImageRemove: AsyncParsableCommand {\n @OptionGroup\n var options: RemoveImageOptions\n\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Remove one or more images\",\n aliases: [\"rm\"])\n\n func validate() throws {\n try RemoveImageImplementation.validate(options: options)\n }\n\n mutating func run() async throws {\n try await RemoveImageImplementation.removeImage(options: options)\n }\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerBuild\nimport ContainerClient\nimport ContainerNetworkService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct BuilderStart: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"start\"\n config._superCommandName = \"builder\"\n config.abstract = \"Start builder\"\n config.usage = \"\\nbuilder start [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64 = 2\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n public var memory: String = \"2048MB\"\n\n func run() async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n totalTasks: 4\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n try await Self.start(cpus: self.cpus, memory: self.memory, progressUpdate: progress.handler)\n progress.finish()\n }\n\n static func start(cpus: Int64?, memory: String?, progressUpdate: @escaping ProgressUpdateHandler) async throws {\n await progressUpdate([\n .setDescription(\"Fetching BuildKit image\"),\n .setItemsName(\"blobs\"),\n ])\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n\n let builderImage: String = ClientDefaults.get(key: .defaultBuilderImage)\n let exportsMount: String = Application.appRoot.appendingPathComponent(\".build\").absolutePath()\n\n if !FileManager.default.fileExists(atPath: exportsMount) {\n try FileManager.default.createDirectory(\n atPath: exportsMount,\n withIntermediateDirectories: true,\n attributes: nil\n )\n }\n\n let builderPlatform = ContainerizationOCI.Platform(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n\n let existingContainer = try? await ClientContainer.get(id: \"buildkit\")\n if let existingContainer {\n let existingImage = existingContainer.configuration.image.reference\n let existingResources = existingContainer.configuration.resources\n\n // Check if we need to recreate the builder due to different image\n let imageChanged = existingImage != builderImage\n let cpuChanged = {\n if let cpus {\n if existingResources.cpus != cpus {\n return true\n }\n }\n return false\n }()\n let memChanged = try {\n if let memory {\n let memoryInBytes = try Parser.resources(cpus: nil, memory: memory).memoryInBytes\n if existingResources.memoryInBytes != memoryInBytes {\n return true\n }\n }\n return false\n }()\n\n switch existingContainer.status {\n case .running:\n guard imageChanged || cpuChanged || memChanged else {\n // If image, mem and cpu are the same, continue using the existing builder\n return\n }\n // If they changed, stop and delete the existing builder\n try await existingContainer.stop()\n try await existingContainer.delete()\n case .stopped:\n // If the builder is stopped and matches our requirements, start it\n // Otherwise, delete it and create a new one\n guard imageChanged || cpuChanged || memChanged else {\n try await existingContainer.startBuildKit(progressUpdate, nil)\n return\n }\n try await existingContainer.delete()\n case .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"builder is stopping, please wait until it is fully stopped before proceeding\"\n )\n case .unknown:\n break\n }\n }\n\n let shimArguments: [String] = [\n \"--debug\",\n \"--vsock\",\n ]\n\n let id = \"buildkit\"\n try ContainerClient.Utility.validEntityName(id)\n\n let processConfig = ProcessConfiguration(\n executable: \"/usr/local/bin/container-builder-shim\",\n arguments: shimArguments,\n environment: [],\n workingDirectory: \"/\",\n terminal: false,\n user: .id(uid: 0, gid: 0)\n )\n\n let resources = try Parser.resources(\n cpus: cpus,\n memory: memory\n )\n\n let image = try await ClientImage.fetch(\n reference: builderImage,\n platform: builderPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progressUpdate)\n )\n // Unpack fetched image before use\n await progressUpdate([\n .setDescription(\"Unpacking BuildKit image\"),\n .setItemsName(\"entries\"),\n ])\n\n let unpackTask = await taskManager.startTask()\n _ = try await image.getCreateSnapshot(\n platform: builderPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progressUpdate)\n )\n let imageConfig = ImageDescription(\n reference: builderImage,\n descriptor: image.descriptor\n )\n\n var config = ContainerConfiguration(id: id, image: imageConfig, process: processConfig)\n config.resources = resources\n config.mounts = [\n .init(\n type: .tmpfs,\n source: \"\",\n destination: \"/run\",\n options: []\n ),\n .init(\n type: .virtiofs,\n source: exportsMount,\n destination: \"/var/lib/container-builder-shim/exports\",\n options: []\n ),\n ]\n // Enable Rosetta only if the user didn't ask to disable it\n config.rosetta = ClientDefaults.getBool(key: .buildRosetta) ?? true\n\n let network = try await ClientNetwork.get(id: ClientNetwork.defaultNetworkName)\n guard case .running(_, let networkStatus) = network else {\n throw ContainerizationError(.invalidState, message: \"default network is not running\")\n }\n config.networks = [network.id]\n let subnet = try CIDRAddress(networkStatus.address)\n let nameserver = IPv4Address(fromValue: subnet.lower.value + 1).description\n let nameservers = [nameserver]\n config.dns = ContainerConfiguration.DNSConfiguration(nameservers: nameservers)\n\n let kernel = try await {\n await progressUpdate([\n .setDescription(\"Fetching kernel\"),\n .setItemsName(\"binary\"),\n ])\n\n let kernel = try await ClientKernel.getDefaultKernel(for: .current)\n return kernel\n }()\n\n await progressUpdate([\n .setDescription(\"Starting BuildKit container\")\n ])\n\n let container = try await ClientContainer.create(\n configuration: config,\n options: .default,\n kernel: kernel\n )\n\n try await container.startBuildKit(progressUpdate, taskManager)\n }\n }\n}\n\n// MARK: - ClientContainer Extension for BuildKit\n\nextension ClientContainer {\n /// Starts the BuildKit process within the container\n /// This method handles bootstrapping the container and starting the BuildKit process\n fileprivate func startBuildKit(_ progress: @escaping ProgressUpdateHandler, _ taskManager: ProgressTaskCoordinator? = nil) async throws {\n do {\n let io = try ProcessIO.create(\n tty: false,\n interactive: false,\n detach: true\n )\n defer { try? io.close() }\n let process = try await bootstrap()\n _ = try await process.start(io.stdio)\n await taskManager?.finish()\n try io.closeAfterStart()\n log.debug(\"starting BuildKit and BuildKit-shim\")\n } catch {\n try? await stop()\n try? await delete()\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to start BuildKit: \\(error)\")\n }\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/SandboxService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\nimport SocketForwarder\n\nimport struct ContainerizationOCI.Mount\nimport struct ContainerizationOCI.Process\n\n/// An XPC service that manages the lifecycle of a single VM-backed container.\npublic actor SandboxService {\n private let root: URL\n private let interfaceStrategy: InterfaceStrategy\n private var container: ContainerInfo?\n private let monitor: ExitMonitor\n private let eventLoopGroup: any EventLoopGroup\n private var waiters: [String: [CheckedContinuation]] = [:]\n private let lock: AsyncLock = AsyncLock()\n private let log: Logging.Logger\n private var state: State = .created\n private var processes: [String: ProcessInfo] = [:]\n private var socketForwarders: [SocketForwarderResult] = []\n\n /// Create an instance with a bundle that describes the container.\n ///\n /// - Parameters:\n /// - root: The file URL for the bundle root.\n /// - interfaceStrategy: The strategy for producing network interface\n /// objects for each network to which the container attaches.\n /// - log: The destination for log messages.\n public init(root: URL, interfaceStrategy: InterfaceStrategy, eventLoopGroup: any EventLoopGroup, log: Logger) {\n self.root = root\n self.interfaceStrategy = interfaceStrategy\n self.log = log\n self.monitor = ExitMonitor(log: log)\n self.eventLoopGroup = eventLoopGroup\n }\n\n /// Start the VM and the guest agent process for a container.\n ///\n /// - Parameters:\n /// - message: An XPC message with no parameters.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func bootstrap(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`bootstrap` xpc handler\")\n return try await self.lock.withLock { _ in\n guard await self.state == .created else {\n throw ContainerizationError(\n .invalidState,\n message: \"container expected to be in created state, got: \\(await self.state)\"\n )\n }\n\n let bundle = ContainerClient.Bundle(path: self.root)\n try bundle.createLogFile()\n\n let vmm = VZVirtualMachineManager(\n kernel: try bundle.kernel,\n initialFilesystem: bundle.initialFilesystem.asMount,\n bootlog: bundle.bootlog.path,\n logger: self.log\n )\n var config = try bundle.configuration\n let container = LinuxContainer(\n config.id,\n rootfs: try bundle.containerRootfs.asMount,\n vmm: vmm,\n logger: self.log\n )\n\n // dynamically configure the DNS nameserver from a network if no explicit configuration\n if let dns = config.dns, dns.nameservers.isEmpty {\n if let nameserver = try await self.getDefaultNameserver(networks: config.networks) {\n config.dns = ContainerConfiguration.DNSConfiguration(\n nameservers: [nameserver],\n domain: dns.domain,\n searchDomains: dns.searchDomains,\n options: dns.options\n )\n }\n }\n\n try await self.configureContainer(container: container, config: config)\n\n let fqdn: String\n if let hostname = config.hostname {\n if let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName),\n let dnsDomain = suite.string(forKey: \"dns.domain\"),\n !hostname.contains(\".\")\n {\n // TODO: Make the suiteName a constant defined in ClientDefaults and use that.\n // This will need some re-working of dependencies between SandboxService and Client\n fqdn = \"\\(hostname).\\(dnsDomain).\"\n } else {\n fqdn = \"\\(hostname).\"\n }\n } else {\n fqdn = config.id\n }\n\n var attachments: [Attachment] = []\n for index in 0.. XPCMessage {\n self.log.info(\"`start` xpc handler\")\n return try await self.lock.withLock { lock in\n let id = try message.id()\n let stdio = message.stdio()\n let containerInfo = try await self.getContainer()\n let containerId = containerInfo.container.id\n if id == containerId {\n try await self.startInitProcess(stdio: stdio, lock: lock)\n await self.setState(.running)\n try await self.sendContainerEvent(.containerStart(id: id))\n } else {\n try await self.startExecProcess(processId: id, stdio: stdio, lock: lock)\n }\n return message.reply()\n }\n }\n\n private func startInitProcess(stdio: [FileHandle?], lock: AsyncLock.Context) async throws {\n let info = try self.getContainer()\n let container = info.container\n let bundle = info.bundle\n let id = container.id\n guard self.state == .booted else {\n throw ContainerizationError(\n .invalidState,\n message: \"container expected to be in booted state, got: \\(self.state)\"\n )\n }\n let containerLog = try FileHandle(forWritingTo: bundle.containerLog)\n let config = info.config\n let stdout = {\n if let h = stdio[1] {\n return MultiWriter(handles: [h, containerLog])\n }\n return MultiWriter(handles: [containerLog])\n }()\n let stderr: MultiWriter? = {\n if !config.initProcess.terminal {\n if let h = stdio[2] {\n return MultiWriter(handles: [h, containerLog])\n }\n return MultiWriter(handles: [containerLog])\n }\n return nil\n }()\n if let h = stdio[0] {\n container.stdin = h\n }\n container.stdout = stdout\n if let stderr {\n container.stderr = stderr\n }\n self.setState(.starting)\n do {\n try await container.start()\n let waitFunc: ExitMonitor.WaitHandler = {\n let code = try await container.wait()\n if let out = stdio[1] {\n try self.closeHandle(out.fileDescriptor)\n }\n if let err = stdio[2] {\n try self.closeHandle(err.fileDescriptor)\n }\n return code\n }\n try await self.monitor.track(id: id, waitingOn: waitFunc)\n } catch {\n try? await self.cleanupContainer()\n self.setState(.created)\n try await self.sendContainerEvent(.containerExit(id: id, exitCode: -1))\n throw error\n }\n }\n\n private func startExecProcess(processId id: String, stdio: [FileHandle?], lock: AsyncLock.Context) async throws {\n let container = try self.getContainer().container\n guard let processInfo = self.processes[id] else {\n throw ContainerizationError(.notFound, message: \"Process with id \\(id)\")\n }\n let ociConfig = self.configureProcessConfig(config: processInfo.config)\n let stdin: ReaderStream? = {\n if let h = stdio[0] {\n return h\n }\n return nil\n }()\n let process = try await container.exec(\n id,\n configuration: ociConfig,\n stdin: stdin,\n stdout: stdio[1],\n stderr: stdio[2]\n )\n try self.setUnderlyingProcess(id, process)\n try await process.start()\n let waitFunc: ExitMonitor.WaitHandler = {\n let code = try await process.wait()\n if let out = stdio[1] {\n try self.closeHandle(out.fileDescriptor)\n }\n if let err = stdio[2] {\n try self.closeHandle(err.fileDescriptor)\n }\n return code\n }\n try await self.monitor.track(id: id, waitingOn: waitFunc)\n }\n\n private func startSocketForwarders(containerIpAddress: String, publishedPorts: [PublishPort]) async throws {\n var forwarders: [SocketForwarderResult] = []\n try await withThrowingTaskGroup(of: SocketForwarderResult.self) { group in\n for publishedPort in publishedPorts {\n let proxyAddress = try SocketAddress(ipAddress: publishedPort.hostAddress, port: Int(publishedPort.hostPort))\n let serverAddress = try SocketAddress(ipAddress: containerIpAddress, port: Int(publishedPort.containerPort))\n log.info(\n \"creating forwarder for\",\n metadata: [\n \"proxy\": \"\\(proxyAddress)\",\n \"server\": \"\\(serverAddress)\",\n \"protocol\": \"\\(publishedPort.proto)\",\n ])\n group.addTask {\n let forwarder: SocketForwarder\n switch publishedPort.proto {\n case .tcp:\n forwarder = try TCPForwarder(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: self.log\n )\n case .udp:\n forwarder = try UDPForwarder(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: self.log\n )\n }\n return try await forwarder.run().get()\n }\n }\n for try await result in group {\n forwarders.append(result)\n }\n }\n\n self.socketForwarders = forwarders\n }\n\n private func stopSocketForwarders() async {\n log.info(\"closing forwarders\")\n for forwarder in self.socketForwarders {\n forwarder.close()\n try? await forwarder.wait()\n }\n log.info(\"closed forwarders\")\n }\n\n /// Create a process inside the virtual machine for the container.\n ///\n /// Use this procedure to run ad hoc processes in the virtual\n /// machine (`container exec`).\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: A client identifier for the process.\n /// - processConfig: JSON serialization of the `ProcessConfiguration`\n /// containing the process attributes.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func createProcess(_ message: XPCMessage) async throws -> XPCMessage {\n log.info(\"`createProcess` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped(_), .starting, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot exec: container is not running\"\n )\n case .running, .booted:\n let id = try message.id()\n let config = try message.processConfig()\n await self.addNewProcess(id, config)\n try await self.monitor.registerProcess(\n id: id,\n onExit: { id, code in\n guard let process = await self.processes[id]?.process else {\n throw ContainerizationError(.invalidState, message: \"ProcessInfo missing for process \\(id)\")\n }\n for cc in await self.waiters[id] ?? [] {\n cc.resume(returning: code)\n }\n await self.removeWaiters(for: id)\n try await process.delete()\n try await self.setProcessState(id: id, state: .stopped(code))\n })\n return message.reply()\n }\n }\n }\n\n /// Return the state for the sandbox and its containers.\n ///\n /// - Parameters:\n /// - message: An XPC message with no parameters.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - snapshot: The JSON serialization of the `SandboxSnapshot`\n /// that contains the state information.\n @Sendable\n public func state(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`state` xpc handler\")\n var status: RuntimeStatus = .unknown\n var networks: [Attachment] = []\n var cs: ContainerSnapshot?\n\n switch state {\n case .created, .stopped(_), .starting, .booted:\n status = .stopped\n case .stopping:\n status = .stopping\n case .running:\n let ctr = try getContainer()\n\n status = .running\n networks = ctr.attachments\n cs = ContainerSnapshot(\n configuration: ctr.config,\n status: RuntimeStatus.running,\n networks: networks\n )\n }\n\n let reply = message.reply()\n try reply.setState(\n .init(\n status: status,\n networks: networks,\n containers: cs != nil ? [cs!] : []\n )\n )\n return reply\n }\n\n /// Stop the container workload, any ad hoc processes, and the underlying\n /// virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - stopOptions: JSON serialization of `ContainerStopOptions`\n /// that modify stop behavior.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func stop(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`stop` xpc handler\")\n let reply = try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .stopped(_), .created, .stopping:\n return message.reply()\n case .starting:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot stop: container is not running\"\n )\n case .running, .booted:\n let ctr = try await getContainer()\n let stopOptions = try message.stopOptions()\n do {\n try await gracefulStopContainer(\n ctr.container,\n stopOpts: stopOptions\n )\n } catch {\n log.notice(\"failed to stop sandbox gracefully: \\(error)\")\n }\n await setState(.stopping)\n return message.reply()\n }\n }\n do {\n try await cleanupContainer()\n } catch {\n self.log.error(\"failed to cleanup container: \\(error)\")\n }\n return reply\n }\n\n /// Signal a process running in the virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n /// - signal: The signal value.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func kill(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`kill` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped, .starting, .booted, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot kill: container is not running\"\n )\n case .running:\n let ctr = try await getContainer()\n let id = try message.id()\n if id != ctr.container.id {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) does not exist\")\n }\n\n guard let proc = processInfo.process else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not started\")\n }\n try await proc.kill(Int32(try message.signal()))\n return message.reply()\n }\n\n // TODO: fix underlying signal value to int64\n try await ctr.container.kill(Int32(try message.signal()))\n return message.reply()\n }\n }\n }\n\n /// Resize the terminal for a process.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n /// - width: The terminal width.\n /// - height: The terminal height.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func resize(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`resize` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped, .starting, .booted, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot resize: container is not running\"\n )\n case .running:\n let id = try message.id()\n let ctr = try await getContainer()\n let width = message.uint64(key: .width)\n let height = message.uint64(key: .height)\n if id != ctr.container.id {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) does not exist\")\n }\n\n guard let proc = processInfo.process else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not started\")\n }\n\n try await proc.resize(to: .init(width: UInt16(width), height: UInt16(height)))\n return message.reply()\n }\n\n try await ctr.container.resize(to: .init(width: UInt16(width), height: UInt16(height)))\n return message.reply()\n }\n }\n }\n\n /// Wait for a process.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - exitCode: The exit code for the process.\n @Sendable\n public func wait(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`wait` xpc handler\")\n guard let id = message.string(key: .id) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing id in wait xpc message\")\n }\n\n let cachedCode: Int32? = try await self.lock.withLock { _ in\n let ctrInfo = try await self.getContainer()\n let ctr = ctrInfo.container\n if id == ctr.id {\n switch await self.state {\n case .stopped(let code):\n return code\n default:\n break\n }\n } else {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.notFound, message: \"Process with id \\(id)\")\n }\n switch processInfo.state {\n case .stopped(let code):\n return code\n default:\n break\n }\n }\n return nil\n }\n if let cachedCode {\n let reply = message.reply()\n reply.set(key: .exitCode, value: Int64(cachedCode))\n return reply\n }\n\n let exitCode = await withCheckedContinuation { cc in\n // Is this safe since we are in an actor? :(\n self.addWaiter(id: id, cont: cc)\n }\n let reply = message.reply()\n reply.set(key: .exitCode, value: Int64(exitCode))\n return reply\n }\n\n /// Dial a vsock port on the virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - port: The port number.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - fd: The file descriptor for the vsock.\n @Sendable\n public func dial(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`dial` xpc handler\")\n switch self.state {\n case .starting, .created, .stopped, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot dial: container is not running\"\n )\n case .running, .booted:\n let port = message.uint64(key: .port)\n guard port > 0 else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"no vsock port supplied for dial\"\n )\n }\n\n let ctr = try getContainer()\n let fh = try await ctr.container.dialVsock(port: UInt32(port))\n\n let reply = message.reply()\n reply.set(key: .fd, value: fh)\n return reply\n }\n }\n\n private func onContainerExit(id: String, code: Int32) async throws {\n self.log.info(\"init process exited with: \\(code)\")\n\n try await self.lock.withLock { [self] _ in\n let ctrInfo = try await getContainer()\n let ctr = ctrInfo.container\n // Did someone explicitly call stop and we're already\n // cleaning up?\n switch await self.state {\n case .stopped(_):\n return\n default:\n break\n }\n\n do {\n try await ctr.stop()\n } catch {\n log.notice(\"failed to stop sandbox gracefully: \\(error)\")\n }\n\n do {\n try await cleanupContainer()\n } catch {\n self.log.error(\"failed to cleanup container: \\(error)\")\n }\n await setState(.stopped(code))\n let waiters = await self.waiters[id] ?? []\n for cc in waiters {\n cc.resume(returning: code)\n }\n await self.removeWaiters(for: id)\n try await self.sendContainerEvent(.containerExit(id: id, exitCode: Int64(code)))\n exit(code)\n }\n }\n\n private func configureContainer(container: LinuxContainer, config: ContainerConfiguration) throws {\n container.cpus = config.resources.cpus\n container.memoryInBytes = config.resources.memoryInBytes\n container.rosetta = config.rosetta\n container.sysctl = config.sysctls.reduce(into: [String: String]()) {\n $0[$1.key] = $1.value\n }\n\n for mount in config.mounts {\n if try mount.isSocket() {\n let socket = UnixSocketConfiguration(\n source: URL(filePath: mount.source),\n destination: URL(filePath: mount.destination)\n )\n container.sockets.append(socket)\n } else {\n container.mounts.append(mount.asMount)\n }\n }\n\n for publishedSocket in config.publishedSockets {\n let socketConfig = UnixSocketConfiguration(\n source: publishedSocket.containerPath,\n destination: publishedSocket.hostPath,\n permissions: publishedSocket.permissions,\n direction: .outOf\n )\n container.sockets.append(socketConfig)\n }\n\n container.hostname = config.hostname ?? config.id\n\n if let dns = config.dns {\n container.dns = DNS(\n nameservers: dns.nameservers, domain: dns.domain,\n searchDomains: dns.searchDomains, options: dns.options)\n }\n\n configureInitialProcess(container: container, process: config.initProcess)\n }\n\n private func getDefaultNameserver(networks: [String]) async throws -> String? {\n for network in networks {\n let client = NetworkClient(id: network)\n let state = try await client.state()\n guard case .running(_, let status) = state else {\n continue\n }\n return status.gateway\n }\n\n return nil\n }\n\n private func configureInitialProcess(container: LinuxContainer, process: ProcessConfiguration) {\n container.arguments = [process.executable] + process.arguments\n container.environment = modifyingEnvironment(process)\n container.terminal = process.terminal\n container.workingDirectory = process.workingDirectory\n container.rlimits = process.rlimits.map {\n .init(type: $0.limit, hard: $0.hard, soft: $0.soft)\n }\n switch process.user {\n case .raw(let name):\n container.user = .init(\n uid: 0,\n gid: 0,\n umask: nil,\n additionalGids: process.supplementalGroups,\n username: name\n )\n case .id(let uid, let gid):\n container.user = .init(\n uid: uid,\n gid: gid,\n umask: nil,\n additionalGids: process.supplementalGroups,\n username: \"\"\n )\n }\n }\n\n private nonisolated func configureProcessConfig(config: ProcessConfiguration) -> ContainerizationOCI.Process {\n var proc = ContainerizationOCI.Process()\n proc.args = [config.executable] + config.arguments\n proc.env = modifyingEnvironment(config)\n proc.terminal = config.terminal\n proc.cwd = config.workingDirectory\n proc.rlimits = config.rlimits.map {\n .init(type: $0.limit, hard: $0.hard, soft: $0.soft)\n }\n switch config.user {\n case .raw(let name):\n proc.user = .init(\n uid: 0,\n gid: 0,\n umask: nil,\n additionalGids: config.supplementalGroups,\n username: name\n )\n case .id(let uid, let gid):\n proc.user = .init(\n uid: uid,\n gid: gid,\n umask: nil,\n additionalGids: config.supplementalGroups,\n username: \"\"\n )\n }\n\n return proc\n }\n\n private nonisolated func closeHandle(_ handle: Int32) throws {\n guard close(handle) == 0 else {\n guard let errCode = POSIXErrorCode(rawValue: errno) else {\n fatalError(\"failed to convert errno to POSIXErrorCode\")\n }\n throw POSIXError(errCode)\n }\n }\n\n private nonisolated func modifyingEnvironment(_ config: ProcessConfiguration) -> [String] {\n guard config.terminal else {\n return config.environment\n }\n // Prepend the TERM env var. If the user has it specified our value will be overridden.\n return [\"TERM=xterm\"] + config.environment\n }\n\n private func getContainer() throws -> ContainerInfo {\n guard let container else {\n throw ContainerizationError(\n .invalidState,\n message: \"no container found\"\n )\n }\n return container\n }\n\n private func gracefulStopContainer(_ lc: LinuxContainer, stopOpts: ContainerStopOptions) async throws {\n // Try and gracefully shut down the process. Even if this succeeds we need to power off\n // the vm, but we should try this first always.\n do {\n try await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n try await lc.wait()\n }\n group.addTask {\n try await lc.kill(stopOpts.signal)\n try await Task.sleep(for: .seconds(stopOpts.timeoutInSeconds))\n try await lc.kill(SIGKILL)\n }\n try await group.next()\n group.cancelAll()\n }\n } catch {}\n // Now actually bring down the vm.\n try await lc.stop()\n }\n\n private func cleanupContainer() async throws {\n // Give back our lovely IP(s)\n await self.stopSocketForwarders()\n let containerInfo = try self.getContainer()\n for attachment in containerInfo.attachments {\n let client = NetworkClient(id: attachment.network)\n do {\n try await client.deallocate(hostname: attachment.hostname)\n } catch {\n self.log.error(\"failed to deallocate hostname \\(attachment.hostname) on network \\(attachment.network): \\(error)\")\n }\n }\n }\n\n private func sendContainerEvent(_ event: ContainerEvent) async throws {\n let serviceIdentifier = \"com.apple.container.apiserver\"\n let client = XPCClient(service: serviceIdentifier)\n let message = XPCMessage(route: .containerEvent)\n\n let data = try JSONEncoder().encode(event)\n message.set(key: .containerEvent, value: data)\n try await client.send(message)\n }\n\n}\n\nextension XPCMessage {\n fileprivate func signal() throws -> Int64 {\n self.int64(key: .signal)\n }\n\n fileprivate func stopOptions() throws -> ContainerStopOptions {\n guard let data = self.dataNoCopy(key: .stopOptions) else {\n throw ContainerizationError(.invalidArgument, message: \"empty StopOptions\")\n }\n return try JSONDecoder().decode(ContainerStopOptions.self, from: data)\n }\n\n fileprivate func setState(_ state: SandboxSnapshot) throws {\n let data = try JSONEncoder().encode(state)\n self.set(key: .snapshot, value: data)\n }\n\n fileprivate func stdio() -> [FileHandle?] {\n var handles = [FileHandle?](repeating: nil, count: 3)\n if let stdin = self.fileHandle(key: .stdin) {\n handles[0] = stdin\n }\n if let stdout = self.fileHandle(key: .stdout) {\n handles[1] = stdout\n }\n if let stderr = self.fileHandle(key: .stderr) {\n handles[2] = stderr\n }\n return handles\n }\n\n fileprivate func setFileHandle(_ handle: FileHandle) {\n self.set(key: .fd, value: handle)\n }\n\n fileprivate func processConfig() throws -> ProcessConfiguration {\n guard let data = self.dataNoCopy(key: .processConfig) else {\n throw ContainerizationError(.invalidArgument, message: \"empty process configuration\")\n }\n return try JSONDecoder().decode(ProcessConfiguration.self, from: data)\n }\n}\n\nextension ContainerClient.Bundle {\n /// The pathname for the workload log file.\n public var containerLog: URL {\n path.appendingPathComponent(\"stdio.log\")\n }\n\n func createLogFile() throws {\n // Create the log file we'll write stdio to.\n // O_TRUNC resolves a log delay issue on restarted containers by force-updating internal state\n let fd = Darwin.open(self.containerLog.path, O_CREAT | O_RDONLY | O_TRUNC, 0o644)\n guard fd > 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n close(fd)\n }\n}\n\nextension Filesystem {\n var asMount: Containerization.Mount {\n switch self.type {\n case .tmpfs:\n return .any(\n type: \"tmpfs\",\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n case .virtiofs:\n return .share(\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n case .block(let format, _, _):\n return .block(\n format: format,\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n }\n }\n\n func isSocket() throws -> Bool {\n if !self.isVirtiofs {\n return false\n }\n let info = try File.info(self.source)\n return info.isSocket\n }\n}\n\nstruct MultiWriter: Writer {\n let handles: [FileHandle]\n\n func write(_ data: Data) throws {\n for handle in self.handles {\n try handle.write(contentsOf: data)\n }\n }\n}\n\nextension FileHandle: @retroactive ReaderStream, @retroactive Writer {\n public func write(_ data: Data) throws {\n try self.write(contentsOf: data)\n }\n\n public func stream() -> AsyncStream {\n .init { cont in\n self.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n self.readabilityHandler = nil\n cont.finish()\n return\n }\n cont.yield(data)\n }\n }\n }\n}\n\n// MARK: State handler helpers\n\nextension SandboxService {\n private func addWaiter(id: String, cont: CheckedContinuation) {\n var current = self.waiters[id] ?? []\n current.append(cont)\n self.waiters[id] = current\n }\n\n private func removeWaiters(for id: String) {\n self.waiters[id] = []\n }\n\n private func setUnderlyingProcess(_ id: String, _ process: LinuxProcess) throws {\n guard var info = self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not found\")\n }\n info.process = process\n self.processes[id] = info\n }\n\n private func setProcessState(id: String, state: State) throws {\n guard var info = self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not found\")\n }\n info.state = state\n self.processes[id] = info\n }\n\n private func setContainer(_ info: ContainerInfo) {\n self.container = info\n }\n\n private func addNewProcess(_ id: String, _ config: ProcessConfiguration) {\n self.processes[id] = ProcessInfo(config: config, process: nil, state: .created)\n }\n\n private struct ProcessInfo {\n let config: ProcessConfiguration\n var process: LinuxProcess?\n var state: State\n }\n\n private struct ContainerInfo {\n let container: LinuxContainer\n let config: ContainerConfiguration\n let attachments: [Attachment]\n let bundle: ContainerClient.Bundle\n }\n\n public enum State: Sendable, Equatable {\n case created\n case booted\n case starting\n case running\n case stopping\n case stopped(Int32)\n }\n\n func setState(_ new: State) {\n self.state = new\n }\n}\n"], ["/container/Sources/CLI/BuildCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerBuild\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport NIO\nimport TerminalProgress\n\nextension Application {\n struct BuildCommand: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"build\"\n config.abstract = \"Build an image from a Dockerfile\"\n config._superCommandName = \"container\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64 = 2\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n var memory: String = \"2048MB\"\n\n @Option(name: .long, help: ArgumentHelp(\"Set build-time variables\", valueName: \"key=val\"))\n var buildArg: [String] = []\n\n @Argument(help: \"Build directory\")\n var contextDir: String = \".\"\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Path to Dockerfile\", valueName: \"path\"))\n var file: String = \"Dockerfile\"\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Set a label\", valueName: \"key=val\"))\n var label: [String] = []\n\n @Flag(name: .long, help: \"Do not use cache\")\n var noCache: Bool = false\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Output configuration for the build\", valueName: \"value\"))\n var output: [String] = {\n [\"type=oci\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Cache imports for the build\", valueName: \"value\", visibility: .hidden))\n var cacheIn: [String] = {\n []\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Cache exports for the build\", valueName: \"value\", visibility: .hidden))\n var cacheOut: [String] = {\n []\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"set the build architecture\", valueName: \"value\"))\n var arch: [String] = {\n [\"arm64\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"set the build os\", valueName: \"value\"))\n var os: [String] = {\n [\"linux\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Progress type - one of [auto|plain|tty]\", valueName: \"type\"))\n var progress: String = \"auto\"\n\n @Option(name: .long, help: ArgumentHelp(\"Builder-shim vsock port\", valueName: \"port\"))\n var vsockPort: UInt32 = 8088\n\n @Option(name: [.customShort(\"t\"), .customLong(\"tag\")], help: ArgumentHelp(\"Name for the built image\", valueName: \"name\"))\n var targetImageName: String = UUID().uuidString.lowercased()\n\n @Option(name: .long, help: ArgumentHelp(\"Set the target build stage\", valueName: \"stage\"))\n var target: String = \"\"\n\n @Flag(name: .shortAndLong, help: \"Suppress build output\")\n var quiet: Bool = false\n\n func run() async throws {\n do {\n let timeout: Duration = .seconds(300)\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Dialing builder\")\n\n let builder: Builder? = try await withThrowingTaskGroup(of: Builder.self) { group in\n defer {\n group.cancelAll()\n }\n\n group.addTask {\n while true {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n let fh = try await container.dial(self.vsockPort)\n\n let threadGroup: MultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n let b = try Builder(socket: fh, group: threadGroup)\n\n // If this call succeeds, then BuildKit is running.\n let _ = try await b.info()\n return b\n } catch {\n // If we get here, \"Dialing builder\" is shown for such a short period\n // of time that it's invisible to the user.\n progress.set(tasks: 0)\n progress.set(totalTasks: 3)\n\n try await BuilderStart.start(\n cpus: self.cpus,\n memory: self.memory,\n progressUpdate: progress.handler\n )\n\n // wait (seconds) for builder to start listening on vsock\n try await Task.sleep(for: .seconds(5))\n continue\n }\n }\n }\n\n group.addTask {\n try await Task.sleep(for: timeout)\n throw ValidationError(\n \"\"\"\n Timeout waiting for connection to builder\n \"\"\"\n )\n }\n\n return try await group.next()\n }\n\n guard let builder else {\n throw ValidationError(\"builder is not running\")\n }\n\n let dockerfile = try Data(contentsOf: URL(filePath: file))\n let exportPath = Application.appRoot.appendingPathComponent(\".build\")\n\n let buildID = UUID().uuidString\n let tempURL = exportPath.appendingPathComponent(buildID)\n try FileManager.default.createDirectory(at: tempURL, withIntermediateDirectories: true, attributes: nil)\n defer {\n try? FileManager.default.removeItem(at: tempURL)\n }\n\n let imageName: String = try {\n let parsedReference = try Reference.parse(targetImageName)\n parsedReference.normalize()\n return parsedReference.description\n }()\n\n var terminal: Terminal?\n switch self.progress {\n case \"tty\":\n terminal = try Terminal(descriptor: STDERR_FILENO)\n case \"auto\":\n terminal = try? Terminal(descriptor: STDERR_FILENO)\n case \"plain\":\n terminal = nil\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid progress mode \\(self.progress)\")\n }\n\n defer { terminal?.tryReset() }\n\n let exports: [Builder.BuildExport] = try output.map { output in\n var exp = try Builder.BuildExport(from: output)\n if exp.destination == nil {\n exp.destination = tempURL.appendingPathComponent(\"out.tar\")\n }\n return exp\n }\n\n try await withThrowingTaskGroup(of: Void.self) { [terminal] group in\n defer {\n group.cancelAll()\n }\n group.addTask {\n let handler = AsyncSignalHandler.create(notify: [SIGTERM, SIGINT, SIGUSR1, SIGUSR2])\n for await sig in handler.signals {\n throw ContainerizationError(.interrupted, message: \"exiting on signal \\(sig)\")\n }\n }\n let platforms: [Platform] = try {\n var results: [Platform] = []\n for o in self.os {\n for a in self.arch {\n guard let platform = try? Platform(from: \"\\(o)/\\(a)\") else {\n throw ValidationError(\"invalid os/architecture combination \\(o)/\\(a)\")\n }\n results.append(platform)\n }\n }\n return results\n }()\n group.addTask { [terminal] in\n let config = ContainerBuild.Builder.BuildConfig(\n buildID: buildID,\n contentStore: RemoteContentStoreClient(),\n buildArgs: buildArg,\n contextDir: contextDir,\n dockerfile: dockerfile,\n labels: label,\n noCache: noCache,\n platforms: platforms,\n terminal: terminal,\n tag: imageName,\n target: target,\n quiet: quiet,\n exports: exports,\n cacheIn: cacheIn,\n cacheOut: cacheOut\n )\n progress.finish()\n\n try await builder.build(config)\n }\n\n try await group.next()\n }\n\n let unpackProgressConfig = try ProgressConfig(\n description: \"Unpacking built image\",\n itemsName: \"entries\",\n showTasks: exports.count > 1,\n totalTasks: exports.count\n )\n let unpackProgress = ProgressBar(config: unpackProgressConfig)\n defer {\n unpackProgress.finish()\n }\n unpackProgress.start()\n\n var finalMessage = \"Successfully built \\(imageName)\"\n let taskManager = ProgressTaskCoordinator()\n // Currently, only a single export can be specified.\n for exp in exports {\n unpackProgress.add(tasks: 1)\n let unpackTask = await taskManager.startTask()\n switch exp.type {\n case \"oci\":\n try Task.checkCancellation()\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let loaded = try await ClientImage.load(from: dest.absolutePath())\n\n for image in loaded {\n try Task.checkCancellation()\n try await image.unpack(platform: nil, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: unpackProgress.handler))\n }\n case \"tar\":\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let tarURL = tempURL.appendingPathComponent(\"out.tar\")\n try FileManager.default.moveItem(at: tarURL, to: dest)\n finalMessage = \"Successfully exported to \\(dest.absolutePath())\"\n case \"local\":\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let localDir = tempURL.appendingPathComponent(\"local\")\n\n guard FileManager.default.fileExists(atPath: localDir.path) else {\n throw ContainerizationError(.invalidArgument, message: \"expected local output not found\")\n }\n try FileManager.default.copyItem(at: localDir, to: dest)\n finalMessage = \"Successfully exported to \\(dest.absolutePath())\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid exporter \\(exp.rawValue)\")\n }\n }\n await taskManager.finish()\n unpackProgress.finish()\n print(finalMessage)\n } catch {\n throw NSError(domain: \"Build\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"\\(error)\"])\n }\n }\n\n func validate() throws {\n guard FileManager.default.fileExists(atPath: file) else {\n throw ValidationError(\"Dockerfile does not exist at path: \\(file)\")\n }\n guard FileManager.default.fileExists(atPath: contextDir) else {\n throw ValidationError(\"context dir does not exist \\(contextDir)\")\n }\n guard let _ = try? Reference.parse(targetImageName) else {\n throw ValidationError(\"invalid reference \\(targetImageName)\")\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerLogs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Darwin\nimport Dispatch\nimport Foundation\n\nextension Application {\n struct ContainerLogs: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"logs\",\n abstract: \"Fetch container stdio or boot logs\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Flag(name: .shortAndLong, help: \"Follow log output\")\n var follow: Bool = false\n\n @Flag(name: .long, help: \"Display the boot log for the container instead of stdio\")\n var boot: Bool = false\n\n @Option(name: [.customShort(\"n\")], help: \"Number of lines to show from the end of the logs. If not provided this will print all of the logs\")\n var numLines: Int?\n\n @Argument(help: \"Container to fetch logs for\")\n var container: String\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: container)\n let fhs = try await container.logs()\n let fileHandle = boot ? fhs[1] : fhs[0]\n\n try await Self.tail(\n fh: fileHandle,\n n: numLines,\n follow: follow\n )\n } catch {\n throw ContainerizationError(\n .invalidArgument,\n message: \"failed to fetch container logs for \\(container): \\(error)\"\n )\n }\n }\n\n private static func tail(\n fh: FileHandle,\n n: Int?,\n follow: Bool\n ) async throws {\n if let n {\n var buffer = Data()\n let size = try fh.seekToEnd()\n var offset = size\n var lines: [String] = []\n\n while offset > 0, lines.count < n {\n let readSize = min(1024, offset)\n offset -= readSize\n try fh.seek(toOffset: offset)\n\n let data = fh.readData(ofLength: Int(readSize))\n buffer.insert(contentsOf: data, at: 0)\n\n if let chunk = String(data: buffer, encoding: .utf8) {\n lines = chunk.components(separatedBy: .newlines)\n lines = lines.filter { !$0.isEmpty }\n }\n }\n\n lines = Array(lines.suffix(n))\n for line in lines {\n print(line)\n }\n } else {\n // Fast path if all they want is the full file.\n guard let data = try fh.readToEnd() else {\n // Seems you get nil if it's a zero byte read, or you\n // try and read from dev/null.\n return\n }\n guard let str = String(data: data, encoding: .utf8) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to convert container logs to utf8\"\n )\n }\n print(str.trimmingCharacters(in: .newlines))\n }\n\n fflush(stdout)\n if follow {\n setbuf(stdout, nil)\n try await Self.followFile(fh: fh)\n }\n }\n\n private static func followFile(fh: FileHandle) async throws {\n _ = try fh.seekToEnd()\n let stream = AsyncStream { cont in\n fh.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n // Triggers on container restart - can exit here as well\n do {\n _ = try fh.seekToEnd() // To continue streaming existing truncated log files\n } catch {\n fh.readabilityHandler = nil\n cont.finish()\n return\n }\n }\n if let str = String(data: data, encoding: .utf8), !str.isEmpty {\n var lines = str.components(separatedBy: .newlines)\n lines = lines.filter { !$0.isEmpty }\n for line in lines {\n cont.yield(line)\n }\n }\n }\n }\n\n for await line in stream {\n print(line)\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationExtras\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct NetworkList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List networks\",\n aliases: [\"ls\"])\n\n @Flag(name: .shortAndLong, help: \"Only output the network name\")\n var quiet = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let networks = try await ClientNetwork.list()\n try printNetworks(networks: networks, format: format)\n }\n\n private func createHeader() -> [[String]] {\n [[\"NETWORK\", \"STATE\", \"SUBNET\"]]\n }\n\n private func printNetworks(networks: [NetworkState], format: ListFormat) throws {\n if format == .json {\n let printables = networks.map {\n PrintableNetwork($0)\n }\n let data = try JSONEncoder().encode(printables)\n print(String(data: data, encoding: .utf8)!)\n\n return\n }\n\n if self.quiet {\n networks.forEach {\n print($0.id)\n }\n return\n }\n\n var rows = createHeader()\n for network in networks {\n rows.append(network.asRow)\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n }\n}\n\nextension NetworkState {\n var asRow: [String] {\n switch self {\n case .created(_):\n return [self.id, self.state, \"none\"]\n case .running(_, let status):\n return [self.id, self.state, status.address]\n }\n }\n}\n\nstruct PrintableNetwork: Codable {\n let id: String\n let state: String\n let config: NetworkConfiguration\n let status: NetworkStatus?\n\n init(_ network: NetworkState) {\n self.id = network.id\n self.state = network.state\n switch network {\n case .created(let config):\n self.config = config\n self.status = nil\n case .running(let config, let status):\n self.config = config\n self.status = status\n }\n }\n}\n"], ["/container/Sources/APIServer/APIServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerPlugin\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport DNSServer\nimport Foundation\nimport Logging\n\n@main\nstruct APIServer: AsyncParsableCommand {\n static let listenAddress = \"127.0.0.1\"\n static let dnsPort = 2053\n\n static let configuration = CommandConfiguration(\n commandName: \"container-apiserver\",\n abstract: \"Container management API server\",\n version: releaseVersion()\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .shortAndLong, help: \"Daemon root directory\")\n var root = Self.appRoot.path\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n func run() async throws {\n let commandName = Self.configuration.commandName ?? \"container-apiserver\"\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n do {\n log.info(\"configuring XPC server\")\n let root = URL(filePath: root)\n var routes = [XPCRoute: XPCServer.RouteHandler]()\n let pluginLoader = try initializePluginLoader(log: log)\n try await initializePlugins(pluginLoader: pluginLoader, log: log, routes: &routes)\n try initializeContainerService(root: root, pluginLoader: pluginLoader, log: log, routes: &routes)\n let networkService = try await initializeNetworkService(\n root: root,\n pluginLoader: pluginLoader,\n log: log,\n routes: &routes\n )\n initializeHealthCheckService(log: log, routes: &routes)\n try initializeKernelService(log: log, routes: &routes)\n\n let server = XPCServer(\n identifier: \"com.apple.container.apiserver\",\n routes: routes.reduce(\n into: [String: XPCServer.RouteHandler](),\n {\n $0[$1.key.rawValue] = $1.value\n }), log: log)\n\n await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n log.info(\"starting XPC server\")\n try await server.listen()\n }\n // start up host table DNS\n group.addTask {\n let hostsResolver = ContainerDNSHandler(networkService: networkService)\n let nxDomainResolver = NxDomainResolver()\n let compositeResolver = CompositeResolver(handlers: [hostsResolver, nxDomainResolver])\n let hostsQueryValidator = StandardQueryValidator(handler: compositeResolver)\n let dnsServer: DNSServer = DNSServer(handler: hostsQueryValidator, log: log)\n log.info(\n \"starting DNS host query resolver\",\n metadata: [\n \"host\": \"\\(Self.listenAddress)\",\n \"port\": \"\\(Self.dnsPort)\",\n ]\n )\n try await dnsServer.run(host: Self.listenAddress, port: Self.dnsPort)\n }\n }\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n APIServer.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"APIServer\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n return log\n }\n\n private func initializePluginLoader(log: Logger) throws -> PluginLoader {\n let installRoot = CommandLine.executablePathUrl\n .deletingLastPathComponent()\n .appendingPathComponent(\"..\")\n .standardized\n let pluginsURL = PluginLoader.userPluginsDir(root: installRoot)\n var directoryExists: ObjCBool = false\n _ = FileManager.default.fileExists(atPath: pluginsURL.path, isDirectory: &directoryExists)\n let userPluginsURL = directoryExists.boolValue ? pluginsURL : nil\n\n // plugins built into the application installed as a macOS app bundle\n let appBundlePluginsURL = Bundle.main.resourceURL?.appending(path: \"plugins\")\n\n // plugins built into the application installed as a Unix-like application\n let installRootPluginsURL =\n installRoot\n .appendingPathComponent(\"libexec\")\n .appendingPathComponent(\"container\")\n .appendingPathComponent(\"plugins\")\n .standardized\n\n let pluginDirectories = [\n userPluginsURL,\n appBundlePluginsURL,\n installRootPluginsURL,\n ].compactMap { $0 }\n\n let pluginFactories: [PluginFactory] = [\n DefaultPluginFactory(),\n AppBundlePluginFactory(),\n ]\n\n log.info(\"PLUGINS: \\(pluginDirectories)\")\n let statePath = PluginLoader.defaultPluginResourcePath(root: Self.appRoot)\n try FileManager.default.createDirectory(at: statePath, withIntermediateDirectories: true)\n return PluginLoader(pluginDirectories: pluginDirectories, pluginFactories: pluginFactories, defaultResourcePath: statePath, log: log)\n }\n\n // First load all of the plugins we can find. Then just expose\n // the handlers for clients to do whatever they want.\n private func initializePlugins(\n pluginLoader: PluginLoader,\n log: Logger,\n routes: inout [XPCRoute: XPCServer.RouteHandler]\n ) async throws {\n let bootPlugins = pluginLoader.findPlugins().filter { $0.shouldBoot }\n\n let service = PluginsService(pluginLoader: pluginLoader, log: log)\n try await service.loadAll(bootPlugins)\n\n let harness = PluginsHarness(service: service, log: log)\n routes[XPCRoute.pluginGet] = harness.get\n routes[XPCRoute.pluginList] = harness.list\n routes[XPCRoute.pluginLoad] = harness.load\n routes[XPCRoute.pluginUnload] = harness.unload\n routes[XPCRoute.pluginRestart] = harness.restart\n }\n\n private func initializeHealthCheckService(log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) {\n let svc = HealthCheckHarness(log: log)\n routes[XPCRoute.ping] = svc.ping\n }\n\n private func initializeKernelService(log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) throws {\n let svc = try KernelService(log: log, appRoot: Self.appRoot)\n let harness = KernelHarness(service: svc, log: log)\n routes[XPCRoute.installKernel] = harness.install\n routes[XPCRoute.getDefaultKernel] = harness.getDefaultKernel\n }\n\n private func initializeContainerService(root: URL, pluginLoader: PluginLoader, log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) throws {\n let service = try ContainersService(\n root: root,\n pluginLoader: pluginLoader,\n log: log\n )\n let harness = ContainersHarness(service: service, log: log)\n\n routes[XPCRoute.listContainer] = harness.list\n routes[XPCRoute.createContainer] = harness.create\n routes[XPCRoute.deleteContainer] = harness.delete\n routes[XPCRoute.containerLogs] = harness.logs\n routes[XPCRoute.containerEvent] = harness.eventHandler\n }\n\n private func initializeNetworkService(\n root: URL,\n pluginLoader: PluginLoader,\n log: Logger,\n routes: inout [XPCRoute: XPCServer.RouteHandler]\n ) async throws -> NetworksService {\n let resourceRoot = root.appendingPathComponent(\"networks\")\n let service = try await NetworksService(\n pluginLoader: pluginLoader,\n resourceRoot: resourceRoot,\n log: log\n )\n\n let defaultNetwork = try await service.list()\n .filter { $0.id == ClientNetwork.defaultNetworkName }\n .first\n if defaultNetwork == nil {\n let config = NetworkConfiguration(id: ClientNetwork.defaultNetworkName, mode: .nat)\n _ = try await service.create(configuration: config)\n }\n\n let harness = NetworksHarness(service: service, log: log)\n\n routes[XPCRoute.networkCreate] = harness.create\n routes[XPCRoute.networkDelete] = harness.delete\n routes[XPCRoute.networkList] = harness.list\n return service\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/ContainerClient/Utility.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct Utility {\n private static let infraImages = [\n ClientDefaults.get(key: .defaultBuilderImage),\n ClientDefaults.get(key: .defaultInitImage),\n ]\n\n public static func createContainerID(name: String?) -> String {\n guard let name else {\n return UUID().uuidString.lowercased()\n }\n return name\n }\n\n public static func isInfraImage(name: String) -> Bool {\n for infraImage in infraImages {\n if name == infraImage {\n return true\n }\n }\n return false\n }\n\n public static func trimDigest(digest: String) -> String {\n var digest = digest\n digest.trimPrefix(\"sha256:\")\n if digest.count > 24 {\n digest = String(digest.prefix(24)) + \"...\"\n }\n return digest\n }\n\n public static func validEntityName(_ name: String) throws {\n let pattern = #\"^[a-zA-Z0-9][a-zA-Z0-9_.-]+$\"#\n let regex = try Regex(pattern)\n if try regex.firstMatch(in: name) == nil {\n throw ContainerizationError(.invalidArgument, message: \"invalid entity name \\(name)\")\n }\n }\n\n public static func containerConfigFromFlags(\n id: String,\n image: String,\n arguments: [String],\n process: Flags.Process,\n management: Flags.Management,\n resource: Flags.Resource,\n registry: Flags.Registry,\n progressUpdate: @escaping ProgressUpdateHandler\n ) async throws -> (ContainerConfiguration, Kernel) {\n let requestedPlatform = Parser.platform(os: management.os, arch: management.arch)\n let scheme = try RequestScheme(registry.scheme)\n\n await progressUpdate([\n .setDescription(\"Fetching image\"),\n .setItemsName(\"blobs\"),\n ])\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n let img = try await ClientImage.fetch(\n reference: image,\n platform: requestedPlatform,\n scheme: scheme,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progressUpdate)\n )\n\n // Unpack a fetched image before use\n await progressUpdate([\n .setDescription(\"Unpacking image\"),\n .setItemsName(\"entries\"),\n ])\n let unpackTask = await taskManager.startTask()\n try await img.getCreateSnapshot(\n platform: requestedPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progressUpdate))\n\n await progressUpdate([\n .setDescription(\"Fetching kernel\"),\n .setItemsName(\"binary\"),\n ])\n\n let kernel = try await self.getKernel(management: management)\n\n // Pull and unpack the initial filesystem\n await progressUpdate([\n .setDescription(\"Fetching init image\"),\n .setItemsName(\"blobs\"),\n ])\n let fetchInitTask = await taskManager.startTask()\n let initImage = try await ClientImage.fetch(\n reference: ClientImage.initImageRef, platform: .current, scheme: scheme,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchInitTask, from: progressUpdate))\n\n await progressUpdate([\n .setDescription(\"Unpacking init image\"),\n .setItemsName(\"entries\"),\n ])\n let unpackInitTask = await taskManager.startTask()\n _ = try await initImage.getCreateSnapshot(\n platform: .current,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackInitTask, from: progressUpdate))\n\n await taskManager.finish()\n\n let imageConfig = try await img.config(for: requestedPlatform).config\n let description = img.description\n let pc = try Parser.process(\n arguments: arguments,\n processFlags: process,\n managementFlags: management,\n config: imageConfig\n )\n\n var config = ContainerConfiguration(id: id, image: description, process: pc)\n config.platform = requestedPlatform\n config.hostname = id\n\n config.resources = try Parser.resources(\n cpus: resource.cpus,\n memory: resource.memory\n )\n\n let tmpfs = try Parser.tmpfsMounts(management.tmpFs)\n let volumes = try Parser.volumes(management.volumes)\n var mounts = try Parser.mounts(management.mounts)\n mounts.append(contentsOf: tmpfs)\n mounts.append(contentsOf: volumes)\n config.mounts = mounts\n\n if management.networks.isEmpty {\n config.networks = [ClientNetwork.defaultNetworkName]\n } else {\n // networks may only be specified for macOS 26+\n guard #available(macOS 26, *) else {\n throw ContainerizationError(.invalidArgument, message: \"non-default network configuration requires macOS 26 or newer\")\n }\n config.networks = management.networks\n }\n\n var networkStatuses: [NetworkStatus] = []\n for networkName in config.networks {\n let network: NetworkState = try await ClientNetwork.get(id: networkName)\n guard case .running(_, let networkStatus) = network else {\n throw ContainerizationError(.invalidState, message: \"network \\(networkName) is not running\")\n }\n networkStatuses.append(networkStatus)\n }\n\n if management.dnsDisabled {\n config.dns = nil\n } else {\n let domain = management.dnsDomain ?? ClientDefaults.getOptional(key: .defaultDNSDomain)\n config.dns = .init(\n nameservers: management.dnsNameservers,\n domain: domain,\n searchDomains: management.dnsSearchDomains,\n options: management.dnsOptions\n )\n }\n\n if Platform.current.architecture == \"arm64\" && requestedPlatform.architecture == \"amd64\" {\n config.rosetta = true\n }\n\n config.labels = try Parser.labels(management.labels)\n\n config.publishedPorts = try Parser.publishPorts(management.publishPorts)\n\n // Parse --publish-socket arguments and add to container configuration\n // to enable socket forwarding from container to host.\n config.publishedSockets = try Parser.publishSockets(management.publishSockets)\n\n return (config, kernel)\n }\n\n private static func getKernel(management: Flags.Management) async throws -> Kernel {\n // For the image itself we'll take the user input and try with it as we can do userspace\n // emulation for x86, but for the kernel we need it to match the hosts architecture.\n let s: SystemPlatform = .current\n if let userKernel = management.kernel {\n guard FileManager.default.fileExists(atPath: userKernel) else {\n throw ContainerizationError(.notFound, message: \"Kernel file not found at path \\(userKernel)\")\n }\n let p = URL(filePath: userKernel)\n return .init(path: p, platform: s)\n }\n return try await ClientKernel.getDefaultKernel(for: s)\n }\n}\n"], ["/container/Sources/CLI/Application.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerPlugin\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport TerminalProgress\n\n// `log` is updated only once in the `validate()` method.\nnonisolated(unsafe) var log = {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"CLI\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n log.logLevel = .debug\n return log\n}()\n\n@main\nstruct Application: AsyncParsableCommand {\n @OptionGroup\n var global: Flags.Global\n\n static let configuration = CommandConfiguration(\n commandName: \"container\",\n abstract: \"A container platform for macOS\",\n version: releaseVersion(),\n subcommands: [\n DefaultCommand.self\n ],\n groupedSubcommands: [\n CommandGroup(\n name: \"Container\",\n subcommands: [\n ContainerCreate.self,\n ContainerDelete.self,\n ContainerExec.self,\n ContainerInspect.self,\n ContainerKill.self,\n ContainerList.self,\n ContainerLogs.self,\n ContainerRunCommand.self,\n ContainerStart.self,\n ContainerStop.self,\n ]\n ),\n CommandGroup(\n name: \"Image\",\n subcommands: [\n BuildCommand.self,\n ImagesCommand.self,\n RegistryCommand.self,\n ]\n ),\n CommandGroup(\n name: \"Other\",\n subcommands: Self.otherCommands()\n ),\n ],\n // Hidden command to handle plugins on unrecognized input.\n defaultSubcommand: DefaultCommand.self\n )\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n static let pluginLoader: PluginLoader = {\n let installRoot = CommandLine.executablePathUrl\n .deletingLastPathComponent()\n .appendingPathComponent(\"..\")\n .standardized\n let pluginsURL = PluginLoader.userPluginsDir(root: installRoot)\n var directoryExists: ObjCBool = false\n _ = FileManager.default.fileExists(atPath: pluginsURL.path, isDirectory: &directoryExists)\n let userPluginsURL = directoryExists.boolValue ? pluginsURL : nil\n\n // plugins built into the application installed as a macOS app bundle\n let appBundlePluginsURL = Bundle.main.resourceURL?.appending(path: \"plugins\")\n\n // plugins built into the application installed as a Unix-like application\n let installRootPluginsURL =\n installRoot\n .appendingPathComponent(\"libexec\")\n .appendingPathComponent(\"container\")\n .appendingPathComponent(\"plugins\")\n .standardized\n\n let pluginDirectories = [\n userPluginsURL,\n appBundlePluginsURL,\n installRootPluginsURL,\n ].compactMap { $0 }\n\n let pluginFactories = [\n DefaultPluginFactory()\n ]\n\n let statePath = PluginLoader.defaultPluginResourcePath(root: Self.appRoot)\n try! FileManager.default.createDirectory(at: statePath, withIntermediateDirectories: true)\n return PluginLoader(pluginDirectories: pluginDirectories, pluginFactories: pluginFactories, defaultResourcePath: statePath, log: log)\n }()\n\n public static func main() async throws {\n restoreCursorAtExit()\n\n #if DEBUG\n let warning = \"Running debug build. Performance may be degraded.\"\n let formattedWarning = \"\\u{001B}[33mWarning!\\u{001B}[0m \\(warning)\\n\"\n let warningData = Data(formattedWarning.utf8)\n FileHandle.standardError.write(warningData)\n #endif\n\n let fullArgs = CommandLine.arguments\n let args = Array(fullArgs.dropFirst())\n\n do {\n // container -> defaultHelpCommand\n var command = try Application.parseAsRoot(args)\n if var asyncCommand = command as? AsyncParsableCommand {\n try await asyncCommand.run()\n } else {\n try command.run()\n }\n } catch {\n // Regular ol `command` with no args will get caught by DefaultCommand. --help\n // on the root command will land here.\n let containsHelp = fullArgs.contains(\"-h\") || fullArgs.contains(\"--help\")\n if fullArgs.count <= 2 && containsHelp {\n Self.printModifiedHelpText()\n return\n }\n let errorAsString: String = String(describing: error)\n if errorAsString.contains(\"XPC connection error\") {\n let modifiedError = ContainerizationError(.interrupted, message: \"\\(error)\\nEnsure container system service has been started with `container system start`.\")\n Application.exit(withError: modifiedError)\n } else {\n Application.exit(withError: error)\n }\n }\n }\n\n static func handleProcess(io: ProcessIO, process: ClientProcess) async throws -> Int32 {\n let signals = AsyncSignalHandler.create(notify: Application.signalSet)\n return try await withThrowingTaskGroup(of: Int32?.self, returning: Int32.self) { group in\n let waitAdded = group.addTaskUnlessCancelled {\n let code = try await process.wait()\n try await io.wait()\n return code\n }\n\n guard waitAdded else {\n group.cancelAll()\n return -1\n }\n\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n\n if let current = io.console {\n let size = try current.size\n // It's supremely possible the process could've exited already. We shouldn't treat\n // this as fatal.\n try? await process.resize(size)\n _ = group.addTaskUnlessCancelled {\n let winchHandler = AsyncSignalHandler.create(notify: [SIGWINCH])\n for await _ in winchHandler.signals {\n do {\n try await process.resize(try current.size)\n } catch {\n log.error(\n \"failed to send terminal resize event\",\n metadata: [\n \"error\": \"\\(error)\"\n ]\n )\n }\n }\n return nil\n }\n } else {\n _ = group.addTaskUnlessCancelled {\n for await sig in signals.signals {\n do {\n try await process.kill(sig)\n } catch {\n log.error(\n \"failed to send signal\",\n metadata: [\n \"signal\": \"\\(sig)\",\n \"error\": \"\\(error)\",\n ]\n )\n }\n }\n return nil\n }\n }\n\n while true {\n let result = try await group.next()\n if result == nil {\n return -1\n }\n let status = result!\n if let status {\n group.cancelAll()\n return status\n }\n }\n return -1\n }\n }\n\n func validate() throws {\n // Not really a \"validation\", but a cheat to run this before\n // any of the commands do their business.\n let debugEnvVar = ProcessInfo.processInfo.environment[\"CONTAINER_DEBUG\"]\n if self.global.debug || debugEnvVar != nil {\n log.logLevel = .debug\n }\n // Ensure we're not running under Rosetta.\n if try isTranslated() {\n throw ValidationError(\n \"\"\"\n `container` is currently running under Rosetta Translation, which could be\n caused by your terminal application. Please ensure this is turned off.\n \"\"\"\n )\n }\n }\n\n private static func otherCommands() -> [any ParsableCommand.Type] {\n guard #available(macOS 26, *) else {\n return [\n BuilderCommand.self,\n SystemCommand.self,\n ]\n }\n\n return [\n BuilderCommand.self,\n NetworkCommand.self,\n SystemCommand.self,\n ]\n }\n\n private static func restoreCursorAtExit() {\n let signalHandler: @convention(c) (Int32) -> Void = { signal in\n let exitCode = ExitCode(signal + 128)\n Application.exit(withError: exitCode)\n }\n // Termination by Ctrl+C.\n signal(SIGINT, signalHandler)\n // Termination using `kill`.\n signal(SIGTERM, signalHandler)\n // Normal and explicit exit.\n atexit {\n if let progressConfig = try? ProgressConfig() {\n let progressBar = ProgressBar(config: progressConfig)\n progressBar.resetCursor()\n }\n }\n }\n}\n\nextension Application {\n // Because we support plugins, we need to modify the help text to display\n // any if we found some.\n static func printModifiedHelpText() {\n let altered = Self.pluginLoader.alterCLIHelpText(\n original: Application.helpMessage(for: Application.self)\n )\n print(altered)\n }\n\n enum ListFormat: String, CaseIterable, ExpressibleByArgument {\n case json\n case table\n }\n\n static let signalSet: [Int32] = [\n SIGTERM,\n SIGINT,\n SIGUSR1,\n SIGUSR2,\n SIGWINCH,\n ]\n\n func isTranslated() throws -> Bool {\n do {\n return try Sysctl.byName(\"sysctl.proc_translated\") == 1\n } catch let posixErr as POSIXError {\n if posixErr.code == .ENOENT {\n return false\n }\n throw posixErr\n }\n }\n\n private static func releaseVersion() -> String {\n var versionDetails: [String: String] = [\"build\": \"release\"]\n #if DEBUG\n versionDetails[\"build\"] = \"debug\"\n #endif\n let gitCommit = {\n let sha = get_git_commit().map { String(cString: $0) }\n guard let sha else {\n return \"unspecified\"\n }\n return String(sha.prefix(7))\n }()\n versionDetails[\"commit\"] = gitCommit\n let extras: String = versionDetails.map { \"\\($0): \\($1)\" }.sorted().joined(separator: \", \")\n\n let bundleVersion = (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String)\n let releaseVersion = bundleVersion ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n\n return \"container CLI version \\(releaseVersion) (\\(extras))\"\n }\n}\n"], ["/container/Sources/Helpers/NetworkVmnet/NetworkVmnetHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\n@main\nstruct NetworkVmnetHelper: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"container-network-vmnet\",\n abstract: \"XPC service for managing a vmnet network\",\n version: releaseVersion(),\n subcommands: [\n Start.self\n ]\n )\n}\n\nextension NetworkVmnetHelper {\n struct Start: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Starts the network plugin\"\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .long, help: \"XPC service identifier\")\n var serviceIdentifier: String\n\n @Option(name: .shortAndLong, help: \"Network identifier\")\n var id: String\n\n @Option(name: .shortAndLong, help: \"CIDR address for the subnet\")\n var subnet: String?\n\n func run() async throws {\n let commandName = NetworkVmnetHelper._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n do {\n log.info(\"configuring XPC server\")\n let subnet = try self.subnet.map { try CIDRAddress($0) }\n let configuration = NetworkConfiguration(id: id, mode: .nat, subnet: subnet?.description)\n let network = try Self.createNetwork(configuration: configuration, log: log)\n try await network.start()\n let server = try await NetworkService(network: network, log: log)\n let xpc = XPCServer(\n identifier: serviceIdentifier,\n routes: [\n NetworkRoutes.state.rawValue: server.state,\n NetworkRoutes.allocate.rawValue: server.allocate,\n NetworkRoutes.deallocate.rawValue: server.deallocate,\n NetworkRoutes.lookup.rawValue: server.lookup,\n NetworkRoutes.disableAllocator.rawValue: server.disableAllocator,\n ],\n log: log\n )\n\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n NetworkVmnetHelper.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"NetworkVmnetHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n log[metadataKey: \"id\"] = \"\\(id)\"\n return log\n }\n\n private static func createNetwork(configuration: NetworkConfiguration, log: Logger) throws -> Network {\n guard #available(macOS 26, *) else {\n return try AllocationOnlyVmnetNetwork(configuration: configuration, log: log)\n }\n\n return try ReservedVmnetNetwork(configuration: configuration, log: log)\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/CLI/RunCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Foundation\nimport NIOCore\nimport NIOPosix\nimport TerminalProgress\n\nextension Application {\n struct ContainerRunCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"run\",\n abstract: \"Run a container\")\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var resourceFlags: Flags.Resource\n\n @OptionGroup\n var managementFlags: Flags.Management\n\n @OptionGroup\n var registryFlags: Flags.Registry\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Argument(help: \"Image name\")\n var image: String\n\n @Argument(parsing: .captureForPassthrough, help: \"Container init process arguments\")\n var arguments: [String] = []\n\n func run() async throws {\n var exitCode: Int32 = 127\n let id = Utility.createContainerID(name: self.managementFlags.name)\n\n var progressConfig: ProgressConfig\n if progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 6\n )\n }\n\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n try Utility.validEntityName(id)\n\n // Check if container with id already exists.\n let existing = try? await ClientContainer.get(id: id)\n guard existing == nil else {\n throw ContainerizationError(\n .exists,\n message: \"container with id \\(id) already exists\"\n )\n }\n\n let ck = try await Utility.containerConfigFromFlags(\n id: id,\n image: image,\n arguments: arguments,\n process: processFlags,\n management: managementFlags,\n resource: resourceFlags,\n registry: registryFlags,\n progressUpdate: progress.handler\n )\n\n progress.set(description: \"Starting container\")\n\n let options = ContainerCreateOptions(autoRemove: managementFlags.remove)\n let container = try await ClientContainer.create(\n configuration: ck.0,\n options: options,\n kernel: ck.1\n )\n\n let detach = self.managementFlags.detach\n\n let process = try await container.bootstrap()\n progress.finish()\n\n do {\n let io = try ProcessIO.create(\n tty: self.processFlags.tty,\n interactive: self.processFlags.interactive,\n detach: detach\n )\n\n if !self.managementFlags.cidfile.isEmpty {\n let path = self.managementFlags.cidfile\n let data = id.data(using: .utf8)\n var attributes = [FileAttributeKey: Any]()\n attributes[.posixPermissions] = 0o644\n let success = FileManager.default.createFile(\n atPath: path,\n contents: data,\n attributes: attributes\n )\n guard success else {\n throw ContainerizationError(\n .internalError, message: \"failed to create cidfile at \\(path): \\(errno)\")\n }\n }\n\n if detach {\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n print(id)\n return\n }\n\n if !self.processFlags.tty {\n var handler = SignalThreshold(threshold: 3, signals: [SIGINT, SIGTERM])\n handler.start {\n print(\"Received 3 SIGINT/SIGTERM's, forcefully exiting.\")\n Darwin.exit(1)\n }\n }\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to run container: \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n\nstruct ProcessIO {\n let stdin: Pipe?\n let stdout: Pipe?\n let stderr: Pipe?\n var ioTracker: IoTracker?\n\n struct IoTracker {\n let stream: AsyncStream\n let cont: AsyncStream.Continuation\n let configuredStreams: Int\n }\n\n let stdio: [FileHandle?]\n\n let console: Terminal?\n\n func closeAfterStart() throws {\n try stdin?.fileHandleForReading.close()\n try stdout?.fileHandleForWriting.close()\n try stderr?.fileHandleForWriting.close()\n }\n\n func close() throws {\n try console?.reset()\n }\n\n static func create(tty: Bool, interactive: Bool, detach: Bool) throws -> ProcessIO {\n let current: Terminal? = try {\n if !tty || !interactive {\n return nil\n }\n let current = try Terminal.current\n try current.setraw()\n return current\n }()\n\n var stdio = [FileHandle?](repeating: nil, count: 3)\n\n let stdin: Pipe? = {\n if !interactive && !tty {\n return nil\n }\n return Pipe()\n }()\n\n if let stdin {\n if interactive {\n let pin = FileHandle.standardInput\n let stdinOSFile = OSFile(fd: pin.fileDescriptor)\n let pipeOSFile = OSFile(fd: stdin.fileHandleForWriting.fileDescriptor)\n try stdinOSFile.makeNonBlocking()\n nonisolated(unsafe) let buf = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n\n pin.readabilityHandler = { _ in\n Self.streamStdin(\n from: stdinOSFile,\n to: pipeOSFile,\n buffer: buf,\n ) {\n pin.readabilityHandler = nil\n buf.deallocate()\n try? stdin.fileHandleForWriting.close()\n }\n }\n }\n stdio[0] = stdin.fileHandleForReading\n }\n\n let stdout: Pipe? = {\n if detach {\n return nil\n }\n return Pipe()\n }()\n\n var configuredStreams = 0\n let (stream, cc) = AsyncStream.makeStream()\n if let stdout {\n configuredStreams += 1\n let pout: FileHandle = {\n if let current {\n return current.handle\n }\n return .standardOutput\n }()\n\n let rout = stdout.fileHandleForReading\n rout.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n rout.readabilityHandler = nil\n cc.yield()\n return\n }\n try! pout.write(contentsOf: data)\n }\n stdio[1] = stdout.fileHandleForWriting\n }\n\n let stderr: Pipe? = {\n if detach || tty {\n return nil\n }\n return Pipe()\n }()\n if let stderr {\n configuredStreams += 1\n let perr: FileHandle = .standardError\n let rerr = stderr.fileHandleForReading\n rerr.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n rerr.readabilityHandler = nil\n cc.yield()\n return\n }\n try! perr.write(contentsOf: data)\n }\n stdio[2] = stderr.fileHandleForWriting\n }\n\n var ioTracker: IoTracker? = nil\n if configuredStreams > 0 {\n ioTracker = .init(stream: stream, cont: cc, configuredStreams: configuredStreams)\n }\n\n return .init(\n stdin: stdin,\n stdout: stdout,\n stderr: stderr,\n ioTracker: ioTracker,\n stdio: stdio,\n console: current\n )\n }\n\n static func streamStdin(\n from: OSFile,\n to: OSFile,\n buffer: UnsafeMutableBufferPointer,\n onErrorOrEOF: () -> Void,\n ) {\n while true {\n let (bytesRead, action) = from.read(buffer)\n if bytesRead > 0 {\n let view = UnsafeMutableBufferPointer(\n start: buffer.baseAddress,\n count: bytesRead\n )\n\n let (bytesWritten, _) = to.write(view)\n if bytesWritten != bytesRead {\n onErrorOrEOF()\n return\n }\n }\n\n switch action {\n case .error(_), .eof, .brokenPipe:\n onErrorOrEOF()\n return\n case .again:\n return\n case .success:\n break\n }\n }\n }\n\n public func wait() async throws {\n guard let ioTracker = self.ioTracker else {\n return\n }\n do {\n try await Timeout.run(seconds: 3) {\n var counter = ioTracker.configuredStreams\n for await _ in ioTracker.stream {\n counter -= 1\n if counter == 0 {\n ioTracker.cont.finish()\n break\n }\n }\n }\n } catch {\n log.error(\"Timeout waiting for IO to complete : \\(error)\")\n throw error\n }\n }\n}\n\nstruct OSFile: Sendable {\n private let fd: Int32\n\n enum IOAction: Equatable {\n case eof\n case again\n case success\n case brokenPipe\n case error(_ errno: Int32)\n }\n\n init(fd: Int32) {\n self.fd = fd\n }\n\n init(handle: FileHandle) {\n self.fd = handle.fileDescriptor\n }\n\n func makeNonBlocking() throws {\n let flags = fcntl(fd, F_GETFL)\n guard flags != -1 else {\n throw POSIXError.fromErrno()\n }\n\n if fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1 {\n throw POSIXError.fromErrno()\n }\n }\n\n func write(_ buffer: UnsafeMutableBufferPointer) -> (wrote: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesWrote: Int = 0\n while true {\n let n = Darwin.write(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesWrote),\n buffer.count - bytesWrote\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesWrote, .again)\n }\n return (bytesWrote, .error(errno))\n }\n\n if n == 0 {\n return (bytesWrote, .brokenPipe)\n }\n\n bytesWrote += n\n if bytesWrote < buffer.count {\n continue\n }\n return (bytesWrote, .success)\n }\n }\n\n func read(_ buffer: UnsafeMutableBufferPointer) -> (read: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesRead: Int = 0\n while true {\n let n = Darwin.read(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesRead),\n buffer.count - bytesRead\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesRead, .again)\n }\n return (bytesRead, .error(errno))\n }\n\n if n == 0 {\n return (bytesRead, .eof)\n }\n\n bytesRead += n\n if bytesRead < buffer.count {\n continue\n }\n return (bytesRead, .success)\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginLoader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\npublic struct PluginLoader: Sendable {\n // A path on disk managed by the PluginLoader, where it stores\n // runtime data for loaded plugins. This includes the launchd plists\n // and logs files.\n private let defaultPluginResourcePath: URL\n\n private let pluginDirectories: [URL]\n\n private let pluginFactories: [PluginFactory]\n\n private let log: Logger?\n\n public typealias PluginQualifier = ((Plugin) -> Bool)\n\n public init(pluginDirectories: [URL], pluginFactories: [PluginFactory], defaultResourcePath: URL, log: Logger? = nil) {\n self.pluginDirectories = pluginDirectories\n self.pluginFactories = pluginFactories\n self.log = log\n self.defaultPluginResourcePath = defaultResourcePath\n }\n\n static public func defaultPluginResourcePath(root: URL) -> URL {\n root.appending(path: \"plugin-state\")\n }\n\n static public func userPluginsDir(root: URL) -> URL {\n root\n .appending(path: \"libexec\")\n .appending(path: \"container-plugins\")\n .resolvingSymlinksInPath()\n }\n}\n\nextension PluginLoader {\n public func alterCLIHelpText(original: String) -> String {\n var plugins = findPlugins()\n plugins = plugins.filter { $0.config.isCLI }\n guard !plugins.isEmpty else {\n return original\n }\n\n var lines = original.split(separator: \"\\n\").map { String($0) }\n\n let sectionHeader = \"PLUGINS:\"\n lines.append(sectionHeader)\n\n for plugin in plugins {\n let helpText = plugin.helpText(padding: 24)\n lines.append(helpText)\n }\n\n return lines.joined(separator: \"\\n\")\n }\n\n public func findPlugins() -> [Plugin] {\n let fm = FileManager.default\n\n var pluginNames = Set()\n var plugins: [Plugin] = []\n\n for pluginDir in pluginDirectories {\n if !fm.fileExists(atPath: pluginDir.path) {\n continue\n }\n\n guard\n var dirs = try? fm.contentsOfDirectory(\n at: pluginDir,\n includingPropertiesForKeys: [.isDirectoryKey],\n options: .skipsHiddenFiles\n )\n else {\n continue\n }\n dirs = dirs.filter {\n $0.isDirectory\n }\n\n for installURL in dirs {\n do {\n guard\n let plugin = try\n (pluginFactories.compactMap {\n try $0.create(installURL: installURL)\n }.first)\n else {\n log?.warning(\n \"Not installing plugin with missing configuration\",\n metadata: [\n \"path\": \"\\(installURL.path)\"\n ]\n )\n continue\n }\n\n guard !pluginNames.contains(plugin.name) else {\n log?.warning(\n \"Not installing shadowed plugin\",\n metadata: [\n \"path\": \"\\(installURL.path)\",\n \"name\": \"\\(plugin.name)\",\n ])\n continue\n }\n\n plugins.append(plugin)\n pluginNames.insert(plugin.name)\n } catch {\n log?.warning(\n \"Not installing plugin with invalid configuration\",\n metadata: [\n \"path\": \"\\(installURL.path)\",\n \"error\": \"\\(error)\",\n ]\n )\n }\n }\n }\n\n return plugins\n }\n\n public func findPlugin(name: String, log: Logger? = nil) -> Plugin? {\n do {\n return\n try pluginDirectories\n .compactMap { installURL in\n try pluginFactories.compactMap { try $0.create(installURL: installURL.appending(path: name)) }.first\n }\n .first\n } catch {\n log?.warning(\n \"Not installing plugin with invalid configuration\",\n metadata: [\n \"name\": \"\\(name)\",\n \"error\": \"\\(error)\",\n ]\n )\n return nil\n }\n }\n}\n\nextension PluginLoader {\n public func registerWithLaunchd(\n plugin: Plugin,\n rootURL: URL? = nil,\n args: [String]? = nil,\n instanceId: String? = nil\n ) throws {\n // We only care about loading plugins that have a service\n // to expose; otherwise, they may just be CLI commands.\n guard let serviceConfig = plugin.config.servicesConfig else {\n return\n }\n\n let id = plugin.getLaunchdLabel(instanceId: instanceId)\n log?.info(\"Registering plugin\", metadata: [\"id\": \"\\(id)\"])\n let rootURL = rootURL ?? self.defaultPluginResourcePath.appending(path: plugin.name)\n try FileManager.default.createDirectory(at: rootURL, withIntermediateDirectories: true)\n let env = ProcessInfo.processInfo.environment.filter { key, _ in\n key.hasPrefix(\"CONTAINER_\")\n }\n let logUrl = rootURL.appendingPathComponent(\"service.log\")\n let plist = LaunchPlist(\n label: id,\n arguments: [plugin.binaryURL.path] + (args ?? serviceConfig.defaultArguments),\n environment: env,\n limitLoadToSessionType: [.Aqua, .Background, .System],\n runAtLoad: serviceConfig.runAtLoad,\n stdout: logUrl.path,\n stderr: logUrl.path,\n machServices: plugin.getMachServices(instanceId: instanceId)\n )\n\n let plistUrl = rootURL.appendingPathComponent(\"service.plist\")\n let data = try plist.encode()\n try data.write(to: plistUrl)\n try ServiceManager.register(plistPath: plistUrl.path)\n }\n\n public func deregisterWithLaunchd(plugin: Plugin, instanceId: String? = nil) throws {\n // We only care about loading plugins that have a service\n // to expose; otherwise, they may just be CLI commands.\n guard plugin.config.servicesConfig != nil else {\n return\n }\n let domain = try ServiceManager.getDomainString()\n let label = \"\\(domain)/\\(plugin.getLaunchdLabel(instanceId: instanceId))\"\n log?.info(\"Deregistering plugin\", metadata: [\"id\": \"\\(plugin.getLaunchdLabel())\"])\n try ServiceManager.deregister(fullServiceLabel: label)\n }\n}\n"], ["/container/Sources/CLI/Image/ImageList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ListImageOptions: ParsableArguments {\n @Flag(name: .shortAndLong, help: \"Only output the image name\")\n var quiet = false\n\n @Flag(name: .shortAndLong, help: \"Verbose output\")\n var verbose = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n }\n\n struct ListImageImplementation {\n static private func createHeader() -> [[String]] {\n [[\"NAME\", \"TAG\", \"DIGEST\"]]\n }\n\n static private func createVerboseHeader() -> [[String]] {\n [[\"NAME\", \"TAG\", \"INDEX DIGEST\", \"OS\", \"ARCH\", \"VARIANT\", \"SIZE\", \"CREATED\", \"MANIFEST DIGEST\"]]\n }\n\n static private func printImagesVerbose(images: [ClientImage]) async throws {\n\n var rows = createVerboseHeader()\n for image in images {\n let formatter = ByteCountFormatter()\n for descriptor in try await image.index().manifests {\n // Don't list attestation manifests\n if let referenceType = descriptor.annotations?[\"vnd.docker.reference.type\"],\n referenceType == \"attestation-manifest\"\n {\n continue\n }\n\n guard let platform = descriptor.platform else {\n continue\n }\n\n let os = platform.os\n let arch = platform.architecture\n let variant = platform.variant ?? \"\"\n\n var config: ContainerizationOCI.Image\n var manifest: ContainerizationOCI.Manifest\n do {\n config = try await image.config(for: platform)\n manifest = try await image.manifest(for: platform)\n } catch {\n continue\n }\n\n let created = config.created ?? \"\"\n let size = descriptor.size + manifest.config.size + manifest.layers.reduce(0, { (l, r) in l + r.size })\n let formattedSize = formatter.string(fromByteCount: size)\n\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n let reference = try ContainerizationOCI.Reference.parse(processedReferenceString)\n let row = [\n reference.name,\n reference.tag ?? \"\",\n Utility.trimDigest(digest: image.descriptor.digest),\n os,\n arch,\n variant,\n formattedSize,\n created,\n Utility.trimDigest(digest: descriptor.digest),\n ]\n rows.append(row)\n }\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n\n static private func printImages(images: [ClientImage], format: ListFormat, options: ListImageOptions) async throws {\n var images = images\n images.sort {\n $0.reference < $1.reference\n }\n\n if format == .json {\n let data = try JSONEncoder().encode(images.map { $0.description })\n print(String(data: data, encoding: .utf8)!)\n return\n }\n\n if options.quiet {\n try images.forEach { image in\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n print(processedReferenceString)\n }\n return\n }\n\n if options.verbose {\n try await Self.printImagesVerbose(images: images)\n return\n }\n\n var rows = createHeader()\n for image in images {\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n let reference = try ContainerizationOCI.Reference.parse(processedReferenceString)\n rows.append([\n reference.name,\n reference.tag ?? \"\",\n Utility.trimDigest(digest: image.descriptor.digest),\n ])\n }\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n\n static func validate(options: ListImageOptions) throws {\n if options.quiet && options.verbose {\n throw ContainerizationError(.invalidArgument, message: \"Cannot use flag --quite and --verbose together\")\n }\n let modifier = options.quiet || options.verbose\n if modifier && options.format == .json {\n throw ContainerizationError(.invalidArgument, message: \"Cannot use flag --quite or --verbose along with --format json\")\n }\n }\n\n static func listImages(options: ListImageOptions) async throws {\n let images = try await ClientImage.list().filter { img in\n !Utility.isInfraImage(name: img.reference)\n }\n try await printImages(images: images, format: options.format, options: options)\n }\n }\n\n struct ImageList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List images\",\n aliases: [\"ls\"])\n\n @OptionGroup\n var options: ListImageOptions\n\n mutating func run() async throws {\n try ListImageImplementation.validate(options: options)\n try await ListImageImplementation.listImages(options: options)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\npublic struct ClientNetwork {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n\n public static let defaultNetworkName = \"default\"\n}\n\nextension ClientNetwork {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n private static func xpcSend(\n client: XPCClient,\n message: XPCMessage,\n timeout: Duration? = .seconds(15)\n ) async throws -> XPCMessage {\n try await client.send(message, responseTimeout: timeout)\n }\n\n public static func create(configuration: NetworkConfiguration) async throws -> NetworkState {\n let client = Self.newClient()\n let request = XPCMessage(route: .networkCreate)\n request.set(key: .networkId, value: configuration.id)\n\n let data = try JSONEncoder().encode(configuration)\n request.set(key: .networkConfig, value: data)\n\n let response = try await xpcSend(client: client, message: request)\n let responseData = response.dataNoCopy(key: .networkState)\n guard let responseData else {\n throw ContainerizationError(.invalidArgument, message: \"network configuration not received\")\n }\n let state = try JSONDecoder().decode(NetworkState.self, from: responseData)\n return state\n }\n\n public static func list() async throws -> [NetworkState] {\n let client = Self.newClient()\n let request = XPCMessage(route: .networkList)\n\n let response = try await xpcSend(client: client, message: request, timeout: .seconds(1))\n let responseData = response.dataNoCopy(key: .networkStates)\n guard let responseData else {\n return []\n }\n let states = try JSONDecoder().decode([NetworkState].self, from: responseData)\n return states\n }\n\n /// Get the network for the provided id.\n public static func get(id: String) async throws -> NetworkState {\n let networks = try await list()\n guard let network = networks.first(where: { $0.id == id }) else {\n throw ContainerizationError(.notFound, message: \"network \\(id) not found\")\n }\n return network\n }\n\n /// Delete the network with the given id.\n public static func delete(id: String) async throws {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .networkDelete)\n request.set(key: .networkId, value: id)\n try await client.send(request)\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationExtras\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ContainerList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List containers\",\n aliases: [\"ls\"])\n\n @Flag(name: .shortAndLong, help: \"Show stopped containers as well\")\n var all = false\n\n @Flag(name: .shortAndLong, help: \"Only output the container ID\")\n var quiet = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let containers = try await ClientContainer.list()\n try printContainers(containers: containers, format: format)\n }\n\n private func createHeader() -> [[String]] {\n [[\"ID\", \"IMAGE\", \"OS\", \"ARCH\", \"STATE\", \"ADDR\"]]\n }\n\n private func printContainers(containers: [ClientContainer], format: ListFormat) throws {\n if format == .json {\n let printables = containers.map {\n PrintableContainer($0)\n }\n let data = try JSONEncoder().encode(printables)\n print(String(data: data, encoding: .utf8)!)\n\n return\n }\n\n if self.quiet {\n containers.forEach {\n if !self.all && $0.status != .running {\n return\n }\n print($0.id)\n }\n return\n }\n\n var rows = createHeader()\n for container in containers {\n if !self.all && container.status != .running {\n continue\n }\n rows.append(container.asRow)\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n }\n}\n\nextension ClientContainer {\n var asRow: [String] {\n [\n self.id,\n self.configuration.image.reference,\n self.configuration.platform.os,\n self.configuration.platform.architecture,\n self.status.rawValue,\n self.networks.compactMap { try? CIDRAddress($0.address).address.description }.joined(separator: \",\"),\n ]\n }\n}\n\nstruct PrintableContainer: Codable {\n let status: RuntimeStatus\n let configuration: ContainerConfiguration\n let networks: [Attachment]\n\n init(_ container: ClientContainer) {\n self.status = container.status\n self.configuration = container.configuration\n self.networks = container.networks\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderDelete: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"delete\"\n config._superCommandName = \"builder\"\n config.abstract = \"Delete builder\"\n config.usage = \"\\n\\t builder delete [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Flag(name: .shortAndLong, help: \"Force delete builder even if it is running\")\n var force = false\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n if container.status != .stopped {\n guard force else {\n throw ContainerizationError(.invalidState, message: \"BuildKit container is not stopped, use --force to override\")\n }\n try await container.stop()\n }\n try await container.delete()\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\n\npublic struct XPCClient: Sendable {\n private nonisolated(unsafe) let connection: xpc_connection_t\n private let q: DispatchQueue?\n private let service: String\n\n public init(service: String, queue: DispatchQueue? = nil) {\n let connection = xpc_connection_create_mach_service(service, queue, 0)\n self.connection = connection\n self.q = queue\n self.service = service\n\n xpc_connection_set_event_handler(connection) { _ in }\n xpc_connection_set_target_queue(connection, self.q)\n xpc_connection_activate(connection)\n }\n}\n\nextension XPCClient {\n /// Close the underlying XPC connection.\n public func close() {\n xpc_connection_cancel(connection)\n }\n\n /// Returns the pid of process to which we have a connection.\n /// Note: `xpc_connection_get_pid` returns 0 if no activity\n /// has taken place on the connection prior to it being called.\n public func remotePid() -> pid_t {\n xpc_connection_get_pid(self.connection)\n }\n\n /// Send the provided message to the service.\n @discardableResult\n public func send(_ message: XPCMessage, responseTimeout: Duration? = nil) async throws -> XPCMessage {\n try await withThrowingTaskGroup(of: XPCMessage.self, returning: XPCMessage.self) { group in\n if let responseTimeout {\n group.addTask {\n try await Task.sleep(for: responseTimeout)\n let route = message.string(key: XPCMessage.routeKey) ?? \"nil\"\n throw ContainerizationError(.internalError, message: \"XPC timeout for request to \\(self.service)/\\(route)\")\n }\n }\n\n group.addTask {\n try await withCheckedThrowingContinuation { cont in\n xpc_connection_send_message_with_reply(self.connection, message.underlying, nil) { reply in\n do {\n let message = try self.parseReply(reply)\n cont.resume(returning: message)\n } catch {\n cont.resume(throwing: error)\n }\n }\n }\n }\n\n let response = try await group.next()\n // once one task has finished, cancel the rest.\n group.cancelAll()\n // we don't really care about the second error here\n // as it's most likely a `CancellationError`.\n try? await group.waitForAll()\n\n guard let response else {\n throw ContainerizationError(.invalidState, message: \"failed to receive XPC response\")\n }\n return response\n }\n }\n\n private func parseReply(_ reply: xpc_object_t) throws -> XPCMessage {\n switch xpc_get_type(reply) {\n case XPC_TYPE_ERROR:\n var code = ContainerizationError.Code.invalidState\n if reply.connectionError {\n code = .interrupted\n }\n throw ContainerizationError(\n code,\n message: \"XPC connection error: \\(reply.errorDescription ?? \"unknown\")\"\n )\n case XPC_TYPE_DICTIONARY:\n let message = XPCMessage(object: reply)\n // check errors from our protocol\n try message.error()\n return message\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(reply))\")\n }\n }\n}\n\n#endif\n"], ["/container/Sources/APIServer/Containers/ContainersService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CVersion\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerSandboxService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ContainersService {\n private static let machServicePrefix = \"com.apple.container\"\n private static let launchdDomainString = try! ServiceManager.getDomainString()\n\n private let log: Logger\n private let containerRoot: URL\n private let pluginLoader: PluginLoader\n private let runtimePlugins: [Plugin]\n\n private let lock = AsyncLock()\n private var containers: [String: Item]\n\n struct Item: Sendable {\n let bundle: ContainerClient.Bundle\n var state: State\n\n enum State: Sendable {\n case dead\n case alive(SandboxClient)\n case exited(Int32)\n\n func isDead() -> Bool {\n switch self {\n case .dead: return true\n default: return false\n }\n }\n }\n }\n\n public init(root: URL, pluginLoader: PluginLoader, log: Logger) throws {\n let containerRoot = root.appendingPathComponent(\"containers\")\n try FileManager.default.createDirectory(at: containerRoot, withIntermediateDirectories: true)\n self.containerRoot = containerRoot\n self.pluginLoader = pluginLoader\n self.log = log\n self.runtimePlugins = pluginLoader.findPlugins().filter { $0.hasType(.runtime) }\n self.containers = try Self.loadAtBoot(root: containerRoot, loader: pluginLoader, log: log)\n }\n\n static func loadAtBoot(root: URL, loader: PluginLoader, log: Logger) throws -> [String: Item] {\n var directories = try FileManager.default.contentsOfDirectory(\n at: root,\n includingPropertiesForKeys: [.isDirectoryKey]\n )\n directories = directories.filter {\n $0.isDirectory\n }\n\n let runtimePlugins = loader.findPlugins().filter { $0.hasType(.runtime) }\n var results = [String: Item]()\n for dir in directories {\n do {\n let bundle = ContainerClient.Bundle(path: dir)\n let config = try bundle.configuration\n results[config.id] = .init(bundle: bundle, state: .dead)\n let plugin = runtimePlugins.first { $0.name == config.runtimeHandler }\n guard let plugin else {\n throw ContainerizationError(.internalError, message: \"Failed to find runtime plugin \\(config.runtimeHandler)\")\n }\n try Self.registerService(plugin: plugin, loader: loader, configuration: config, path: dir)\n } catch {\n try? FileManager.default.removeItem(at: dir)\n log.warning(\"failed to load container bundle at \\(dir.path)\")\n }\n }\n return results\n }\n\n private func setContainer(_ id: String, _ item: Item, context: AsyncLock.Context) async {\n self.containers[id] = item\n }\n\n /// List all containers registered with the service.\n public func list() async throws -> [ContainerSnapshot] {\n self.log.debug(\"\\(#function)\")\n return await lock.withLock { context in\n var snapshots = [ContainerSnapshot]()\n\n for (id, item) in await self.containers {\n do {\n let result = try await item.asSnapshot()\n snapshots.append(result.0)\n } catch {\n self.log.error(\"unable to load bundle for \\(id) \\(error)\")\n }\n }\n return snapshots\n }\n }\n\n /// Create a new container from the provided id and configuration.\n public func create(configuration: ContainerConfiguration, kernel: Kernel, options: ContainerCreateOptions) async throws {\n self.log.debug(\"\\(#function)\")\n\n let runtimePlugin = self.runtimePlugins.filter {\n $0.name == configuration.runtimeHandler\n }.first\n guard let runtimePlugin else {\n throw ContainerizationError(.notFound, message: \"unable to locate runtime plugin \\(configuration.runtimeHandler)\")\n }\n\n let path = self.containerRoot.appendingPathComponent(configuration.id)\n let systemPlatform = kernel.platform\n let initFs = try await getInitBlock(for: systemPlatform.ociPlatform())\n\n let bundle = try ContainerClient.Bundle.create(\n path: path,\n initialFilesystem: initFs,\n kernel: kernel,\n containerConfiguration: configuration\n )\n do {\n let containerImage = ClientImage(description: configuration.image)\n let imageFs = try await containerImage.getCreateSnapshot(platform: configuration.platform)\n try bundle.setContainerRootFs(cloning: imageFs)\n try bundle.write(filename: \"options.json\", value: options)\n\n try Self.registerService(\n plugin: runtimePlugin,\n loader: self.pluginLoader,\n configuration: configuration,\n path: path\n )\n } catch {\n do {\n try bundle.delete()\n } catch {\n self.log.error(\"failed to delete bundle for container \\(configuration.id): \\(error)\")\n }\n throw error\n }\n self.containers[configuration.id] = Item(bundle: bundle, state: .dead)\n }\n\n private func getInitBlock(for platform: Platform) async throws -> Filesystem {\n let initImage = try await ClientImage.fetch(reference: ClientImage.initImageRef, platform: platform)\n var fs = try await initImage.getCreateSnapshot(platform: platform)\n fs.options = [\"ro\"]\n return fs\n }\n\n private static func registerService(\n plugin: Plugin,\n loader: PluginLoader,\n configuration: ContainerConfiguration,\n path: URL\n ) throws {\n let args = [\n \"--root\", path.path,\n \"--uuid\", configuration.id,\n \"--debug\",\n ]\n try loader.registerWithLaunchd(\n plugin: plugin,\n rootURL: path,\n args: args,\n instanceId: configuration.id\n )\n }\n\n private func get(id: String, context: AsyncLock.Context) throws -> Item {\n try self._get(id: id)\n }\n\n private func _get(id: String) throws -> Item {\n let item = self.containers[id]\n guard let item else {\n throw ContainerizationError(\n .notFound,\n message: \"container with ID \\(id) not found\"\n )\n }\n return item\n }\n\n /// Delete a container and its resources.\n public func delete(id: String) async throws {\n self.log.debug(\"\\(#function)\")\n let item = try self._get(id: id)\n switch item.state {\n case .alive(let client):\n let state = try await client.state()\n if state.status == .running || state.status == .stopping {\n throw ContainerizationError(\n .invalidState,\n message: \"container \\(id) is not yet stopped and can not be deleted\"\n )\n }\n try self._cleanup(id: id, item: item)\n case .dead, .exited(_):\n try self._cleanup(id: id, item: item)\n }\n }\n\n private static func fullLaunchdServiceLabel(runtimeName: String, instanceId: String) -> String {\n \"\\(Self.launchdDomainString)/\\(Self.machServicePrefix).\\(runtimeName).\\(instanceId)\"\n }\n\n private func _cleanup(id: String, item: Item) throws {\n self.log.debug(\"\\(#function)\")\n let config = try item.bundle.configuration\n let label = Self.fullLaunchdServiceLabel(runtimeName: config.runtimeHandler, instanceId: id)\n try ServiceManager.deregister(fullServiceLabel: label)\n try item.bundle.delete()\n self.containers.removeValue(forKey: id)\n }\n\n private func _shutdown(id: String, item: Item) throws {\n let config = try item.bundle.configuration\n let label = Self.fullLaunchdServiceLabel(runtimeName: config.runtimeHandler, instanceId: id)\n try ServiceManager.kill(fullServiceLabel: label)\n }\n\n private func cleanup(id: String, item: Item, context: AsyncLock.Context) async throws {\n try self._cleanup(id: id, item: item)\n }\n\n private func containerProcessExitHandler(_ id: String, _ exitCode: Int32, context: AsyncLock.Context) async {\n self.log.info(\"Handling container \\(id) exit. Code \\(exitCode)\")\n do {\n var item = try self.get(id: id, context: context)\n switch item.state {\n case .dead, .exited(_):\n break\n case .alive(_):\n item.state = .exited(exitCode)\n await self.setContainer(id, item, context: context)\n }\n let options: ContainerCreateOptions = try item.bundle.load(filename: \"options.json\")\n if options.autoRemove {\n try await self.cleanup(id: id, item: item, context: context)\n }\n } catch {\n self.log.error(\n \"Failed to handle container exit\",\n metadata: [\n \"id\": .string(id),\n \"error\": .string(String(describing: error)),\n ])\n }\n }\n\n private func containerStartHandler(_ id: String, context: AsyncLock.Context) async throws {\n self.log.debug(\"\\(#function)\")\n self.log.info(\"Handling container \\(id) Start.\")\n do {\n var item = try self.get(id: id, context: context)\n let configuration = try item.bundle.configuration\n let client = SandboxClient(id: configuration.id, runtime: configuration.runtimeHandler)\n item.state = .alive(client)\n await self.setContainer(id, item, context: context)\n } catch {\n self.log.error(\n \"Failed to handle container start\",\n metadata: [\n \"id\": .string(id),\n \"error\": .string(String(describing: error)),\n ])\n }\n }\n}\n\nextension ContainersService {\n public func handleContainerEvents(event: ContainerEvent) async throws {\n self.log.debug(\"\\(#function)\")\n try await self.lock.withLock { context in\n switch event {\n case .containerExit(let id, let code):\n await self.containerProcessExitHandler(id, Int32(code), context: context)\n case .containerStart(let id):\n try await self.containerStartHandler(id, context: context)\n }\n }\n }\n\n /// Stop all containers inside the sandbox, aborting any processes currently\n /// executing inside the container, before stopping the underlying sandbox.\n public func stop(id: String, options: ContainerStopOptions) async throws {\n self.log.debug(\"\\(#function)\")\n try await lock.withLock { context in\n let item = try await self.get(id: id, context: context)\n switch item.state {\n case .dead, .exited(_):\n return\n case .alive(let client):\n try await client.stop(options: options)\n }\n }\n }\n\n public func logs(id: String) async throws -> [FileHandle] {\n self.log.debug(\"\\(#function)\")\n // Logs doesn't care if the container is running or not, just that\n // the bundle is there, and that the files actually exist.\n do {\n let item = try self._get(id: id)\n return [\n try FileHandle(forReadingFrom: item.bundle.containerLog),\n try FileHandle(forReadingFrom: item.bundle.bootlog),\n ]\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to open container logs: \\(error)\"\n )\n }\n }\n}\n\nextension ContainersService.Item {\n func asSnapshot() async throws -> (ContainerSnapshot, RuntimeStatus) {\n let config = try self.bundle.configuration\n\n switch self.state {\n case .dead, .exited(_):\n return (\n .init(\n configuration: config,\n status: RuntimeStatus.stopped,\n networks: []\n ), .stopped\n )\n case .alive(let client):\n let state = try await client.state()\n return (\n .init(\n configuration: config,\n status: state.status,\n networks: state.networks\n ), state.status\n )\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Parser.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\npublic struct Parser {\n public static func memoryString(_ memory: String) throws -> Int64 {\n let ram = try Measurement.parse(parsing: memory)\n let mb = ram.converted(to: .mebibytes)\n return Int64(mb.value)\n }\n\n public static func user(\n user: String?, uid: UInt32?, gid: UInt32?,\n defaultUser: ProcessConfiguration.User = .id(uid: 0, gid: 0)\n ) -> (user: ProcessConfiguration.User, groups: [UInt32]) {\n\n var supplementalGroups: [UInt32] = []\n let user: ProcessConfiguration.User = {\n if let user = user, !user.isEmpty {\n return .raw(userString: user)\n }\n if let uid, let gid {\n return .id(uid: uid, gid: gid)\n }\n if uid == nil, gid == nil {\n // Neither uid nor gid is set. return the default user\n return defaultUser\n }\n // One of uid / gid is left unspecified. Set the user accordingly\n if let uid {\n return .raw(userString: \"\\(uid)\")\n }\n if let gid {\n supplementalGroups.append(gid)\n }\n return defaultUser\n }()\n return (user, supplementalGroups)\n }\n\n public static func platform(os: String, arch: String) -> ContainerizationOCI.Platform {\n .init(arch: arch, os: os)\n }\n\n public static func resources(cpus: Int64?, memory: String?) throws -> ContainerConfiguration.Resources {\n var resource = ContainerConfiguration.Resources()\n if let cpus {\n resource.cpus = Int(cpus)\n }\n if let memory {\n resource.memoryInBytes = try Parser.memoryString(memory).mib()\n }\n return resource\n }\n\n public static func allEnv(imageEnvs: [String], envFiles: [String], envs: [String]) throws -> [String] {\n var output: [String] = []\n output.append(contentsOf: Parser.env(envList: imageEnvs))\n for envFile in envFiles {\n let content = try Parser.envFile(path: envFile)\n output.append(contentsOf: content)\n }\n output.append(contentsOf: Parser.env(envList: envs))\n return output\n }\n\n static func envFile(path: String) throws -> [String] {\n guard FileManager.default.fileExists(atPath: path) else {\n throw ContainerizationError(.notFound, message: \"envfile at \\(path) not found\")\n }\n\n let data = try String(contentsOfFile: path, encoding: .utf8)\n let lines = data.components(separatedBy: .newlines)\n var envVars: [String] = []\n for line in lines {\n let line = line.trimmingCharacters(in: .whitespaces)\n if line.isEmpty {\n continue\n }\n if !line.hasPrefix(\"#\") {\n let keyVals = line.split(separator: \"=\")\n if keyVals.count != 2 {\n continue\n }\n let key = keyVals[0].trimmingCharacters(in: .whitespaces)\n let val = keyVals[1].trimmingCharacters(in: .whitespaces)\n if key.isEmpty || val.isEmpty {\n continue\n }\n envVars.append(\"\\(key)=\\(val)\")\n }\n }\n return envVars\n }\n\n static func env(envList: [String]) -> [String] {\n var envVar: [String] = []\n for env in envList {\n var env = env\n let parts = env.split(separator: \"=\", maxSplits: 2)\n if parts.count == 1 {\n guard let val = ProcessInfo.processInfo.environment[env] else {\n continue\n }\n env = \"\\(env)=\\(val)\"\n }\n envVar.append(env)\n }\n return envVar\n }\n\n static func labels(_ rawLabels: [String]) throws -> [String: String] {\n var result: [String: String] = [:]\n for label in rawLabels {\n if label.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"label cannot be an empty string\")\n }\n let parts = label.split(separator: \"=\", maxSplits: 2)\n switch parts.count {\n case 1:\n result[String(parts[0])] = \"\"\n case 2:\n result[String(parts[0])] = String(parts[1])\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid label format \\(label)\")\n }\n }\n return result\n }\n\n static func process(\n arguments: [String],\n processFlags: Flags.Process,\n managementFlags: Flags.Management,\n config: ContainerizationOCI.ImageConfig?\n ) throws -> ProcessConfiguration {\n\n let imageEnvVars = config?.env ?? []\n let envvars = try Parser.allEnv(imageEnvs: imageEnvVars, envFiles: processFlags.envFile, envs: processFlags.env)\n\n let workingDir: String = {\n if let cwd = processFlags.cwd {\n return cwd\n }\n if let cwd = config?.workingDir {\n return cwd\n }\n return \"/\"\n }()\n\n let processArguments: [String]? = {\n var result: [String] = []\n var hasEntrypointOverride: Bool = false\n // ensure the entrypoint is honored if it has been explicitly set by the user\n if let entrypoint = managementFlags.entryPoint, !entrypoint.isEmpty {\n result = [entrypoint]\n hasEntrypointOverride = true\n } else if let entrypoint = config?.entrypoint, !entrypoint.isEmpty {\n result = entrypoint\n }\n if !arguments.isEmpty {\n result.append(contentsOf: arguments)\n } else {\n if let cmd = config?.cmd, !hasEntrypointOverride, !cmd.isEmpty {\n result.append(contentsOf: cmd)\n }\n }\n return result.count > 0 ? result : nil\n }()\n\n guard let commandToRun = processArguments, commandToRun.count > 0 else {\n throw ContainerizationError(.invalidArgument, message: \"Command/Entrypoint not specified for container process\")\n }\n\n let defaultUser: ProcessConfiguration.User = {\n if let u = config?.user {\n return .raw(userString: u)\n }\n return .id(uid: 0, gid: 0)\n }()\n\n let (user, additionalGroups) = Parser.user(\n user: processFlags.user, uid: processFlags.uid,\n gid: processFlags.gid, defaultUser: defaultUser)\n\n return .init(\n executable: commandToRun.first!,\n arguments: [String](commandToRun.dropFirst()),\n environment: envvars,\n workingDirectory: workingDir,\n terminal: processFlags.tty,\n user: user,\n supplementalGroups: additionalGroups\n )\n }\n\n // MARK: Mounts\n\n static let mountTypes = [\n \"virtiofs\",\n \"bind\",\n \"tmpfs\",\n ]\n\n static let defaultDirectives = [\"type\": \"virtiofs\"]\n\n static func tmpfsMounts(_ mounts: [String]) throws -> [Filesystem] {\n var result: [Filesystem] = []\n let mounts = mounts.dedupe()\n for tmpfs in mounts {\n let fs = Filesystem.tmpfs(destination: tmpfs, options: [])\n try validateMount(fs)\n result.append(fs)\n }\n return result\n }\n\n static func mounts(_ rawMounts: [String]) throws -> [Filesystem] {\n var mounts: [Filesystem] = []\n let rawMounts = rawMounts.dedupe()\n for mount in rawMounts {\n let m = try Parser.mount(mount)\n try validateMount(m)\n mounts.append(m)\n }\n return mounts\n }\n\n static func mount(_ mount: String) throws -> Filesystem {\n let parts = mount.split(separator: \",\")\n if parts.count == 0 {\n throw ContainerizationError(.invalidArgument, message: \"invalid mount format: \\(mount)\")\n }\n var directives = defaultDirectives\n for part in parts {\n let keyVal = part.split(separator: \"=\", maxSplits: 2)\n var key = String(keyVal[0])\n var skipValue = false\n switch key {\n case \"type\", \"size\", \"mode\":\n break\n case \"source\", \"src\":\n key = \"source\"\n case \"destination\", \"dst\", \"target\":\n key = \"destination\"\n case \"readonly\", \"ro\":\n key = \"ro\"\n skipValue = true\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown directive \\(key) when parsing mount \\(mount)\")\n }\n var value = \"\"\n if !skipValue {\n if keyVal.count != 2 {\n throw ContainerizationError(.invalidArgument, message: \"invalid directive format missing value \\(part) in \\(mount)\")\n }\n value = String(keyVal[1])\n }\n directives[key] = value\n }\n\n var fs = Filesystem()\n for (key, val) in directives {\n var val = val\n let type = directives[\"type\"] ?? \"\"\n\n switch key {\n case \"type\":\n if val == \"bind\" {\n val = \"virtiofs\"\n }\n switch val {\n case \"virtiofs\":\n fs.type = Filesystem.FSType.virtiofs\n case \"tmpfs\":\n fs.type = Filesystem.FSType.tmpfs\n default:\n throw ContainerizationError(.invalidArgument, message: \"unsupported mount type \\(val)\")\n }\n\n case \"ro\":\n fs.options.append(\"ro\")\n case \"size\":\n if type != \"tmpfs\" {\n throw ContainerizationError(.invalidArgument, message: \"unsupported option size for \\(type) mount\")\n }\n var overflow: Bool\n var memory = try Parser.memoryString(val)\n (memory, overflow) = memory.multipliedReportingOverflow(by: 1024 * 1024)\n if overflow {\n throw ContainerizationError(.invalidArgument, message: \"overflow encountered when parsing memory string: \\(val)\")\n }\n let s = \"size=\\(memory)\"\n fs.options.append(s)\n case \"mode\":\n if type != \"tmpfs\" {\n throw ContainerizationError(.invalidArgument, message: \"unsupported option mode for \\(type) mount\")\n }\n let s = \"mode=\\(val)\"\n fs.options.append(s)\n case \"source\":\n let absPath = URL(filePath: val).absoluteURL.path\n switch type {\n case \"virtiofs\", \"bind\":\n fs.source = absPath\n case \"tmpfs\":\n throw ContainerizationError(.invalidArgument, message: \"cannot specify source for tmpfs mount\")\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown mount type \\(type)\")\n }\n case \"destination\":\n fs.destination = val\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown mount directive \\(key)\")\n }\n }\n return fs\n }\n\n static func volumes(_ rawVolumes: [String]) throws -> [Filesystem] {\n var mounts: [Filesystem] = []\n for volume in rawVolumes {\n let m = try Parser.volume(volume)\n try Parser.validateMount(m)\n mounts.append(m)\n }\n return mounts\n }\n\n private static func volume(_ volume: String) throws -> Filesystem {\n var vol = volume\n vol.trimLeft(char: \":\")\n\n let parts = vol.split(separator: \":\")\n switch parts.count {\n case 1:\n throw ContainerizationError(.invalidArgument, message: \"anonymous volumes are not supported\")\n case 2, 3:\n // Bind / volume mounts.\n let src = String(parts[0])\n let dst = String(parts[1])\n\n let abs = URL(filePath: src).absoluteURL.path\n if !FileManager.default.fileExists(atPath: abs) {\n throw ContainerizationError(.invalidArgument, message: \"named volumes are not supported\")\n }\n\n var fs = Filesystem.virtiofs(\n source: URL(fileURLWithPath: src).absolutePath(),\n destination: dst,\n options: []\n )\n if parts.count == 3 {\n fs.options = parts[2].split(separator: \",\").map { String($0) }\n }\n return fs\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid volume format \\(volume)\")\n }\n }\n\n static func validMountType(_ type: String) -> Bool {\n mountTypes.contains(type)\n }\n\n static func validateMount(_ mount: Filesystem) throws {\n if !mount.isTmpfs {\n if !mount.source.isAbsolutePath() {\n throw ContainerizationError(\n .invalidArgument, message: \"\\(mount.source) is not an absolute path on the host\")\n }\n if !FileManager.default.fileExists(atPath: mount.source) {\n throw ContainerizationError(.invalidArgument, message: \"file path '\\(mount.source)' does not exist\")\n }\n }\n\n if mount.destination.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"mount destination cannot be empty\")\n }\n }\n\n /// Parse --publish-port arguments into PublishPort objects\n /// The format of each argument is `[host-ip:]host-port:container-port[/protocol]`\n /// (e.g., \"127.0.0.1:8080:80/tcp\")\n ///\n /// - Parameter rawPublishPorts: Array of port arguments\n /// - Returns: Array of PublishPort objects\n /// - Throws: ContainerizationError if parsing fails\n static func publishPorts(_ rawPublishPorts: [String]) throws -> [PublishPort] {\n var sockets: [PublishPort] = []\n\n // Process each raw port string\n for socket in rawPublishPorts {\n let parsedSocket = try Parser.publishPort(socket)\n sockets.append(parsedSocket)\n }\n return sockets\n }\n\n // Parse a single `--publish-port` argument into a `PublishPort`.\n private static func publishPort(_ portText: String) throws -> PublishPort {\n let protoSplit = portText.split(separator: \"/\")\n let proto: PublishProtocol\n let addressAndPortText: String\n switch protoSplit.count {\n case 1:\n addressAndPortText = String(protoSplit[0])\n proto = .tcp\n case 2:\n addressAndPortText = String(protoSplit[0])\n let protoText = String(protoSplit[1])\n guard let parsedProto = PublishProtocol(protoText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish protocol: \\(protoText)\")\n }\n proto = parsedProto\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid publish value: \\(portText)\")\n }\n\n let hostAddress: String\n let hostPortText: String\n let containerPortText: String\n let parts = addressAndPortText.split(separator: \":\")\n switch parts.count {\n case 2:\n hostAddress = \"0.0.0.0\"\n hostPortText = String(parts[0])\n containerPortText = String(parts[1])\n case 3:\n hostAddress = String(parts[0])\n hostPortText = String(parts[1])\n containerPortText = String(parts[2])\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid publish address: \\(portText)\")\n }\n\n guard let hostPort = Int(hostPortText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish host port: \\(hostPortText)\")\n }\n\n guard let containerPort = Int(containerPortText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish container port: \\(containerPortText)\")\n }\n\n return PublishPort(\n hostAddress: hostAddress,\n hostPort: hostPort,\n containerPort: containerPort,\n proto: proto\n )\n }\n\n /// Parse --publish-socket arguments into PublishSocket objects\n /// The format of each argument is `host_path:container_path`\n /// (e.g., \"/tmp/docker.sock:/var/run/docker.sock\")\n ///\n /// - Parameter rawPublishSockets: Array of socket arguments\n /// - Returns: Array of PublishSocket objects\n /// - Throws: ContainerizationError if parsing fails or a path is invalid\n static func publishSockets(_ rawPublishSockets: [String]) throws -> [PublishSocket] {\n var sockets: [PublishSocket] = []\n\n // Process each raw socket string\n for socket in rawPublishSockets {\n let parsedSocket = try Parser.publishSocket(socket)\n sockets.append(parsedSocket)\n }\n return sockets\n }\n\n // Parse a single `--publish-socket`` argument into a `PublishSocket`.\n private static func publishSocket(_ socketText: String) throws -> PublishSocket {\n // Split by colon to two parts: [host_path, container_path]\n let parts = socketText.split(separator: \":\")\n\n switch parts.count {\n case 2:\n // Extract host and container paths\n let hostPath = String(parts[0])\n let containerPath = String(parts[1])\n\n // Validate paths are not empty\n if hostPath.isEmpty {\n throw ContainerizationError(\n .invalidArgument, message: \"host socket path cannot be empty\")\n }\n if containerPath.isEmpty {\n throw ContainerizationError(\n .invalidArgument, message: \"container socket path cannot be empty\")\n }\n\n // Ensure container path must start with /\n if !containerPath.hasPrefix(\"/\") {\n throw ContainerizationError(\n .invalidArgument,\n message: \"container socket path must be absolute: \\(containerPath)\")\n }\n\n // Convert host path to absolute path for consistency\n let hostURL = URL(fileURLWithPath: hostPath)\n let absoluteHostPath = hostURL.absoluteURL.path\n\n // Check if host socket already exists and might be in use\n if FileManager.default.fileExists(atPath: absoluteHostPath) {\n do {\n let attrs = try FileManager.default.attributesOfItem(atPath: absoluteHostPath)\n if let fileType = attrs[.type] as? FileAttributeType, fileType == .typeSocket {\n throw ContainerizationError(\n .invalidArgument,\n message: \"host socket \\(absoluteHostPath) already exists and may be in use\")\n }\n // If it exists but is not a socket, we can remove it and create socket\n try FileManager.default.removeItem(atPath: absoluteHostPath)\n } catch let error as ContainerizationError {\n throw error\n } catch {\n // For other file system errors, continue with creation\n }\n }\n\n // Create host directory if it doesn't exist\n let hostDir = hostURL.deletingLastPathComponent()\n if !FileManager.default.fileExists(atPath: hostDir.path) {\n try FileManager.default.createDirectory(\n at: hostDir, withIntermediateDirectories: true)\n }\n\n // Create and return PublishSocket object with validated paths\n return PublishSocket(\n containerPath: URL(fileURLWithPath: containerPath),\n hostPath: URL(fileURLWithPath: absoluteHostPath),\n permissions: nil\n )\n\n default:\n throw ContainerizationError(\n .invalidArgument,\n message:\n \"invalid publish-socket format \\(socketText). Expected: host_path:container_path\")\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/ReservedVmnetNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport Dispatch\nimport Foundation\nimport Logging\nimport SendableProperty\nimport SystemConfiguration\nimport XPC\nimport vmnet\n\n/// Creates a vmnet network with reservation APIs.\n@available(macOS 26, *)\npublic final class ReservedVmnetNetwork: Network {\n @SendablePropertyUnchecked\n private var _state: NetworkState\n private let log: Logger\n\n @SendableProperty\n private var network: vmnet_network_ref?\n @SendableProperty\n private var interface: interface_ref?\n private let networkLock = NSLock()\n\n /// Configure a bridge network that allows external system access using\n /// network address translation.\n public init(\n configuration: NetworkConfiguration,\n log: Logger\n ) throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.unsupported, message: \"invalid network mode \\(configuration.mode)\")\n }\n\n log.info(\"creating vmnet network\")\n self.log = log\n _state = .created(configuration)\n log.info(\"created vmnet network\")\n }\n\n public var state: NetworkState {\n get async { _state }\n }\n\n public nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws {\n try networkLock.withLock {\n try handler(network.map { try Self.serialize_network_ref(ref: $0) })\n }\n }\n\n public func start() async throws {\n guard case .created(let configuration) = _state else {\n throw ContainerizationError(.invalidArgument, message: \"cannot start network that is in \\(_state.state) state\")\n }\n\n try startNetwork(configuration: configuration, log: log)\n }\n\n private static func serialize_network_ref(ref: vmnet_network_ref) throws -> XPCMessage {\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let refObject = vmnet_network_copy_serialization(ref, &status) else {\n throw ContainerizationError(.invalidArgument, message: \"cannot serialize vmnet_network_ref to XPC object, status \\(status)\")\n }\n return XPCMessage(object: refObject)\n }\n\n private func startNetwork(configuration: NetworkConfiguration, log: Logger) throws {\n log.info(\n \"starting vmnet network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n ]\n )\n let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName)\n let subnetText = configuration.subnet ?? suite?.string(forKey: \"network.subnet\")\n\n // with the reservation API, subnet priority is CLI argument, UserDefault, auto\n let subnet = try subnetText.map { try CIDRAddress($0) }\n\n // set up the vmnet configuration\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let vmnetConfiguration = vmnet_network_configuration_create(vmnet.operating_modes_t.VMNET_SHARED_MODE, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet config with status \\(status)\")\n }\n\n vmnet_network_configuration_disable_dhcp(vmnetConfiguration)\n\n // set the subnet if the caller provided one\n if let subnet {\n let gateway = IPv4Address(fromValue: subnet.lower.value + 1)\n var gatewayAddr = in_addr()\n inet_pton(AF_INET, gateway.description, &gatewayAddr)\n let mask = IPv4Address(fromValue: subnet.prefixLength.prefixMask32)\n var maskAddr = in_addr()\n inet_pton(AF_INET, mask.description, &maskAddr)\n log.info(\n \"configuring vmnet subnet\",\n metadata: [\"cidr\": \"\\(subnet)\"]\n )\n let status = vmnet_network_configuration_set_ipv4_subnet(vmnetConfiguration, &gatewayAddr, &maskAddr)\n guard status == .VMNET_SUCCESS else {\n throw ContainerizationError(.internalError, message: \"failed to set subnet \\(subnet) for network \\(configuration.id)\")\n }\n }\n\n // reserve the network\n guard let network = vmnet_network_create(vmnetConfiguration, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet network with status \\(status)\")\n }\n self.network = network\n\n // retrieve the subnet since the caller may not have provided one\n var subnetAddr = in_addr()\n var maskAddr = in_addr()\n vmnet_network_get_ipv4_subnet(network, &subnetAddr, &maskAddr)\n let subnetValue = UInt32(bigEndian: subnetAddr.s_addr)\n let maskValue = UInt32(bigEndian: maskAddr.s_addr)\n let lower = IPv4Address(fromValue: subnetValue & maskValue)\n let upper = IPv4Address(fromValue: lower.value + ~maskValue)\n let runningSubnet = try CIDRAddress(lower: lower, upper: upper)\n let runningGateway = IPv4Address(fromValue: runningSubnet.lower.value + 1)\n self._state = .running(configuration, NetworkStatus(address: runningSubnet.description, gateway: runningGateway.description))\n log.info(\n \"started vmnet network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n \"cidr\": \"\\(runningSubnet)\",\n ]\n )\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildPipelineHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport GRPC\nimport NIO\n\nprotocol BuildPipelineHandler: Sendable {\n func accept(_ packet: ServerStream) throws -> Bool\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws\n}\n\npublic actor BuildPipeline {\n let handlers: [BuildPipelineHandler]\n public init(_ config: Builder.BuildConfig) async throws {\n self.handlers =\n [\n try BuildFSSync(URL(filePath: config.contextDir)),\n try BuildRemoteContentProxy(config.contentStore),\n try BuildImageResolver(config.contentStore),\n try BuildStdio(quiet: config.quiet, output: config.terminal?.handle ?? FileHandle.standardError),\n ]\n }\n\n public func run(\n sender: AsyncStream.Continuation,\n receiver: GRPCAsyncResponseStream\n ) async throws {\n defer { sender.finish() }\n try await untilFirstError { group in\n for try await packet in receiver {\n try Task.checkCancellation()\n for handler in self.handlers {\n try Task.checkCancellation()\n guard try handler.accept(packet) else {\n continue\n }\n try Task.checkCancellation()\n try await handler.handle(sender, packet)\n break\n }\n }\n }\n }\n\n /// untilFirstError() throws when any one of its submitted tasks fail.\n /// This is useful for asynchronous packet processing scenarios which\n /// have the following 3 requirements:\n /// - the packet should be processed without blocking I/O\n /// - the packet stream is never-ending\n /// - when the first task fails, the error needs to be propagated to the caller\n ///\n /// Usage:\n ///\n /// ```\n /// try await untilFirstError { group in\n /// for try await packet in receiver {\n /// group.addTask {\n /// try await handler.handle(sender, packet)\n /// }\n /// }\n /// }\n /// ```\n ///\n ///\n /// WithThrowingTaskGroup cannot accomplish this because it\n /// doesn't provide a mechanism to exit when one of the tasks fail\n /// before all the tasks have been added. i.e. it is more suitable for\n /// tasks that are limited. Here's a sample code where withThrowingTaskGroup\n /// doesn't solve the problem:\n ///\n /// ```\n /// withThrowingTaskGroup { group in\n /// for try await packet in receiver {\n /// group.addTask {\n /// /* process packet */\n /// }\n /// } /* this loop blocks forever waiting for more packets */\n /// try await group.next() /* this never gets called */\n /// }\n /// ```\n /// The above closure never returns even when a handler encounters an error\n /// because the blocking operation `try await group.next()` cannot be\n /// called while iterating over the receiver stream.\n private func untilFirstError(body: @Sendable @escaping (UntilFirstError) async throws -> Void) async throws {\n let group = try await UntilFirstError()\n var taskContinuation: AsyncStream>.Continuation?\n let tasks = AsyncStream> { continuation in\n taskContinuation = continuation\n }\n guard let taskContinuation else {\n throw NSError(\n domain: \"untilFirstError\",\n code: 1,\n userInfo: [NSLocalizedDescriptionKey: \"Failed to initialize task continuation\"])\n }\n defer { taskContinuation.finish() }\n let stream = AsyncStream { continuation in\n let processTasks = Task {\n let taskStream = await group.tasks()\n defer {\n continuation.finish()\n }\n for await item in taskStream {\n try Task.checkCancellation()\n let addedTask = Task {\n try Task.checkCancellation()\n do {\n try await item()\n } catch {\n continuation.yield(error)\n await group.continuation?.finish()\n throw error\n }\n }\n taskContinuation.yield(addedTask)\n }\n }\n taskContinuation.yield(processTasks)\n\n let mainTask = Task { @Sendable in\n defer {\n continuation.finish()\n processTasks.cancel()\n taskContinuation.finish()\n }\n do {\n try Task.checkCancellation()\n try await body(group)\n } catch {\n continuation.yield(error)\n await group.continuation?.finish()\n throw error\n }\n }\n taskContinuation.yield(mainTask)\n }\n\n // when the first handler fails, cancel all tasks and throw error\n for await item in stream {\n try Task.checkCancellation()\n Task {\n for await task in tasks {\n task.cancel()\n }\n }\n throw item\n }\n // if none of the handlers fail, wait for all subtasks to complete\n for await task in tasks {\n try Task.checkCancellation()\n try await task.value\n }\n }\n\n private actor UntilFirstError {\n var stream: AsyncStream<@Sendable () async throws -> Void>?\n var continuation: AsyncStream<@Sendable () async throws -> Void>.Continuation?\n\n init() async throws {\n self.stream = AsyncStream { cont in\n self.continuation = cont\n }\n guard let _ = continuation else {\n throw NSError()\n }\n }\n\n func addTask(body: @Sendable @escaping () async throws -> Void) {\n if !Task.isCancelled {\n self.continuation?.yield(body)\n }\n }\n\n func tasks() -> AsyncStream<@Sendable () async throws -> Void> {\n self.stream!\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct ClientContainer: Sendable, Codable {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n\n private var sandboxClient: SandboxClient {\n SandboxClient(id: configuration.id, runtime: configuration.runtimeHandler)\n }\n\n /// Identifier of the container.\n public var id: String {\n configuration.id\n }\n\n public let status: RuntimeStatus\n\n /// Configured platform for the container.\n public var platform: ContainerizationOCI.Platform {\n configuration.platform\n }\n\n /// Configuration for the container.\n public let configuration: ContainerConfiguration\n\n /// Network allocated to the container.\n public let networks: [Attachment]\n\n package init(configuration: ContainerConfiguration) {\n self.configuration = configuration\n self.status = .stopped\n self.networks = []\n }\n\n init(snapshot: ContainerSnapshot) {\n self.configuration = snapshot.configuration\n self.status = snapshot.status\n self.networks = snapshot.networks\n }\n\n public var initProcess: ClientProcess {\n ClientProcessImpl(containerId: self.id, client: self.sandboxClient)\n }\n}\n\nextension ClientContainer {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n @discardableResult\n private static func xpcSend(\n client: XPCClient,\n message: XPCMessage,\n timeout: Duration? = .seconds(15)\n ) async throws -> XPCMessage {\n try await client.send(message, responseTimeout: timeout)\n }\n\n public static func create(\n configuration: ContainerConfiguration,\n options: ContainerCreateOptions = .default,\n kernel: Kernel\n ) async throws -> ClientContainer {\n do {\n let client = Self.newClient()\n let request = XPCMessage(route: .createContainer)\n\n let data = try JSONEncoder().encode(configuration)\n let kdata = try JSONEncoder().encode(kernel)\n let odata = try JSONEncoder().encode(options)\n request.set(key: .containerConfig, value: data)\n request.set(key: .kernel, value: kdata)\n request.set(key: .containerOptions, value: odata)\n\n try await xpcSend(client: client, message: request)\n return ClientContainer(configuration: configuration)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to create container\",\n cause: error\n )\n }\n }\n\n public static func list() async throws -> [ClientContainer] {\n do {\n let client = Self.newClient()\n let request = XPCMessage(route: .listContainer)\n\n let response = try await xpcSend(\n client: client,\n message: request,\n timeout: .seconds(10)\n )\n let data = response.dataNoCopy(key: .containers)\n guard let data else {\n return []\n }\n let configs = try JSONDecoder().decode([ContainerSnapshot].self, from: data)\n return configs.map { ClientContainer(snapshot: $0) }\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to list containers\",\n cause: error\n )\n }\n }\n\n /// Get the container for the provided id.\n public static func get(id: String) async throws -> ClientContainer {\n let containers = try await list()\n guard let container = containers.first(where: { $0.id == id }) else {\n throw ContainerizationError(\n .notFound,\n message: \"get failed: container \\(id) not found\"\n )\n }\n return container\n }\n}\n\nextension ClientContainer {\n public func bootstrap() async throws -> ClientProcess {\n let client = self.sandboxClient\n try await client.bootstrap()\n return ClientProcessImpl(containerId: self.id, client: self.sandboxClient)\n }\n\n /// Stop the container and all processes currently executing inside.\n public func stop(opts: ContainerStopOptions = ContainerStopOptions.default) async throws {\n do {\n let client = self.sandboxClient\n try await client.stop(options: opts)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to stop container\",\n cause: error\n )\n }\n }\n\n /// Delete the container along with any resources.\n public func delete() async throws {\n do {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .deleteContainer)\n request.set(key: .id, value: self.id)\n try await client.send(request)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to delete container\",\n cause: error\n )\n }\n }\n}\n\nextension ClientContainer {\n /// Execute a new process inside a running container.\n public func createProcess(id: String, configuration: ProcessConfiguration) async throws -> ClientProcess {\n do {\n let client = self.sandboxClient\n try await client.createProcess(id, config: configuration)\n return ClientProcessImpl(containerId: self.id, processId: id, client: client)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to exec in container\",\n cause: error\n )\n }\n }\n\n /// Send or \"kill\" a signal to the initial process of the container.\n /// Kill does not wait for the process to exit, it only delivers the signal.\n public func kill(_ signal: Int32) async throws {\n do {\n let client = self.sandboxClient\n try await client.kill(self.id, signal: Int64(signal))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill container \\(self.id)\",\n cause: error\n )\n }\n }\n\n public func logs() async throws -> [FileHandle] {\n do {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .containerLogs)\n request.set(key: .id, value: self.id)\n\n let response = try await client.send(request)\n let fds = response.fileHandles(key: .logs)\n guard let fds else {\n throw ContainerizationError(\n .internalError,\n message: \"No log fds returned\"\n )\n }\n return fds\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get logs for container \\(self.id)\",\n cause: error\n )\n }\n }\n\n public func dial(_ port: UInt32) async throws -> FileHandle {\n do {\n let client = self.sandboxClient\n return try await client.dial(port)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to dial \\(port) in container \\(self.id)\",\n cause: error\n )\n }\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\nimport Logging\nimport os\nimport Synchronization\n\npublic struct XPCServer: Sendable {\n public typealias RouteHandler = @Sendable (XPCMessage) async throws -> XPCMessage\n\n private let routes: [String: RouteHandler]\n // Access to `connection` is protected by a lock\n private nonisolated(unsafe) let connection: xpc_connection_t\n private let lock = NSLock()\n\n let log: Logging.Logger\n\n public init(identifier: String, routes: [String: RouteHandler], log: Logging.Logger) {\n let connection = xpc_connection_create_mach_service(\n identifier,\n nil,\n UInt64(XPC_CONNECTION_MACH_SERVICE_LISTENER))\n\n self.routes = routes\n self.connection = connection\n self.log = log\n }\n\n public func listen() async throws {\n let connections = AsyncStream { cont in\n lock.withLock {\n xpc_connection_set_event_handler(self.connection) { object in\n switch xpc_get_type(object) {\n case XPC_TYPE_CONNECTION:\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n cont.yield(object)\n case XPC_TYPE_ERROR:\n if object.connectionError {\n cont.finish()\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(object))\")\n }\n }\n }\n }\n\n defer {\n lock.withLock {\n xpc_connection_cancel(self.connection)\n }\n }\n\n lock.withLock {\n xpc_connection_activate(self.connection)\n }\n try await withThrowingDiscardingTaskGroup { group in\n for await conn in connections {\n // `conn` isn't used concurrently.\n nonisolated(unsafe) let conn = conn\n let added = group.addTaskUnlessCancelled { @Sendable in\n try await self.handleClientConnection(connection: conn)\n xpc_connection_cancel(conn)\n }\n\n if !added {\n break\n }\n }\n\n group.cancelAll()\n }\n }\n\n func handleClientConnection(connection: xpc_connection_t) async throws {\n let replySent = Mutex(false)\n\n let objects = AsyncStream { cont in\n xpc_connection_set_event_handler(connection) { object in\n switch xpc_get_type(object) {\n case XPC_TYPE_DICTIONARY:\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n cont.yield(object)\n case XPC_TYPE_ERROR:\n if object.connectionError {\n cont.finish()\n }\n if !(replySent.withLock({ $0 }) && object.connectionClosed) {\n // When a xpc connection is closed, the framework sends a final XPC_ERROR_CONNECTION_INVALID message.\n // We can ignore this if we know we have already handled the request.\n self.log.error(\"xpc client handler connection error \\(object.errorDescription ?? \"no description\")\")\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(object))\")\n }\n }\n }\n defer {\n xpc_connection_cancel(connection)\n }\n\n xpc_connection_activate(connection)\n try await withThrowingDiscardingTaskGroup { group in\n // `connection` isn't used concurrently.\n nonisolated(unsafe) let connection = connection\n for await object in objects {\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n let added = group.addTaskUnlessCancelled { @Sendable in\n try await self.handleMessage(connection: connection, object: object)\n replySent.withLock { $0 = true }\n }\n if !added {\n break\n }\n }\n group.cancelAll()\n }\n }\n\n func handleMessage(connection: xpc_connection_t, object: xpc_object_t) async throws {\n guard let route = object.route else {\n log.error(\"empty route\")\n return\n }\n\n if let handler = routes[route] {\n let message = XPCMessage(object: object)\n do {\n let response = try await handler(message)\n xpc_connection_send_message(connection, response.underlying)\n } catch let error as ContainerizationError {\n let reply = message.reply()\n log.error(\"handler for \\(route) threw error \\(error)\")\n reply.set(error: error)\n xpc_connection_send_message(connection, reply.underlying)\n } catch {\n let reply = message.reply()\n log.error(\"handler for \\(route) threw error \\(error)\")\n let err = ContainerizationError(.unknown, message: String(describing: error))\n reply.set(error: err)\n xpc_connection_send_message(connection, reply.underlying)\n }\n }\n }\n}\n\nextension xpc_object_t {\n var route: String? {\n let croute = xpc_dictionary_get_string(self, XPCMessage.routeKey)\n guard let croute else {\n return nil\n }\n return String(cString: croute)\n }\n\n var connectionError: Bool {\n precondition(isError, \"Not an error\")\n return xpc_equal(self, XPC_ERROR_CONNECTION_INVALID) || xpc_equal(self, XPC_ERROR_CONNECTION_INTERRUPTED)\n }\n\n var connectionClosed: Bool {\n precondition(isError, \"Not an error\")\n return xpc_equal(self, XPC_ERROR_CONNECTION_INVALID)\n }\n\n var isError: Bool {\n xpc_get_type(self) == XPC_TYPE_ERROR\n }\n\n var errorDescription: String? {\n precondition(isError, \"Not an error\")\n let cstring = xpc_dictionary_get_string(self, XPC_ERROR_KEY_DESCRIPTION)\n guard let cstring else {\n return nil\n }\n return String(cString: cstring)\n }\n}\n\n#endif\n"], ["/container/Sources/CLI/Network/NetworkInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct NetworkInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more networks\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Networks to inspect\")\n var networks: [String]\n\n func run() async throws {\n let objects: [any Codable] = try await ClientNetwork.list().filter {\n networks.contains($0.id)\n }.map {\n PrintableNetwork($0)\n }\n print(try objects.jsonArray())\n }\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderStatus: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"status\"\n config._superCommandName = \"builder\"\n config.abstract = \"Print builder status\"\n config.usage = \"\\n\\t builder status [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Flag(name: .long, help: ArgumentHelp(\"Display detailed status in json format\"))\n var json: Bool = false\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n if json {\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.prettyPrinted, .sortedKeys]\n let jsonData = try encoder.encode(container)\n\n guard let jsonString = String(data: jsonData, encoding: .utf8) else {\n throw ContainerizationError(.internalError, message: \"failed to encode BuildKit container as json\")\n }\n print(jsonString)\n return\n }\n\n let image = container.configuration.image.reference\n let resources = container.configuration.resources\n let cpus = resources.cpus\n let memory = resources.memoryInBytes / (1024 * 1024) // bytes to MB\n let addr = \"\"\n\n print(\"ID IMAGE STATE ADDR CPUS MEMORY\")\n print(\"\\(container.id) \\(image) \\(container.status.rawValue.uppercased()) \\(addr) \\(cpus) \\(memory) MB\")\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n print(\"builder is not running\")\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct SystemStart: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Start `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Path to the `container-apiserver` binary\")\n var path: String = Bundle.main.executablePath ?? \"\"\n\n @Flag(name: .long, help: \"Enable debug logging for the runtime daemon.\")\n var debug = false\n\n @Flag(\n name: .long, inversion: .prefixedEnableDisable,\n help: \"Specify whether the default kernel should be installed or not. The default behavior is to prompt the user for a response.\")\n var kernelInstall: Bool?\n\n func run() async throws {\n // Without the true path to the binary in the plist, `container-apiserver` won't launch properly.\n let executableUrl = URL(filePath: path)\n .resolvingSymlinksInPath()\n .deletingLastPathComponent()\n .appendingPathComponent(\"container-apiserver\")\n\n var args = [executableUrl.absolutePath()]\n if debug {\n args.append(\"--debug\")\n }\n\n let apiServerDataUrl = appRoot.appending(path: \"apiserver\")\n try! FileManager.default.createDirectory(at: apiServerDataUrl, withIntermediateDirectories: true)\n let env = ProcessInfo.processInfo.environment.filter { key, _ in\n key.hasPrefix(\"CONTAINER_\")\n }\n\n let logURL = apiServerDataUrl.appending(path: \"apiserver.log\")\n let plist = LaunchPlist(\n label: \"com.apple.container.apiserver\",\n arguments: args,\n environment: env,\n limitLoadToSessionType: [.Aqua, .Background, .System],\n runAtLoad: true,\n stdout: logURL.path,\n stderr: logURL.path,\n machServices: [\"com.apple.container.apiserver\"]\n )\n\n let plistURL = apiServerDataUrl.appending(path: \"apiserver.plist\")\n let data = try plist.encode()\n try data.write(to: plistURL)\n\n try ServiceManager.register(plistPath: plistURL.path)\n\n // Now ping our friendly daemon. Fail if we don't get a response.\n do {\n print(\"Verifying apiserver is running...\")\n try await ClientHealthCheck.ping(timeout: .seconds(10))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get a response from apiserver: \\(error)\"\n )\n }\n\n if await !initImageExists() {\n try? await installInitialFilesystem()\n }\n\n guard await !kernelExists() else {\n return\n }\n try await installDefaultKernel()\n }\n\n private func installInitialFilesystem() async throws {\n let dep = Dependencies.initFs\n let pullCommand = ImagePull(reference: dep.source)\n print(\"Installing base container filesystem...\")\n do {\n try await pullCommand.run()\n } catch {\n log.error(\"Failed to install base container filesystem: \\(error)\")\n }\n }\n\n private func installDefaultKernel() async throws {\n let kernelDependency = Dependencies.kernel\n let defaultKernelURL = kernelDependency.source\n let defaultKernelBinaryPath = ClientDefaults.get(key: .defaultKernelBinaryPath)\n\n var shouldInstallKernel = false\n if kernelInstall == nil {\n print(\"No default kernel configured.\")\n print(\"Install the recommended default kernel from [\\(kernelDependency.source)]? [Y/n]: \", terminator: \"\")\n guard let read = readLine(strippingNewline: true) else {\n throw ContainerizationError(.internalError, message: \"Failed to read user input\")\n }\n guard read.lowercased() == \"y\" || read.count == 0 else {\n print(\"Please use the `container system kernel set --recommended` command to configure the default kernel\")\n return\n }\n shouldInstallKernel = true\n } else {\n shouldInstallKernel = kernelInstall ?? false\n }\n guard shouldInstallKernel else {\n return\n }\n print(\"Installing kernel...\")\n try await KernelSet.downloadAndInstallWithProgressBar(tarRemoteURL: defaultKernelURL, kernelFilePath: defaultKernelBinaryPath)\n }\n\n private func initImageExists() async -> Bool {\n do {\n let img = try await ClientImage.get(reference: Dependencies.initFs.source)\n let _ = try await img.getSnapshot(platform: .current)\n return true\n } catch {\n return false\n }\n }\n\n private func kernelExists() async -> Bool {\n do {\n try await ClientKernel.getDefaultKernel(for: .current)\n return true\n } catch {\n return false\n }\n }\n }\n\n private enum Dependencies: String {\n case kernel\n case initFs\n\n var source: String {\n switch self {\n case .initFs:\n return ClientDefaults.get(key: .defaultInitImage)\n case .kernel:\n return ClientDefaults.get(key: .defaultKernelURL)\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Registry/Login.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Login: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: \"Login to a registry\"\n )\n\n @Option(name: .shortAndLong, help: \"Username\")\n var username: String = \"\"\n\n @Flag(help: \"Take the password from stdin\")\n var passwordStdin: Bool = false\n\n @Argument(help: \"Registry server name\")\n var server: String\n\n @OptionGroup\n var registry: Flags.Registry\n\n func run() async throws {\n var username = self.username\n var password = \"\"\n if passwordStdin {\n if username == \"\" {\n throw ContainerizationError(\n .invalidArgument, message: \"must provide --username with --password-stdin\")\n }\n guard let passwordData = try FileHandle.standardInput.readToEnd() else {\n throw ContainerizationError(.invalidArgument, message: \"failed to read password from stdin\")\n }\n password = String(decoding: passwordData, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)\n }\n let keychain = KeychainHelper(id: Constants.keychainID)\n if username == \"\" {\n username = try keychain.userPrompt(domain: server)\n }\n if password == \"\" {\n password = try keychain.passwordPrompt()\n print()\n }\n\n let server = Reference.resolveDomain(domain: server)\n let scheme = try RequestScheme(registry.scheme).schemeFor(host: server)\n let _url = \"\\(scheme)://\\(server)\"\n guard let url = URL(string: _url) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n guard let host = url.host else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid host \\(server)\")\n }\n\n let client = RegistryClient(\n host: host,\n scheme: scheme.rawValue,\n port: url.port,\n authentication: BasicAuthentication(username: username, password: password),\n retryOptions: .init(\n maxRetries: 10,\n retryInterval: 300_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n )\n try await client.ping()\n try keychain.save(domain: server, username: username, password: password)\n print(\"Login succeeded\")\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport TerminalProgress\n\nextension Application {\n struct ContainerStart: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Start a container\")\n\n @Flag(name: .shortAndLong, help: \"Attach STDOUT/STDERR\")\n var attach = false\n\n @Flag(name: .shortAndLong, help: \"Attach container's STDIN\")\n var interactive = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Container's ID\")\n var containerID: String\n\n func run() async throws {\n var exitCode: Int32 = 127\n\n let progressConfig = try ProgressConfig(\n description: \"Starting container\"\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let container = try await ClientContainer.get(id: containerID)\n let process = try await container.bootstrap()\n\n progress.set(description: \"Starting init process\")\n let detach = !self.attach && !self.interactive\n do {\n let io = try ProcessIO.create(\n tty: container.configuration.initProcess.terminal,\n interactive: self.interactive,\n detach: detach\n )\n progress.finish()\n if detach {\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n print(self.containerID)\n return\n }\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n try? await container.stop()\n\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to start container: \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nextension Application {\n struct SystemStop: AsyncParsableCommand {\n private static let stopTimeoutSeconds: Int32 = 5\n private static let shutdownTimeoutSeconds: Int32 = 20\n\n static let configuration = CommandConfiguration(\n commandName: \"stop\",\n abstract: \"Stop all `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Launchd prefix for `container` services\")\n var prefix: String = \"com.apple.container.\"\n\n func run() async throws {\n let log = Logger(\n label: \"com.apple.container.cli\",\n factory: { label in\n StreamLogHandler.standardOutput(label: label)\n }\n )\n\n let launchdDomainString = try ServiceManager.getDomainString()\n let fullLabel = \"\\(launchdDomainString)/\\(prefix)apiserver\"\n\n log.info(\"stopping containers\", metadata: [\"stopTimeoutSeconds\": \"\\(Self.stopTimeoutSeconds)\"])\n do {\n let containers = try await ClientContainer.list()\n let signal = try Signals.parseSignal(\"SIGTERM\")\n let opts = ContainerStopOptions(timeoutInSeconds: Self.stopTimeoutSeconds, signal: signal)\n let failed = try await ContainerStop.stopContainers(containers: containers, stopOptions: opts)\n if !failed.isEmpty {\n log.warning(\"some containers could not be stopped gracefully\", metadata: [\"ids\": \"\\(failed)\"])\n }\n\n } catch {\n log.warning(\"failed to stop all containers\", metadata: [\"error\": \"\\(error)\"])\n }\n\n log.info(\"waiting for containers to exit\")\n do {\n for _ in 0.. Void) throws {\n try handler(nil)\n }\n\n public func start() async throws {\n guard case .created(let configuration) = _state else {\n throw ContainerizationError(.invalidState, message: \"cannot start network \\(_state.id) in \\(_state.state) state\")\n }\n var defaultSubnet = \"192.168.64.1/24\"\n\n log.info(\n \"starting allocation-only network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(NetworkMode.nat.rawValue)\",\n ]\n )\n\n if let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName) {\n // TODO: Make the suiteName a constant defined in ClientDefaults and use that.\n // This will need some re-working of dependencies between NetworkService and Client\n defaultSubnet = suite.string(forKey: \"network.subnet\") ?? defaultSubnet\n }\n\n let subnet = try CIDRAddress(defaultSubnet)\n let gateway = IPv4Address(fromValue: subnet.lower.value + 1)\n self._state = .running(configuration, NetworkStatus(address: subnet.description, gateway: gateway.description))\n log.info(\n \"started allocation-only network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n \"cidr\": \"\\(defaultSubnet)\",\n ]\n )\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientImage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\n// MARK: ClientImage structure\n\npublic struct ClientImage: Sendable {\n private let contentStore: ContentStore = RemoteContentStoreClient()\n public let description: ImageDescription\n\n public var digest: String { description.digest }\n public var descriptor: Descriptor { description.descriptor }\n public var reference: String { description.reference }\n\n public init(description: ImageDescription) {\n self.description = description\n }\n\n /// Returns the underlying OCI index for the image.\n public func index() async throws -> Index {\n guard let content: Content = try await contentStore.get(digest: description.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(description.digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the manifest for the specified platform.\n public func manifest(for platform: Platform) async throws -> Manifest {\n let index = try await self.index()\n let desc = index.manifests.first { desc in\n desc.platform == platform\n }\n guard let desc else {\n throw ContainerizationError(.unsupported, message: \"Platform \\(platform.description)\")\n }\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the OCI config for the specified platform.\n public func config(for platform: Platform) async throws -> ContainerizationOCI.Image {\n let manifest = try await self.manifest(for: platform)\n let desc = manifest.config\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n return try content.decode()\n }\n}\n\n// MARK: ClientImage constants\n\nextension ClientImage {\n private static let serviceIdentifier = \"com.apple.container.core.container-core-images\"\n public static let initImageRef = ClientDefaults.get(key: .defaultInitImage)\n\n private static func newXPCClient() -> XPCClient {\n XPCClient(service: Self.serviceIdentifier)\n }\n\n private static func newRequest(_ route: ImagesServiceXPCRoute) -> XPCMessage {\n XPCMessage(route: route)\n }\n\n private static var defaultRegistryDomain: String {\n ClientDefaults.get(key: .defaultRegistryDomain)\n }\n}\n\n// MARK: Static methods\n\nextension ClientImage {\n private static let legacyDockerRegistryHost = \"docker.io\"\n private static let dockerRegistryHost = \"registry-1.docker.io\"\n private static let defaultDockerRegistryRepo = \"library\"\n\n public static func normalizeReference(_ ref: String) throws -> String {\n guard ref != Self.initImageRef else {\n // Don't modify the default init image reference.\n // This is to allow for easier local development against\n // an updated containerization.\n return ref\n }\n // Check if the input reference has a domain specified\n var updatedRawReference: String = ref\n let r = try Reference.parse(ref)\n if r.domain == nil {\n updatedRawReference = \"\\(Self.defaultRegistryDomain)/\\(ref)\"\n }\n\n let updatedReference = try Reference.parse(updatedRawReference)\n\n // Handle adding the :latest tag if it isn't specified,\n // as well as adding the \"library/\" repository if it isn't set only if the host is docker.io\n updatedReference.normalize()\n return updatedReference.description\n }\n\n public static func denormalizeReference(_ ref: String) throws -> String {\n var updatedRawReference: String = ref\n let r = try Reference.parse(ref)\n let defaultRegistry = Self.defaultRegistryDomain\n if r.domain == defaultRegistry {\n updatedRawReference = \"\\(r.path)\"\n if let tag = r.tag {\n updatedRawReference += \":\\(tag)\"\n } else if let digest = r.digest {\n updatedRawReference += \"@\\(digest)\"\n }\n if defaultRegistry == dockerRegistryHost || defaultRegistry == legacyDockerRegistryHost {\n updatedRawReference.trimPrefix(\"\\(defaultDockerRegistryRepo)/\")\n }\n }\n return updatedRawReference\n }\n\n public static func list() async throws -> [ClientImage] {\n let client = newXPCClient()\n let request = newRequest(.imageList)\n let response = try await client.send(request)\n\n let imageDescriptions = try response.imageDescriptions()\n return imageDescriptions.map { desc in\n ClientImage(description: desc)\n }\n }\n\n public static func get(names: [String]) async throws -> (images: [ClientImage], error: [String]) {\n let all = try await self.list()\n var errors: [String] = []\n var found: [ClientImage] = []\n for name in names {\n do {\n guard let img = try Self._search(reference: name, in: all) else {\n errors.append(name)\n continue\n }\n found.append(img)\n } catch {\n errors.append(name)\n }\n }\n return (found, errors)\n }\n\n public static func get(reference: String) async throws -> ClientImage {\n let all = try await self.list()\n guard let found = try self._search(reference: reference, in: all) else {\n throw ContainerizationError(.notFound, message: \"Image with reference \\(reference)\")\n }\n return found\n }\n\n private static func _search(reference: String, in all: [ClientImage]) throws -> ClientImage? {\n let locallyBuiltImage = try {\n // Check if we have an image whose index descriptor contains the image name\n // as an annotation. Prefer this in all cases, since these are locally built images.\n let r = try Reference.parse(reference)\n r.normalize()\n let withDefaultTag = r.description\n\n let localImageMatches = all.filter { $0.description.nameFromAnnotation() == withDefaultTag }\n guard localImageMatches.count > 1 else {\n return localImageMatches.first\n }\n // More than one image matched. Check against the tagged reference\n return localImageMatches.first { $0.reference == withDefaultTag }\n }()\n if let locallyBuiltImage {\n return locallyBuiltImage\n }\n // If we don't find a match, try matching `ImageDescription.name` against the given\n // input string, while also checking against its normalized form.\n // Return the first match.\n let normalizedReference = try Self.normalizeReference(reference)\n return all.first(where: { image in\n image.reference == reference || image.reference == normalizedReference\n })\n }\n\n public static func pull(reference: String, platform: Platform? = nil, scheme: RequestScheme = .auto, progressUpdate: ProgressUpdateHandler? = nil) async throws -> ClientImage {\n let client = newXPCClient()\n let request = newRequest(.imagePull)\n\n let reference = try self.normalizeReference(reference)\n guard let host = try Reference.parse(reference).domain else {\n throw ContainerizationError(.invalidArgument, message: \"Could not extract host from reference \\(reference)\")\n }\n\n request.set(key: .imageReference, value: reference)\n try request.set(platform: platform)\n\n let insecure = try scheme.schemeFor(host: host) == .http\n request.set(key: .insecureFlag, value: insecure)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n\n let response = try await client.send(request)\n let description = try response.imageDescription()\n let image = ClientImage(description: description)\n\n await progressUpdateClient?.finish()\n return image\n }\n\n public static func delete(reference: String, garbageCollect: Bool = false) async throws {\n let client = newXPCClient()\n let request = newRequest(.imageDelete)\n request.set(key: .imageReference, value: reference)\n request.set(key: .garbageCollect, value: garbageCollect)\n let _ = try await client.send(request)\n }\n\n public static func load(from tarFile: String) async throws -> [ClientImage] {\n let client = newXPCClient()\n let request = newRequest(.imageLoad)\n request.set(key: .filePath, value: tarFile)\n let reply = try await client.send(request)\n\n let loaded = try reply.imageDescriptions()\n return loaded.map { desc in\n ClientImage(description: desc)\n }\n }\n\n public static func pruneImages() async throws -> ([String], UInt64) {\n let client = newXPCClient()\n let request = newRequest(.imagePrune)\n let response = try await client.send(request)\n let digests = try response.digests()\n let size = response.uint64(key: .size)\n return (digests, size)\n }\n\n public static func fetch(reference: String, platform: Platform? = nil, scheme: RequestScheme = .auto, progressUpdate: ProgressUpdateHandler? = nil) async throws -> ClientImage\n {\n do {\n let match = try await self.get(reference: reference)\n if let platform {\n // The image exists, but we dont know if we have the right platform pulled\n // Check if we do, if not pull the requested platform\n _ = try await match.config(for: platform)\n }\n return match\n } catch let err as ContainerizationError {\n guard err.isCode(.notFound) else {\n throw err\n }\n return try await Self.pull(reference: reference, platform: platform, scheme: scheme, progressUpdate: progressUpdate)\n }\n }\n}\n\n// MARK: Instance methods\n\nextension ClientImage {\n public func push(platform: Platform? = nil, scheme: RequestScheme, progressUpdate: ProgressUpdateHandler?) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imagePush)\n\n guard let host = try Reference.parse(reference).domain else {\n throw ContainerizationError(.invalidArgument, message: \"Could not extract host from reference \\(reference)\")\n }\n request.set(key: .imageReference, value: reference)\n\n let insecure = try scheme.schemeFor(host: host) == .http\n request.set(key: .insecureFlag, value: insecure)\n\n try request.set(platform: platform)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n _ = try await client.send(request)\n await progressUpdateClient?.finish()\n }\n\n @discardableResult\n public func tag(new: String) async throws -> ClientImage {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageTag)\n request.set(key: .imageReference, value: self.description.reference)\n request.set(key: .imageNewReference, value: new)\n let reply = try await client.send(request)\n let description = try reply.imageDescription()\n return ClientImage(description: description)\n }\n\n // MARK: Snapshot Methods\n\n public func save(out: String, platform: Platform? = nil) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageSave)\n try request.set(description: self.description)\n request.set(key: .filePath, value: out)\n try request.set(platform: platform)\n let _ = try await client.send(request)\n }\n\n public func unpack(platform: Platform?, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageUnpack)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n\n try await client.send(request)\n\n await progressUpdateClient?.finish()\n }\n\n public func deleteSnapshot(platform: Platform?) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.snapshotDelete)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n try await client.send(request)\n }\n\n public func getSnapshot(platform: Platform) async throws -> Filesystem {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.snapshotGet)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n let response = try await client.send(request)\n let fs = try response.filesystem()\n return fs\n }\n\n @discardableResult\n public func getCreateSnapshot(platform: Platform, progressUpdate: ProgressUpdateHandler? = nil) async throws -> Filesystem {\n do {\n return try await self.getSnapshot(platform: platform)\n } catch let err as ContainerizationError {\n guard err.code == .notFound else {\n throw err\n }\n try await self.unpack(platform: platform, progressUpdate: progressUpdate)\n return try await self.getSnapshot(platform: platform)\n }\n }\n}\n\nextension XPCMessage {\n fileprivate func set(description: ImageDescription) throws {\n let descData = try JSONEncoder().encode(description)\n self.set(key: .imageDescription, value: descData)\n }\n\n fileprivate func set(descriptions: [ImageDescription]) throws {\n let descData = try JSONEncoder().encode(descriptions)\n self.set(key: .imageDescriptions, value: descData)\n }\n\n fileprivate func set(platform: Platform?) throws {\n guard let platform else {\n return\n }\n let platformData = try JSONEncoder().encode(platform)\n self.set(key: .ociPlatform, value: platformData)\n }\n\n fileprivate func imageDescription() throws -> ImageDescription {\n let responseData = self.dataNoCopy(key: .imageDescription)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"imageDescription not received\")\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: responseData)\n return description\n }\n\n fileprivate func imageDescriptions() throws -> [ImageDescription] {\n let responseData = self.dataNoCopy(key: .imageDescriptions)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"imageDescriptions not received\")\n }\n let descriptions = try JSONDecoder().decode([ImageDescription].self, from: responseData)\n return descriptions\n }\n\n fileprivate func filesystem() throws -> Filesystem {\n let responseData = self.dataNoCopy(key: .filesystem)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"filesystem not received\")\n }\n let fs = try JSONDecoder().decode(Filesystem.self, from: responseData)\n return fs\n }\n\n fileprivate func digests() throws -> [String] {\n let responseData = self.dataNoCopy(key: .digests)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"digests not received\")\n }\n let digests = try JSONDecoder().decode([String].self, from: responseData)\n return digests\n }\n}\n\nextension ImageDescription {\n fileprivate func nameFromAnnotation() -> String? {\n guard let annotations = self.descriptor.annotations else {\n return nil\n }\n guard let name = annotations[AnnotationKeys.containerizationImageName] else {\n return nil\n }\n return name\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ContainerCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a new container\")\n\n @Argument(help: \"Image name\")\n var image: String\n\n @Argument(help: \"Container init process arguments\")\n var arguments: [String] = []\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var resourceFlags: Flags.Resource\n\n @OptionGroup\n var managementFlags: Flags.Management\n\n @OptionGroup\n var registryFlags: Flags.Registry\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 3\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let id = Utility.createContainerID(name: self.managementFlags.name)\n try Utility.validEntityName(id)\n\n let ck = try await Utility.containerConfigFromFlags(\n id: id,\n image: image,\n arguments: arguments,\n process: processFlags,\n management: managementFlags,\n resource: resourceFlags,\n registry: registryFlags,\n progressUpdate: progress.handler\n )\n\n let options = ContainerCreateOptions(autoRemove: managementFlags.remove)\n let container = try await ClientContainer.create(configuration: ck.0, options: options, kernel: ck.1)\n\n if !self.managementFlags.cidfile.isEmpty {\n let path = self.managementFlags.cidfile\n let data = container.id.data(using: .utf8)\n var attributes = [FileAttributeKey: Any]()\n attributes[.posixPermissions] = 0o644\n let success = FileManager.default.createFile(\n atPath: path,\n contents: data,\n attributes: attributes\n )\n guard success else {\n throw ContainerizationError(\n .internalError, message: \"failed to create cidfile at \\(path): \\(errno)\")\n }\n }\n progress.finish()\n\n print(container.id)\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerExec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct ContainerExec: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"exec\",\n abstract: \"Run a new command in a running container\")\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Running containers ID\")\n var containerID: String\n\n @Argument(parsing: .captureForPassthrough, help: \"New process arguments\")\n var arguments: [String]\n\n func run() async throws {\n var exitCode: Int32 = 127\n let container = try await ClientContainer.get(id: containerID)\n try ensureRunning(container: container)\n\n let stdin = self.processFlags.interactive\n let tty = self.processFlags.tty\n\n var config = container.configuration.initProcess\n config.executable = arguments.first!\n config.arguments = [String](self.arguments.dropFirst())\n config.terminal = tty\n config.environment.append(\n contentsOf: try Parser.allEnv(\n imageEnvs: [],\n envFiles: self.processFlags.envFile,\n envs: self.processFlags.env\n ))\n\n if let cwd = self.processFlags.cwd {\n config.workingDirectory = cwd\n }\n\n let defaultUser = config.user\n let (user, additionalGroups) = Parser.user(\n user: processFlags.user, uid: processFlags.uid,\n gid: processFlags.gid, defaultUser: defaultUser)\n config.user = user\n config.supplementalGroups.append(contentsOf: additionalGroups)\n\n do {\n let io = try ProcessIO.create(tty: tty, interactive: stdin, detach: false)\n\n if !self.processFlags.tty {\n var handler = SignalThreshold(threshold: 3, signals: [SIGINT, SIGTERM])\n handler.start {\n print(\"Received 3 SIGINT/SIGTERM's, forcefully exiting.\")\n Darwin.exit(1)\n }\n }\n\n let process = try await container.createProcess(\n id: UUID().uuidString.lowercased(),\n configuration: config)\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to exec process \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/SnapshotStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport TerminalProgress\n\npublic actor SnapshotStore {\n private static let snapshotFileName = \"snapshot\"\n private static let snapshotInfoFileName = \"snapshot-info\"\n private static let ingestDirName = \"ingest\"\n\n /// Return the Unpacker to use for a given image.\n /// If the given platform for the image cannot be unpacked return `nil`.\n public typealias UnpackStrategy = @Sendable (Containerization.Image, Platform) async throws -> Unpacker?\n\n public static let defaultUnpackStrategy: UnpackStrategy = { image, platform in\n guard platform.os == \"linux\" else {\n return nil\n }\n var minBlockSize = 512.gib()\n if image.reference == ClientDefaults.get(key: .defaultInitImage) {\n minBlockSize = 512.mib()\n }\n return EXT4Unpacker(blockSizeInBytes: minBlockSize)\n }\n\n let path: URL\n let fm = FileManager.default\n let ingestDir: URL\n let unpackStrategy: UnpackStrategy\n let log: Logger?\n\n public init(path: URL, unpackStrategy: @escaping UnpackStrategy, log: Logger?) throws {\n let root = path.appendingPathComponent(\"snapshots\")\n self.path = root\n self.ingestDir = self.path.appendingPathComponent(Self.ingestDirName)\n self.unpackStrategy = unpackStrategy\n self.log = log\n try self.fm.createDirectory(at: root, withIntermediateDirectories: true)\n try self.fm.createDirectory(at: self.ingestDir, withIntermediateDirectories: true)\n }\n\n public func unpack(image: Containerization.Image, platform: Platform? = nil, progressUpdate: ProgressUpdateHandler?) async throws {\n var toUnpack: [Descriptor] = []\n if let platform {\n let desc = try await image.descriptor(for: platform)\n toUnpack = [desc]\n } else {\n toUnpack = try await image.unpackableDescriptors()\n }\n\n let taskManager = ProgressTaskCoordinator()\n var taskUpdateProgress: ProgressUpdateHandler?\n\n for desc in toUnpack {\n try Task.checkCancellation()\n let snapshotDir = self.snapshotDir(desc)\n guard !self.fm.fileExists(atPath: snapshotDir.absolutePath()) else {\n // We have already unpacked this image + platform. Skip\n continue\n }\n guard let platform = desc.platform else {\n throw ContainerizationError(.internalError, message: \"Missing platform for descriptor \\(desc.digest)\")\n }\n guard let unpacker = try await self.unpackStrategy(image, platform) else {\n self.log?.warning(\"Skipping unpack for \\(image.reference) for platform \\(platform.description). No unpacker configured.\")\n continue\n }\n let currentSubTask = await taskManager.startTask()\n if let progressUpdate {\n let _taskUpdateProgress = ProgressTaskCoordinator.handler(for: currentSubTask, from: progressUpdate)\n await _taskUpdateProgress([\n .setSubDescription(\"for platform \\(platform.description)\")\n ])\n taskUpdateProgress = _taskUpdateProgress\n }\n\n let tempDir = try self.tempUnpackDir()\n\n let tempSnapshotPath = tempDir.appendingPathComponent(Self.snapshotFileName, isDirectory: false)\n let infoPath = tempDir.appendingPathComponent(Self.snapshotInfoFileName, isDirectory: false)\n do {\n let progress = ContainerizationProgressAdapter.handler(from: taskUpdateProgress)\n let mount = try await unpacker.unpack(image, for: platform, at: tempSnapshotPath, progress: progress)\n let fs = Filesystem.block(\n format: mount.type,\n source: self.snapshotPath(desc).absolutePath(),\n destination: mount.destination,\n options: mount.options\n )\n let snapshotInfo = try JSONEncoder().encode(fs)\n self.fm.createFile(atPath: infoPath.absolutePath(), contents: snapshotInfo)\n } catch {\n try? self.fm.removeItem(at: tempDir)\n throw error\n }\n do {\n try fm.moveItem(at: tempDir, to: snapshotDir)\n } catch let err as NSError {\n guard err.code == NSFileWriteFileExistsError else {\n throw err\n }\n try? self.fm.removeItem(at: tempDir)\n }\n }\n await taskManager.finish()\n }\n\n public func delete(for image: Containerization.Image, platform: Platform? = nil) async throws {\n var toDelete: [Descriptor] = []\n if let platform {\n let desc = try await image.descriptor(for: platform)\n toDelete.append(desc)\n } else {\n toDelete = try await image.unpackableDescriptors()\n }\n for desc in toDelete {\n let p = self.snapshotDir(desc)\n guard self.fm.fileExists(atPath: p.absolutePath()) else {\n continue\n }\n try self.fm.removeItem(at: p)\n }\n }\n\n public func get(for image: Containerization.Image, platform: Platform) async throws -> Filesystem {\n let desc = try await image.descriptor(for: platform)\n let infoPath = snapshotInfoPath(desc)\n let fsPath = snapshotPath(desc)\n\n guard self.fm.fileExists(atPath: infoPath.absolutePath()),\n self.fm.fileExists(atPath: fsPath.absolutePath())\n else {\n throw ContainerizationError(.notFound, message: \"image snapshot for \\(image.reference) with platform \\(platform.description)\")\n }\n let decoder = JSONDecoder()\n let data = try Data(contentsOf: infoPath)\n let fs = try decoder.decode(Filesystem.self, from: data)\n return fs\n }\n\n public func clean(keepingSnapshotsFor images: [Containerization.Image] = []) async throws -> UInt64 {\n var toKeep: [String] = [Self.ingestDirName]\n for image in images {\n for manifest in try await image.index().manifests {\n guard let platform = manifest.platform else {\n continue\n }\n let desc = try await image.descriptor(for: platform)\n toKeep.append(desc.digest.trimmingDigestPrefix)\n }\n }\n let all = try self.fm.contentsOfDirectory(at: self.path, includingPropertiesForKeys: [.totalFileAllocatedSizeKey]).map {\n $0.lastPathComponent\n }\n let delete = Set(all).subtracting(Set(toKeep))\n var deletedBytes: UInt64 = 0\n for dir in delete {\n let unpackedPath = self.path.appending(path: dir, directoryHint: .isDirectory)\n guard self.fm.fileExists(atPath: unpackedPath.absolutePath()) else {\n continue\n }\n deletedBytes += (try? self.fm.directorySize(dir: unpackedPath)) ?? 0\n try self.fm.removeItem(at: unpackedPath)\n }\n return deletedBytes\n }\n\n private func snapshotDir(_ desc: Descriptor) -> URL {\n let p = self.path.appendingPathComponent(desc.digest.trimmingDigestPrefix, isDirectory: true)\n return p\n }\n\n private func snapshotPath(_ desc: Descriptor) -> URL {\n let p = self.snapshotDir(desc)\n .appendingPathComponent(Self.snapshotFileName, isDirectory: false)\n return p\n }\n\n private func snapshotInfoPath(_ desc: Descriptor) -> URL {\n let p = self.snapshotDir(desc)\n .appendingPathComponent(Self.snapshotInfoFileName, isDirectory: false)\n return p\n }\n\n private func tempUnpackDir() throws -> URL {\n let uniqueDirectoryURL = ingestDir.appendingPathComponent(UUID().uuidString, isDirectory: true)\n try self.fm.createDirectory(at: uniqueDirectoryURL, withIntermediateDirectories: true, attributes: nil)\n return uniqueDirectoryURL\n }\n}\n\nextension FileManager {\n fileprivate func directorySize(dir: URL) throws -> UInt64 {\n var size = 0\n let resourceKeys: [URLResourceKey] = [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey]\n let contents = try self.contentsOfDirectory(\n at: dir,\n includingPropertiesForKeys: resourceKeys)\n\n for p in contents {\n let val = try p.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey])\n size += val.totalFileAllocatedSize ?? val.fileAllocatedSize ?? 0\n }\n return UInt64(size)\n }\n}\n\nextension Containerization.Image {\n fileprivate func unpackableDescriptors() async throws -> [Descriptor] {\n let index = try await self.index()\n return index.manifests.filter { desc in\n guard desc.platform != nil else {\n return false\n }\n if let referenceType = desc.annotations?[\"vnd.docker.reference.type\"], referenceType == \"attestation-manifest\" {\n return false\n }\n return true\n }\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/RuntimeLinuxHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\nimport NIO\n\n@main\nstruct RuntimeLinuxHelper: AsyncParsableCommand {\n static let label = \"com.apple.container.runtime.container-runtime-linux\"\n\n static let configuration = CommandConfiguration(\n commandName: \"container-runtime-linux\",\n abstract: \"XPC Service for managing a Linux sandbox\",\n version: releaseVersion()\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .shortAndLong, help: \"Sandbox UUID\")\n var uuid: String\n\n @Option(name: .shortAndLong, help: \"Root directory for the sandbox\")\n var root: String\n\n var machServiceLabel: String {\n \"\\(Self.label).\\(uuid)\"\n }\n\n func run() async throws {\n let commandName = Self._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n do {\n try adjustLimits()\n signal(SIGPIPE, SIG_IGN)\n\n log.info(\"configuring XPC server\")\n let interfaceStrategy: any InterfaceStrategy\n if #available(macOS 26, *) {\n interfaceStrategy = NonisolatedInterfaceStrategy(log: log)\n } else {\n interfaceStrategy = IsolatedInterfaceStrategy()\n }\n let server = SandboxService(root: .init(fileURLWithPath: root), interfaceStrategy: interfaceStrategy, eventLoopGroup: eventLoopGroup, log: log)\n let xpc = XPCServer(\n identifier: machServiceLabel,\n routes: [\n SandboxRoutes.bootstrap.rawValue: server.bootstrap,\n SandboxRoutes.createProcess.rawValue: server.createProcess,\n SandboxRoutes.state.rawValue: server.state,\n SandboxRoutes.stop.rawValue: server.stop,\n SandboxRoutes.kill.rawValue: server.kill,\n SandboxRoutes.resize.rawValue: server.resize,\n SandboxRoutes.wait.rawValue: server.wait,\n SandboxRoutes.start.rawValue: server.startProcess,\n SandboxRoutes.dial.rawValue: server.dial,\n ],\n log: log\n )\n\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n try? await eventLoopGroup.shutdownGracefully()\n RuntimeLinuxHelper.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"RuntimeLinuxHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n log[metadataKey: \"uuid\"] = \"\\(uuid)\"\n return log\n }\n\n private func adjustLimits() throws {\n var limits = rlimit()\n guard getrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n limits.rlim_cur = 65536\n limits.rlim_max = 65536\n guard setrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/CLI/Image/ImageInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ImageInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more images\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Images to inspect\")\n var images: [String]\n\n func run() async throws {\n var printable = [any Codable]()\n let result = try await ClientImage.get(names: images)\n let notFound = result.error\n for image in result.images {\n guard !Utility.isInfraImage(name: image.reference) else {\n continue\n }\n printable.append(try await image.details())\n }\n if printable.count > 0 {\n print(try printable.jsonArray())\n }\n if notFound.count > 0 {\n throw ContainerizationError(.notFound, message: \"Images: \\(notFound.joined(separator: \"\\n\"))\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/HostDNSResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n/// Functions for managing local DNS domains for containers.\npublic struct HostDNSResolver {\n public static let defaultConfigPath = URL(filePath: \"/etc/resolver\")\n\n // prefix used to mark our files as /etc/resolver/{prefix}{domainName}\n private static let containerizationPrefix = \"containerization.\"\n\n private let configURL: URL\n\n public init(configURL: URL = Self.defaultConfigPath) {\n self.configURL = configURL\n }\n\n /// Creates a DNS resolver configuration file for domain resolved by the application.\n public func createDomain(name: String) throws {\n let path = self.configURL.appending(path: \"\\(Self.containerizationPrefix)\\(name)\").path\n let fm: FileManager = FileManager.default\n\n if fm.fileExists(atPath: self.configURL.path) {\n guard let isDir = try self.configURL.resourceValues(forKeys: [.isDirectoryKey]).isDirectory, isDir else {\n throw ContainerizationError(.invalidState, message: \"expected \\(self.configURL.path) to be a directory, but found a file\")\n }\n } else {\n try fm.createDirectory(at: self.configURL, withIntermediateDirectories: true)\n }\n\n guard !fm.fileExists(atPath: path) else {\n throw ContainerizationError(.exists, message: \"domain \\(name) already exists\")\n }\n\n let resolverText = \"\"\"\n domain \\(name)\n search \\(name)\n nameserver 127.0.0.1\n port 2053\n \"\"\"\n\n do {\n try resolverText.write(toFile: path, atomically: true, encoding: .utf8)\n } catch {\n throw ContainerizationError(.invalidState, message: \"failed to write resolver configuration for \\(name)\")\n }\n }\n\n /// Removes a DNS resolver configuration file for domain resolved by the application.\n public func deleteDomain(name: String) throws {\n let path = self.configURL.appending(path: \"\\(Self.containerizationPrefix)\\(name)\").path\n let fm = FileManager.default\n guard fm.fileExists(atPath: path) else {\n throw ContainerizationError(.notFound, message: \"domain \\(name) at \\(path) not found\")\n }\n\n do {\n try fm.removeItem(atPath: path)\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot delete domain (try sudo?)\")\n }\n }\n\n /// Lists application-created local DNS domains.\n public func listDomains() -> [String] {\n let fm: FileManager = FileManager.default\n guard\n let resolverPaths = try? fm.contentsOfDirectory(\n at: self.configURL,\n includingPropertiesForKeys: [.isDirectoryKey]\n )\n else {\n return []\n }\n\n return\n resolverPaths\n .filter { $0.lastPathComponent.starts(with: Self.containerizationPrefix) }\n .compactMap { try? getDomainFromResolver(url: $0) }\n .sorted()\n }\n\n /// Reinitializes the macOS DNS daemon.\n public static func reinitialize() throws {\n do {\n let kill = Foundation.Process()\n kill.executableURL = URL(fileURLWithPath: \"/usr/bin/killall\")\n kill.arguments = [\"-HUP\", \"mDNSResponder\"]\n\n let null = FileHandle.nullDevice\n kill.standardOutput = null\n kill.standardError = null\n\n try kill.run()\n kill.waitUntilExit()\n let status = kill.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(.internalError, message: \"mDNSResponder restart failed with status \\(status)\")\n }\n }\n }\n\n private func getDomainFromResolver(url: URL) throws -> String? {\n let text = try String(contentsOf: url, encoding: .utf8)\n for line in text.components(separatedBy: .newlines) {\n let trimmed = line.trimmingCharacters(in: .whitespaces)\n let components = trimmed.split(whereSeparator: { $0.isWhitespace })\n guard components.count == 2 else {\n continue\n }\n guard components[0] == \"domain\" else {\n continue\n }\n\n return String(components[1])\n }\n\n return nil\n }\n}\n"], ["/container/Sources/CLI/System/SystemLogs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport OSLog\n\nextension Application {\n struct SystemLogs: AsyncParsableCommand {\n static let subsystem = \"com.apple.container\"\n\n static let configuration = CommandConfiguration(\n commandName: \"logs\",\n abstract: \"Fetch system logs for `container` services\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(\n name: .long,\n help: \"Fetch logs starting from the specified time period (minus the current time); supported formats: m, h, d\"\n )\n var last: String = \"5m\"\n\n @Flag(name: .shortAndLong, help: \"Follow log output\")\n var follow: Bool = false\n\n func run() async throws {\n let process = Process()\n let sigHandler = AsyncSignalHandler.create(notify: [SIGINT, SIGTERM])\n\n Task {\n for await _ in sigHandler.signals {\n process.terminate()\n Darwin.exit(0)\n }\n }\n\n do {\n var args = [\"log\"]\n args.append(self.follow ? \"stream\" : \"show\")\n args.append(contentsOf: [\"--info\", \"--debug\"])\n if !self.follow {\n args.append(contentsOf: [\"--last\", last])\n }\n args.append(contentsOf: [\"--predicate\", \"subsystem = 'com.apple.container'\"])\n\n process.launchPath = \"/usr/bin/env\"\n process.arguments = args\n\n process.standardOutput = FileHandle.standardOutput\n process.standardError = FileHandle.standardError\n\n try process.run()\n process.waitUntilExit()\n } catch {\n throw ContainerizationError(\n .invalidArgument,\n message: \"failed to system logs: \\(error)\"\n )\n }\n throw ArgumentParser.ExitCode(process.terminationStatus)\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIO\nimport NIOHPACK\nimport NIOHTTP2\n\npublic struct Builder: Sendable {\n let client: BuilderClientProtocol\n let clientAsync: BuilderClientAsyncProtocol\n let group: EventLoopGroup\n let builderShimSocket: FileHandle\n let channel: GRPCChannel\n\n public init(socket: FileHandle, group: EventLoopGroup) throws {\n try socket.setSendBufSize(4 << 20)\n try socket.setRecvBufSize(2 << 20)\n var config = ClientConnection.Configuration.default(\n target: .connectedSocket(socket.fileDescriptor),\n eventLoopGroup: group\n )\n config.connectionIdleTimeout = TimeAmount(.seconds(600))\n config.connectionKeepalive = .init(\n interval: TimeAmount(.seconds(600)),\n timeout: TimeAmount(.seconds(500)),\n permitWithoutCalls: true\n )\n config.connectionBackoff = .init(\n initialBackoff: TimeInterval(1),\n maximumBackoff: TimeInterval(10)\n )\n config.callStartBehavior = .fastFailure\n config.httpMaxFrameSize = 8 << 10\n config.maximumReceiveMessageLength = 512 << 20\n config.httpTargetWindowSize = 16 << 10\n\n let channel = ClientConnection(configuration: config)\n self.channel = channel\n self.clientAsync = BuilderClientAsync(channel: channel)\n self.client = BuilderClient(channel: channel)\n self.group = group\n self.builderShimSocket = socket\n }\n\n public func info() throws -> InfoResponse {\n let resp = self.client.info(InfoRequest(), callOptions: CallOptions())\n return try resp.response.wait()\n }\n\n public func info() async throws -> InfoResponse {\n let opts = CallOptions(timeLimit: .timeout(.seconds(30)))\n return try await self.clientAsync.info(InfoRequest(), callOptions: opts)\n }\n\n // TODO\n // - Symlinks in build context dir\n // - cache-to, cache-from\n // - output (other than the default OCI image output, e.g., local, tar, Docker)\n public func build(_ config: BuildConfig) async throws {\n var continuation: AsyncStream.Continuation?\n let reqStream = AsyncStream { (cont: AsyncStream.Continuation) in\n continuation = cont\n }\n guard let continuation else {\n throw Error.invalidContinuation\n }\n\n defer {\n continuation.finish()\n }\n\n if let terminal = config.terminal {\n Task {\n let winchHandler = AsyncSignalHandler.create(notify: [SIGWINCH])\n let setWinch = { (rows: UInt16, cols: UInt16) in\n var winch = ClientStream()\n winch.command = .init()\n if let cmdString = try TerminalCommand(rows: rows, cols: cols).json() {\n winch.command.command = cmdString\n continuation.yield(winch)\n }\n }\n let size = try terminal.size\n var width = size.width\n var height = size.height\n try setWinch(height, width)\n\n for await _ in winchHandler.signals {\n let size = try terminal.size\n let cols = size.width\n let rows = size.height\n if cols != width || rows != height {\n width = cols\n height = rows\n try setWinch(height, width)\n }\n }\n }\n }\n\n let respStream = self.clientAsync.performBuild(reqStream, callOptions: try CallOptions(config))\n let pipeline = try await BuildPipeline(config)\n do {\n try await pipeline.run(sender: continuation, receiver: respStream)\n } catch Error.buildComplete {\n _ = channel.close()\n try await group.shutdownGracefully()\n return\n }\n }\n\n public struct BuildExport: Sendable {\n public let type: String\n public var destination: URL?\n public let additionalFields: [String: String]\n public let rawValue: String\n\n public init(type: String, destination: URL?, additionalFields: [String: String], rawValue: String) {\n self.type = type\n self.destination = destination\n self.additionalFields = additionalFields\n self.rawValue = rawValue\n }\n\n public init(from input: String) throws {\n var typeValue: String?\n var destinationValue: URL?\n var additionalFields: [String: String] = [:]\n\n let pairs = input.components(separatedBy: \",\")\n for pair in pairs {\n let parts = pair.components(separatedBy: \"=\")\n guard parts.count == 2 else { continue }\n\n let key = parts[0].trimmingCharacters(in: .whitespaces)\n let value = parts[1].trimmingCharacters(in: .whitespaces)\n\n switch key {\n case \"type\":\n typeValue = value\n case \"dest\":\n destinationValue = try Self.resolveDestination(dest: value)\n default:\n additionalFields[key] = value\n }\n }\n\n guard let type = typeValue else {\n throw Builder.Error.invalidExport(input, \"type field is required\")\n }\n\n switch type {\n case \"oci\":\n break\n case \"tar\":\n if destinationValue == nil {\n throw Builder.Error.invalidExport(input, \"dest field is required\")\n }\n case \"local\":\n if destinationValue == nil {\n throw Builder.Error.invalidExport(input, \"dest field is required\")\n }\n default:\n throw Builder.Error.invalidExport(input, \"unsupported output type\")\n }\n\n self.init(type: type, destination: destinationValue, additionalFields: additionalFields, rawValue: input)\n }\n\n public var stringValue: String {\n get throws {\n var components = [\"type=\\(type)\"]\n\n switch type {\n case \"oci\", \"tar\", \"local\":\n break // ignore destination\n default:\n throw Builder.Error.invalidExport(rawValue, \"unsupported output type\")\n }\n\n for (key, value) in additionalFields {\n components.append(\"\\(key)=\\(value)\")\n }\n\n return components.joined(separator: \",\")\n }\n }\n\n static func resolveDestination(dest: String) throws -> URL {\n let destination = URL(fileURLWithPath: dest)\n let fileManager = FileManager.default\n\n if fileManager.fileExists(atPath: destination.path) {\n let resourceValues = try destination.resourceValues(forKeys: [.isDirectoryKey])\n let isDir = resourceValues.isDirectory\n if isDir != nil && isDir == false {\n throw Builder.Error.invalidExport(dest, \"dest path already exists\")\n }\n\n var finalDestination = destination.appendingPathComponent(\"out.tar\")\n var index = 1\n while fileManager.fileExists(atPath: finalDestination.path) {\n let path = \"out.tar.\\(index)\"\n finalDestination = destination.appendingPathComponent(path)\n index += 1\n }\n return finalDestination\n } else {\n let parentDirectory = destination.deletingLastPathComponent()\n try? fileManager.createDirectory(at: parentDirectory, withIntermediateDirectories: true, attributes: nil)\n }\n\n return destination\n }\n }\n\n public struct BuildConfig: Sendable {\n public let buildID: String\n public let contentStore: ContentStore\n public let buildArgs: [String]\n public let contextDir: String\n public let dockerfile: Data\n public let labels: [String]\n public let noCache: Bool\n public let platforms: [Platform]\n public let terminal: Terminal?\n public let tag: String\n public let target: String\n public let quiet: Bool\n public let exports: [BuildExport]\n public let cacheIn: [String]\n public let cacheOut: [String]\n\n public init(\n buildID: String,\n contentStore: ContentStore,\n buildArgs: [String],\n contextDir: String,\n dockerfile: Data,\n labels: [String],\n noCache: Bool,\n platforms: [Platform],\n terminal: Terminal?,\n tag: String,\n target: String,\n quiet: Bool,\n exports: [BuildExport],\n cacheIn: [String],\n cacheOut: [String],\n ) {\n self.buildID = buildID\n self.contentStore = contentStore\n self.buildArgs = buildArgs\n self.contextDir = contextDir\n self.dockerfile = dockerfile\n self.labels = labels\n self.noCache = noCache\n self.platforms = platforms\n self.terminal = terminal\n self.tag = tag\n self.target = target\n self.quiet = quiet\n self.exports = exports\n self.cacheIn = cacheIn\n self.cacheOut = cacheOut\n }\n }\n}\n\nextension Builder {\n enum Error: Swift.Error, CustomStringConvertible {\n case invalidContinuation\n case buildComplete\n case invalidExport(String, String)\n\n var description: String {\n switch self {\n case .invalidContinuation:\n return \"continuation could not created\"\n case .buildComplete:\n return \"build completed\"\n case .invalidExport(let exp, let reason):\n return \"export entry \\(exp) is invalid: \\(reason)\"\n }\n }\n }\n}\n\nextension CallOptions {\n public init(_ config: Builder.BuildConfig) throws {\n var headers: [(String, String)] = [\n (\"build-id\", config.buildID),\n (\"context\", URL(filePath: config.contextDir).path(percentEncoded: false)),\n (\"dockerfile\", config.dockerfile.base64EncodedString()),\n (\"progress\", config.terminal != nil ? \"tty\" : \"plain\"),\n (\"tag\", config.tag),\n (\"target\", config.target),\n ]\n for platform in config.platforms {\n headers.append((\"platforms\", platform.description))\n }\n if config.noCache {\n headers.append((\"no-cache\", \"\"))\n }\n for label in config.labels {\n headers.append((\"labels\", label))\n }\n for buildArg in config.buildArgs {\n headers.append((\"build-args\", buildArg))\n }\n for output in config.exports {\n headers.append((\"outputs\", try output.stringValue))\n }\n for cacheIn in config.cacheIn {\n headers.append((\"cache-in\", cacheIn))\n }\n for cacheOut in config.cacheOut {\n headers.append((\"cache-out\", cacheOut))\n }\n\n self.init(\n customMetadata: HPACKHeaders(headers)\n )\n }\n}\n\nextension FileHandle {\n @discardableResult\n func setSendBufSize(_ bytes: Int) throws -> Int {\n try setSockOpt(\n level: SOL_SOCKET,\n name: SO_SNDBUF,\n value: bytes)\n return bytes\n }\n\n @discardableResult\n func setRecvBufSize(_ bytes: Int) throws -> Int {\n try setSockOpt(\n level: SOL_SOCKET,\n name: SO_RCVBUF,\n value: bytes)\n return bytes\n }\n\n private func setSockOpt(level: Int32, name: Int32, value: Int) throws {\n var v = Int32(value)\n let res = withUnsafePointer(to: &v) { ptr -> Int32 in\n ptr.withMemoryRebound(\n to: UInt8.self,\n capacity: MemoryLayout.size\n ) { raw in\n #if canImport(Darwin)\n return setsockopt(\n self.fileDescriptor,\n level, name,\n raw,\n socklen_t(MemoryLayout.size))\n #else\n fatalError(\"unsupported platform\")\n #endif\n }\n }\n if res == -1 {\n throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EPERM)\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\npublic actor NetworkService: Sendable {\n private let network: any Network\n private let log: Logger?\n private var allocator: AttachmentAllocator\n\n /// Set up a network service for the specified network.\n public init(\n network: any Network,\n log: Logger? = nil\n ) async throws {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let subnet = try CIDRAddress(status.address)\n\n let size = Int(subnet.upper.value - subnet.lower.value - 3)\n self.allocator = try AttachmentAllocator(lower: subnet.lower.value + 2, size: size)\n self.network = network\n self.log = log\n }\n\n @Sendable\n public func state(_ message: XPCMessage) async throws -> XPCMessage {\n let reply = message.reply()\n let state = await network.state\n try reply.setState(state)\n return reply\n }\n\n @Sendable\n public func allocate(_ message: XPCMessage) async throws -> XPCMessage {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let hostname = try message.hostname()\n let index = try await allocator.allocate(hostname: hostname)\n let subnet = try CIDRAddress(status.address)\n let ip = IPv4Address(fromValue: index)\n let attachment = Attachment(\n network: state.id,\n hostname: hostname,\n address: try CIDRAddress(ip, prefixLength: subnet.prefixLength).description,\n gateway: status.gateway\n )\n log?.info(\n \"allocated attachment\",\n metadata: [\n \"hostname\": \"\\(hostname)\",\n \"address\": \"\\(attachment.address)\",\n \"gateway\": \"\\(attachment.gateway)\",\n ])\n let reply = message.reply()\n try reply.setAttachment(attachment)\n try network.withAdditionalData {\n if let additionalData = $0 {\n try reply.setAdditionalData(additionalData.underlying)\n }\n }\n return reply\n }\n\n @Sendable\n public func deallocate(_ message: XPCMessage) async throws -> XPCMessage {\n let hostname = try message.hostname()\n try await allocator.deallocate(hostname: hostname)\n log?.info(\"released attachments\", metadata: [\"hostname\": \"\\(hostname)\"])\n return message.reply()\n }\n\n @Sendable\n public func lookup(_ message: XPCMessage) async throws -> XPCMessage {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let hostname = try message.hostname()\n let index = try await allocator.lookup(hostname: hostname)\n let reply = message.reply()\n guard let index else {\n return reply\n }\n\n let address = IPv4Address(fromValue: index)\n let subnet = try CIDRAddress(status.address)\n let attachment = Attachment(\n network: state.id,\n hostname: hostname,\n address: try CIDRAddress(address, prefixLength: subnet.prefixLength).description,\n gateway: status.gateway\n )\n log?.debug(\n \"lookup attachment\",\n metadata: [\n \"hostname\": \"\\(hostname)\",\n \"address\": \"\\(address)\",\n ])\n try reply.setAttachment(attachment)\n return reply\n }\n\n @Sendable\n public func disableAllocator(_ message: XPCMessage) async throws -> XPCMessage {\n let success = await allocator.disableAllocator()\n log?.info(\"attempted allocator disable\", metadata: [\"success\": \"\\(success)\"])\n let reply = message.reply()\n reply.setAllocatorDisabled(success)\n return reply\n }\n}\n\nextension XPCMessage {\n fileprivate func setAdditionalData(_ additionalData: xpc_object_t) throws {\n xpc_dictionary_set_value(self.underlying, NetworkKeys.additionalData.rawValue, additionalData)\n }\n\n fileprivate func setAllocatorDisabled(_ allocatorDisabled: Bool) {\n self.set(key: NetworkKeys.allocatorDisabled.rawValue, value: allocatorDisabled)\n }\n\n fileprivate func setAttachment(_ attachment: Attachment) throws {\n let data = try JSONEncoder().encode(attachment)\n self.set(key: NetworkKeys.attachment.rawValue, value: data)\n }\n\n fileprivate func setState(_ state: NetworkState) throws {\n let data = try JSONEncoder().encode(state)\n self.set(key: NetworkKeys.state.rawValue, value: data)\n }\n}\n"], ["/container/Sources/APIServer/Networks/NetworksHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nstruct NetworksHarness: Sendable {\n let log: Logging.Logger\n let service: NetworksService\n\n init(service: NetworksService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let containers = try await service.list()\n let data = try JSONEncoder().encode(containers)\n\n let reply = message.reply()\n reply.set(key: .networkStates, value: data)\n return reply\n }\n\n @Sendable\n func create(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .networkConfig)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"network configuration cannot be empty\")\n }\n\n let config = try JSONDecoder().decode(NetworkConfiguration.self, from: data)\n let networkState = try await service.create(configuration: config)\n\n let networkData = try JSONEncoder().encode(networkState)\n\n let reply = message.reply()\n reply.set(key: .networkState, value: networkData)\n return reply\n }\n\n @Sendable\n func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .networkId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"id cannot be empty\")\n }\n try await service.delete(id: id)\n\n return message.reply()\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderStop: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"stop\"\n config._superCommandName = \"builder\"\n config.abstract = \"Stop builder\"\n config.usage = \"\\n\\t builder stop\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n try await container.stop()\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n print(\"builder is not running\")\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SendableProperty\nimport Synchronization\n\n/// A progress bar that updates itself as tasks are completed.\npublic final class ProgressBar: Sendable {\n let config: ProgressConfig\n let state: Mutex\n @SendableProperty\n var printedWidth = 0\n let term: FileHandle?\n let termQueue = DispatchQueue(label: \"com.apple.container.ProgressBar\")\n private let standardError = StandardError()\n\n /// Returns `true` if the progress bar has finished.\n public var isFinished: Bool {\n state.withLock { $0.finished }\n }\n\n /// Creates a new progress bar.\n /// - Parameter config: The configuration for the progress bar.\n public init(config: ProgressConfig) {\n self.config = config\n term = isatty(config.terminal.fileDescriptor) == 1 ? config.terminal : nil\n let state = State(\n description: config.initialDescription, itemsName: config.initialItemsName, totalTasks: config.initialTotalTasks,\n totalItems: config.initialTotalItems,\n totalSize: config.initialTotalSize)\n self.state = Mutex(state)\n display(EscapeSequence.hideCursor)\n }\n\n deinit {\n clear()\n }\n\n /// Allows resetting the progress state.\n public func reset() {\n state.withLock {\n $0 = State(description: config.initialDescription)\n }\n }\n\n /// Allows resetting the progress state of the current task.\n public func resetCurrentTask() {\n state.withLock {\n $0 = State(description: $0.description, itemsName: $0.itemsName, tasks: $0.tasks, totalTasks: $0.totalTasks, startTime: $0.startTime)\n }\n }\n\n private func printFullDescription() {\n let (description, subDescription) = state.withLock { ($0.description, $0.subDescription) }\n\n if subDescription != \"\" {\n standardError.write(\"\\(description) \\(subDescription)\")\n } else {\n standardError.write(description)\n }\n }\n\n /// Updates the description of the progress bar and increments the tasks by one.\n /// - Parameter description: The description of the action being performed.\n public func set(description: String) {\n resetCurrentTask()\n\n state.withLock {\n $0.description = description\n $0.subDescription = \"\"\n $0.tasks += 1\n }\n if config.disableProgressUpdates {\n printFullDescription()\n }\n }\n\n /// Updates the additional description of the progress bar.\n /// - Parameter subDescription: The additional description of the action being performed.\n public func set(subDescription: String) {\n resetCurrentTask()\n\n state.withLock { $0.subDescription = subDescription }\n if config.disableProgressUpdates {\n printFullDescription()\n }\n }\n\n private func start(intervalSeconds: TimeInterval) async {\n if config.disableProgressUpdates && !state.withLock({ $0.description.isEmpty }) {\n printFullDescription()\n }\n\n while !state.withLock({ $0.finished }) {\n let intervalNanoseconds = UInt64(intervalSeconds * 1_000_000_000)\n render()\n state.withLock { $0.iteration += 1 }\n if (try? await Task.sleep(nanoseconds: intervalNanoseconds)) == nil {\n return\n }\n }\n }\n\n /// Starts an animation of the progress bar.\n /// - Parameter intervalSeconds: The time interval between updates in seconds.\n public func start(intervalSeconds: TimeInterval = 0.04) {\n Task(priority: .utility) {\n await start(intervalSeconds: intervalSeconds)\n }\n }\n\n /// Finishes the progress bar.\n public func finish() {\n guard !state.withLock({ $0.finished }) else {\n return\n }\n\n state.withLock { $0.finished = true }\n\n // The last render.\n render(force: true)\n\n if !config.disableProgressUpdates && !config.clearOnFinish {\n displayText(state.withLock { $0.output }, terminating: \"\\n\")\n }\n\n if config.clearOnFinish {\n clearAndResetCursor()\n } else {\n resetCursor()\n }\n // Allow printed output to flush.\n usleep(100_000)\n }\n}\n\nextension ProgressBar {\n private func secondsSinceStart() -> Int {\n let timeDifferenceNanoseconds = DispatchTime.now().uptimeNanoseconds - state.withLock { $0.startTime.uptimeNanoseconds }\n let timeDifferenceSeconds = Int(floor(Double(timeDifferenceNanoseconds) / 1_000_000_000))\n return timeDifferenceSeconds\n }\n\n func render(force: Bool = false) {\n guard term != nil && !config.disableProgressUpdates && (force || !state.withLock { $0.finished }) else {\n return\n }\n let output = draw()\n displayText(output)\n }\n\n func draw() -> String {\n let state = self.state.withLock { $0 }\n\n var components = [String]()\n if config.showSpinner && !config.showProgressBar {\n if !state.finished {\n let spinnerIcon = config.theme.getSpinnerIcon(state.iteration)\n components.append(\"\\(spinnerIcon)\")\n } else {\n components.append(\"\\(config.theme.done)\")\n }\n }\n\n if config.showTasks, let totalTasks = state.totalTasks {\n let tasks = min(state.tasks, totalTasks)\n components.append(\"[\\(tasks)/\\(totalTasks)]\")\n }\n\n if config.showDescription && !state.description.isEmpty {\n components.append(\"\\(state.description)\")\n if !state.subDescription.isEmpty {\n components.append(\"\\(state.subDescription)\")\n }\n }\n\n let allowProgress = !config.ignoreSmallSize || state.totalSize == nil || state.totalSize! > Int64(1024 * 1024)\n\n let value = state.totalSize != nil ? state.size : Int64(state.items)\n let total = state.totalSize ?? Int64(state.totalItems ?? 0)\n\n if config.showPercent && total > 0 && allowProgress {\n components.append(\"\\(state.finished ? \"100%\" : state.percent)\")\n }\n\n if config.showProgressBar, total > 0, allowProgress {\n let usedWidth = components.joined(separator: \" \").count + 45 /* the maximum number of characters we may need */\n let remainingWidth = max(config.width - usedWidth, 1 /* the minimum width of a progress bar */)\n let barLength = state.finished ? remainingWidth : Int(Int64(remainingWidth) * value / total)\n let barPaddingLength = remainingWidth - barLength\n let bar = \"\\(String(repeating: config.theme.bar, count: barLength))\\(String(repeating: \" \", count: barPaddingLength))\"\n components.append(\"|\\(bar)|\")\n }\n\n var additionalComponents = [String]()\n\n if config.showItems, state.items > 0 {\n var itemsName = \"\"\n if !state.itemsName.isEmpty {\n itemsName = \" \\(state.itemsName)\"\n }\n if state.finished {\n if let totalItems = state.totalItems {\n additionalComponents.append(\"\\(totalItems.formattedNumber())\\(itemsName)\")\n }\n } else {\n if let totalItems = state.totalItems {\n additionalComponents.append(\"\\(state.items.formattedNumber()) of \\(totalItems.formattedNumber())\\(itemsName)\")\n } else {\n additionalComponents.append(\"\\(state.items.formattedNumber())\\(itemsName)\")\n }\n }\n }\n\n if state.size > 0 && allowProgress {\n if state.finished {\n if config.showSize {\n if let totalSize = state.totalSize {\n var formattedTotalSize = totalSize.formattedSize()\n formattedTotalSize = adjustFormattedSize(formattedTotalSize)\n additionalComponents.append(formattedTotalSize)\n }\n }\n } else {\n var formattedCombinedSize = \"\"\n if config.showSize {\n var formattedSize = state.size.formattedSize()\n formattedSize = adjustFormattedSize(formattedSize)\n if let totalSize = state.totalSize {\n var formattedTotalSize = totalSize.formattedSize()\n formattedTotalSize = adjustFormattedSize(formattedTotalSize)\n formattedCombinedSize = combineSize(size: formattedSize, totalSize: formattedTotalSize)\n } else {\n formattedCombinedSize = formattedSize\n }\n }\n\n var formattedSpeed = \"\"\n if config.showSpeed {\n formattedSpeed = \"\\(state.sizeSpeed ?? state.averageSizeSpeed)\"\n formattedSpeed = adjustFormattedSize(formattedSpeed)\n }\n\n if config.showSize && config.showSpeed {\n additionalComponents.append(formattedCombinedSize)\n additionalComponents.append(formattedSpeed)\n } else if config.showSize {\n additionalComponents.append(formattedCombinedSize)\n } else if config.showSpeed {\n additionalComponents.append(formattedSpeed)\n }\n }\n }\n\n if additionalComponents.count > 0 {\n let joinedAdditionalComponents = additionalComponents.joined(separator: \", \")\n components.append(\"(\\(joinedAdditionalComponents))\")\n }\n\n if config.showTime {\n let timeDifferenceSeconds = secondsSinceStart()\n let formattedTime = timeDifferenceSeconds.formattedTime()\n components.append(\"[\\(formattedTime)]\")\n }\n\n return components.joined(separator: \" \")\n }\n\n private func adjustFormattedSize(_ size: String) -> String {\n // Ensure we always have one digit after the decimal point to prevent flickering.\n let zero = Int64(0).formattedSize()\n guard !size.contains(\".\"), let first = size.first, first.isNumber || !size.contains(zero) else {\n return size\n }\n var size = size\n for unit in [\"MB\", \"GB\", \"TB\"] {\n size = size.replacingOccurrences(of: \" \\(unit)\", with: \".0 \\(unit)\")\n }\n return size\n }\n\n private func combineSize(size: String, totalSize: String) -> String {\n let sizeComponents = size.split(separator: \" \", maxSplits: 1)\n let totalSizeComponents = totalSize.split(separator: \" \", maxSplits: 1)\n guard sizeComponents.count == 2, totalSizeComponents.count == 2 else {\n return \"\\(size)/\\(totalSize)\"\n }\n let sizeNumber = sizeComponents[0]\n let sizeUnit = sizeComponents[1]\n let totalSizeNumber = totalSizeComponents[0]\n let totalSizeUnit = totalSizeComponents[1]\n guard sizeUnit == totalSizeUnit else {\n return \"\\(size)/\\(totalSize)\"\n }\n return \"\\(sizeNumber)/\\(totalSizeNumber) \\(totalSizeUnit)\"\n }\n}\n"], ["/container/Sources/CLI/Registry/RegistryDefault.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct RegistryDefault: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"default\",\n abstract: \"Manage the default image registry\",\n subcommands: [\n DefaultSetCommand.self,\n DefaultUnsetCommand.self,\n DefaultInspectCommand.self,\n ]\n )\n }\n\n struct DefaultSetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default registry\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @Argument\n var host: String\n\n func run() async throws {\n let scheme = try RequestScheme(registry.scheme).schemeFor(host: host)\n\n let _url = \"\\(scheme)://\\(host)\"\n guard let url = URL(string: _url), let domain = url.host() else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n let resolvedDomain = Reference.resolveDomain(domain: domain)\n let client = RegistryClient(host: resolvedDomain, scheme: scheme.rawValue, port: url.port)\n do {\n try await client.ping()\n } catch let err as RegistryClient.Error {\n switch err {\n case .invalidStatus(url: _, .unauthorized, _), .invalidStatus(url: _, .forbidden, _):\n break\n default:\n throw err\n }\n }\n ClientDefaults.set(value: host, key: .defaultRegistryDomain)\n print(\"Set default registry to \\(host)\")\n }\n }\n\n struct DefaultUnsetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"unset\",\n abstract: \"Unset the default registry\",\n aliases: [\"clear\"]\n )\n\n func run() async throws {\n ClientDefaults.unset(key: .defaultRegistryDomain)\n print(\"Unset the default registry domain\")\n }\n }\n\n struct DefaultInspectCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display the default registry domain\"\n )\n\n func run() async throws {\n print(ClientDefaults.get(key: .defaultRegistryDomain))\n }\n }\n}\n"], ["/container/Sources/SocketForwarder/UDPForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\nimport Synchronization\n\n// Proxy backend for a single client address (clientIP, clientPort).\nprivate final class UDPProxyBackend: ChannelInboundHandler, Sendable {\n typealias InboundIn = AddressedEnvelope\n typealias OutboundOut = AddressedEnvelope\n\n private struct State {\n var queuedPayloads: Deque\n var channel: (any Channel)?\n }\n\n private let clientAddress: SocketAddress\n private let serverAddress: SocketAddress\n private let frontendChannel: any Channel\n private let log: Logger?\n private let state: Mutex\n\n init(clientAddress: SocketAddress, serverAddress: SocketAddress, frontendChannel: any Channel, log: Logger? = nil) {\n self.clientAddress = clientAddress\n self.serverAddress = serverAddress\n self.frontendChannel = frontendChannel\n self.log = log\n let state = State(queuedPayloads: Deque(), channel: nil)\n self.state = Mutex(state)\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n // relay data from server to client.\n let inbound = self.unwrapInboundIn(data)\n let outbound = OutboundOut(remoteAddress: self.clientAddress, data: inbound.data)\n self.log?.trace(\"backend - writing datagram to client\")\n _ = self.frontendChannel.writeAndFlush(outbound)\n }\n\n func channelActive(context: ChannelHandlerContext) {\n state.withLock {\n if !$0.queuedPayloads.isEmpty {\n self.log?.trace(\"backend - writing \\($0.queuedPayloads.count) queued datagrams to server\")\n while let queuedData = $0.queuedPayloads.popFirst() {\n let outbound: UDPProxyBackend.OutboundOut = OutboundOut(remoteAddress: self.serverAddress, data: queuedData)\n _ = context.channel.writeAndFlush(outbound)\n }\n }\n $0.channel = context.channel\n }\n }\n\n func write(data: ByteBuffer) {\n // change package remote address from proxy server to real server\n state.withLock {\n if let channel = $0.channel {\n // channel has been initialized, so relay any queued packets, along with this one to outbound\n self.log?.trace(\"backend - writing datagram to server\")\n let outbound: UDPProxyBackend.OutboundOut = OutboundOut(remoteAddress: self.serverAddress, data: data)\n _ = channel.writeAndFlush(outbound)\n } else {\n // channel is initializing, queue\n self.log?.trace(\"backend - queuing datagram\")\n $0.queuedPayloads.append(data)\n }\n }\n }\n\n func close() {\n state.withLock {\n guard let channel = $0.channel else {\n self.log?.warning(\"backend - close on inactive channel\")\n return\n }\n _ = channel.close()\n }\n }\n}\n\nprivate struct ProxyContext {\n public let proxy: UDPProxyBackend\n public let closeFuture: EventLoopFuture\n}\n\nprivate final class UDPProxyFrontend: ChannelInboundHandler, Sendable {\n typealias InboundIn = AddressedEnvelope\n typealias OutboundOut = AddressedEnvelope\n private let maxProxies = UInt(256)\n\n private let proxyAddress: SocketAddress\n private let serverAddress: SocketAddress\n private let eventLoopGroup: any EventLoopGroup\n private let log: Logger?\n\n private let proxies: Mutex>\n\n init(proxyAddress: SocketAddress, serverAddress: SocketAddress, eventLoopGroup: any EventLoopGroup, log: Logger? = nil) {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.proxies = Mutex(LRUCache(size: maxProxies))\n self.log = log\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n let inbound = self.unwrapInboundIn(data)\n\n guard let clientIP = inbound.remoteAddress.ipAddress else {\n log?.error(\"frontend - no client IP address in inbound payload\")\n return\n }\n\n guard let clientPort = inbound.remoteAddress.port else {\n log?.error(\"frontend - no client port in inbound payload\")\n return\n }\n\n let key = \"\\(clientIP):\\(clientPort)\"\n do {\n try proxies.withLock {\n if let context = $0.get(key) {\n context.proxy.write(data: inbound.data)\n } else {\n self.log?.trace(\"frontend - creating backend\")\n let proxy = UDPProxyBackend(\n clientAddress: inbound.remoteAddress,\n serverAddress: self.serverAddress,\n frontendChannel: context.channel,\n log: log\n )\n let proxyAddress = try SocketAddress(ipAddress: \"0.0.0.0\", port: 0)\n let proxyToServerFuture = DatagramBootstrap(group: self.eventLoopGroup)\n .channelInitializer {\n self.log?.trace(\"frontend - initializing backend\")\n return $0.pipeline.addHandler(proxy)\n }\n .bind(to: proxyAddress)\n .flatMap { $0.closeFuture }\n let context = ProxyContext(proxy: proxy, closeFuture: proxyToServerFuture)\n if let (_, evictedContext) = $0.put(key: key, value: context) {\n self.log?.trace(\"frontend - closing evicted backend\")\n evictedContext.proxy.close()\n }\n\n proxy.write(data: inbound.data)\n }\n }\n } catch {\n log?.error(\"server handler - backend channel creation failed with error: \\(error)\")\n return\n }\n }\n}\n\npublic struct UDPForwarder: SocketForwarder {\n private let proxyAddress: SocketAddress\n\n private let serverAddress: SocketAddress\n\n private let eventLoopGroup: any EventLoopGroup\n\n private let log: Logger?\n\n public init(\n proxyAddress: SocketAddress,\n serverAddress: SocketAddress,\n eventLoopGroup: any EventLoopGroup,\n log: Logger? = nil\n ) throws {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.log = log\n }\n\n public func run() throws -> EventLoopFuture {\n self.log?.trace(\"frontend - creating channel\")\n let proxyToServerHandler = UDPProxyFrontend(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: log\n )\n let bootstrap = DatagramBootstrap(group: self.eventLoopGroup)\n .channelInitializer { serverChannel in\n self.log?.trace(\"frontend - initializing channel\")\n return serverChannel.pipeline.addHandler(proxyToServerHandler)\n }\n return\n bootstrap\n .bind(to: proxyAddress)\n .flatMap { $0.eventLoop.makeSucceededFuture(SocketForwarderResult(channel: $0)) }\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct DNSDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete a local DNS domain (must run as an administrator)\",\n aliases: [\"rm\"]\n )\n\n @Argument(help: \"the local domain name\")\n var domainName: String\n\n func run() async throws {\n let resolver = HostDNSResolver()\n do {\n try resolver.deleteDomain(name: domainName)\n print(domainName)\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot create domain (try sudo?)\")\n }\n\n do {\n try HostDNSResolver.reinitialize()\n } catch {\n throw ContainerizationError(.invalidState, message: \"mDNSResponder restart failed, run `sudo killall -HUP mDNSResponder` to deactivate domain\")\n }\n }\n }\n}\n"], ["/container/Sources/Helpers/Images/ImagesHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerImagesService\nimport ContainerImagesServiceClient\nimport ContainerLog\nimport ContainerXPC\nimport Containerization\nimport Foundation\nimport Logging\n\n@main\nstruct ImagesHelper: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"container-core-images\",\n abstract: \"XPC service for managing OCI images\",\n version: releaseVersion(),\n subcommands: [\n Start.self\n ]\n )\n}\n\nextension ImagesHelper {\n struct Start: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Starts the image plugin\"\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .long, help: \"XPC service prefix\")\n var serviceIdentifier: String = \"com.apple.container.core.container-core-images\"\n\n @Option(name: .shortAndLong, help: \"Daemon root directory\")\n var root = Self.appRoot.path\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n private static let unpackStrategy = SnapshotStore.defaultUnpackStrategy\n\n func run() async throws {\n let commandName = ImagesHelper._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n do {\n log.info(\"configuring XPC server\")\n let root = URL(filePath: root)\n var routes = [String: XPCServer.RouteHandler]()\n try self.initializeContentService(root: root, log: log, routes: &routes)\n try self.initializeImagesService(root: root, log: log, routes: &routes)\n let xpc = XPCServer(\n identifier: serviceIdentifier,\n routes: routes,\n log: log\n )\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n ImagesHelper.exit(withError: error)\n }\n }\n\n private func initializeImagesService(root: URL, log: Logger, routes: inout [String: XPCServer.RouteHandler]) throws {\n let contentStore = RemoteContentStoreClient()\n let imageStore = try ImageStore(path: root, contentStore: contentStore)\n let snapshotStore = try SnapshotStore(path: root, unpackStrategy: Self.unpackStrategy, log: log)\n let service = try ImagesService(contentStore: contentStore, imageStore: imageStore, snapshotStore: snapshotStore, log: log)\n let harness = ImagesServiceHarness(service: service, log: log)\n\n routes[ImagesServiceXPCRoute.imagePull.rawValue] = harness.pull\n routes[ImagesServiceXPCRoute.imageList.rawValue] = harness.list\n routes[ImagesServiceXPCRoute.imageDelete.rawValue] = harness.delete\n routes[ImagesServiceXPCRoute.imageTag.rawValue] = harness.tag\n routes[ImagesServiceXPCRoute.imagePush.rawValue] = harness.push\n routes[ImagesServiceXPCRoute.imageSave.rawValue] = harness.save\n routes[ImagesServiceXPCRoute.imageLoad.rawValue] = harness.load\n routes[ImagesServiceXPCRoute.imageUnpack.rawValue] = harness.unpack\n routes[ImagesServiceXPCRoute.imagePrune.rawValue] = harness.prune\n routes[ImagesServiceXPCRoute.snapshotDelete.rawValue] = harness.deleteSnapshot\n routes[ImagesServiceXPCRoute.snapshotGet.rawValue] = harness.getSnapshot\n }\n\n private func initializeContentService(root: URL, log: Logger, routes: inout [String: XPCServer.RouteHandler]) throws {\n let service = try ContentStoreService(root: root, log: log)\n let harness = ContentServiceHarness(service: service, log: log)\n\n routes[ImagesServiceXPCRoute.contentClean.rawValue] = harness.clean\n routes[ImagesServiceXPCRoute.contentGet.rawValue] = harness.get\n routes[ImagesServiceXPCRoute.contentDelete.rawValue] = harness.delete\n routes[ImagesServiceXPCRoute.contentIngestStart.rawValue] = harness.newIngestSession\n routes[ImagesServiceXPCRoute.contentIngestCancel.rawValue] = harness.cancelIngestSession\n routes[ImagesServiceXPCRoute.contentIngestComplete.rawValue] = harness.completeIngestSession\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"ImagesHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n return log\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/ContainerBuild/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension String {\n fileprivate var fs_cleaned: String {\n var value = self\n\n if value.hasPrefix(\"file://\") {\n value.removeFirst(\"file://\".count)\n }\n\n if value.count > 1 && value.last == \"/\" {\n value.removeLast()\n }\n\n return value.removingPercentEncoding ?? value\n }\n\n fileprivate var fs_components: [String] {\n var parts: [String] = []\n for segment in self.split(separator: \"/\", omittingEmptySubsequences: true) {\n switch segment {\n case \".\":\n continue\n case \"..\":\n if !parts.isEmpty { parts.removeLast() }\n default:\n parts.append(String(segment))\n }\n }\n return parts\n }\n\n fileprivate var fs_isAbsolute: Bool { first == \"/\" }\n}\n\nextension URL {\n var cleanPath: String {\n self.path.fs_cleaned\n }\n\n func parentOf(_ url: URL) -> Bool {\n let parentPath = self.absoluteURL.cleanPath\n let childPath = url.absoluteURL.cleanPath\n\n guard parentPath.fs_isAbsolute else {\n return true\n }\n\n let parentParts = parentPath.fs_components\n let childParts = childPath.fs_components\n\n guard parentParts.count <= childParts.count else { return false }\n return zip(parentParts, childParts).allSatisfy { $0 == $1 }\n }\n\n func relativeChildPath(to context: URL) throws -> String {\n guard context.parentOf(self) else {\n throw BuildFSSync.Error.pathIsNotChild(cleanPath, context.cleanPath)\n }\n\n let ctxParts = context.cleanPath.fs_components\n let selfParts = cleanPath.fs_components\n\n return selfParts.dropFirst(ctxParts.count).joined(separator: \"/\")\n }\n\n func relativePathFrom(from base: URL) -> String {\n let destParts = cleanPath.fs_components\n let baseParts = base.cleanPath.fs_components\n\n let common = zip(destParts, baseParts).prefix { $0 == $1 }.count\n guard common > 0 else { return cleanPath }\n\n let ups = Array(repeating: \"..\", count: baseParts.count - common)\n let remainder = destParts.dropFirst(common)\n return (ups + remainder).joined(separator: \"/\")\n }\n\n func zeroCopyReader(\n chunk: Int = 1024 * 1024,\n buffer: AsyncStream.Continuation.BufferingPolicy = .unbounded\n ) throws -> AsyncStream {\n\n let path = self.cleanPath\n let fd = open(path, O_RDONLY | O_NONBLOCK)\n guard fd >= 0 else { throw POSIXError.fromErrno() }\n\n let channel = DispatchIO(\n type: .stream,\n fileDescriptor: fd,\n queue: .global(qos: .userInitiated)\n ) { errno in\n close(fd)\n }\n\n channel.setLimit(highWater: chunk)\n return AsyncStream(bufferingPolicy: buffer) { continuation in\n\n channel.read(\n offset: 0, length: Int.max,\n queue: .global(qos: .userInitiated)\n ) { done, ddata, err in\n if err != 0 {\n continuation.finish()\n return\n }\n\n if let ddata, ddata.count > -1 {\n let data = Data(ddata)\n\n switch continuation.yield(data) {\n case .terminated:\n channel.close(flags: .stop)\n default: break\n }\n }\n\n if done {\n channel.close(flags: .stop)\n continuation.finish()\n }\n }\n }\n }\n\n func bufferedCopyReader(chunkSize: Int = 4 * 1024 * 1024) throws -> BufferedCopyReader {\n try BufferedCopyReader(url: self, chunkSize: chunkSize)\n }\n}\n\n/// A synchronous buffered reader that reads one chunk at a time from a file\n/// Uses a configurable buffer size (default 4MB) and only reads when nextChunk() is called\n/// Implements AsyncSequence for use with `for await` loops\npublic final class BufferedCopyReader: AsyncSequence {\n public typealias Element = Data\n public typealias AsyncIterator = BufferedCopyReaderIterator\n\n private let inputStream: InputStream\n private let chunkSize: Int\n private var isFinished: Bool = false\n private let reusableBuffer: UnsafeMutablePointer\n\n /// Initialize a buffered copy reader for the given URL\n /// - Parameters:\n /// - url: The file URL to read from\n /// - chunkSize: Size of each chunk to read (default: 4MB)\n public init(url: URL, chunkSize: Int = 4 * 1024 * 1024) throws {\n guard let stream = InputStream(url: url) else {\n throw CocoaError(.fileReadNoSuchFile)\n }\n self.inputStream = stream\n self.chunkSize = chunkSize\n self.reusableBuffer = UnsafeMutablePointer.allocate(capacity: chunkSize)\n self.inputStream.open()\n }\n\n deinit {\n inputStream.close()\n reusableBuffer.deallocate()\n }\n\n /// Create an async iterator for this sequence\n public func makeAsyncIterator() -> BufferedCopyReaderIterator {\n BufferedCopyReaderIterator(reader: self)\n }\n\n /// Read the next chunk of data from the file\n /// - Returns: Data chunk, or nil if end of file reached\n /// - Throws: Any file reading errors\n public func nextChunk() throws -> Data? {\n guard !isFinished else { return nil }\n\n // Read directly into our reusable buffer\n let bytesRead = inputStream.read(reusableBuffer, maxLength: chunkSize)\n\n // Check for errors\n if bytesRead < 0 {\n if let error = inputStream.streamError {\n throw error\n }\n throw CocoaError(.fileReadUnknown)\n }\n\n // If we read no data, we've reached the end\n if bytesRead == 0 {\n isFinished = true\n return nil\n }\n\n // If we read less than the chunk size, this is the last chunk\n if bytesRead < chunkSize {\n isFinished = true\n }\n\n // Create Data object only with the bytes actually read\n return Data(bytes: reusableBuffer, count: bytesRead)\n }\n\n /// Check if the reader has finished reading the file\n public var hasFinished: Bool {\n isFinished\n }\n\n /// Reset the reader to the beginning of the file\n /// Note: InputStream doesn't support seeking, so this recreates the stream\n /// - Throws: Any file opening errors\n public func reset() throws {\n inputStream.close()\n // Note: InputStream doesn't provide a way to get the original URL,\n // so reset functionality is limited. Consider removing this method\n // or storing the original URL if reset is needed.\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Reset not supported with InputStream-based implementation\"\n ])\n }\n\n /// Get the current file offset\n /// Note: InputStream doesn't provide offset information\n /// - Returns: Current position in the file\n /// - Throws: Unsupported operation error\n public func currentOffset() throws -> UInt64 {\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Offset tracking not supported with InputStream-based implementation\"\n ])\n }\n\n /// Seek to a specific offset in the file\n /// Note: InputStream doesn't support seeking\n /// - Parameter offset: The byte offset to seek to\n /// - Throws: Unsupported operation error\n public func seek(to offset: UInt64) throws {\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Seeking not supported with InputStream-based implementation\"\n ])\n }\n\n /// Close the input stream explicitly (called automatically in deinit)\n public func close() {\n inputStream.close()\n isFinished = true\n }\n}\n\n/// AsyncIteratorProtocol implementation for BufferedCopyReader\npublic struct BufferedCopyReaderIterator: AsyncIteratorProtocol {\n public typealias Element = Data\n\n private let reader: BufferedCopyReader\n\n init(reader: BufferedCopyReader) {\n self.reader = reader\n }\n\n /// Get the next chunk of data asynchronously\n /// - Returns: Next data chunk, or nil when finished\n /// - Throws: Any file reading errors\n public mutating func next() async throws -> Data? {\n // Yield control to allow other tasks to run, then read synchronously\n await Task.yield()\n return try reader.nextChunk()\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct NetworkCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a new network\")\n\n @Argument(help: \"Network name\")\n var name: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let config = NetworkConfiguration(id: self.name, mode: .nat)\n let state = try await ClientNetwork.create(configuration: config)\n print(state.id)\n }\n }\n}\n"], ["/container/Sources/ContainerPersistence/EntityStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nlet metadataFilename: String = \"entity.json\"\n\npublic protocol EntityStore {\n associatedtype T: Codable & Identifiable & Sendable\n\n func list() async throws -> [T]\n func create(_ entity: T) async throws\n func retrieve(_ id: String) async throws -> T?\n func update(_ entity: T) async throws\n func upsert(_ entity: T) async throws\n func delete(_ id: String) async throws\n}\n\npublic actor FilesystemEntityStore: EntityStore where T: Codable & Identifiable & Sendable {\n typealias Index = [String: T]\n\n private let path: URL\n private let type: String\n private var index: Index\n private let log: Logger\n private let encoder = JSONEncoder()\n\n public init(path: URL, type: String, log: Logger) throws {\n self.path = path\n self.type = type\n self.log = log\n self.index = try Self.load(path: path, log: log)\n }\n\n public func list() async throws -> [T] {\n Array(index.values)\n }\n\n public func create(_ entity: T) async throws {\n let metadataUrl = metadataUrl(entity.id)\n guard !FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.exists, message: \"Entity \\(entity.id) already exist\")\n }\n\n try FileManager.default.createDirectory(at: entityUrl(entity.id), withIntermediateDirectories: true)\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func retrieve(_ id: String) throws -> T? {\n index[id]\n }\n\n public func update(_ entity: T) async throws {\n let metadataUrl: URL = metadataUrl(entity.id)\n guard FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.notFound, message: \"Entity \\(entity.id) not found\")\n }\n\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func upsert(_ entity: T) async throws {\n let metadataUrl: URL = metadataUrl(entity.id)\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func delete(_ id: String) async throws {\n let metadataUrl = entityUrl(id)\n guard FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.notFound, message: \"entity \\(id) not found\")\n }\n try FileManager.default.removeItem(at: metadataUrl)\n index.removeValue(forKey: id)\n }\n\n public func entityUrl(_ id: String) -> URL {\n path.appendingPathComponent(id)\n }\n\n private static func load(path: URL, log: Logger) throws -> Index {\n let directories = try FileManager.default.contentsOfDirectory(at: path, includingPropertiesForKeys: nil)\n var index: FilesystemEntityStore.Index = Index()\n let decoder = JSONDecoder()\n\n for entityUrl in directories {\n do {\n let metadataUrl = entityUrl.appendingPathComponent(metadataFilename)\n let data = try Data(contentsOf: metadataUrl)\n let entity = try decoder.decode(T.self, from: data)\n index[entity.id] = entity\n } catch {\n log.warning(\n \"failed to load entity, ignoring\",\n metadata: [\n \"path\": \"\\(entityUrl)\"\n ])\n }\n }\n\n return index\n }\n\n private func metadataUrl(_ id: String) -> URL {\n entityUrl(id).appendingPathComponent(metadataFilename)\n }\n}\n"], ["/container/Sources/CLI/System/Kernel/KernelSet.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct KernelSet: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default kernel\"\n )\n\n @Option(name: .customLong(\"binary\"), help: \"Path to the binary to set as the default kernel. If used with --tar, this points to a location inside the tar\")\n var binaryPath: String? = nil\n\n @Option(name: .customLong(\"tar\"), help: \"Filesystem path or remote URL to a tar ball that contains the kernel to use\")\n var tarPath: String? = nil\n\n @Option(name: .customLong(\"arch\"), help: \"The architecture of the kernel binary. One of (amd64, arm64)\")\n var architecture: String = ContainerizationOCI.Platform.current.architecture.description\n\n @Flag(name: .customLong(\"recommended\"), help: \"Download and install the recommended kernel as the default. This flag ignores any other arguments\")\n var recommended: Bool = false\n\n func run() async throws {\n if recommended {\n let url = ClientDefaults.get(key: .defaultKernelURL)\n let path = ClientDefaults.get(key: .defaultKernelBinaryPath)\n print(\"Installing the recommended kernel from \\(url)...\")\n try await Self.downloadAndInstallWithProgressBar(tarRemoteURL: url, kernelFilePath: path)\n return\n }\n guard tarPath != nil else {\n return try await self.setKernelFromBinary()\n }\n try await self.setKernelFromTar()\n }\n\n private func setKernelFromBinary() async throws {\n guard let binaryPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--binary'\")\n }\n let absolutePath = URL(fileURLWithPath: binaryPath, relativeTo: .currentDirectory()).absoluteURL.absoluteString\n let platform = try getSystemPlatform()\n try await ClientKernel.installKernel(kernelFilePath: absolutePath, platform: platform)\n }\n\n private func setKernelFromTar() async throws {\n guard let binaryPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--binary'\")\n }\n guard let tarPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--tar\")\n }\n let platform = try getSystemPlatform()\n let localTarPath = URL(fileURLWithPath: tarPath, relativeTo: .currentDirectory()).absoluteString\n let fm = FileManager.default\n if fm.fileExists(atPath: localTarPath) {\n try await ClientKernel.installKernelFromTar(tarFile: localTarPath, kernelFilePath: binaryPath, platform: platform)\n return\n }\n guard let remoteURL = URL(string: tarPath) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid remote URL '\\(tarPath)' for argument '--tar'. Missing protocol?\")\n }\n try await Self.downloadAndInstallWithProgressBar(tarRemoteURL: remoteURL.absoluteString, kernelFilePath: binaryPath, platform: platform)\n }\n\n private func getSystemPlatform() throws -> SystemPlatform {\n switch architecture {\n case \"arm64\":\n return .linuxArm\n case \"amd64\":\n return .linuxAmd\n default:\n throw ContainerizationError(.unsupported, message: \"Unsupported architecture \\(architecture)\")\n }\n }\n\n public static func downloadAndInstallWithProgressBar(tarRemoteURL: String, kernelFilePath: String, platform: SystemPlatform = .current) async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n totalTasks: 2\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n try await ClientKernel.installKernelFromTar(tarFile: tarRemoteURL, kernelFilePath: kernelFilePath, platform: platform, progressUpdate: progress.handler)\n progress.finish()\n }\n\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildFSSync.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport ContainerClient\nimport ContainerizationArchive\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\n\nactor BuildFSSync: BuildPipelineHandler {\n let contextDir: URL\n\n init(_ contextDir: URL) throws {\n guard FileManager.default.fileExists(atPath: contextDir.cleanPath) else {\n throw Error.contextNotFound(contextDir.cleanPath)\n }\n guard try contextDir.isDir() else {\n throw Error.contextIsNotDirectory(contextDir.cleanPath)\n }\n\n self.contextDir = contextDir\n }\n\n nonisolated func accept(_ packet: ServerStream) throws -> Bool {\n guard let buildTransfer = packet.getBuildTransfer() else {\n return false\n }\n guard buildTransfer.stage() == \"fssync\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let buildTransfer = packet.getBuildTransfer() else {\n throw Error.buildTransferMissing\n }\n guard let method = buildTransfer.method() else {\n throw Error.methodMissing\n }\n switch try FSSyncMethod(method) {\n case .read:\n try await self.read(sender, buildTransfer, packet.buildID)\n case .info:\n try await self.info(sender, buildTransfer, packet.buildID)\n case .walk:\n try await self.walk(sender, buildTransfer, packet.buildID)\n }\n }\n\n func read(_ sender: AsyncStream.Continuation, _ packet: BuildTransfer, _ buildID: String) async throws {\n let offset: UInt64 = packet.offset() ?? 0\n let size: Int = packet.len() ?? 0\n var path: URL\n if packet.source.hasPrefix(\"/\") {\n path = URL(fileURLWithPath: packet.source).standardizedFileURL\n } else {\n path =\n contextDir\n .appendingPathComponent(packet.source)\n .standardizedFileURL\n }\n if !FileManager.default.fileExists(atPath: path.cleanPath) {\n path = URL(filePath: self.contextDir.cleanPath)\n path.append(components: packet.source.cleanPathComponent)\n }\n let data = try {\n if try path.isDir() {\n return Data()\n }\n let file = try LocalContent(path: path.standardizedFileURL)\n return try file.data(offset: offset, length: size) ?? Data()\n }()\n\n let transfer = try path.buildTransfer(id: packet.id, contextDir: self.contextDir, complete: true, data: data)\n var response = ClientStream()\n response.buildID = buildID\n response.buildTransfer = transfer\n response.packetType = .buildTransfer(transfer)\n sender.yield(response)\n }\n\n func info(_ sender: AsyncStream.Continuation, _ packet: BuildTransfer, _ buildID: String) async throws {\n let path: URL\n if packet.source.hasPrefix(\"/\") {\n path = URL(fileURLWithPath: packet.source).standardizedFileURL\n } else {\n path =\n contextDir\n .appendingPathComponent(packet.source)\n .standardizedFileURL\n }\n let transfer = try path.buildTransfer(id: packet.id, contextDir: self.contextDir, complete: true)\n var response = ClientStream()\n response.buildID = buildID\n response.buildTransfer = transfer\n response.packetType = .buildTransfer(transfer)\n sender.yield(response)\n }\n\n private struct DirEntry: Hashable {\n let url: URL\n let isDirectory: Bool\n let relativePath: String\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(relativePath)\n }\n\n static func == (lhs: DirEntry, rhs: DirEntry) -> Bool {\n lhs.relativePath == rhs.relativePath\n }\n }\n\n func walk(\n _ sender: AsyncStream.Continuation,\n _ packet: BuildTransfer,\n _ buildID: String\n ) async throws {\n let wantsTar = packet.mode() == \"tar\"\n\n var entries: [String: Set] = [:]\n let followPaths: [String] = packet.followPaths() ?? []\n\n let followPathsWalked = try walk(root: self.contextDir, includePatterns: followPaths)\n for url in followPathsWalked {\n guard self.contextDir.absoluteURL.cleanPath != url.absoluteURL.cleanPath else {\n continue\n }\n guard self.contextDir.parentOf(url) else {\n continue\n }\n\n let relPath = try url.relativeChildPath(to: contextDir)\n let parentPath = try url.deletingLastPathComponent().relativeChildPath(to: contextDir)\n let entry = DirEntry(url: url, isDirectory: url.hasDirectoryPath, relativePath: relPath)\n entries[parentPath, default: []].insert(entry)\n\n if url.isSymlink {\n let target: URL = url.resolvingSymlinksInPath()\n if self.contextDir.parentOf(target) {\n let relPath = try target.relativeChildPath(to: self.contextDir)\n let entry = DirEntry(url: target, isDirectory: target.hasDirectoryPath, relativePath: relPath)\n let parentPath: String = try target.deletingLastPathComponent().relativeChildPath(to: self.contextDir)\n entries[parentPath, default: []].insert(entry)\n }\n }\n }\n\n var fileOrder = [String]()\n try processDirectory(\"\", inputEntries: entries, processedPaths: &fileOrder)\n\n if !wantsTar {\n let fileInfos = try fileOrder.map { rel -> FileInfo in\n try FileInfo(path: contextDir.appendingPathComponent(rel), contextDir: contextDir)\n }\n\n let data = try JSONEncoder().encode(fileInfos)\n let transfer = BuildTransfer(\n id: packet.id,\n source: packet.source,\n complete: true,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"json\",\n ],\n data: data\n )\n var resp = ClientStream()\n resp.buildID = buildID\n resp.buildTransfer = transfer\n resp.packetType = .buildTransfer(transfer)\n sender.yield(resp)\n return\n }\n\n let tarURL = URL.temporaryDirectory\n .appendingPathComponent(UUID().uuidString + \".tar\")\n\n defer { try? FileManager.default.removeItem(at: tarURL) }\n\n let writerCfg = ArchiveWriterConfiguration(\n format: .paxRestricted,\n filter: .none)\n\n try Archiver.compress(\n source: contextDir,\n destination: tarURL,\n writerConfiguration: writerCfg\n ) { url in\n guard let rel = try? url.relativeChildPath(to: contextDir) else {\n return nil\n }\n\n guard let parent = try? url.deletingLastPathComponent().relativeChildPath(to: self.contextDir) else {\n return nil\n }\n\n guard let items = entries[parent] else {\n return nil\n }\n\n let include = items.contains { item in\n item.relativePath == rel\n }\n\n guard include else {\n return nil\n }\n\n return Archiver.ArchiveEntryInfo(\n pathOnHost: url,\n pathInArchive: URL(fileURLWithPath: rel))\n }\n\n for try await chunk in try tarURL.bufferedCopyReader() {\n let part = BuildTransfer(\n id: packet.id,\n source: tarURL.path,\n complete: false,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"tar\",\n ],\n data: chunk\n )\n var resp = ClientStream()\n resp.buildID = buildID\n resp.buildTransfer = part\n resp.packetType = .buildTransfer(part)\n sender.yield(resp)\n }\n\n let done = BuildTransfer(\n id: packet.id,\n source: tarURL.path,\n complete: true,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"tar\",\n ],\n data: Data()\n )\n\n var finalResp = ClientStream()\n finalResp.buildID = buildID\n finalResp.buildTransfer = done\n finalResp.packetType = .buildTransfer(done)\n sender.yield(finalResp)\n }\n\n func walk(root: URL, includePatterns: [String]) throws -> [URL] {\n let globber = Globber(root)\n\n for p in includePatterns {\n try globber.match(p)\n }\n return Array(globber.results)\n }\n\n private func processDirectory(\n _ currentDir: String,\n inputEntries: [String: Set],\n processedPaths: inout [String]\n ) throws {\n guard let entries = inputEntries[currentDir] else {\n return\n }\n\n // Sort purely by lexicographical order of relativePath\n let sortedEntries = entries.sorted { $0.relativePath < $1.relativePath }\n\n for entry in sortedEntries {\n processedPaths.append(entry.relativePath)\n\n if entry.isDirectory {\n try processDirectory(\n entry.relativePath,\n inputEntries: inputEntries,\n processedPaths: &processedPaths\n )\n }\n }\n }\n\n struct FileInfo: Codable {\n let name: String\n let modTime: String\n let mode: UInt32\n let size: UInt64\n let isDir: Bool\n let uid: UInt32\n let gid: UInt32\n let target: String\n\n init(path: URL, contextDir: URL) throws {\n if path.isSymlink {\n let target: URL = path.resolvingSymlinksInPath()\n if contextDir.parentOf(target) {\n self.target = target.relativePathFrom(from: path)\n } else {\n self.target = target.cleanPath\n }\n } else {\n self.target = \"\"\n }\n\n self.name = try path.relativeChildPath(to: contextDir)\n self.modTime = try path.modTime()\n self.mode = try path.mode()\n self.size = try path.size()\n self.isDir = path.hasDirectoryPath\n self.uid = 0\n self.gid = 0\n }\n }\n\n enum FSSyncMethod: String {\n case read = \"Read\"\n case info = \"Info\"\n case walk = \"Walk\"\n\n init(_ method: String) throws {\n switch method {\n case \"Read\":\n self = .read\n case \"Info\":\n self = .info\n case \"Walk\":\n self = .walk\n default:\n throw Error.unknownMethod(method)\n }\n }\n }\n}\n\nextension BuildFSSync {\n enum Error: Swift.Error, CustomStringConvertible, Equatable {\n case buildTransferMissing\n case methodMissing\n case unknownMethod(String)\n case contextNotFound(String)\n case contextIsNotDirectory(String)\n case couldNotDetermineFileSize(String)\n case couldNotDetermineModTime(String)\n case couldNotDetermineFileMode(String)\n case invalidOffsetSizeForFile(String, UInt64, Int)\n case couldNotDetermineUID(String)\n case couldNotDetermineGID(String)\n case pathIsNotChild(String, String)\n\n var description: String {\n switch self {\n case .buildTransferMissing:\n return \"buildTransfer field missing in packet\"\n case .methodMissing:\n return \"method is missing in request\"\n case .unknownMethod(let m):\n return \"unknown content-store method \\(m)\"\n case .contextNotFound(let path):\n return \"context dir \\(path) not found\"\n case .contextIsNotDirectory(let path):\n return \"context \\(path) not a directory\"\n case .couldNotDetermineFileSize(let path):\n return \"could not determine size of file \\(path)\"\n case .couldNotDetermineModTime(let path):\n return \"could not determine last modified time of \\(path)\"\n case .couldNotDetermineFileMode(let path):\n return \"could not determine posix permissions (FileMode) of \\(path)\"\n case .invalidOffsetSizeForFile(let digest, let offset, let size):\n return \"invalid request for file: \\(digest) with offset: \\(offset) size: \\(size)\"\n case .couldNotDetermineUID(let path):\n return \"could not determine UID of file at path: \\(path)\"\n case .couldNotDetermineGID(let path):\n return \"could not determine GID of file at path: \\(path)\"\n case .pathIsNotChild(let path, let parent):\n return \"\\(path) is not a child of \\(parent)\"\n }\n }\n }\n}\n\nextension BuildTransfer {\n fileprivate init(id: String, source: String, complete: Bool, isDir: Bool, metadata: [String: String], data: Data? = nil) {\n self.init()\n self.id = id\n self.source = source\n self.direction = .outof\n self.complete = complete\n self.metadata = metadata\n self.isDirectory = isDir\n if let data {\n self.data = data\n }\n }\n}\n\nextension URL {\n fileprivate func size() throws -> UInt64 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let size = attrs[FileAttributeKey.size] as? UInt64 {\n return size\n }\n throw BuildFSSync.Error.couldNotDetermineFileSize(self.cleanPath)\n }\n\n fileprivate func modTime() throws -> String {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let date = attrs[FileAttributeKey.modificationDate] as? Date {\n return date.rfc3339()\n }\n throw BuildFSSync.Error.couldNotDetermineModTime(self.cleanPath)\n }\n\n fileprivate func isDir() throws -> Bool {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n guard let t = attrs[.type] as? FileAttributeType, t == .typeDirectory else {\n return false\n }\n return true\n }\n\n fileprivate func mode() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let mode = attrs[FileAttributeKey.posixPermissions] as? NSNumber {\n return mode.uint32Value\n }\n throw BuildFSSync.Error.couldNotDetermineFileMode(self.cleanPath)\n }\n\n fileprivate func uid() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let uid = attrs[.ownerAccountID] as? UInt32 {\n return uid\n }\n throw BuildFSSync.Error.couldNotDetermineUID(self.cleanPath)\n }\n\n fileprivate func gid() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let gid = attrs[.groupOwnerAccountID] as? UInt32 {\n return gid\n }\n throw BuildFSSync.Error.couldNotDetermineGID(self.cleanPath)\n }\n\n fileprivate func buildTransfer(\n id: String,\n contextDir: URL? = nil,\n complete: Bool = false,\n data: Data = Data()\n ) throws -> BuildTransfer {\n let p = try {\n if let contextDir { return try self.relativeChildPath(to: contextDir) }\n return self.cleanPath\n }()\n return BuildTransfer(\n id: id,\n source: String(p),\n complete: complete,\n isDir: try self.isDir(),\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": String(try self.mode()),\n \"size\": String(try self.size()),\n \"modified_at\": try self.modTime(),\n \"uid\": String(try self.uid()),\n \"gid\": String(try self.gid()),\n ],\n data: data\n )\n }\n}\n\nextension Date {\n fileprivate func rfc3339() -> String {\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"yyyy-MM-dd'T'HH:mm:ssZZZZZ\"\n dateFormatter.locale = Locale(identifier: \"en_US_POSIX\")\n dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // Adjust if necessary\n\n return dateFormatter.string(from: self)\n }\n}\n\nextension String {\n var cleanPathComponent: String {\n let trimmed = self.trimmingCharacters(in: CharacterSet(charactersIn: \"/\"))\n if let clean = trimmed.removingPercentEncoding {\n return clean\n }\n return trimmed\n }\n}\n"], ["/container/Sources/ContainerClient/Archiver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationArchive\nimport ContainerizationOS\nimport Foundation\n\npublic final class Archiver: Sendable {\n public struct ArchiveEntryInfo: Sendable {\n let pathOnHost: URL\n let pathInArchive: URL\n\n public init(pathOnHost: URL, pathInArchive: URL) {\n self.pathOnHost = pathOnHost\n self.pathInArchive = pathInArchive\n }\n }\n\n public static func compress(\n source: URL,\n destination: URL,\n followSymlinks: Bool = false,\n writerConfiguration: ArchiveWriterConfiguration = ArchiveWriterConfiguration(format: .paxRestricted, filter: .gzip),\n closure: (URL) -> ArchiveEntryInfo?\n ) throws {\n let source = source.standardizedFileURL\n let destination = destination.standardizedFileURL\n\n let fileManager = FileManager.default\n try? fileManager.removeItem(at: destination)\n\n do {\n let directory = destination.deletingLastPathComponent()\n try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)\n\n guard\n let enumerator = FileManager.default.enumerator(\n at: source,\n includingPropertiesForKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]\n )\n else {\n throw Error.fileDoesNotExist(source)\n }\n\n var entryInfo = [ArchiveEntryInfo]()\n if !source.isDirectory {\n if let info = closure(source) {\n entryInfo.append(info)\n }\n } else {\n while let url = enumerator.nextObject() as? URL {\n guard let info = closure(url) else {\n continue\n }\n entryInfo.append(info)\n }\n }\n\n let archiver = try ArchiveWriter(\n configuration: writerConfiguration\n )\n try archiver.open(file: destination)\n\n for info in entryInfo {\n guard let entry = try Self._createEntry(entryInfo: info) else {\n throw Error.failedToCreateEntry\n }\n try Self._compressFile(item: info.pathOnHost, entry: entry, archiver: archiver)\n }\n try archiver.finishEncoding()\n } catch {\n try? fileManager.removeItem(at: destination)\n throw error\n }\n }\n\n public static func uncompress(source: URL, destination: URL) throws {\n let source = source.standardizedFileURL\n let destination = destination.standardizedFileURL\n\n // TODO: ArchiveReader needs some enhancement to support buffered uncompression\n let reader = try ArchiveReader(\n format: .paxRestricted,\n filter: .gzip,\n file: source\n )\n\n for (entry, data) in reader {\n guard let path = entry.path else {\n continue\n }\n let uncompressPath = destination.appendingPathComponent(path)\n\n let fileManager = FileManager.default\n switch entry.fileType {\n case .blockSpecial, .characterSpecial, .socket:\n continue\n case .directory:\n try fileManager.createDirectory(\n at: uncompressPath,\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: entry.permissions\n ]\n )\n case .regular:\n try fileManager.createDirectory(\n at: uncompressPath.deletingLastPathComponent(),\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: 0o755\n ]\n )\n let success = fileManager.createFile(\n atPath: uncompressPath.path,\n contents: data,\n attributes: [\n FileAttributeKey.posixPermissions: entry.permissions\n ]\n )\n if !success {\n throw POSIXError.fromErrno()\n }\n try data.write(to: uncompressPath)\n case .symbolicLink:\n guard let target = entry.symlinkTarget else {\n continue\n }\n try fileManager.createDirectory(\n at: uncompressPath.deletingLastPathComponent(),\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: 0o755\n ]\n )\n try fileManager.createSymbolicLink(atPath: uncompressPath.path, withDestinationPath: target)\n continue\n default:\n continue\n }\n\n // FIXME: uid/gid for compress.\n try fileManager.setAttributes(\n [.posixPermissions: NSNumber(value: entry.permissions)],\n ofItemAtPath: uncompressPath.path\n )\n\n if let creationDate = entry.creationDate {\n try fileManager.setAttributes(\n [.creationDate: creationDate],\n ofItemAtPath: uncompressPath.path\n )\n }\n\n if let modificationDate = entry.modificationDate {\n try fileManager.setAttributes(\n [.modificationDate: modificationDate],\n ofItemAtPath: uncompressPath.path\n )\n }\n }\n }\n\n // MARK: private functions\n private static func _compressFile(item: URL, entry: WriteEntry, archiver: ArchiveWriter) throws {\n guard let stream = InputStream(url: item) else {\n return\n }\n\n let writer = archiver.makeTransactionWriter()\n\n let bufferSize = Int(1.mib())\n let readBuffer = UnsafeMutablePointer.allocate(capacity: bufferSize)\n\n stream.open()\n try writer.writeHeader(entry: entry)\n while true {\n let byteRead = stream.read(readBuffer, maxLength: bufferSize)\n if byteRead <= 0 {\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n try data.withUnsafeBytes { pointer in\n try writer.writeChunk(data: pointer)\n }\n }\n }\n stream.close()\n try writer.finish()\n }\n\n private static func _createEntry(entryInfo: ArchiveEntryInfo, pathPrefix: String = \"\") throws -> WriteEntry? {\n let entry = WriteEntry()\n let fileManager = FileManager.default\n let attributes = try fileManager.attributesOfItem(atPath: entryInfo.pathOnHost.path)\n\n if let fileType = attributes[.type] as? FileAttributeType {\n switch fileType {\n case .typeBlockSpecial, .typeCharacterSpecial, .typeSocket:\n return nil\n case .typeDirectory:\n entry.fileType = .directory\n case .typeRegular:\n entry.fileType = .regular\n case .typeSymbolicLink:\n entry.fileType = .symbolicLink\n let symlinkTarget = try fileManager.destinationOfSymbolicLink(atPath: entryInfo.pathOnHost.path)\n entry.symlinkTarget = symlinkTarget\n default:\n return nil\n }\n }\n if let posixPermissions = attributes[.posixPermissions] as? NSNumber {\n #if os(macOS)\n entry.permissions = posixPermissions.uint16Value\n #else\n entry.permissions = posixPermissions.uint32Value\n #endif\n }\n if let fileSize = attributes[.size] as? UInt64 {\n entry.size = Int64(fileSize)\n }\n if let uid = attributes[.ownerAccountID] as? NSNumber {\n entry.owner = uid.uint32Value\n }\n if let gid = attributes[.groupOwnerAccountID] as? NSNumber {\n entry.group = gid.uint32Value\n }\n if let creationDate = attributes[.creationDate] as? Date {\n entry.creationDate = creationDate\n }\n if let modificationDate = attributes[.modificationDate] as? Date {\n entry.modificationDate = modificationDate\n }\n\n let pathTrimmed = Self._trimPathPrefix(entryInfo.pathInArchive.relativePath, pathPrefix: pathPrefix)\n entry.path = pathTrimmed\n return entry\n }\n\n private static func _trimPathPrefix(_ path: String, pathPrefix: String) -> String {\n guard !path.isEmpty && !pathPrefix.isEmpty else {\n return path\n }\n\n let decodedPath = path.removingPercentEncoding ?? path\n\n guard decodedPath.hasPrefix(pathPrefix) else {\n return decodedPath\n }\n let trimmedPath = String(decodedPath.suffix(from: pathPrefix.endIndex))\n return trimmedPath\n }\n\n private static func _isSymbolicLink(_ path: URL) throws -> Bool {\n let resourceValues = try path.resourceValues(forKeys: [.isSymbolicLinkKey])\n if let isSymbolicLink = resourceValues.isSymbolicLink {\n if isSymbolicLink {\n return true\n }\n }\n return false\n }\n}\n\nextension Archiver {\n public enum Error: Swift.Error, CustomStringConvertible {\n case failedToCreateEntry\n case fileDoesNotExist(_ url: URL)\n\n public var description: String {\n switch self {\n case .failedToCreateEntry:\n return \"failed to create entry\"\n case .fileDoesNotExist(let url):\n return \"file \\(url.path) does not exist\"\n }\n }\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/NonisolatedInterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Logging\nimport Virtualization\nimport vmnet\n\n/// Interface strategy for containers that use macOS's custom network feature.\n@available(macOS 26, *)\nstruct NonisolatedInterfaceStrategy: InterfaceStrategy {\n private let log: Logger\n\n public init(log: Logger) {\n self.log = log\n }\n\n public func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) throws -> Interface {\n guard let additionalData else {\n throw ContainerizationError(.invalidState, message: \"network state does not contain custom network reference\")\n }\n\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let networkRef = vmnet_network_create_with_serialization(additionalData.underlying, &status) else {\n throw ContainerizationError(.invalidState, message: \"cannot deserialize custom network reference, status \\(status)\")\n }\n\n log.info(\"creating NATNetworkInterface with network reference\")\n let gateway = interfaceIndex == 0 ? attachment.gateway : nil\n return NATNetworkInterface(address: attachment.address, gateway: gateway, reference: networkRef)\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientProcess.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport NIOCore\nimport NIOPosix\nimport TerminalProgress\n\n/// A protocol that defines the methods and data members available to a process\n/// started inside of a container.\npublic protocol ClientProcess: Sendable {\n /// Identifier for the process.\n var id: String { get }\n\n /// Start the underlying process inside of the container.\n func start(_ stdio: [FileHandle?]) async throws\n /// Send a terminal resize request to the process `id`.\n func resize(_ size: Terminal.Size) async throws\n /// Send or \"kill\" a signal to the process `id`.\n /// Kill does not wait for the process to exit, it only delivers the signal.\n func kill(_ signal: Int32) async throws\n /// Wait for the process `id` to complete and return its exit code.\n /// This method blocks until the process exits and the code is obtained.\n func wait() async throws -> Int32\n}\n\nstruct ClientProcessImpl: ClientProcess, Sendable {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n /// Identifier of the container.\n public let containerId: String\n\n private let client: SandboxClient\n\n /// Identifier of a process. That is running inside of a container.\n /// This field is nil if the process this objects refers to is the\n /// init process of the container.\n public let processId: String?\n\n public var id: String {\n processId ?? containerId\n }\n\n init(containerId: String, processId: String? = nil, client: SandboxClient) {\n self.containerId = containerId\n self.processId = processId\n self.client = client\n }\n\n /// Start the container and return the initial process.\n public func start(_ stdio: [FileHandle?]) async throws {\n do {\n let client = self.client\n try await client.startProcess(self.id, stdio: stdio)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to start container\",\n cause: error\n )\n }\n }\n\n public func kill(_ signal: Int32) async throws {\n do {\n\n let client = self.client\n try await client.kill(self.id, signal: Int64(signal))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill process\",\n cause: error\n )\n }\n }\n\n public func resize(_ size: ContainerizationOS.Terminal.Size) async throws {\n do {\n\n let client = self.client\n try await client.resize(self.id, size: size)\n\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to resize process\",\n cause: error\n )\n }\n }\n\n public func wait() async throws -> Int32 {\n do {\n let client = self.client\n return try await client.wait(self.id)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to wait on process\",\n cause: error\n )\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport Foundation\n\n/// A client for interacting with a single network.\npublic struct NetworkClient: Sendable {\n // FIXME: need more flexibility than a hard-coded constant?\n static let label = \"com.apple.container.network.container-network-vmnet\"\n\n private var machServiceLabel: String {\n \"\\(Self.label).\\(id)\"\n }\n\n let id: String\n\n /// Create a client for a network.\n public init(id: String) {\n self.id = id\n }\n}\n\n// Runtime Methods\nextension NetworkClient {\n public func state() async throws -> NetworkState {\n let request = XPCMessage(route: NetworkRoutes.state.rawValue)\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n let state = try response.state()\n return state\n }\n\n public func allocate(hostname: String) async throws -> (attachment: Attachment, additionalData: XPCMessage?) {\n let request = XPCMessage(route: NetworkRoutes.allocate.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n let attachment = try response.attachment()\n let additionalData = response.additionalData()\n return (attachment, additionalData)\n }\n\n public func deallocate(hostname: String) async throws {\n let request = XPCMessage(route: NetworkRoutes.deallocate.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func lookup(hostname: String) async throws -> Attachment? {\n let request = XPCMessage(route: NetworkRoutes.lookup.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.dataNoCopy(key: NetworkKeys.attachment.rawValue).map {\n try JSONDecoder().decode(Attachment.self, from: $0)\n }\n }\n\n public func disableAllocator() async throws -> Bool {\n let request = XPCMessage(route: NetworkRoutes.disableAllocator.rawValue)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.allocatorDisabled()\n }\n\n private func createClient() -> XPCClient {\n XPCClient(service: machServiceLabel)\n }\n}\n\nextension XPCMessage {\n func additionalData() -> XPCMessage? {\n guard let additionalData = xpc_dictionary_get_dictionary(self.underlying, NetworkKeys.additionalData.rawValue) else {\n return nil\n }\n return XPCMessage(object: additionalData)\n }\n\n func allocatorDisabled() throws -> Bool {\n self.bool(key: NetworkKeys.allocatorDisabled.rawValue)\n }\n\n func attachment() throws -> Attachment {\n let data = self.dataNoCopy(key: NetworkKeys.attachment.rawValue)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No network attachment snapshot data in message\")\n }\n return try JSONDecoder().decode(Attachment.self, from: data)\n }\n\n func hostname() throws -> String {\n let hostname = self.string(key: NetworkKeys.hostname.rawValue)\n guard let hostname else {\n throw ContainerizationError(.invalidArgument, message: \"No hostname data in message\")\n }\n return hostname\n }\n\n func state() throws -> NetworkState {\n let data = self.dataNoCopy(key: NetworkKeys.state.rawValue)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No network snapshot data in message\")\n }\n return try JSONDecoder().decode(NetworkState.self, from: data)\n }\n}\n"], ["/container/Sources/ContainerClient/Flags.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationError\nimport Foundation\n\npublic struct Flags {\n public struct Global: ParsableArguments {\n public init() {}\n\n @Flag(name: .long, help: \"Enable debug output [environment: CONTAINER_DEBUG]\")\n public var debug = false\n }\n\n public struct Process: ParsableArguments {\n public init() {}\n\n @Option(\n name: [.customLong(\"cwd\"), .customShort(\"w\"), .customLong(\"workdir\")],\n help: \"Current working directory for the container\")\n public var cwd: String?\n\n @Option(name: [.customLong(\"env\"), .customShort(\"e\")], help: \"Set environment variables\")\n public var env: [String] = []\n\n @Option(name: .customLong(\"env-file\"), help: \"Read in a file of environment variables\")\n public var envFile: [String] = []\n\n @Option(name: .customLong(\"uid\"), help: \"Set the uid for the process\")\n public var uid: UInt32?\n\n @Option(name: .customLong(\"gid\"), help: \"Set the gid for the process\")\n public var gid: UInt32?\n\n @Flag(name: [.customLong(\"interactive\"), .customShort(\"i\")], help: \"Keep Stdin open even if not attached\")\n public var interactive = false\n\n @Flag(name: [.customLong(\"tty\"), .customShort(\"t\")], help: \"Open a tty with the process\")\n public var tty = false\n\n @Option(name: [.customLong(\"user\"), .customShort(\"u\")], help: \"Set the user for the process\")\n public var user: String?\n }\n\n public struct Resource: ParsableArguments {\n public init() {}\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64?\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n public var memory: String?\n }\n\n public struct Registry: ParsableArguments {\n public init() {}\n\n public init(scheme: String) {\n self.scheme = scheme\n }\n\n @Option(help: \"Scheme to use when connecting to the container registry. One of (http, https, auto)\")\n public var scheme: String = \"auto\"\n }\n\n public struct Management: ParsableArguments {\n public init() {}\n\n @Flag(name: [.customLong(\"detach\"), .short], help: \"Run the container and detach from the process\")\n public var detach = false\n\n @Option(name: .customLong(\"entrypoint\"), help: \"Override the entrypoint of the image\")\n public var entryPoint: String?\n\n @Option(name: .customLong(\"mount\"), help: \"Add a mount to the container (type=<>,source=<>,target=<>,readonly)\")\n public var mounts: [String] = []\n\n @Option(name: [.customLong(\"publish\"), .short], help: \"Publish a port from container to host (format: [host-ip:]host-port:container-port[/protocol])\")\n public var publishPorts: [String] = []\n\n @Option(name: .customLong(\"publish-socket\"), help: \"Publish a socket from container to host (format: host_path:container_path)\")\n public var publishSockets: [String] = []\n\n @Option(name: .customLong(\"tmpfs\"), help: \"Add a tmpfs mount to the container at the given path\")\n public var tmpFs: [String] = []\n\n @Option(name: .customLong(\"name\"), help: \"Assign a name to the container. If excluded will be a generated UUID\")\n public var name: String?\n\n @Flag(name: [.customLong(\"remove\"), .customLong(\"rm\")], help: \"Remove the container after it stops\")\n public var remove = false\n\n @Option(name: .customLong(\"os\"), help: \"Set OS if image can target multiple operating systems\")\n public var os = \"linux\"\n\n @Option(\n name: [.customLong(\"arch\"), .short], help: \"Set arch if image can target multiple architectures\")\n public var arch: String = Arch.hostArchitecture().rawValue\n\n @Option(name: [.customLong(\"volume\"), .short], help: \"Bind mount a volume into the container\")\n public var volumes: [String] = []\n\n @Option(\n name: [.customLong(\"kernel\"), .short], help: \"Set a custom kernel path\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n public var kernel: String?\n\n @Option(name: [.customLong(\"network\")], help: \"Attach the container to a network\")\n public var networks: [String] = []\n\n @Option(name: .customLong(\"cidfile\"), help: \"Write the container ID to the path provided\")\n public var cidfile = \"\"\n\n @Flag(name: [.customLong(\"no-dns\")], help: \"Do not configure DNS in the container\")\n public var dnsDisabled = false\n\n @Option(name: .customLong(\"dns\"), help: \"DNS nameserver IP address\")\n public var dnsNameservers: [String] = []\n\n @Option(name: .customLong(\"dns-domain\"), help: \"Default DNS domain\")\n public var dnsDomain: String? = nil\n\n @Option(name: .customLong(\"dns-search\"), help: \"DNS search domains\")\n public var dnsSearchDomains: [String] = []\n\n @Option(name: .customLong(\"dns-option\"), help: \"DNS options\")\n public var dnsOptions: [String] = []\n\n @Option(name: [.customLong(\"label\"), .short], help: \"Add a key=value label to the container\")\n public var labels: [String] = []\n }\n\n public struct Progress: ParsableArguments {\n public init() {}\n\n public init(disableProgressUpdates: Bool) {\n self.disableProgressUpdates = disableProgressUpdates\n }\n\n @Flag(name: .customLong(\"disable-progress-updates\"), help: \"Disable progress bar updates\")\n public var disableProgressUpdates = false\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\n\nextension Application {\n struct DNSCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a local DNS domain for containers (must run as an administrator)\"\n )\n\n @Argument(help: \"the local domain name\")\n var domainName: String\n\n func run() async throws {\n let resolver: HostDNSResolver = HostDNSResolver()\n do {\n try resolver.createDomain(name: domainName)\n print(domainName)\n } catch let error as ContainerizationError {\n throw error\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot create domain (try sudo?)\")\n }\n\n do {\n try HostDNSResolver.reinitialize()\n } catch {\n throw ContainerizationError(.invalidState, message: \"mDNSResponder restart failed, run `sudo killall -HUP mDNSResponder` to deactivate domain\")\n }\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ImageService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport Logging\nimport TerminalProgress\n\npublic actor ImagesService {\n public static let keychainID = \"com.apple.container\"\n\n private let log: Logger\n private let contentStore: ContentStore\n private let imageStore: ImageStore\n private let snapshotStore: SnapshotStore\n\n public init(contentStore: ContentStore, imageStore: ImageStore, snapshotStore: SnapshotStore, log: Logger) throws {\n self.contentStore = contentStore\n self.imageStore = imageStore\n self.snapshotStore = snapshotStore\n self.log = log\n }\n\n private func _list() async throws -> [Containerization.Image] {\n try await imageStore.list()\n }\n\n private func _get(_ reference: String) async throws -> Containerization.Image {\n try await imageStore.get(reference: reference)\n }\n\n private func _get(_ description: ImageDescription) async throws -> Containerization.Image {\n let exists = try await self._get(description.reference)\n guard exists.descriptor == description.descriptor else {\n throw ContainerizationError(.invalidState, message: \"Descriptor mismatch. Expected \\(description.descriptor), got \\(exists.descriptor)\")\n }\n return exists\n }\n\n public func list() async throws -> [ImageDescription] {\n self.log.info(\"ImagesService: \\(#function)\")\n return try await imageStore.list().map { $0.description.fromCZ }\n }\n\n public func pull(reference: String, platform: Platform?, insecure: Bool, progressUpdate: ProgressUpdateHandler?) async throws -> ImageDescription {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference), platform: \\(String(describing: platform)), insecure: \\(insecure)\")\n let img = try await Self.withAuthentication(ref: reference) { auth in\n try await self.imageStore.pull(\n reference: reference, platform: platform, insecure: insecure, auth: auth, progress: ContainerizationProgressAdapter.handler(from: progressUpdate))\n }\n guard let img else {\n throw ContainerizationError(.internalError, message: \"Failed to pull image \\(reference)\")\n }\n return img.description.fromCZ\n }\n\n public func push(reference: String, platform: Platform?, insecure: Bool, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference), platform: \\(String(describing: platform)), insecure: \\(insecure)\")\n try await Self.withAuthentication(ref: reference) { auth in\n try await self.imageStore.push(\n reference: reference, platform: platform, insecure: insecure, auth: auth, progress: ContainerizationProgressAdapter.handler(from: progressUpdate))\n }\n }\n\n public func tag(old: String, new: String) async throws -> ImageDescription {\n self.log.info(\"ImagesService: \\(#function) - old: \\(old), new: \\(new)\")\n let img = try await self.imageStore.tag(existing: old, new: new)\n return img.description.fromCZ\n }\n\n public func delete(reference: String, garbageCollect: Bool) async throws {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference)\")\n try await self.imageStore.delete(reference: reference, performCleanup: garbageCollect)\n }\n\n public func save(reference: String, out: URL, platform: Platform?) async throws {\n self.log.info(\"ImagesService: \\(#function) - reference: \\(reference) , platform: \\(String(describing: platform))\")\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try await self.imageStore.save(references: [reference], out: tempDir, platform: platform)\n let writer = try ArchiveWriter(format: .pax, filter: .none, file: out)\n try writer.archiveDirectory(tempDir)\n try writer.finishEncoding()\n }\n\n public func load(from tarFile: URL) async throws -> [ImageDescription] {\n self.log.info(\"ImagesService: \\(#function) from: \\(tarFile.absolutePath())\")\n let reader = try ArchiveReader(file: tarFile)\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try reader.extractContents(to: tempDir)\n let loaded = try await self.imageStore.load(from: tempDir)\n var images: [ImageDescription] = []\n for image in loaded {\n images.append(image.description.fromCZ)\n }\n return images\n }\n\n public func prune() async throws -> ([String], UInt64) {\n let images = try await self._list()\n let freedSnapshotBytes = try await self.snapshotStore.clean(keepingSnapshotsFor: images)\n let (deleted, freedContentBytes) = try await self.imageStore.prune()\n return (deleted, freedContentBytes + freedSnapshotBytes)\n }\n}\n\n// MARK: Image Snapshot Methods\n\nextension ImagesService {\n public func unpack(description: ImageDescription, platform: Platform?, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n try await self.snapshotStore.unpack(image: img, platform: platform, progressUpdate: progressUpdate)\n }\n\n public func deleteImageSnapshot(description: ImageDescription, platform: Platform?) async throws {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n try await self.snapshotStore.delete(for: img, platform: platform)\n }\n\n public func getImageSnapshot(description: ImageDescription, platform: Platform) async throws -> Filesystem {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n return try await self.snapshotStore.get(for: img, platform: platform)\n }\n}\n\n// MARK: Static Methods\n\nextension ImagesService {\n private static func withAuthentication(\n ref: String, _ body: @Sendable @escaping (_ auth: Authentication?) async throws -> T?\n ) async throws -> T? {\n var authentication: Authentication?\n let ref = try Reference.parse(ref)\n guard let host = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"No host specified in image reference: \\(ref)\")\n }\n authentication = Self.authenticationFromEnv(host: host)\n if let authentication {\n return try await body(authentication)\n }\n let keychain = KeychainHelper(id: Self.keychainID)\n do {\n authentication = try keychain.lookup(domain: host)\n } catch let err as KeychainHelper.Error {\n guard case .keyNotFound = err else {\n throw ContainerizationError(.internalError, message: \"Error querying keychain for \\(host)\", cause: err)\n }\n }\n do {\n return try await body(authentication)\n } catch let err as RegistryClient.Error {\n guard case .invalidStatus(_, let status, _) = err else {\n throw err\n }\n guard status == .unauthorized || status == .forbidden else {\n throw err\n }\n guard authentication != nil else {\n throw ContainerizationError(.internalError, message: \"\\(String(describing: err)). No credentials found for host \\(host)\")\n }\n throw err\n }\n }\n\n private static func authenticationFromEnv(host: String) -> Authentication? {\n let env = ProcessInfo.processInfo.environment\n guard env[\"CONTAINER_REGISTRY_HOST\"] == host else {\n return nil\n }\n guard let user = env[\"CONTAINER_REGISTRY_USER\"], let password = env[\"CONTAINER_REGISTRY_TOKEN\"] else {\n return nil\n }\n return BasicAuthentication(username: user, password: password)\n }\n}\n\nextension ImageDescription {\n public var toCZ: Containerization.Image.Description {\n .init(reference: self.reference, descriptor: self.descriptor)\n }\n}\n\nextension Containerization.Image.Description {\n public var fromCZ: ImageDescription {\n .init(\n reference: self.reference,\n descriptor: self.descriptor\n )\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePull.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport TerminalProgress\n\nextension Application {\n struct ImagePull: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"pull\",\n abstract: \"Pull an image\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Argument var reference: String\n\n init() {}\n\n init(platform: String? = nil, scheme: String = \"auto\", reference: String, disableProgress: Bool = false) {\n self.global = Flags.Global()\n self.registry = Flags.Registry(scheme: scheme)\n self.progressFlags = Flags.Progress(disableProgressUpdates: disableProgress)\n self.platform = platform\n self.reference = reference\n }\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let scheme = try RequestScheme(registry.scheme)\n\n let processedReference = try ClientImage.normalizeReference(reference)\n\n var progressConfig: ProgressConfig\n if self.progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: self.progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 2\n )\n }\n\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Fetching image\")\n progress.set(itemsName: \"blobs\")\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n let image = try await ClientImage.pull(\n reference: processedReference, platform: p, scheme: scheme, progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progress.handler)\n )\n\n progress.set(description: \"Unpacking image\")\n progress.set(itemsName: \"entries\")\n let unpackTask = await taskManager.startTask()\n try await image.unpack(platform: p, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progress.handler))\n await taskManager.finish()\n progress.finish()\n }\n }\n}\n"], ["/container/Sources/APIServer/Kernel/FileDownloader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\ninternal struct FileDownloader {\n public static func downloadFile(url: URL, to destination: URL, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let request = try HTTPClient.Request(url: url)\n\n let delegate = try FileDownloadDelegate(\n path: destination.path(),\n reportHead: {\n let expectedSizeString = $0.headers[\"Content-Length\"].first ?? \"\"\n if let expectedSize = Int64(expectedSizeString) {\n if let progressUpdate {\n Task {\n await progressUpdate([\n .addTotalSize(expectedSize)\n ])\n }\n }\n }\n },\n reportProgress: {\n let receivedBytes = Int64($0.receivedBytes)\n if let progressUpdate {\n Task {\n await progressUpdate([\n .setSize(receivedBytes)\n ])\n }\n }\n })\n\n let client = FileDownloader.createClient()\n _ = try await client.execute(request: request, delegate: delegate).get()\n try await client.shutdown()\n }\n\n private static func createClient() -> HTTPClient {\n var httpConfiguration = HTTPClient.Configuration()\n let proxyConfig: HTTPClient.Configuration.Proxy? = {\n let proxyEnv = ProcessInfo.processInfo.environment[\"HTTP_PROXY\"]\n guard let proxyEnv else {\n return nil\n }\n guard let url = URL(string: proxyEnv), let host = url.host(), let port = url.port else {\n return nil\n }\n return .server(host: host, port: port)\n }()\n httpConfiguration.proxy = proxyConfig\n return HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration)\n }\n}\n"], ["/container/Sources/SocketForwarder/ConnectHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Logging\nimport NIOCore\nimport NIOPosix\n\nfinal class ConnectHandler {\n private var pendingBytes: [NIOAny]\n private let serverAddress: SocketAddress\n private var log: Logger? = nil\n\n init(serverAddress: SocketAddress, log: Logger?) {\n self.pendingBytes = []\n self.serverAddress = serverAddress\n self.log = log\n }\n}\n\nextension ConnectHandler: ChannelInboundHandler {\n typealias InboundIn = ByteBuffer\n typealias OutboundOut = ByteBuffer\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n if self.pendingBytes.isEmpty {\n self.connectToServer(context: context)\n }\n self.pendingBytes.append(data)\n }\n\n func handlerAdded(context: ChannelHandlerContext) {\n // Add logger metadata.\n self.log?[metadataKey: \"proxy\"] = \"\\(context.channel.localAddress?.description ?? \"none\")\"\n self.log?[metadataKey: \"server\"] = \"\\(context.channel.remoteAddress?.description ?? \"none\")\"\n }\n}\n\nextension ConnectHandler: RemovableChannelHandler {\n func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) {\n var didRead = false\n\n // We are being removed, and need to deliver any pending bytes we may have if we're upgrading.\n while self.pendingBytes.count > 0 {\n let data = self.pendingBytes.removeFirst()\n context.fireChannelRead(data)\n didRead = true\n }\n\n if didRead {\n context.fireChannelReadComplete()\n }\n\n self.log?.trace(\"backend - removing connect handler from pipeline\")\n context.leavePipeline(removalToken: removalToken)\n }\n}\n\nextension ConnectHandler {\n private func connectToServer(context: ChannelHandlerContext) {\n self.log?.trace(\"backend - connecting\")\n\n ClientBootstrap(group: context.eventLoop)\n .connect(to: serverAddress)\n .assumeIsolatedUnsafeUnchecked()\n .whenComplete { result in\n switch result {\n case .success(let channel):\n self.log?.trace(\"backend - connected\")\n self.glue(channel, context: context)\n case .failure(let error):\n self.log?.error(\"backend - connect failed: \\(error)\")\n context.close(promise: nil)\n context.fireErrorCaught(error)\n }\n }\n }\n\n private func glue(_ peerChannel: Channel, context: ChannelHandlerContext) {\n self.log?.trace(\"backend - gluing channels\")\n\n // Now we need to glue our channel and the peer channel together.\n let (localGlue, peerGlue) = GlueHandler.matchedPair()\n do {\n try context.channel.pipeline.syncOperations.addHandler(localGlue)\n try peerChannel.pipeline.syncOperations.addHandler(peerGlue)\n context.pipeline.syncOperations.removeHandler(self, promise: nil)\n } catch {\n // Close connected peer channel before closing our channel.\n peerChannel.close(mode: .all, promise: nil)\n context.close(promise: nil)\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/RemoteContentStoreClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Crypto\nimport ContainerizationError\nimport Foundation\nimport ContainerizationOCI\nimport ContainerXPC\n\npublic struct RemoteContentStoreClient: ContentStore {\n private static let serviceIdentifier = \"com.apple.container.core.container-core-images\"\n private static let encoder = JSONEncoder()\n\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public init() {}\n\n private func _get(digest: String) async throws -> URL? {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentGet)\n request.set(key: .digest, value: digest)\n do {\n let response = try await client.send(request)\n guard let path = response.string(key: .contentPath) else {\n return nil\n }\n return URL(filePath: path)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return nil\n }\n throw error\n }\n }\n\n public func get(digest: String) async throws -> Content? {\n guard let url = try await self._get(digest: digest) else {\n return nil\n }\n return try LocalContent(path: url)\n }\n\n public func get(digest: String) async throws -> T? {\n guard let content: Content = try await self.get(digest: digest) else {\n return nil\n }\n return try content.decode()\n }\n\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentClean)\n\n let d = try Self.encoder.encode(keeping)\n request.set(key: .digests, value: d)\n let response = try await client.send(request)\n\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let deleted = try decoder.decode([String].self, from: data)\n let size = response.uint64(key: .size)\n return (deleted, size)\n }\n\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentDelete)\n\n let d = try Self.encoder.encode(digests)\n request.set(key: .digests, value: d)\n let response = try await client.send(request)\n\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let deleted = try decoder.decode([String].self, from: data)\n let size = response.uint64(key: .size)\n return (deleted, size)\n }\n\n @discardableResult\n public func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String] {\n let (id, tempPath) = try await self.newIngestSession()\n try await body(tempPath)\n return try await self.completeIngestSession(id)\n }\n\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestStart)\n let response = try await client.send(request)\n guard let id = response.string(key: .ingestSessionId) else {\n throw ContainerizationError.init(.internalError, message: \"failed create new ingest session\")\n }\n guard let dir = response.string(key: .directory) else {\n throw ContainerizationError.init(.internalError, message: \"failed create new ingest session\")\n }\n return (id, URL(filePath: dir))\n }\n\n @discardableResult\n public func completeIngestSession(_ id: String) async throws -> [String] {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestComplete)\n\n request.set(key: .ingestSessionId, value: id)\n\n let response = try await client.send(request)\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let ingested = try decoder.decode([String].self, from: data)\n return ingested\n }\n\n public func cancelIngestSession(_ id: String) async throws {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestCancel)\n request.set(key: .ingestSessionId, value: id)\n try await client.send(request)\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerBuild/BuildRemoteContentProxy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\n\nstruct BuildRemoteContentProxy: BuildPipelineHandler {\n let local: ContentStore\n\n public init(_ contentStore: ContentStore) throws {\n self.local = contentStore\n }\n\n func accept(_ packet: ServerStream) throws -> Bool {\n guard let imageTransfer = packet.getImageTransfer() else {\n return false\n }\n guard imageTransfer.stage() == \"content-store\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let imageTransfer = packet.getImageTransfer() else {\n throw Error.imageTransferMissing\n }\n\n guard let method = imageTransfer.method() else {\n throw Error.methodMissing\n }\n\n switch try ContentStoreMethod(method) {\n case .info:\n try await self.info(sender, imageTransfer, packet.buildID)\n case .readerAt:\n try await self.readerAt(sender, imageTransfer, packet.buildID)\n default:\n throw Error.unknownMethod(method)\n }\n }\n\n func info(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer, _ buildID: String) async throws {\n let descriptor = try await local.get(digest: packet.tag)\n let size = try descriptor?.size()\n let transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.info.rawValue,\n size: size\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n }\n\n func readerAt(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer, _ buildID: String) async throws {\n let digest = packet.descriptor.digest\n let offset: UInt64 = packet.offset() ?? 0\n let size: Int = packet.len() ?? 0\n guard let descriptor = try await local.get(digest: digest) else {\n throw Error.contentMissing\n }\n if offset == 0 && size == 0 { // Metadata request\n var transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.readerAt.rawValue,\n size: descriptor.size(),\n data: Data()\n )\n transfer.complete = true\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n return\n }\n guard let data = try descriptor.data(offset: offset, length: size) else {\n throw Error.invalidOffsetSizeForContent(packet.descriptor.digest, offset, size)\n }\n\n let transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.readerAt.rawValue,\n size: UInt64(data.count),\n data: data\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n }\n\n func delete(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.delete)\"])\n }\n\n func update(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.update)\"])\n }\n\n func walk(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.walk)\"])\n }\n\n enum ContentStoreMethod: String {\n case info = \"/containerd.services.content.v1.Content/Info\"\n case readerAt = \"/containerd.services.content.v1.Content/ReaderAt\"\n case delete = \"/containerd.services.content.v1.Content/Delete\"\n case update = \"/containerd.services.content.v1.Content/Update\"\n case walk = \"/containerd.services.content.v1.Content/Walk\"\n\n init(_ method: String) throws {\n guard let value = ContentStoreMethod(rawValue: method) else {\n throw Error.unknownMethod(method)\n }\n self = value\n }\n }\n}\n\nextension ImageTransfer {\n fileprivate init(id: String, digest: String, method: String, size: UInt64? = nil, data: Data = Data()) throws {\n self.init()\n self.id = id\n self.tag = digest\n self.metadata = [\n \"os\": \"linux\",\n \"stage\": \"content-store\",\n \"method\": method,\n ]\n if let size {\n self.metadata[\"size\"] = String(size)\n }\n self.complete = true\n self.direction = .into\n self.data = data\n }\n}\n\nextension BuildRemoteContentProxy {\n enum Error: Swift.Error, CustomStringConvertible {\n case imageTransferMissing\n case methodMissing\n case contentMissing\n case unknownMethod(String)\n case invalidOffsetSizeForContent(String, UInt64, Int)\n\n var description: String {\n switch self {\n case .imageTransferMissing:\n return \"imageTransfer is missing\"\n case .methodMissing:\n return \"method is missing in request\"\n case .contentMissing:\n return \"content cannot be found\"\n case .unknownMethod(let m):\n return \"unknown content-store method \\(m)\"\n case .invalidOffsetSizeForContent(let digest, let offset, let size):\n return \"invalid request for content: \\(digest) with offset: \\(offset) size: \\(size)\"\n }\n }\n }\n\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\n\npublic struct ContainerConfiguration: Sendable, Codable {\n /// Identifier for the container.\n public var id: String\n /// Image used to create the container.\n public var image: ImageDescription\n /// External mounts to add to the container.\n public var mounts: [Filesystem] = []\n /// Ports to publish from container to host.\n public var publishedPorts: [PublishPort] = []\n /// Sockets to publish from container to host.\n public var publishedSockets: [PublishSocket] = []\n /// Key/Value labels for the container.\n public var labels: [String: String] = [:]\n /// System controls for the container.\n public var sysctls: [String: String] = [:]\n /// The networks the container will be added to.\n public var networks: [String] = []\n /// The DNS configuration for the container.\n public var dns: DNSConfiguration? = nil\n /// Whether to enable rosetta x86-64 translation for the container.\n public var rosetta: Bool = false\n /// The hostname for the container.\n public var hostname: String? = nil\n /// Initial or main process of the container.\n public var initProcess: ProcessConfiguration\n /// Platform for the container\n public var platform: ContainerizationOCI.Platform = .current\n /// Resource values for the container.\n public var resources: Resources = .init()\n /// Name of the runtime that supports the container\n public var runtimeHandler: String = \"container-runtime-linux\"\n\n enum CodingKeys: String, CodingKey {\n case id\n case image\n case mounts\n case publishedPorts\n case publishedSockets\n case labels\n case sysctls\n case networks\n case dns\n case rosetta\n case hostname\n case initProcess\n case platform\n case resources\n case runtimeHandler\n }\n\n /// Create a configuration from the supplied Decoder, initializing missing\n /// values where possible to reasonable defaults.\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n id = try container.decode(String.self, forKey: .id)\n image = try container.decode(ImageDescription.self, forKey: .image)\n mounts = try container.decodeIfPresent([Filesystem].self, forKey: .mounts) ?? []\n publishedPorts = try container.decodeIfPresent([PublishPort].self, forKey: .publishedPorts) ?? []\n publishedSockets = try container.decodeIfPresent([PublishSocket].self, forKey: .publishedSockets) ?? []\n labels = try container.decodeIfPresent([String: String].self, forKey: .labels) ?? [:]\n sysctls = try container.decodeIfPresent([String: String].self, forKey: .sysctls) ?? [:]\n networks = try container.decodeIfPresent([String].self, forKey: .networks) ?? []\n dns = try container.decodeIfPresent(DNSConfiguration.self, forKey: .dns)\n rosetta = try container.decodeIfPresent(Bool.self, forKey: .rosetta) ?? false\n hostname = try container.decodeIfPresent(String.self, forKey: .hostname)\n initProcess = try container.decode(ProcessConfiguration.self, forKey: .initProcess)\n platform = try container.decodeIfPresent(ContainerizationOCI.Platform.self, forKey: .platform) ?? .current\n resources = try container.decodeIfPresent(Resources.self, forKey: .resources) ?? .init()\n runtimeHandler = try container.decodeIfPresent(String.self, forKey: .runtimeHandler) ?? \"container-runtime-linux\"\n }\n\n public struct DNSConfiguration: Sendable, Codable {\n public static let defaultNameservers = [\"1.1.1.1\"]\n\n public let nameservers: [String]\n public let domain: String?\n public let searchDomains: [String]\n public let options: [String]\n\n public init(\n nameservers: [String] = defaultNameservers,\n domain: String? = nil,\n searchDomains: [String] = [],\n options: [String] = []\n ) {\n self.nameservers = nameservers\n self.domain = domain\n self.searchDomains = searchDomains\n self.options = options\n }\n }\n\n /// Resources like cpu, memory, and storage quota.\n public struct Resources: Sendable, Codable {\n /// Number of CPU cores allocated.\n public var cpus: Int = 4\n /// Memory in bytes allocated.\n public var memoryInBytes: UInt64 = 1024.mib()\n /// Storage quota/size in bytes.\n public var storage: UInt64?\n\n public init() {}\n }\n\n public init(\n id: String,\n image: ImageDescription,\n process: ProcessConfiguration\n ) {\n self.id = id\n self.image = image\n self.initProcess = process\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ImagesServiceHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\npublic struct ImagesServiceHarness: Sendable {\n let log: Logging.Logger\n let service: ImagesService\n\n public init(service: ImagesService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n public func pull(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let insecure = message.bool(key: .insecureFlag)\n\n let progressUpdateService = ProgressUpdateService(message: message)\n let imageDescription = try await service.pull(reference: ref, platform: platform, insecure: insecure, progressUpdate: progressUpdateService?.handler)\n\n let imageData = try JSONEncoder().encode(imageDescription)\n let reply = message.reply()\n reply.set(key: .imageDescription, value: imageData)\n return reply\n }\n\n @Sendable\n public func push(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let insecure = message.bool(key: .insecureFlag)\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await service.push(reference: ref, platform: platform, insecure: insecure, progressUpdate: progressUpdateService?.handler)\n\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func tag(_ message: XPCMessage) async throws -> XPCMessage {\n let old = message.string(key: .imageReference)\n guard let old else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let new = message.string(key: .imageNewReference)\n guard let new else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing new image reference\"\n )\n }\n let newDescription = try await service.tag(old: old, new: new)\n let descData = try JSONEncoder().encode(newDescription)\n let reply = message.reply()\n reply.set(key: .imageDescription, value: descData)\n return reply\n }\n\n @Sendable\n public func list(_ message: XPCMessage) async throws -> XPCMessage {\n let images = try await service.list()\n let imageData = try JSONEncoder().encode(images)\n let reply = message.reply()\n reply.set(key: .imageDescriptions, value: imageData)\n return reply\n }\n\n @Sendable\n public func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let garbageCollect = message.bool(key: .garbageCollect)\n try await self.service.delete(reference: ref, garbageCollect: garbageCollect)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func save(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .imageDescription)\n guard let data else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let imageDescription = try JSONDecoder().decode(ImageDescription.self, from: data)\n\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let out = message.string(key: .filePath)\n guard let out else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing output file path\"\n )\n }\n try await service.save(reference: imageDescription.reference, out: URL(filePath: out), platform: platform)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func load(_ message: XPCMessage) async throws -> XPCMessage {\n let input = message.string(key: .filePath)\n guard let input else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing input file path\"\n )\n }\n let images = try await service.load(from: URL(filePath: input))\n let data = try JSONEncoder().encode(images)\n let reply = message.reply()\n reply.set(key: .imageDescriptions, value: data)\n return reply\n }\n\n @Sendable\n public func prune(_ message: XPCMessage) async throws -> XPCMessage {\n let (deleted, size) = try await service.prune()\n let reply = message.reply()\n let data = try JSONEncoder().encode(deleted)\n reply.set(key: .digests, value: data)\n reply.set(key: .size, value: size)\n return reply\n }\n}\n\n// MARK: Image Snapshot Methods\n\nextension ImagesServiceHarness {\n @Sendable\n public func unpack(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing Image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n var platform: Platform?\n if let platformData = message.dataNoCopy(key: .ociPlatform) {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await self.service.unpack(description: description, platform: platform, progressUpdate: progressUpdateService?.handler)\n\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func deleteSnapshot(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform?\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n try await self.service.deleteImageSnapshot(description: description, platform: platform)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func getSnapshot(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n let platformData = message.dataNoCopy(key: .ociPlatform)\n guard let platformData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing OCI platform\"\n )\n }\n let platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n let fs = try await self.service.getImageSnapshot(description: description, platform: platform)\n let fsData = try JSONEncoder().encode(fs)\n let reply = message.reply()\n reply.set(key: .filesystem, value: fsData)\n return reply\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildImageResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\nimport Logging\n\nstruct BuildImageResolver: BuildPipelineHandler {\n let contentStore: ContentStore\n\n public init(_ contentStore: ContentStore) throws {\n self.contentStore = contentStore\n }\n\n func accept(_ packet: ServerStream) throws -> Bool {\n guard let imageTransfer = packet.getImageTransfer() else {\n return false\n }\n guard imageTransfer.stage() == \"resolver\" else {\n return false\n }\n guard imageTransfer.method() == \"/resolve\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let imageTransfer = packet.getImageTransfer() else {\n throw Error.imageTransferMissing\n }\n guard let ref = imageTransfer.ref() else {\n throw Error.tagMissing\n }\n\n guard let platform = try imageTransfer.platform() else {\n throw Error.platformMissing\n }\n\n let img = try await {\n guard let img = try? await ClientImage.pull(reference: ref, platform: platform) else {\n return try await ClientImage.fetch(reference: ref, platform: platform)\n }\n return img\n }()\n\n let index: Index = try await img.index()\n let buildID = packet.buildID\n let platforms = index.manifests.compactMap { $0.platform }\n for pl in platforms {\n if pl == platform {\n let manifest = try await img.manifest(for: pl)\n guard let ociImage: ContainerizationOCI.Image = try await self.contentStore.get(digest: manifest.config.digest) else {\n continue\n }\n let enc = JSONEncoder()\n let data = try enc.encode(ociImage)\n let transfer = try ImageTransfer(\n id: imageTransfer.id,\n digest: img.descriptor.digest,\n ref: ref,\n platform: platform.description,\n data: data\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n return\n }\n }\n throw Error.unknownPlatformForImage(platform.description, ref)\n }\n}\n\nextension ImageTransfer {\n fileprivate init(id: String, digest: String, ref: String, platform: String, data: Data) throws {\n self.init()\n self.id = id\n self.tag = digest\n self.metadata = [\n \"os\": \"linux\",\n \"stage\": \"resolver\",\n \"method\": \"/resolve\",\n \"ref\": ref,\n \"platform\": platform,\n ]\n self.complete = true\n self.direction = .into\n self.data = data\n }\n}\n\nextension BuildImageResolver {\n enum Error: Swift.Error, CustomStringConvertible {\n case imageTransferMissing\n case tagMissing\n case platformMissing\n case imageNameMissing\n case imageTagMissing\n case imageNotFound\n case indexDigestMissing(String)\n case unknownRegistry(String)\n case digestIsNotIndex(String)\n case digestIsNotManifest(String)\n case unknownPlatformForImage(String, String)\n\n var description: String {\n switch self {\n case .imageTransferMissing:\n return \"imageTransfer is missing\"\n case .tagMissing:\n return \"tag parameter missing in metadata\"\n case .platformMissing:\n return \"platform parameter missing in metadata\"\n case .imageNameMissing:\n return \"image name missing in $ref parameter\"\n case .imageTagMissing:\n return \"image tag missing in $ref parameter\"\n case .imageNotFound:\n return \"image not found\"\n case .indexDigestMissing(let ref):\n return \"index digest is missing for image: \\(ref)\"\n case .unknownRegistry(let registry):\n return \"registry \\(registry) is unknown\"\n case .digestIsNotIndex(let digest):\n return \"digest \\(digest) is not a descriptor to an index\"\n case .digestIsNotManifest(let digest):\n return \"digest \\(digest) is not a descriptor to a manifest\"\n case .unknownPlatformForImage(let platform, let ref):\n return \"platform \\(platform) for image \\(ref) not found\"\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/SandboxClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport TerminalProgress\n\n/// A client for interacting with a single sandbox.\npublic struct SandboxClient: Sendable, Codable {\n static let label = \"com.apple.container.runtime\"\n\n public static func machServiceLabel(runtime: String, id: String) -> String {\n \"\\(Self.label).\\(runtime).\\(id)\"\n }\n\n private var machServiceLabel: String {\n Self.machServiceLabel(runtime: runtime, id: id)\n }\n\n let id: String\n let runtime: String\n\n /// Create a container.\n public init(id: String, runtime: String) {\n self.id = id\n self.runtime = runtime\n }\n}\n\n// Runtime Methods\nextension SandboxClient {\n public func bootstrap() async throws {\n let request = XPCMessage(route: SandboxRoutes.bootstrap.rawValue)\n let client = createClient()\n defer { client.close() }\n\n try await client.send(request)\n }\n\n public func state() async throws -> SandboxSnapshot {\n let request = XPCMessage(route: SandboxRoutes.state.rawValue)\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.sandboxSnapshot()\n }\n\n public func createProcess(_ id: String, config: ProcessConfiguration) async throws {\n let request = XPCMessage(route: SandboxRoutes.createProcess.rawValue)\n request.set(key: .id, value: id)\n let data = try JSONEncoder().encode(config)\n request.set(key: .processConfig, value: data)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func startProcess(_ id: String, stdio: [FileHandle?]) async throws {\n let request = XPCMessage(route: SandboxRoutes.start.rawValue)\n for (i, h) in stdio.enumerated() {\n let key: XPCKeys = {\n switch i {\n case 0: .stdin\n case 1: .stdout\n case 2: .stderr\n default:\n fatalError(\"invalid fd \\(i)\")\n }\n }()\n\n if let h {\n request.set(key: key, value: h)\n }\n }\n request.set(key: .id, value: id)\n\n let client = createClient()\n defer { client.close() }\n\n try await client.send(request)\n }\n\n public func stop(options: ContainerStopOptions) async throws {\n let request = XPCMessage(route: SandboxRoutes.stop.rawValue)\n\n let data = try JSONEncoder().encode(options)\n request.set(key: .stopOptions, value: data)\n\n let client = createClient()\n defer { client.close() }\n let responseTimeout = Duration(.seconds(Int64(options.timeoutInSeconds + 1)))\n try await client.send(request, responseTimeout: responseTimeout)\n }\n\n public func kill(_ id: String, signal: Int64) async throws {\n let request = XPCMessage(route: SandboxRoutes.kill.rawValue)\n request.set(key: .id, value: id)\n request.set(key: .signal, value: signal)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func resize(_ id: String, size: Terminal.Size) async throws {\n let request = XPCMessage(route: SandboxRoutes.resize.rawValue)\n request.set(key: .id, value: id)\n request.set(key: .width, value: UInt64(size.width))\n request.set(key: .height, value: UInt64(size.height))\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func wait(_ id: String) async throws -> Int32 {\n let request = XPCMessage(route: SandboxRoutes.wait.rawValue)\n request.set(key: .id, value: id)\n\n let client = createClient()\n defer { client.close() }\n let response = try await client.send(request)\n let code = response.int64(key: .exitCode)\n return Int32(code)\n }\n\n public func dial(_ port: UInt32) async throws -> FileHandle {\n let request = XPCMessage(route: SandboxRoutes.dial.rawValue)\n request.set(key: .port, value: UInt64(port))\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n guard let fh = response.fileHandle(key: .fd) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get fd for vsock port \\(port)\"\n )\n }\n return fh\n }\n\n private func createClient() -> XPCClient {\n XPCClient(service: machServiceLabel)\n }\n}\n\nextension XPCMessage {\n public func id() throws -> String {\n let id = self.string(key: .id)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"No id\")\n }\n return id\n }\n\n func sandboxSnapshot() throws -> SandboxSnapshot {\n let data = self.dataNoCopy(key: .snapshot)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No state data returned\")\n }\n return try JSONDecoder().decode(SandboxSnapshot.self, from: data)\n }\n}\n"], ["/container/Sources/APIServer/ContainerDNSHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\nimport DNSServer\n\n/// Handler that uses table lookup to resolve hostnames.\nstruct ContainerDNSHandler: DNSHandler {\n private let networkService: NetworksService\n private let ttl: UInt32\n\n public init(networkService: NetworksService, ttl: UInt32 = 5) {\n self.networkService = networkService\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n let record: ResourceRecord?\n switch question.type {\n case ResourceRecordType.host:\n record = try await answerHost(question: question)\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n\n guard let record else {\n return nil\n }\n\n return Message(\n id: query.id,\n type: .response,\n returnCode: .noError,\n questions: query.questions,\n answers: [record]\n )\n }\n\n private func answerHost(question: Question) async throws -> ResourceRecord? {\n guard let ipAllocation = try await networkService.lookup(hostname: question.name) else {\n return nil\n }\n\n let components = ipAllocation.address.split(separator: \"/\")\n guard !components.isEmpty else {\n throw DNSResolverError.serverError(\"Invalid IP format: empty address\")\n }\n\n let ipString = String(components[0])\n guard let ip = IPv4(ipString) else {\n throw DNSResolverError.serverError(\"Failed to parse IP address: \\(ipString)\")\n }\n\n return HostRecord(name: question.name, ttl: ttl, ip: ip)\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ContainerInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more containers\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Containers to inspect\")\n var containers: [String]\n\n func run() async throws {\n let objects: [any Codable] = try await ClientContainer.list().filter {\n containers.contains($0.id)\n }.map {\n PrintableContainer($0)\n }\n print(try objects.jsonArray())\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePush.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport TerminalProgress\n\nextension Application {\n struct ImagePush: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"push\",\n abstract: \"Push an image\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Argument var reference: String\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let scheme = try RequestScheme(registry.scheme)\n let image = try await ClientImage.get(reference: reference)\n\n var progressConfig: ProgressConfig\n if progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n description: \"Pushing image \\(image.reference)\",\n itemsName: \"blobs\",\n showItems: true,\n showSpeed: false,\n ignoreSmallSize: true\n )\n }\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n _ = try await image.push(platform: p, scheme: scheme, progressUpdate: progress.handler)\n progress.finish()\n }\n }\n}\n"], ["/container/Sources/DNSServer/DNSServer+Handle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport NIOCore\nimport NIOPosix\n\nextension DNSServer {\n /// Handles the DNS request.\n /// - Parameters:\n /// - outbound: The NIOAsyncChannelOutboundWriter for which to respond.\n /// - packet: The request packet.\n func handle(\n outbound: NIOAsyncChannelOutboundWriter>,\n packet: inout AddressedEnvelope\n ) async throws {\n let chunkSize = 512\n var data = Data()\n\n self.log?.debug(\"reading data\")\n while packet.data.readableBytes > 0 {\n if let chunk = packet.data.readBytes(length: min(chunkSize, packet.data.readableBytes)) {\n data.append(contentsOf: chunk)\n }\n }\n\n self.log?.debug(\"deserializing message\")\n let query = try Message(deserialize: data)\n self.log?.debug(\"processing query: \\(query.questions)\")\n\n // always send response\n let responseData: Data\n do {\n self.log?.debug(\"awaiting processing\")\n var response =\n try await handler.answer(query: query)\n ?? Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n\n // no responses\n if response.answers.isEmpty {\n response.returnCode = .nonExistentDomain\n }\n\n self.log?.debug(\"serializing response\")\n responseData = try response.serialize()\n } catch {\n self.log?.error(\"error processing message from \\(query): \\(error)\")\n let response = Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n responseData = try response.serialize()\n }\n\n self.log?.debug(\"sending response for \\(query.id)\")\n let rData = ByteBuffer(bytes: responseData)\n try? await outbound.write(AddressedEnvelope(remoteAddress: packet.remoteAddress, data: rData))\n\n self.log?.debug(\"processing done\")\n\n }\n}\n"], ["/container/Sources/ContainerPlugin/ServiceManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\npublic struct ServiceManager {\n private static func runLaunchctlCommand(args: [String]) throws -> Int32 {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = args\n\n let null = FileHandle.nullDevice\n launchctl.standardOutput = null\n launchctl.standardError = null\n\n try launchctl.run()\n launchctl.waitUntilExit()\n\n return launchctl.terminationStatus\n }\n\n /// Register a service by providing the path to a plist.\n public static func register(plistPath: String) throws {\n let domain = try Self.getDomainString()\n _ = try runLaunchctlCommand(args: [\"bootstrap\", domain, plistPath])\n }\n\n /// Deregister a service by a launchd label.\n public static func deregister(fullServiceLabel label: String) throws {\n _ = try runLaunchctlCommand(args: [\"bootout\", label])\n }\n\n /// Restart a service by a launchd label.\n public static func kickstart(fullServiceLabel label: String) throws {\n _ = try runLaunchctlCommand(args: [\"kickstart\", \"-k\", label])\n }\n\n /// Send a signal to a service by a launchd label.\n public static func kill(fullServiceLabel label: String, signal: Int32 = 15) throws {\n _ = try runLaunchctlCommand(args: [\"kill\", \"\\(signal)\", label])\n }\n\n /// Retrieve labels for all loaded launch units.\n public static func enumerate() throws -> [String] {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = [\"list\"]\n\n let stdoutPipe = Pipe()\n let stderrPipe = Pipe()\n launchctl.standardOutput = stdoutPipe\n launchctl.standardError = stderrPipe\n\n try launchctl.run()\n let outputData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()\n let stderrData = stderrPipe.fileHandleForReading.readDataToEndOfFile()\n launchctl.waitUntilExit()\n let status = launchctl.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(\n .internalError, message: \"Command `launchctl list` failed with status \\(status). Message: \\(String(data: stderrData, encoding: .utf8) ?? \"No error message\")\")\n }\n\n guard let outputText = String(data: outputData, encoding: .utf8) else {\n throw ContainerizationError(\n .internalError, message: \"Could not decode output of command `launchctl list`. Message: \\(String(data: stderrData, encoding: .utf8) ?? \"No error message\")\")\n }\n\n // The third field of each line of launchctl list output is the label\n return outputText.split { $0.isNewline }\n .map { String($0).split { $0.isWhitespace } }\n .filter { $0.count >= 3 }\n .map { String($0[2]) }\n }\n\n /// Check if a service has been registered or not.\n public static func isRegistered(fullServiceLabel label: String) throws -> Bool {\n let exitStatus = try runLaunchctlCommand(args: [\"list\", label])\n return exitStatus == 0\n }\n\n private static func getLaunchdSessionType() throws -> String {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = [\"managername\"]\n\n let null = FileHandle.nullDevice\n let stdoutPipe = Pipe()\n launchctl.standardOutput = stdoutPipe\n launchctl.standardError = null\n\n try launchctl.run()\n let outputData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()\n launchctl.waitUntilExit()\n let status = launchctl.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(.internalError, message: \"Command `launchctl managername` failed with status \\(status)\")\n }\n guard let outputText = String(data: outputData, encoding: .utf8) else {\n throw ContainerizationError(.internalError, message: \"Could not decode output of command `launchctl managername`\")\n }\n return outputText.trimmingCharacters(in: .whitespacesAndNewlines)\n }\n\n public static func getDomainString() throws -> String {\n let currentSessionType = try getLaunchdSessionType()\n switch currentSessionType {\n case LaunchPlist.Domain.System.rawValue:\n return LaunchPlist.Domain.System.rawValue.lowercased()\n case LaunchPlist.Domain.Background.rawValue:\n return \"user/\\(getuid())\"\n case LaunchPlist.Domain.Aqua.rawValue:\n return \"gui/\\(getuid())\"\n default:\n throw ContainerizationError(.internalError, message: \"Unsupported session type \\(currentSessionType)\")\n }\n }\n}\n"], ["/container/Sources/APIServer/Containers/ContainersHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nstruct ContainersHarness {\n let log: Logging.Logger\n let service: ContainersService\n\n init(service: ContainersService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let containers = try await service.list()\n let data = try JSONEncoder().encode(containers)\n\n let reply = message.reply()\n reply.set(key: .containers, value: data)\n return reply\n }\n\n @Sendable\n func create(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .containerConfig)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"container configuration cannot be empty\")\n }\n let kdata = message.dataNoCopy(key: .kernel)\n guard let kdata else {\n throw ContainerizationError(.invalidArgument, message: \"kernel cannot be empty\")\n }\n let odata = message.dataNoCopy(key: .containerOptions)\n var options: ContainerCreateOptions = .default\n if let odata {\n options = try JSONDecoder().decode(ContainerCreateOptions.self, from: odata)\n }\n let config = try JSONDecoder().decode(ContainerConfiguration.self, from: data)\n let kernel = try JSONDecoder().decode(Kernel.self, from: kdata)\n\n try await service.create(configuration: config, kernel: kernel, options: options)\n return message.reply()\n }\n\n @Sendable\n func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .id)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"id cannot be empty\")\n }\n try await service.delete(id: id)\n return message.reply()\n }\n\n @Sendable\n func logs(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .id)\n guard let id else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"id cannot be empty\"\n )\n }\n let fds = try await service.logs(id: id)\n let reply = message.reply()\n try reply.set(key: .logs, value: fds)\n return reply\n }\n\n @Sendable\n func eventHandler(_ message: XPCMessage) async throws -> XPCMessage {\n let event = try message.containerEvent()\n try await service.handleContainerEvents(event: event)\n return message.reply()\n }\n}\n\nextension XPCMessage {\n public func containerEvent() throws -> ContainerEvent {\n guard let data = self.dataNoCopy(key: .containerEvent) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing container event data\")\n }\n let event = try JSONDecoder().decode(ContainerEvent.self, from: data)\n return event\n }\n}\n"], ["/container/Sources/DNSServer/DNSServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\nimport NIOCore\nimport NIOPosix\n\n/// Provides a DNS server.\n/// - Parameters:\n/// - host: The host address on which to listen.\n/// - port: The port for the server to listen.\npublic struct DNSServer {\n public var handler: DNSHandler\n let log: Logger?\n\n public init(\n handler: DNSHandler,\n log: Logger? = nil\n ) {\n self.handler = handler\n self.log = log\n }\n\n public func run(host: String, port: Int) async throws {\n // TODO: TCP server\n let srv = try await DatagramBootstrap(group: NIOSingletons.posixEventLoopGroup)\n .channelOption(.socketOption(.so_reuseaddr), value: 1)\n .bind(host: host, port: port)\n .flatMapThrowing { channel in\n try NIOAsyncChannel(\n wrappingChannelSynchronously: channel,\n configuration: NIOAsyncChannel.Configuration(\n inboundType: AddressedEnvelope.self,\n outboundType: AddressedEnvelope.self\n )\n )\n }\n .get()\n\n try await srv.executeThenClose { inbound, outbound in\n for try await var packet in inbound {\n try await self.handle(outbound: outbound, packet: &packet)\n }\n }\n }\n\n public func run(socketPath: String) async throws {\n // TODO: TCP server\n let srv = try await DatagramBootstrap(group: NIOSingletons.posixEventLoopGroup)\n .bind(unixDomainSocketPath: socketPath, cleanupExistingSocketFile: true)\n .flatMapThrowing { channel in\n try NIOAsyncChannel(\n wrappingChannelSynchronously: channel,\n configuration: NIOAsyncChannel.Configuration(\n inboundType: AddressedEnvelope.self,\n outboundType: AddressedEnvelope.self\n )\n )\n }\n .get()\n\n try await srv.executeThenClose { inbound, outbound in\n for try await var packet in inbound {\n log?.debug(\"received packet from \\(packet.remoteAddress)\")\n try await self.handle(outbound: outbound, packet: &packet)\n log?.debug(\"sent packet\")\n }\n }\n }\n\n public func stop() async throws {}\n}\n"], ["/container/Sources/ContainerXPC/XPCMessage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\n\n/// A message that can be pass across application boundaries via XPC.\npublic struct XPCMessage: Sendable {\n /// Defined message key storing the route value.\n public static let routeKey = \"com.apple.container.xpc.route\"\n /// Defined message key storing the error value.\n public static let errorKey = \"com.apple.container.xpc.error\"\n\n // Access to `object` is protected by a lock\n private nonisolated(unsafe) let object: xpc_object_t\n private let lock = NSLock()\n private let isErr: Bool\n\n /// The underlying xpc object that the message wraps.\n public var underlying: xpc_object_t {\n lock.withLock {\n object\n }\n }\n public var isErrorType: Bool { isErr }\n\n public init(object: xpc_object_t) {\n self.object = object\n self.isErr = xpc_get_type(self.object) == XPC_TYPE_ERROR\n }\n\n public init(route: String) {\n self.object = xpc_dictionary_create_empty()\n self.isErr = false\n xpc_dictionary_set_string(self.object, Self.routeKey, route)\n }\n}\n\nextension XPCMessage {\n public static func == (lhs: XPCMessage, rhs: xpc_object_t) -> Bool {\n xpc_equal(lhs.underlying, rhs)\n }\n\n public func reply() -> XPCMessage {\n lock.withLock {\n XPCMessage(object: xpc_dictionary_create_reply(object)!)\n }\n }\n\n public func errorKeyDescription() -> String? {\n guard self.isErr,\n let xpcErr = lock.withLock({\n xpc_dictionary_get_string(\n self.object,\n XPC_ERROR_KEY_DESCRIPTION\n )\n })\n else {\n return nil\n }\n return String(cString: xpcErr)\n }\n\n public func error() throws {\n let data = data(key: Self.errorKey)\n if let data {\n let item = try? JSONDecoder().decode(ContainerXPCError.self, from: data)\n precondition(item != nil, \"expected to receive a ContainerXPCXPCError\")\n\n throw ContainerizationError(item!.code, message: item!.message)\n }\n }\n\n public func set(error: ContainerizationError) {\n var message = error.message\n if let cause = error.cause {\n message += \" (cause: \\\"\\(cause)\\\")\"\n }\n let serializableError = ContainerXPCError(code: error.code.description, message: message)\n let data = try? JSONEncoder().encode(serializableError)\n precondition(data != nil)\n\n set(key: Self.errorKey, value: data!)\n }\n}\n\nstruct ContainerXPCError: Codable {\n let code: String\n let message: String\n}\n\nextension XPCMessage {\n public func data(key: String) -> Data? {\n var length: Int = 0\n let bytes = lock.withLock {\n xpc_dictionary_get_data(self.object, key, &length)\n }\n\n guard let bytes else {\n return nil\n }\n\n return Data(bytes: bytes, count: length)\n }\n\n /// dataNoCopy is similar to data, except the data is not copied\n /// to a new buffer. What this means in practice is the second the\n /// underlying xpc_object_t gets released by ARC the data will be\n /// released as well. This variant should be used when you know the\n /// data will be used before the object has no more references.\n public func dataNoCopy(key: String) -> Data? {\n var length: Int = 0\n let bytes = lock.withLock {\n xpc_dictionary_get_data(self.object, key, &length)\n }\n\n guard let bytes else {\n return nil\n }\n\n return Data(\n bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes),\n count: length,\n deallocator: .none\n )\n }\n\n public func set(key: String, value: Data) {\n value.withUnsafeBytes { ptr in\n if let addr = ptr.baseAddress {\n lock.withLock {\n xpc_dictionary_set_data(self.object, key, addr, value.count)\n }\n }\n }\n }\n\n public func string(key: String) -> String? {\n let _id = lock.withLock {\n xpc_dictionary_get_string(self.object, key)\n }\n if let _id {\n return String(cString: _id)\n }\n return nil\n }\n\n public func set(key: String, value: String) {\n lock.withLock {\n xpc_dictionary_set_string(self.object, key, value)\n }\n }\n\n public func bool(key: String) -> Bool {\n lock.withLock {\n xpc_dictionary_get_bool(self.object, key)\n }\n }\n\n public func set(key: String, value: Bool) {\n lock.withLock {\n xpc_dictionary_set_bool(self.object, key, value)\n }\n }\n\n public func uint64(key: String) -> UInt64 {\n lock.withLock {\n xpc_dictionary_get_uint64(self.object, key)\n }\n }\n\n public func set(key: String, value: UInt64) {\n lock.withLock {\n xpc_dictionary_set_uint64(self.object, key, value)\n }\n }\n\n public func int64(key: String) -> Int64 {\n lock.withLock {\n xpc_dictionary_get_int64(self.object, key)\n }\n }\n\n public func set(key: String, value: Int64) {\n lock.withLock {\n xpc_dictionary_set_int64(self.object, key, value)\n }\n }\n\n public func fileHandle(key: String) -> FileHandle? {\n let fd = lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n if let fd {\n let fd2 = xpc_fd_dup(fd)\n return FileHandle(fileDescriptor: fd2, closeOnDealloc: false)\n }\n return nil\n }\n\n public func set(key: String, value: FileHandle) {\n let fd = xpc_fd_create(value.fileDescriptor)\n close(value.fileDescriptor)\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, fd)\n }\n }\n\n public func fileHandles(key: String) -> [FileHandle]? {\n let fds = lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n if let fds {\n let fd1 = xpc_array_dup_fd(fds, 0)\n let fd2 = xpc_array_dup_fd(fds, 1)\n if fd1 == -1 || fd2 == -1 {\n return nil\n }\n return [\n FileHandle(fileDescriptor: fd1, closeOnDealloc: false),\n FileHandle(fileDescriptor: fd2, closeOnDealloc: false),\n ]\n }\n return nil\n }\n\n public func set(key: String, value: [FileHandle]) throws {\n let fdArray = xpc_array_create(nil, 0)\n for fh in value {\n guard let xpcFd = xpc_fd_create(fh.fileDescriptor) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to create xpc fd for \\(fh.fileDescriptor)\"\n )\n }\n xpc_array_append_value(fdArray, xpcFd)\n close(fh.fileDescriptor)\n }\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, fdArray)\n }\n }\n\n public func endpoint(key: String) -> xpc_endpoint_t? {\n lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n }\n\n public func set(key: String, value: xpc_endpoint_t) {\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, value)\n }\n }\n}\n\n#endif\n"], ["/container/Sources/Services/ContainerImagesService/Server/ContentServiceHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\n\npublic struct ContentServiceHarness: Sendable {\n private let log: Logging.Logger\n private let service: ContentStoreService\n\n public init(service: ContentStoreService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n public func get(_ message: XPCMessage) async throws -> XPCMessage {\n let d = message.string(key: .digest)\n guard let d else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n guard let path = try await service.get(digest: d) else {\n let err = ContainerizationError(.notFound, message: \"digest \\(d) not found\")\n let reply = message.reply()\n reply.set(error: err)\n return reply\n }\n let reply = message.reply()\n reply.set(key: .contentPath, value: path.path(percentEncoded: false))\n return reply\n }\n\n @Sendable\n public func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .digests)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n let digests = try JSONDecoder().decode([String].self, from: data)\n let (deleted, size) = try await self.service.delete(digests: digests)\n let d = try JSONEncoder().encode(deleted)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n reply.set(key: .size, value: size)\n return reply\n }\n\n @Sendable\n public func clean(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .digests)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n let digests = try JSONDecoder().decode([String].self, from: data)\n let (deleted, size) = try await self.service.delete(keeping: digests)\n let d = try JSONEncoder().encode(deleted)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n reply.set(key: .size, value: size)\n return reply\n }\n\n @Sendable\n public func newIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let session = try await self.service.newIngestSession()\n let id = session.id\n let dir = session.ingestDir\n let reply = message.reply()\n reply.set(key: .directory, value: dir.path(percentEncoded: false))\n reply.set(key: .ingestSessionId, value: id)\n return reply\n }\n\n @Sendable\n public func cancelIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .ingestSessionId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"missing ingest session id\")\n }\n try await self.service.cancelIngestSession(id)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func completeIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .ingestSessionId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"missing ingest session id\")\n }\n let ingested = try await self.service.completeIngestSession(id)\n let d = try JSONEncoder().encode(ingested)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n return reply\n }\n}\n"], ["/container/Sources/CLI/Image/ImageLoad.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ImageLoad: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"load\",\n abstract: \"Load images from an OCI compatible tar archive\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(\n name: .shortAndLong, help: \"Path to the tar archive to load images from\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var input: String\n\n func run() async throws {\n guard FileManager.default.fileExists(atPath: input) else {\n print(\"File does not exist \\(input)\")\n Application.exit(withError: ArgumentParser.ExitCode(1))\n }\n\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n totalTasks: 2\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Loading tar archive\")\n let loaded = try await ClientImage.load(from: input)\n\n let taskManager = ProgressTaskCoordinator()\n let unpackTask = await taskManager.startTask()\n progress.set(description: \"Unpacking image\")\n progress.set(itemsName: \"entries\")\n for image in loaded {\n try await image.unpack(platform: nil, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progress.handler))\n }\n await taskManager.finish()\n progress.finish()\n print(\"Loaded images:\")\n for image in loaded {\n print(image.reference)\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/ProgressUpdateClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\n/// A client that can be used to receive progress updates from a service.\npublic actor ProgressUpdateClient {\n private var endpointConnection: xpc_connection_t?\n private var endpoint: xpc_endpoint_t?\n\n /// Creates a new client for receiving progress updates from a service.\n /// - Parameters:\n /// - progressUpdate: The handler to invoke when progress updates are received.\n /// - request: The XPC message to send the endpoint to connect to.\n public init(for progressUpdate: @escaping ProgressUpdateHandler, request: XPCMessage) async {\n createEndpoint(for: progressUpdate)\n setEndpoint(to: request)\n }\n\n /// Performs a connection setup for receiving progress updates.\n /// - Parameter progressUpdate: The handler to invoke when progress updates are received.\n private func createEndpoint(for progressUpdate: @escaping ProgressUpdateHandler) {\n let endpointConnection = xpc_connection_create(nil, nil)\n // Access to `reversedConnection` is protected by a lock\n nonisolated(unsafe) var reversedConnection: xpc_connection_t?\n let reversedConnectionLock = NSLock()\n xpc_connection_set_event_handler(endpointConnection) { connectionMessage in\n reversedConnectionLock.withLock {\n switch xpc_get_type(connectionMessage) {\n case XPC_TYPE_CONNECTION:\n reversedConnection = connectionMessage\n xpc_connection_set_event_handler(connectionMessage) { updateMessage in\n Self.handleProgressUpdate(updateMessage, progressUpdate: progressUpdate)\n }\n xpc_connection_activate(connectionMessage)\n case XPC_TYPE_ERROR:\n if let reversedConnectionUnwrapped = reversedConnection {\n xpc_connection_cancel(reversedConnectionUnwrapped)\n reversedConnection = nil\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(connectionMessage))\")\n }\n }\n }\n xpc_connection_activate(endpointConnection)\n\n self.endpointConnection = endpointConnection\n self.endpoint = xpc_endpoint_create(endpointConnection)\n }\n\n /// Performs a setup of the progress update endpoint.\n /// - Parameter request: The XPC message containing the endpoint to use.\n private func setEndpoint(to request: XPCMessage) {\n guard let endpoint else {\n return\n }\n request.set(key: .progressUpdateEndpoint, value: endpoint)\n }\n\n /// Performs cleanup of the created connection.\n public func finish() {\n if let endpointConnection {\n xpc_connection_cancel(endpointConnection)\n self.endpointConnection = nil\n }\n }\n\n private static func handleProgressUpdate(_ message: xpc_object_t, progressUpdate: @escaping ProgressUpdateHandler) {\n switch xpc_get_type(message) {\n case XPC_TYPE_DICTIONARY:\n let message = XPCMessage(object: message)\n handleProgressUpdate(message, progressUpdate: progressUpdate)\n case XPC_TYPE_ERROR:\n break\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(message))\")\n break\n }\n }\n\n private static func handleProgressUpdate(_ message: XPCMessage, progressUpdate: @escaping ProgressUpdateHandler) {\n var events = [ProgressUpdateEvent]()\n\n if let description = message.string(key: .progressUpdateSetDescription) {\n events.append(.setDescription(description))\n }\n if let subDescription = message.string(key: .progressUpdateSetSubDescription) {\n events.append(.setSubDescription(subDescription))\n }\n if let itemsName = message.string(key: .progressUpdateSetItemsName) {\n events.append(.setItemsName(itemsName))\n }\n var tasks = message.int(key: .progressUpdateAddTasks)\n if tasks != 0 {\n events.append(.addTasks(tasks))\n }\n tasks = message.int(key: .progressUpdateSetTasks)\n if tasks != 0 {\n events.append(.setTasks(tasks))\n }\n var totalTasks = message.int(key: .progressUpdateAddTotalTasks)\n if totalTasks != 0 {\n events.append(.addTotalTasks(totalTasks))\n }\n totalTasks = message.int(key: .progressUpdateSetTotalTasks)\n if totalTasks != 0 {\n events.append(.setTotalTasks(totalTasks))\n }\n var items = message.int(key: .progressUpdateAddItems)\n if items != 0 {\n events.append(.addItems(items))\n }\n items = message.int(key: .progressUpdateSetItems)\n if items != 0 {\n events.append(.setItems(items))\n }\n var totalItems = message.int(key: .progressUpdateAddTotalItems)\n if totalItems != 0 {\n events.append(.addTotalItems(totalItems))\n }\n totalItems = message.int(key: .progressUpdateSetTotalItems)\n if totalItems != 0 {\n events.append(.setTotalItems(totalItems))\n }\n var size = message.int64(key: .progressUpdateAddSize)\n if size != 0 {\n events.append(.addSize(size))\n }\n size = message.int64(key: .progressUpdateSetSize)\n if size != 0 {\n events.append(.setSize(size))\n }\n var totalSize = message.int64(key: .progressUpdateAddTotalSize)\n if totalSize != 0 {\n events.append(.addTotalSize(totalSize))\n }\n totalSize = message.int64(key: .progressUpdateSetTotalSize)\n if totalSize != 0 {\n events.append(.setTotalSize(totalSize))\n }\n\n Task {\n await progressUpdate(events)\n }\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/ExitMonitor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\n/// Track when long running work exits, and notify the caller via a callback.\npublic actor ExitMonitor {\n /// A callback that receives the client identifier and exit code.\n public typealias ExitCallback = @Sendable (String, Int32) async throws -> Void\n\n /// A function that waits for work to complete, returning an exit code.\n public typealias WaitHandler = @Sendable () async throws -> Int32\n\n /// Create a new monitor.\n ///\n /// - Parameters:\n /// - log: The destination for log messages.\n public init(log: Logger? = nil) {\n self.log = log\n }\n\n private var exitCallbacks: [String: ExitCallback] = [:]\n private var runningTasks: [String: Task] = [:]\n private let log: Logger?\n\n /// Remove tracked work from the monitor.\n ///\n /// - Parameters:\n /// - id: The client identifier for the tracked work.\n public func stopTracking(id: String) async {\n if let task = self.runningTasks[id] {\n task.cancel()\n }\n exitCallbacks.removeValue(forKey: id)\n runningTasks.removeValue(forKey: id)\n }\n\n /// Register long running work so that the monitor invokes\n /// a callback when the work completes.\n ///\n /// - Parameters:\n /// - id: The client identifier for the work.\n /// - onExit: The callback to invoke when the work completes.\n public func registerProcess(id: String, onExit: @escaping ExitCallback) async throws {\n guard self.exitCallbacks[id] == nil else {\n throw ContainerizationError(.invalidState, message: \"ExitMonitor already setup for process \\(id)\")\n }\n self.exitCallbacks[id] = onExit\n }\n\n /// Await the completion of previously registered item of work.\n ///\n /// - Parameters:\n /// - id: The client identifier for the work.\n /// - waitingOn: A function that waits for the work to complete,\n /// and then returns an exit code.\n public func track(id: String, waitingOn: @escaping WaitHandler) async throws {\n guard let onExit = self.exitCallbacks[id] else {\n throw ContainerizationError(.invalidState, message: \"ExitMonitor not setup for process \\(id)\")\n }\n guard self.runningTasks[id] == nil else {\n throw ContainerizationError(.invalidState, message: \"Already have a running task tracking process \\(id)\")\n }\n self.runningTasks[id] = Task {\n do {\n let exitStatus = try await waitingOn()\n try await onExit(id, exitStatus)\n } catch {\n self.log?.error(\"WaitHandler for \\(id) threw error \\(String(describing: error))\")\n try? await onExit(id, -1)\n }\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/AttachmentAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\n\nactor AttachmentAllocator {\n private let allocator: any AddressAllocator\n private var hostnames: [String: UInt32] = [:]\n\n init(lower: UInt32, size: Int) throws {\n allocator = try UInt32.rotatingAllocator(\n lower: lower,\n size: UInt32(size)\n )\n }\n\n /// Allocate a network address for a host.\n func allocate(hostname: String) async throws -> UInt32 {\n guard hostnames[hostname] == nil else {\n throw ContainerizationError(.exists, message: \"Hostname \\(hostname) already exists on the network\")\n }\n let index = try allocator.allocate()\n hostnames[hostname] = index\n\n return index\n }\n\n /// Free an allocated network address by hostname.\n func deallocate(hostname: String) async throws {\n if let index = hostnames.removeValue(forKey: hostname) {\n try allocator.release(index)\n }\n }\n\n /// If no addresses are allocated, prevent future allocations and return true.\n func disableAllocator() async -> Bool {\n allocator.disableAllocator()\n }\n\n /// Retrieve the allocator index for a hostname.\n func lookup(hostname: String) async throws -> UInt32? {\n hostnames[hostname]\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.pb.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// DO NOT EDIT.\n// swift-format-ignore-file\n// swiftlint:disable all\n//\n// Generated by the Swift generator plugin for the protocol buffer compiler.\n// Source: Builder.proto\n//\n// For information on using the generated types, please see the documentation:\n// https://github.com/apple/swift-protobuf/\n\nimport Foundation\nimport SwiftProtobuf\n\n// If the compiler emits an error on this type, it is because this file\n// was generated by a version of the `protoc` Swift plug-in that is\n// incompatible with the version of SwiftProtobuf to which you are linking.\n// Please ensure that you are building against the same version of the API\n// that was used to generate this file.\nfileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {\n struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}\n typealias Version = _2\n}\n\npublic enum Com_Apple_Container_Build_V1_TransferDirection: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case into // = 0\n case outof // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .into\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .into\n case 1: self = .outof\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .into: return 0\n case .outof: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_TransferDirection] = [\n .into,\n .outof,\n ]\n\n}\n\n/// Standard input/output.\npublic enum Com_Apple_Container_Build_V1_Stdio: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case stdin // = 0\n case stdout // = 1\n case stderr // = 2\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .stdin\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .stdin\n case 1: self = .stdout\n case 2: self = .stderr\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .stdin: return 0\n case .stdout: return 1\n case .stderr: return 2\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_Stdio] = [\n .stdin,\n .stdout,\n .stderr,\n ]\n\n}\n\n/// Build error type.\npublic enum Com_Apple_Container_Build_V1_BuildErrorType: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case buildFailed // = 0\n case `internal` // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .buildFailed\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .buildFailed\n case 1: self = .internal\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .buildFailed: return 0\n case .internal: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_BuildErrorType] = [\n .buildFailed,\n .internal,\n ]\n\n}\n\npublic struct Com_Apple_Container_Build_V1_InfoRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_InfoResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_CreateBuildRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The name of the build stage.\n public var stageName: String = String()\n\n /// The tag of the image to be created.\n public var tag: String = String()\n\n /// Any additional metadata to be associated with the build.\n public var metadata: Dictionary = [:]\n\n /// Additional build arguments.\n public var buildArgs: [String] = []\n\n /// Enable debug logging.\n public var debug: Bool = false\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_CreateBuildResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String = String()\n\n /// Any additional metadata to be associated with the build.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_ClientStream: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String {\n get {return _storage._buildID}\n set {_uniqueStorage()._buildID = newValue}\n }\n\n /// The packet type.\n public var packetType: OneOf_PacketType? {\n get {return _storage._packetType}\n set {_uniqueStorage()._packetType = newValue}\n }\n\n public var signal: Com_Apple_Container_Build_V1_Signal {\n get {\n if case .signal(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_Signal()\n }\n set {_uniqueStorage()._packetType = .signal(newValue)}\n }\n\n public var command: Com_Apple_Container_Build_V1_Run {\n get {\n if case .command(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_Run()\n }\n set {_uniqueStorage()._packetType = .command(newValue)}\n }\n\n public var buildTransfer: Com_Apple_Container_Build_V1_BuildTransfer {\n get {\n if case .buildTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildTransfer()\n }\n set {_uniqueStorage()._packetType = .buildTransfer(newValue)}\n }\n\n public var imageTransfer: Com_Apple_Container_Build_V1_ImageTransfer {\n get {\n if case .imageTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_ImageTransfer()\n }\n set {_uniqueStorage()._packetType = .imageTransfer(newValue)}\n }\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n /// The packet type.\n public enum OneOf_PacketType: Equatable, Sendable {\n case signal(Com_Apple_Container_Build_V1_Signal)\n case command(Com_Apple_Container_Build_V1_Run)\n case buildTransfer(Com_Apple_Container_Build_V1_BuildTransfer)\n case imageTransfer(Com_Apple_Container_Build_V1_ImageTransfer)\n\n }\n\n public init() {}\n\n fileprivate var _storage = _StorageClass.defaultInstance\n}\n\npublic struct Com_Apple_Container_Build_V1_Signal: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A POSIX signal to send to the build process.\n /// Can be used for cancelling builds.\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_Run: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the execution.\n public var id: String = String()\n\n /// The type of command to execute.\n public var command: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_RunComplete: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the execution.\n public var id: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_BuildTransfer: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the transfer.\n public var id: String = String()\n\n /// The direction for transferring data (either to the server or from the\n /// server).\n public var direction: Com_Apple_Container_Build_V1_TransferDirection = .into\n\n /// The absolute path to the source from the server perspective.\n public var source: String {\n get {return _source ?? String()}\n set {_source = newValue}\n }\n /// Returns true if `source` has been explicitly set.\n public var hasSource: Bool {return self._source != nil}\n /// Clears the value of `source`. Subsequent reads from it will return its default value.\n public mutating func clearSource() {self._source = nil}\n\n /// The absolute path for the destination from the server perspective.\n public var destination: String {\n get {return _destination ?? String()}\n set {_destination = newValue}\n }\n /// Returns true if `destination` has been explicitly set.\n public var hasDestination: Bool {return self._destination != nil}\n /// Clears the value of `destination`. Subsequent reads from it will return its default value.\n public mutating func clearDestination() {self._destination = nil}\n\n /// The actual data bytes to be transferred.\n public var data: Data = Data()\n\n /// Signal to indicate that the transfer of data for the request has finished.\n public var complete: Bool = false\n\n /// Boolean to indicate if the content is a directory.\n public var isDirectory: Bool = false\n\n /// Metadata for the transfer.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _source: String? = nil\n fileprivate var _destination: String? = nil\n}\n\npublic struct Com_Apple_Container_Build_V1_ImageTransfer: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the transfer.\n public var id: String = String()\n\n /// The direction for transferring data (either to the server or from the\n /// server).\n public var direction: Com_Apple_Container_Build_V1_TransferDirection = .into\n\n /// The tag for the image.\n public var tag: String = String()\n\n /// The descriptor for the image content.\n public var descriptor: Com_Apple_Container_Build_V1_Descriptor {\n get {return _descriptor ?? Com_Apple_Container_Build_V1_Descriptor()}\n set {_descriptor = newValue}\n }\n /// Returns true if `descriptor` has been explicitly set.\n public var hasDescriptor: Bool {return self._descriptor != nil}\n /// Clears the value of `descriptor`. Subsequent reads from it will return its default value.\n public mutating func clearDescriptor() {self._descriptor = nil}\n\n /// The actual data bytes to be transferred.\n public var data: Data = Data()\n\n /// Signal to indicate that the transfer of data for the request has finished.\n public var complete: Bool = false\n\n /// Metadata for the image.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _descriptor: Com_Apple_Container_Build_V1_Descriptor? = nil\n}\n\npublic struct Com_Apple_Container_Build_V1_ServerStream: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String {\n get {return _storage._buildID}\n set {_uniqueStorage()._buildID = newValue}\n }\n\n /// The packet type.\n public var packetType: OneOf_PacketType? {\n get {return _storage._packetType}\n set {_uniqueStorage()._packetType = newValue}\n }\n\n public var io: Com_Apple_Container_Build_V1_IO {\n get {\n if case .io(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_IO()\n }\n set {_uniqueStorage()._packetType = .io(newValue)}\n }\n\n public var buildError: Com_Apple_Container_Build_V1_BuildError {\n get {\n if case .buildError(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildError()\n }\n set {_uniqueStorage()._packetType = .buildError(newValue)}\n }\n\n public var commandComplete: Com_Apple_Container_Build_V1_RunComplete {\n get {\n if case .commandComplete(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_RunComplete()\n }\n set {_uniqueStorage()._packetType = .commandComplete(newValue)}\n }\n\n public var buildTransfer: Com_Apple_Container_Build_V1_BuildTransfer {\n get {\n if case .buildTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildTransfer()\n }\n set {_uniqueStorage()._packetType = .buildTransfer(newValue)}\n }\n\n public var imageTransfer: Com_Apple_Container_Build_V1_ImageTransfer {\n get {\n if case .imageTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_ImageTransfer()\n }\n set {_uniqueStorage()._packetType = .imageTransfer(newValue)}\n }\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n /// The packet type.\n public enum OneOf_PacketType: Equatable, Sendable {\n case io(Com_Apple_Container_Build_V1_IO)\n case buildError(Com_Apple_Container_Build_V1_BuildError)\n case commandComplete(Com_Apple_Container_Build_V1_RunComplete)\n case buildTransfer(Com_Apple_Container_Build_V1_BuildTransfer)\n case imageTransfer(Com_Apple_Container_Build_V1_ImageTransfer)\n\n }\n\n public init() {}\n\n fileprivate var _storage = _StorageClass.defaultInstance\n}\n\npublic struct Com_Apple_Container_Build_V1_IO: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The type of IO.\n public var type: Com_Apple_Container_Build_V1_Stdio = .stdin\n\n /// The IO data bytes.\n public var data: Data = Data()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_BuildError: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The type of build error.\n public var type: Com_Apple_Container_Build_V1_BuildErrorType = .buildFailed\n\n /// Additional message for the build failure.\n public var message: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n/// OCI Platform metadata.\npublic struct Com_Apple_Container_Build_V1_Platform: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var architecture: String = String()\n\n public var os: String = String()\n\n public var osVersion: String = String()\n\n public var osFeatures: [String] = []\n\n public var variant: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n/// OCI Descriptor metadata.\npublic struct Com_Apple_Container_Build_V1_Descriptor: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var mediaType: String = String()\n\n public var digest: String = String()\n\n public var size: Int64 = 0\n\n public var urls: [String] = []\n\n public var annotations: Dictionary = [:]\n\n public var platform: Com_Apple_Container_Build_V1_Platform {\n get {return _platform ?? Com_Apple_Container_Build_V1_Platform()}\n set {_platform = newValue}\n }\n /// Returns true if `platform` has been explicitly set.\n public var hasPlatform: Bool {return self._platform != nil}\n /// Clears the value of `platform`. Subsequent reads from it will return its default value.\n public mutating func clearPlatform() {self._platform = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _platform: Com_Apple_Container_Build_V1_Platform? = nil\n}\n\n// MARK: - Code below here is support for the SwiftProtobuf runtime.\n\nfileprivate let _protobuf_package = \"com.apple.container.build.v1\"\n\nextension Com_Apple_Container_Build_V1_TransferDirection: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"INTO\"),\n 1: .same(proto: \"OUTOF\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_Stdio: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"STDIN\"),\n 1: .same(proto: \"STDOUT\"),\n 2: .same(proto: \"STDERR\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_BuildErrorType: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"BUILD_FAILED\"),\n 1: .same(proto: \"INTERNAL\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_InfoRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".InfoRequest\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_InfoRequest, rhs: Com_Apple_Container_Build_V1_InfoRequest) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_InfoResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".InfoResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_InfoResponse, rhs: Com_Apple_Container_Build_V1_InfoResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_CreateBuildRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateBuildRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"stage_name\"),\n 2: .same(proto: \"tag\"),\n 3: .same(proto: \"metadata\"),\n 4: .standard(proto: \"build_args\"),\n 5: .same(proto: \"debug\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.stageName) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.tag) }()\n case 3: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.buildArgs) }()\n case 5: try { try decoder.decodeSingularBoolField(value: &self.debug) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.stageName.isEmpty {\n try visitor.visitSingularStringField(value: self.stageName, fieldNumber: 1)\n }\n if !self.tag.isEmpty {\n try visitor.visitSingularStringField(value: self.tag, fieldNumber: 2)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 3)\n }\n if !self.buildArgs.isEmpty {\n try visitor.visitRepeatedStringField(value: self.buildArgs, fieldNumber: 4)\n }\n if self.debug != false {\n try visitor.visitSingularBoolField(value: self.debug, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_CreateBuildRequest, rhs: Com_Apple_Container_Build_V1_CreateBuildRequest) -> Bool {\n if lhs.stageName != rhs.stageName {return false}\n if lhs.tag != rhs.tag {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.buildArgs != rhs.buildArgs {return false}\n if lhs.debug != rhs.debug {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_CreateBuildResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateBuildResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.buildID) }()\n case 2: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.buildID.isEmpty {\n try visitor.visitSingularStringField(value: self.buildID, fieldNumber: 1)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_CreateBuildResponse, rhs: Com_Apple_Container_Build_V1_CreateBuildResponse) -> Bool {\n if lhs.buildID != rhs.buildID {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ClientStream: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ClientStream\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"signal\"),\n 3: .same(proto: \"command\"),\n 4: .standard(proto: \"build_transfer\"),\n 5: .standard(proto: \"image_transfer\"),\n ]\n\n fileprivate class _StorageClass {\n var _buildID: String = String()\n var _packetType: Com_Apple_Container_Build_V1_ClientStream.OneOf_PacketType?\n\n // This property is used as the initial default value for new instances of the type.\n // The type itself is protecting the reference to its storage via CoW semantics.\n // This will force a copy to be made of this reference when the first mutation occurs;\n // hence, it is safe to mark this as `nonisolated(unsafe)`.\n static nonisolated(unsafe) let defaultInstance = _StorageClass()\n\n private init() {}\n\n init(copying source: _StorageClass) {\n _buildID = source._buildID\n _packetType = source._packetType\n }\n }\n\n fileprivate mutating func _uniqueStorage() -> _StorageClass {\n if !isKnownUniquelyReferenced(&_storage) {\n _storage = _StorageClass(copying: _storage)\n }\n return _storage\n }\n\n public mutating func decodeMessage(decoder: inout D) throws {\n _ = _uniqueStorage()\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &_storage._buildID) }()\n case 2: try {\n var v: Com_Apple_Container_Build_V1_Signal?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .signal(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .signal(v)\n }\n }()\n case 3: try {\n var v: Com_Apple_Container_Build_V1_Run?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .command(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .command(v)\n }\n }()\n case 4: try {\n var v: Com_Apple_Container_Build_V1_BuildTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildTransfer(v)\n }\n }()\n case 5: try {\n var v: Com_Apple_Container_Build_V1_ImageTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .imageTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .imageTransfer(v)\n }\n }()\n default: break\n }\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !_storage._buildID.isEmpty {\n try visitor.visitSingularStringField(value: _storage._buildID, fieldNumber: 1)\n }\n switch _storage._packetType {\n case .signal?: try {\n guard case .signal(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 2)\n }()\n case .command?: try {\n guard case .command(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 3)\n }()\n case .buildTransfer?: try {\n guard case .buildTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n }()\n case .imageTransfer?: try {\n guard case .imageTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 5)\n }()\n case nil: break\n }\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ClientStream, rhs: Com_Apple_Container_Build_V1_ClientStream) -> Bool {\n if lhs._storage !== rhs._storage {\n let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in\n let _storage = _args.0\n let rhs_storage = _args.1\n if _storage._buildID != rhs_storage._buildID {return false}\n if _storage._packetType != rhs_storage._packetType {return false}\n return true\n }\n if !storagesAreEqual {return false}\n }\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Signal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Signal\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Signal, rhs: Com_Apple_Container_Build_V1_Signal) -> Bool {\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Run: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Run\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"command\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.command) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if !self.command.isEmpty {\n try visitor.visitSingularStringField(value: self.command, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Run, rhs: Com_Apple_Container_Build_V1_Run) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.command != rhs.command {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_RunComplete: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".RunComplete\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_RunComplete, rhs: Com_Apple_Container_Build_V1_RunComplete) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_BuildTransfer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".BuildTransfer\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"direction\"),\n 3: .same(proto: \"source\"),\n 4: .same(proto: \"destination\"),\n 5: .same(proto: \"data\"),\n 6: .same(proto: \"complete\"),\n 7: .standard(proto: \"is_directory\"),\n 8: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularEnumField(value: &self.direction) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._source) }()\n case 4: try { try decoder.decodeSingularStringField(value: &self._destination) }()\n case 5: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n case 6: try { try decoder.decodeSingularBoolField(value: &self.complete) }()\n case 7: try { try decoder.decodeSingularBoolField(value: &self.isDirectory) }()\n case 8: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.direction != .into {\n try visitor.visitSingularEnumField(value: self.direction, fieldNumber: 2)\n }\n try { if let v = self._source {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try { if let v = self._destination {\n try visitor.visitSingularStringField(value: v, fieldNumber: 4)\n } }()\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 5)\n }\n if self.complete != false {\n try visitor.visitSingularBoolField(value: self.complete, fieldNumber: 6)\n }\n if self.isDirectory != false {\n try visitor.visitSingularBoolField(value: self.isDirectory, fieldNumber: 7)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 8)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_BuildTransfer, rhs: Com_Apple_Container_Build_V1_BuildTransfer) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.direction != rhs.direction {return false}\n if lhs._source != rhs._source {return false}\n if lhs._destination != rhs._destination {return false}\n if lhs.data != rhs.data {return false}\n if lhs.complete != rhs.complete {return false}\n if lhs.isDirectory != rhs.isDirectory {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ImageTransfer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ImageTransfer\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"direction\"),\n 3: .same(proto: \"tag\"),\n 4: .same(proto: \"descriptor\"),\n 5: .same(proto: \"data\"),\n 6: .same(proto: \"complete\"),\n 7: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularEnumField(value: &self.direction) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.tag) }()\n case 4: try { try decoder.decodeSingularMessageField(value: &self._descriptor) }()\n case 5: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n case 6: try { try decoder.decodeSingularBoolField(value: &self.complete) }()\n case 7: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.direction != .into {\n try visitor.visitSingularEnumField(value: self.direction, fieldNumber: 2)\n }\n if !self.tag.isEmpty {\n try visitor.visitSingularStringField(value: self.tag, fieldNumber: 3)\n }\n try { if let v = self._descriptor {\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n } }()\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 5)\n }\n if self.complete != false {\n try visitor.visitSingularBoolField(value: self.complete, fieldNumber: 6)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 7)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ImageTransfer, rhs: Com_Apple_Container_Build_V1_ImageTransfer) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.direction != rhs.direction {return false}\n if lhs.tag != rhs.tag {return false}\n if lhs._descriptor != rhs._descriptor {return false}\n if lhs.data != rhs.data {return false}\n if lhs.complete != rhs.complete {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ServerStream: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ServerStream\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"io\"),\n 3: .standard(proto: \"build_error\"),\n 4: .standard(proto: \"command_complete\"),\n 5: .standard(proto: \"build_transfer\"),\n 6: .standard(proto: \"image_transfer\"),\n ]\n\n fileprivate class _StorageClass {\n var _buildID: String = String()\n var _packetType: Com_Apple_Container_Build_V1_ServerStream.OneOf_PacketType?\n\n // This property is used as the initial default value for new instances of the type.\n // The type itself is protecting the reference to its storage via CoW semantics.\n // This will force a copy to be made of this reference when the first mutation occurs;\n // hence, it is safe to mark this as `nonisolated(unsafe)`.\n static nonisolated(unsafe) let defaultInstance = _StorageClass()\n\n private init() {}\n\n init(copying source: _StorageClass) {\n _buildID = source._buildID\n _packetType = source._packetType\n }\n }\n\n fileprivate mutating func _uniqueStorage() -> _StorageClass {\n if !isKnownUniquelyReferenced(&_storage) {\n _storage = _StorageClass(copying: _storage)\n }\n return _storage\n }\n\n public mutating func decodeMessage(decoder: inout D) throws {\n _ = _uniqueStorage()\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &_storage._buildID) }()\n case 2: try {\n var v: Com_Apple_Container_Build_V1_IO?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .io(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .io(v)\n }\n }()\n case 3: try {\n var v: Com_Apple_Container_Build_V1_BuildError?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildError(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildError(v)\n }\n }()\n case 4: try {\n var v: Com_Apple_Container_Build_V1_RunComplete?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .commandComplete(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .commandComplete(v)\n }\n }()\n case 5: try {\n var v: Com_Apple_Container_Build_V1_BuildTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildTransfer(v)\n }\n }()\n case 6: try {\n var v: Com_Apple_Container_Build_V1_ImageTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .imageTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .imageTransfer(v)\n }\n }()\n default: break\n }\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !_storage._buildID.isEmpty {\n try visitor.visitSingularStringField(value: _storage._buildID, fieldNumber: 1)\n }\n switch _storage._packetType {\n case .io?: try {\n guard case .io(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 2)\n }()\n case .buildError?: try {\n guard case .buildError(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 3)\n }()\n case .commandComplete?: try {\n guard case .commandComplete(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n }()\n case .buildTransfer?: try {\n guard case .buildTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 5)\n }()\n case .imageTransfer?: try {\n guard case .imageTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 6)\n }()\n case nil: break\n }\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ServerStream, rhs: Com_Apple_Container_Build_V1_ServerStream) -> Bool {\n if lhs._storage !== rhs._storage {\n let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in\n let _storage = _args.0\n let rhs_storage = _args.1\n if _storage._buildID != rhs_storage._buildID {return false}\n if _storage._packetType != rhs_storage._packetType {return false}\n return true\n }\n if !storagesAreEqual {return false}\n }\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_IO: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IO\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"data\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularEnumField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.type != .stdin {\n try visitor.visitSingularEnumField(value: self.type, fieldNumber: 1)\n }\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_IO, rhs: Com_Apple_Container_Build_V1_IO) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.data != rhs.data {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_BuildError: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".BuildError\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"message\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularEnumField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.message) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.type != .buildFailed {\n try visitor.visitSingularEnumField(value: self.type, fieldNumber: 1)\n }\n if !self.message.isEmpty {\n try visitor.visitSingularStringField(value: self.message, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_BuildError, rhs: Com_Apple_Container_Build_V1_BuildError) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.message != rhs.message {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Platform: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Platform\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"architecture\"),\n 2: .same(proto: \"os\"),\n 3: .standard(proto: \"os_version\"),\n 4: .standard(proto: \"os_features\"),\n 5: .same(proto: \"variant\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.architecture) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.os) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.osVersion) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.osFeatures) }()\n case 5: try { try decoder.decodeSingularStringField(value: &self.variant) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.architecture.isEmpty {\n try visitor.visitSingularStringField(value: self.architecture, fieldNumber: 1)\n }\n if !self.os.isEmpty {\n try visitor.visitSingularStringField(value: self.os, fieldNumber: 2)\n }\n if !self.osVersion.isEmpty {\n try visitor.visitSingularStringField(value: self.osVersion, fieldNumber: 3)\n }\n if !self.osFeatures.isEmpty {\n try visitor.visitRepeatedStringField(value: self.osFeatures, fieldNumber: 4)\n }\n if !self.variant.isEmpty {\n try visitor.visitSingularStringField(value: self.variant, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Platform, rhs: Com_Apple_Container_Build_V1_Platform) -> Bool {\n if lhs.architecture != rhs.architecture {return false}\n if lhs.os != rhs.os {return false}\n if lhs.osVersion != rhs.osVersion {return false}\n if lhs.osFeatures != rhs.osFeatures {return false}\n if lhs.variant != rhs.variant {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Descriptor: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Descriptor\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"media_type\"),\n 2: .same(proto: \"digest\"),\n 3: .same(proto: \"size\"),\n 4: .same(proto: \"urls\"),\n 5: .same(proto: \"annotations\"),\n 6: .same(proto: \"platform\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.mediaType) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.digest) }()\n case 3: try { try decoder.decodeSingularInt64Field(value: &self.size) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.urls) }()\n case 5: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.annotations) }()\n case 6: try { try decoder.decodeSingularMessageField(value: &self._platform) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.mediaType.isEmpty {\n try visitor.visitSingularStringField(value: self.mediaType, fieldNumber: 1)\n }\n if !self.digest.isEmpty {\n try visitor.visitSingularStringField(value: self.digest, fieldNumber: 2)\n }\n if self.size != 0 {\n try visitor.visitSingularInt64Field(value: self.size, fieldNumber: 3)\n }\n if !self.urls.isEmpty {\n try visitor.visitRepeatedStringField(value: self.urls, fieldNumber: 4)\n }\n if !self.annotations.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.annotations, fieldNumber: 5)\n }\n try { if let v = self._platform {\n try visitor.visitSingularMessageField(value: v, fieldNumber: 6)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Descriptor, rhs: Com_Apple_Container_Build_V1_Descriptor) -> Bool {\n if lhs.mediaType != rhs.mediaType {return false}\n if lhs.digest != rhs.digest {return false}\n if lhs.size != rhs.size {return false}\n if lhs.urls != rhs.urls {return false}\n if lhs.annotations != rhs.annotations {return false}\n if lhs._platform != rhs._platform {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n"], ["/container/Sources/APIServer/Kernel/KernelService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\nimport TerminalProgress\n\nactor KernelService {\n private static let defaultKernelNamePrefix: String = \"default.kernel-\"\n\n private let log: Logger\n private let kernelDirectory: URL\n\n public init(log: Logger, appRoot: URL) throws {\n self.log = log\n self.kernelDirectory = appRoot.appending(path: \"kernels\")\n try FileManager.default.createDirectory(at: self.kernelDirectory, withIntermediateDirectories: true)\n }\n\n /// Copies a kernel binary from a local path on disk into the managed kernels directory\n /// as the default kernel for the provided platform.\n public func installKernel(kernelFile url: URL, platform: SystemPlatform = .linuxArm) throws {\n self.log.info(\"KernelService: \\(#function) - kernelFile: \\(url), platform: \\(String(describing: platform))\")\n let kFile = url.resolvingSymlinksInPath()\n let destPath = self.kernelDirectory.appendingPathComponent(kFile.lastPathComponent)\n try FileManager.default.copyItem(at: kFile, to: destPath)\n try Task.checkCancellation()\n do {\n try self.setDefaultKernel(name: kFile.lastPathComponent, platform: platform)\n } catch {\n try? FileManager.default.removeItem(at: destPath)\n throw error\n }\n }\n\n /// Copies a kernel binary from inside of tar file into the managed kernels directory\n /// as the default kernel for the provided platform.\n /// The parameter `tar` maybe a location to a local file on disk, or a remote URL.\n public func installKernelFrom(tar: URL, kernelFilePath: String, platform: SystemPlatform, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"KernelService: \\(#function) - tar: \\(tar), kernelFilePath: \\(kernelFilePath), platform: \\(String(describing: platform))\")\n\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n\n await progressUpdate?([\n .setDescription(\"Downloading kernel\")\n ])\n let taskManager = ProgressTaskCoordinator()\n let downloadTask = await taskManager.startTask()\n var tarFile = tar\n if !FileManager.default.fileExists(atPath: tar.absoluteString) {\n self.log.debug(\"KernelService: Downloading \\(tar)\")\n tarFile = tempDir.appendingPathComponent(tar.lastPathComponent)\n var downloadProgressUpdate: ProgressUpdateHandler?\n if let progressUpdate {\n downloadProgressUpdate = ProgressTaskCoordinator.handler(for: downloadTask, from: progressUpdate)\n }\n try await FileDownloader.downloadFile(url: tar, to: tarFile, progressUpdate: downloadProgressUpdate)\n }\n await taskManager.finish()\n\n await progressUpdate?([\n .setDescription(\"Unpacking kernel\")\n ])\n let archiveReader = try ArchiveReader(file: tarFile)\n let kernelFile = try archiveReader.extractFile(from: kernelFilePath, to: tempDir)\n try self.installKernel(kernelFile: kernelFile, platform: platform)\n\n if !FileManager.default.fileExists(atPath: tar.absoluteString) {\n try FileManager.default.removeItem(at: tarFile)\n }\n }\n\n private func setDefaultKernel(name: String, platform: SystemPlatform) throws {\n self.log.info(\"KernelService: \\(#function) - name: \\(name), platform: \\(String(describing: platform))\")\n let kernelPath = self.kernelDirectory.appendingPathComponent(name)\n guard FileManager.default.fileExists(atPath: kernelPath.path) else {\n throw ContainerizationError(.notFound, message: \"Kernel not found at \\(kernelPath)\")\n }\n let name = \"\\(Self.defaultKernelNamePrefix)\\(platform.architecture)\"\n let defaultKernelPath = self.kernelDirectory.appendingPathComponent(name)\n try? FileManager.default.removeItem(at: defaultKernelPath)\n try FileManager.default.createSymbolicLink(at: defaultKernelPath, withDestinationURL: kernelPath)\n }\n\n public func getDefaultKernel(platform: SystemPlatform = .linuxArm) async throws -> Kernel {\n self.log.info(\"KernelService: \\(#function) - platform: \\(String(describing: platform))\")\n let name = \"\\(Self.defaultKernelNamePrefix)\\(platform.architecture)\"\n let defaultKernelPath = self.kernelDirectory.appendingPathComponent(name).resolvingSymlinksInPath()\n guard FileManager.default.fileExists(atPath: defaultKernelPath.path) else {\n throw ContainerizationError(.notFound, message: \"Default kernel not found at \\(defaultKernelPath)\")\n }\n return Kernel(path: defaultKernelPath, platform: platform)\n }\n}\n\nextension ArchiveReader {\n fileprivate func extractFile(from: String, to directory: URL) throws -> URL {\n let (_, data) = try self.extractFile(path: from)\n try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)\n let fileName = URL(filePath: from).lastPathComponent\n let fileURL = directory.appendingPathComponent(fileName)\n try data.write(to: fileURL, options: .atomic)\n return fileURL\n }\n}\n"], ["/container/Sources/CLI/Image/ImageSave.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ImageSave: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"save\",\n abstract: \"Save an image as an OCI compatible tar archive\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Option(\n name: .shortAndLong, help: \"Path to save the image tar archive\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var output: String\n\n @Argument var reference: String\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let progressConfig = try ProgressConfig(\n description: \"Saving image\"\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let image = try await ClientImage.get(reference: reference)\n try await image.save(out: output, platform: p)\n\n progress.finish()\n print(\"Image saved\")\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nextension Application {\n struct SystemStatus: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"status\",\n abstract: \"Show the status of `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Launchd prefix for `container` services\")\n var prefix: String = \"com.apple.container.\"\n\n func run() async throws {\n let isRegistered = try ServiceManager.isRegistered(fullServiceLabel: \"\\(prefix)apiserver\")\n if !isRegistered {\n print(\"apiserver is not running and not registered with launchd\")\n Application.exit(withError: ExitCode(1))\n }\n\n // Now ping our friendly daemon. Fail after 10 seconds with no response.\n do {\n print(\"Verifying apiserver is running...\")\n try await ClientHealthCheck.ping(timeout: .seconds(10))\n print(\"apiserver is running\")\n } catch {\n print(\"apiserver is not running\")\n Application.exit(withError: ExitCode(1))\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientKernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct ClientKernel {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n}\n\nextension ClientKernel {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public static func installKernel(kernelFilePath: String, platform: SystemPlatform) async throws {\n let client = newClient()\n let message = XPCMessage(route: .installKernel)\n\n message.set(key: .kernelFilePath, value: kernelFilePath)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n try await client.send(message)\n }\n\n public static func installKernelFromTar(tarFile: String, kernelFilePath: String, platform: SystemPlatform, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let client = newClient()\n let message = XPCMessage(route: .installKernel)\n\n message.set(key: .kernelTarURL, value: tarFile)\n message.set(key: .kernelFilePath, value: kernelFilePath)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: message)\n }\n\n try await client.send(message)\n await progressUpdateClient?.finish()\n }\n\n @discardableResult\n public static func getDefaultKernel(for platform: SystemPlatform) async throws -> Kernel {\n let client = newClient()\n let message = XPCMessage(route: .getDefaultKernel)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n do {\n let reply = try await client.send(message)\n guard let kData = reply.dataNoCopy(key: .kernel) else {\n throw ContainerizationError(.internalError, message: \"Missing kernel data from XPC response\")\n }\n\n let kernel = try JSONDecoder().decode(Kernel.self, from: kData)\n return kernel\n } catch let err as ContainerizationError {\n guard err.isCode(.notFound) else {\n throw err\n }\n throw ContainerizationError(\n .notFound, message: \"Default kernel not configured for architecture \\(platform.architecture). Please use the `container system kernel set` command to configure it\")\n }\n }\n}\n\nextension SystemPlatform {\n public static var current: SystemPlatform {\n switch Platform.current.architecture {\n case \"arm64\":\n return .linuxArm\n case \"amd64\":\n return .linuxAmd\n default:\n fatalError(\"Unknown architecture\")\n }\n }\n}\n"], ["/container/Sources/CLI/DefaultCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\n\nstruct DefaultCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: nil,\n shouldDisplay: false\n )\n\n @OptionGroup(visibility: .hidden)\n var global: Flags.Global\n\n @Argument(parsing: .captureForPassthrough)\n var remaining: [String] = []\n\n func run() async throws {\n // See if we have a possible plugin command.\n guard let command = remaining.first else {\n Application.printModifiedHelpText()\n return\n }\n\n // Check for edge cases and unknown options to match the behavior in the absence of plugins.\n if command.isEmpty {\n throw ValidationError(\"Unknown argument '\\(command)'\")\n } else if command.starts(with: \"-\") {\n throw ValidationError(\"Unknown option '\\(command)'\")\n }\n\n let pluginLoader = Application.pluginLoader\n guard let plugin = pluginLoader.findPlugin(name: command), plugin.config.isCLI else {\n throw ValidationError(\"failed to find plugin named container-\\(command)\")\n }\n // Exec performs execvp (with no fork).\n try plugin.exec(args: remaining)\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/InterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\n\n/// A strategy for mapping network attachment information to a network interface.\npublic protocol InterfaceStrategy: Sendable {\n /// Map a client network attachment request to a network interface specification.\n ///\n /// - Parameters:\n /// - attachment: General attachment information that is common\n /// for all networks.\n /// - interfaceIndex: The zero-based index of the interface.\n /// - additionalData: If present, attachment information that is\n /// specific for the network to which the container will attach.\n ///\n /// - Returns: An XPC message with no parameters.\n func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) throws -> Interface\n}\n"], ["/container/Sources/APIServer/Kernel/KernelHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nstruct KernelHarness {\n private let log: Logging.Logger\n private let service: KernelService\n\n init(service: KernelService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n public func install(_ message: XPCMessage) async throws -> XPCMessage {\n let kernelFilePath = try message.kernelFilePath()\n let platform = try message.platform()\n\n guard let kernelTarUrl = try message.kernelTarURL() else {\n // We have been given a path to a kernel binary on disk\n guard let kernelFile = URL(string: kernelFilePath) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid kernel file path: \\(kernelFilePath)\")\n }\n try await self.service.installKernel(kernelFile: kernelFile, platform: platform)\n return message.reply()\n }\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await self.service.installKernelFrom(tar: kernelTarUrl, kernelFilePath: kernelFilePath, platform: platform, progressUpdate: progressUpdateService?.handler)\n return message.reply()\n }\n\n public func getDefaultKernel(_ message: XPCMessage) async throws -> XPCMessage {\n guard let platformData = message.dataNoCopy(key: .systemPlatform) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing SystemPlatform\")\n }\n let platform = try JSONDecoder().decode(SystemPlatform.self, from: platformData)\n let kernel = try await self.service.getDefaultKernel(platform: platform)\n let reply = message.reply()\n let data = try JSONEncoder().encode(kernel)\n reply.set(key: .kernel, value: data)\n return reply\n }\n}\n\nextension XPCMessage {\n fileprivate func platform() throws -> SystemPlatform {\n guard let platformData = self.dataNoCopy(key: .systemPlatform) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing SystemPlatform in XPC Message\")\n }\n let platform = try JSONDecoder().decode(SystemPlatform.self, from: platformData)\n return platform\n }\n\n fileprivate func kernelFilePath() throws -> String {\n guard let kernelFilePath = self.string(key: .kernelFilePath) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing kernel file path in XPC Message\")\n }\n return kernelFilePath\n }\n\n fileprivate func kernelTarURL() throws -> URL? {\n guard let kernelTarURLString = self.string(key: .kernelTarURL) else {\n return nil\n }\n guard let k = URL(string: kernelTarURLString) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse URL from \\(kernelTarURLString)\")\n }\n return k\n }\n}\n"], ["/container/Sources/ContainerClient/ContainerizationProgressAdapter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport TerminalProgress\n\npublic enum ContainerizationProgressAdapter: ProgressAdapter {\n public static func handler(from progressUpdate: ProgressUpdateHandler?) -> ProgressHandler? {\n guard let progressUpdate else {\n return nil\n }\n return { events in\n var updateEvents = [ProgressUpdateEvent]()\n for event in events {\n if event.event == \"add-items\" {\n if let items = event.value as? Int {\n updateEvents.append(.addItems(items))\n }\n } else if event.event == \"add-total-items\" {\n if let totalItems = event.value as? Int {\n updateEvents.append(.addTotalItems(totalItems))\n }\n } else if event.event == \"add-size\" {\n if let size = event.value as? Int64 {\n updateEvents.append(.addSize(size))\n }\n } else if event.event == \"add-total-size\" {\n if let totalSize = event.value as? Int64 {\n updateEvents.append(.addTotalSize(totalSize))\n }\n }\n }\n await progressUpdate(updateEvents)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/SignalThreshold.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\n\n// For a lot of programs, they don't install their own signal handlers for\n// SIGINT/SIGTERM which poses a somewhat fun problem for containers. Because\n// they're pid 1 (doesn't matter that it isn't in the \"root\" pid namespace)\n// the default actions for SIGINT and SIGTERM now are nops. So this type gives\n// us an opportunity to set a threshold for a certain number of signals received\n// so we can have an escape hatch for users to escape their horrific mistake\n// of cat'ing /dev/urandom by exit(1)'ing :)\npublic struct SignalThreshold {\n private let threshold: Int\n private let signals: [Int32]\n private var t: Task<(), Never>?\n\n public init(\n threshold: Int,\n signals: [Int32],\n ) {\n self.threshold = threshold\n self.signals = signals\n }\n\n // Start kicks off the signal watching. The passed in handler will\n // run only once upon passing the threshold number passed in the constructor.\n mutating public func start(handler: @Sendable @escaping () -> Void) {\n let signals = self.signals\n let threshold = self.threshold\n self.t = Task {\n var received = 0\n let signalHandler = AsyncSignalHandler.create(notify: signals)\n for await _ in signalHandler.signals {\n received += 1\n if received == threshold {\n handler()\n signalHandler.cancel()\n return\n }\n }\n }\n }\n\n public func stop() {\n self.t?.cancel()\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/StandardQueryValidator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Pass standard queries to a delegate handler.\npublic struct StandardQueryValidator: DNSHandler {\n private let handler: DNSHandler\n\n /// Create the handler.\n /// - Parameter delegate: the handler that receives valid queries\n public init(handler: DNSHandler) {\n self.handler = handler\n }\n\n /// Ensures the query is valid before forwarding it to the delegate.\n /// - Parameter msg: the query message\n /// - Returns: the delegate response if the query is valid, and an\n /// error response otherwise\n public func answer(query: Message) async throws -> Message? {\n // Reject response messages.\n guard query.type == .query else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions\n )\n }\n\n // Standard DNS servers handle only query operations.\n guard query.operationCode == .query else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions\n )\n }\n\n // Standard DNS servers only handle messages with exactly one question.\n guard query.questions.count == 1 else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions\n )\n }\n\n return try await handler.answer(query: query)\n }\n}\n"], ["/container/Sources/APIServer/Plugin/PluginsHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nstruct PluginsHarness {\n private let log: Logging.Logger\n private let service: PluginsService\n\n init(service: PluginsService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func load(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.load(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func get(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n let plugin = try await service.get(name: name)\n let data = try JSONEncoder().encode(plugin)\n\n let reply = message.reply()\n reply.set(key: .plugin, value: data)\n return reply\n }\n\n @Sendable\n func restart(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.restart(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func unload(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.unload(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let plugins = try await service.list()\n\n let data = try JSONEncoder().encode(plugins)\n\n let reply = message.reply()\n reply.set(key: .plugins, value: data)\n return reply\n }\n}\n"], ["/container/Sources/ContainerClient/RequestScheme.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\n\n/// The URL scheme to be used for a HTTP request.\npublic enum RequestScheme: String, Sendable {\n case http = \"http\"\n case https = \"https\"\n\n case auto = \"auto\"\n\n public init(_ rawValue: String) throws {\n switch rawValue {\n case RequestScheme.http.rawValue:\n self = .http\n case RequestScheme.https.rawValue:\n self = .https\n case RequestScheme.auto.rawValue:\n self = .auto\n default:\n throw ContainerizationError(.invalidArgument, message: \"Unsupported scheme \\(rawValue)\")\n }\n }\n\n /// Returns the prescribed protocol to use while making a HTTP request to a webserver\n /// - Parameter host: The domain or IP address of the webserver\n /// - Returns: RequestScheme\n package func schemeFor(host: String) throws -> Self {\n guard host.count > 0 else {\n throw ContainerizationError(.invalidArgument, message: \"Host cannot be empty\")\n }\n switch self {\n case .http, .https:\n return self\n case .auto:\n return Self.isInternalHost(host: host) ? .http : .https\n }\n }\n\n /// Checks if the given `host` string is a private IP address\n /// or a domain typically reachable only on the local system.\n private static func isInternalHost(host: String) -> Bool {\n if host.hasPrefix(\"localhost\") || host.hasPrefix(\"127.\") {\n return true\n }\n if host.hasPrefix(\"192.168.\") || host.hasPrefix(\"10.\") {\n return true\n }\n let regex = \"(^172\\\\.1[6-9]\\\\.)|(^172\\\\.2[0-9]\\\\.)|(^172\\\\.3[0-1]\\\\.)\"\n if host.range(of: regex, options: .regularExpression) != nil {\n return true\n }\n let dnsDomain = ClientDefaults.get(key: .defaultDNSDomain)\n if host.hasSuffix(\".\\(dnsDomain)\") {\n return true\n }\n return false\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct NetworkCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"network\",\n abstract: \"Manage container networks\",\n subcommands: [\n NetworkCreate.self,\n NetworkDelete.self,\n NetworkList.self,\n NetworkInspect.self,\n ],\n aliases: [\"n\"]\n )\n }\n}\n"], ["/container/Sources/ContainerClient/Core/Bundle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport Foundation\n\npublic struct Bundle: Sendable {\n private static let initfsFilename = \"initfs.ext4\"\n private static let kernelFilename = \"kernel.json\"\n private static let kernelBinaryFilename = \"kernel.bin\"\n private static let containerRootFsBlockFilename = \"rootfs.ext4\"\n private static let containerRootFsFilename = \"rootfs.json\"\n\n static let containerConfigFilename = \"config.json\"\n\n /// The path to the bundle.\n public let path: URL\n\n public init(path: URL) {\n self.path = path\n }\n\n public var bootlog: URL {\n self.path.appendingPathComponent(\"vminitd.log\")\n }\n\n private var containerRootfsBlock: URL {\n self.path.appendingPathComponent(Self.containerRootFsBlockFilename)\n }\n\n private var containerRootfsConfig: URL {\n self.path.appendingPathComponent(Self.containerRootFsFilename)\n }\n\n public var containerRootfs: Filesystem {\n get throws {\n let data = try Data(contentsOf: containerRootfsConfig)\n let fs = try JSONDecoder().decode(Filesystem.self, from: data)\n return fs\n }\n }\n\n /// Return the initial filesystem for a sandbox.\n public var initialFilesystem: Filesystem {\n .block(\n format: \"ext4\",\n source: self.path.appendingPathComponent(Self.initfsFilename).path,\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n\n public var kernel: Kernel {\n get throws {\n try load(path: self.path.appendingPathComponent(Self.kernelFilename))\n }\n }\n\n public var configuration: ContainerConfiguration {\n get throws {\n try load(path: self.path.appendingPathComponent(Self.containerConfigFilename))\n }\n }\n}\n\nextension Bundle {\n public static func create(\n path: URL,\n initialFilesystem: Filesystem,\n kernel: Kernel,\n containerConfiguration: ContainerConfiguration? = nil\n ) throws -> Bundle {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n let kbin = path.appendingPathComponent(Self.kernelBinaryFilename)\n try FileManager.default.copyItem(at: kernel.path, to: kbin)\n var k = kernel\n k.path = kbin\n try write(path.appendingPathComponent(Self.kernelFilename), value: k)\n\n switch initialFilesystem.type {\n case .block(let fmt, _, _):\n guard fmt == \"ext4\" else {\n fatalError(\"ext4 is the only supported format for initial filesystem\")\n }\n // when saving the Initial Filesystem to the bundle\n // discard any filesystem information and just persist\n // the block into the Bundle.\n _ = try initialFilesystem.clone(to: path.appendingPathComponent(Self.initfsFilename).path)\n default:\n fatalError(\"invalid filesystem type for initial filesystem\")\n }\n let bundle = Bundle(path: path)\n if let containerConfiguration {\n try bundle.write(filename: Self.containerConfigFilename, value: containerConfiguration)\n }\n return bundle\n }\n}\n\nextension Bundle {\n /// Set the value of the configuration for the Bundle.\n public func set(configuration: ContainerConfiguration) throws {\n try write(filename: Self.containerConfigFilename, value: configuration)\n }\n\n /// Return the full filepath for a named resource in the Bundle.\n public func filePath(for name: String) -> URL {\n path.appendingPathComponent(name)\n }\n\n public func setContainerRootFs(cloning fs: Filesystem) throws {\n let cloned = try fs.clone(to: self.containerRootfsBlock.absolutePath())\n let fsData = try JSONEncoder().encode(cloned)\n try fsData.write(to: self.containerRootfsConfig)\n }\n\n /// Delete the bundle and all of the resources contained inside.\n public func delete() throws {\n try FileManager.default.removeItem(at: self.path)\n }\n\n public func write(filename: String, value: Encodable) throws {\n try Self.write(self.path.appendingPathComponent(filename), value: value)\n }\n\n private static func write(_ path: URL, value: Encodable) throws {\n let data = try JSONEncoder().encode(value)\n try data.write(to: path)\n }\n\n public func load(filename: String) throws -> T where T: Decodable {\n try load(path: self.path.appendingPathComponent(filename))\n }\n\n private func load(path: URL) throws -> T where T: Decodable {\n let data = try Data(contentsOf: path)\n return try JSONDecoder().decode(T.self, from: data)\n }\n}\n"], ["/container/Sources/APIServer/Plugin/PluginsService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerPlugin\nimport Foundation\nimport Logging\n\nactor PluginsService {\n private let log: Logger\n private var loaded: [String: Plugin]\n private let pluginLoader: PluginLoader\n\n public init(pluginLoader: PluginLoader, log: Logger) {\n self.log = log\n self.loaded = [:]\n self.pluginLoader = pluginLoader\n }\n\n /// Load the specified plugins, or all plugins with services defined\n /// if none are explicitly specified.\n public func loadAll(\n _ plugins: [Plugin]? = nil,\n ) throws {\n let registerPlugins = plugins ?? pluginLoader.findPlugins()\n for plugin in registerPlugins {\n try pluginLoader.registerWithLaunchd(plugin: plugin)\n loaded[plugin.name] = plugin\n }\n }\n\n /// Stop the specified plugins, or all plugins with services defined\n /// if none are explicitly specified.\n public func stopAll(_ plugins: [Plugin]? = nil) throws {\n let deregisterPlugins = plugins ?? pluginLoader.findPlugins()\n for plugin in deregisterPlugins {\n try pluginLoader.deregisterWithLaunchd(plugin: plugin)\n self.loaded.removeValue(forKey: plugin.name)\n }\n }\n\n // MARK: XPC API surface.\n\n /// Load a single plugin, doing nothing if the plugin is already loaded.\n public func load(name: String) throws {\n guard self.loaded[name] == nil else {\n return\n }\n guard let plugin = pluginLoader.findPlugin(name: name) else {\n throw Error.pluginNotFound(name)\n }\n try pluginLoader.registerWithLaunchd(plugin: plugin)\n self.loaded[plugin.name] = plugin\n }\n\n /// Get information for a loaded plugin.\n public func get(name: String) throws -> Plugin {\n guard let plugin = loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n return plugin\n }\n\n /// Restart a loaded plugin.\n public func restart(name: String) throws {\n guard let plugin = self.loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n try ServiceManager.kickstart(fullServiceLabel: plugin.getLaunchdLabel())\n }\n\n /// Unload a loaded plugin.\n public func unload(name: String) throws {\n guard let plugin = self.loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n try pluginLoader.deregisterWithLaunchd(plugin: plugin)\n self.loaded.removeValue(forKey: plugin.name)\n }\n\n /// List all loaded plugins.\n public func list() throws -> [Plugin] {\n self.loaded.map { $0.value }\n }\n\n public enum Error: Swift.Error, CustomStringConvertible {\n case pluginNotFound(String)\n case pluginNotLoaded(String)\n\n public var description: String {\n switch self {\n case .pluginNotFound(let name):\n return \"plugin not found: \\(name)\"\n case .pluginNotLoaded(let name):\n return \"plugin not loaded: \\(name)\"\n }\n }\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSDefault.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\n\nextension Application {\n struct DNSDefault: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"default\",\n abstract: \"Set or unset the default local DNS domain\",\n subcommands: [\n DefaultSetCommand.self,\n DefaultUnsetCommand.self,\n DefaultInspectCommand.self,\n ]\n )\n\n struct DefaultSetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default local DNS domain\"\n\n )\n\n @Argument(help: \"the default `--domain-name` to use for the `create` or `run` command\")\n var domainName: String\n\n func run() async throws {\n ClientDefaults.set(value: domainName, key: .defaultDNSDomain)\n print(domainName)\n }\n }\n\n struct DefaultUnsetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"unset\",\n abstract: \"Unset the default local DNS domain\",\n aliases: [\"clear\"]\n )\n\n func run() async throws {\n ClientDefaults.unset(key: .defaultDNSDomain)\n print(\"Unset the default local DNS domain\")\n }\n }\n\n struct DefaultInspectCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display the default local DNS domain\"\n )\n\n func run() async throws {\n print(ClientDefaults.getOptional(key: .defaultDNSDomain) ?? \"\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/Globber.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic class Globber {\n let input: URL\n var results: Set = .init()\n\n public init(_ input: URL) {\n self.input = input\n }\n\n public func match(_ pattern: String) throws {\n let adjustedPattern =\n pattern\n .replacingOccurrences(of: #\"^\\./(?=.)\"#, with: \"\", options: .regularExpression)\n .replacingOccurrences(of: \"^\\\\.[/]?$\", with: \"*\", options: .regularExpression)\n .replacingOccurrences(of: \"\\\\*{2,}[/]\", with: \"*/**/\", options: .regularExpression)\n .replacingOccurrences(of: \"[/]\\\\*{2,}([^/])\", with: \"/**/*$1\", options: .regularExpression)\n .replacingOccurrences(of: \"^\\\\*{2,}([^/])\", with: \"**/*$1\", options: .regularExpression)\n\n for child in input.children {\n try self.match(input: child, components: adjustedPattern.split(separator: \"/\").map(String.init))\n }\n }\n\n private func match(input: URL, components: [String]) throws {\n if components.isEmpty {\n var dir = input.standardizedFileURL\n\n while dir != self.input.standardizedFileURL {\n results.insert(dir)\n guard dir.pathComponents.count > 1 else { break }\n dir.deleteLastPathComponent()\n }\n return input.childrenRecursive.forEach { results.insert($0) }\n }\n\n let head = components.first ?? \"\"\n let tail = components.tail\n\n if head == \"**\" {\n var tail: [String] = tail\n while tail.first == \"**\" {\n tail = tail.tail\n }\n try self.match(input: input, components: tail)\n for child in input.children {\n try self.match(input: child, components: components)\n }\n return\n }\n\n if try glob(input.lastPathComponent, head) {\n try self.match(input: input, components: tail)\n\n for child in input.children where try glob(child.lastPathComponent, tail.first ?? \"\") {\n try self.match(input: child, components: tail)\n }\n return\n }\n }\n\n func glob(_ input: String, _ pattern: String) throws -> Bool {\n let regexPattern =\n \"^\"\n + NSRegularExpression.escapedPattern(for: pattern)\n .replacingOccurrences(of: \"\\\\*\", with: \"[^/]*\")\n .replacingOccurrences(of: \"\\\\?\", with: \"[^/]\")\n .replacingOccurrences(of: \"[\\\\^\", with: \"[^\")\n .replacingOccurrences(of: \"\\\\[\", with: \"[\")\n .replacingOccurrences(of: \"\\\\]\", with: \"]\") + \"$\"\n\n // validate the regex pattern created\n let _ = try Regex(regexPattern)\n return input.range(of: regexPattern, options: .regularExpression) != nil\n }\n}\n\nextension URL {\n var children: [URL] {\n\n (try? FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil))\n ?? []\n }\n\n var childrenRecursive: [URL] {\n var results: [URL] = []\n if let enumerator = FileManager.default.enumerator(\n at: self, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey])\n {\n while let child = enumerator.nextObject() as? URL {\n results.append(child)\n }\n }\n return [self] + results\n }\n}\n\nextension [String] {\n var tail: [String] {\n if self.count <= 1 {\n return []\n }\n return Array(self.dropFirst())\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerSnapshot.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\n\n/// A snapshot of a container along with its configuration\n/// and any runtime state information.\npublic struct ContainerSnapshot: Codable, Sendable {\n /// The configuration of the container.\n public let configuration: ContainerConfiguration\n /// The runtime status of the container.\n public let status: RuntimeStatus\n /// Network interfaces attached to the sandbox that are provided to the container.\n public let networks: [Attachment]\n\n public init(\n configuration: ContainerConfiguration,\n status: RuntimeStatus,\n networks: [Attachment]\n ) {\n self.configuration = configuration\n self.status = status\n self.networks = networks\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\nimport Foundation\n\n/// PluginConfig details all of the fields to describe and register a plugin.\n/// A plugin is registered by creating a subdirectory `/user-plugins`,\n/// where the name of the subdirectory is the name of the plugin, and then placing a\n/// file named `config.json` inside with the schema below.\n/// If `services` is filled in then there MUST be a binary named matching the plugin name\n/// in a `bin` subdirectory inside the same directory as the `config.json`.\n/// An example of a valid plugin directory structure would be\n/// $ tree foobar\n/// foobar\n/// ├── bin\n/// │ └── foobar\n/// └── config.json\npublic struct PluginConfig: Sendable, Codable {\n /// Categories of services that can be offered through plugins.\n public enum DaemonPluginType: String, Sendable, Codable {\n /// A runtime plugin provides an XPC API through which the lifecycle\n /// of a **single** container can be managed.\n /// A runtime daemon plugin would typically also have a counterpart\n /// CLI plugin which knows how to talk to the API exposed by the runtime plugin.\n /// The API server ensures that a single instance of the plugin is configured\n /// for a given container such that the client can communicate with it given an instance id.\n case runtime\n /// A network plugin provides an XPC API through which IP address allocations on a given\n /// network can be managed. The API server ensures that a single instance\n /// of this plugin is configured for a given network. Similar to the runtime plugin, it typically\n /// would be accompanied by a CLI plugin that knows how to communicate with the XPC API\n /// given an instance id.\n case network\n /// A core plugin provides an XPC API to manage a given type of resource.\n /// The API server ensures that there exist only a single running instance\n /// of this plugin type. A core plugin can be thought of a singleton whose lifecycle\n /// is tied to that of the API server. Core plugins can be used to expand the base functionality\n /// provided by the API server. As with the other plugin types, it maybe associated with a client\n /// side plugin that communicates with the XPC service exposed by the daemon plugin.\n case core\n /// Reserved for future use. Currently there is no difference between a core and auxiliary daemon plugin.\n case auxiliary\n }\n\n // An XPC service that the plugin publishes.\n public struct Service: Sendable, Codable {\n /// The type of the service the daemon is exposing.\n /// One plugin can expose multiple services of different types.\n ///\n /// The plugin MUST expose a MachService at\n /// `com.apple.container.{type}.{name}.[{id}]` for\n /// each service that it exposes.\n public let type: DaemonPluginType\n /// Optional description of this service.\n public let description: String?\n }\n\n /// Descriptor for the services that the plugin offers.\n public struct ServicesConfig: Sendable, Codable {\n /// Load the plugin into launchd when the API server starts.\n public let loadAtBoot: Bool\n /// Launch the plugin binary as soon as it loads into launchd.\n public let runAtLoad: Bool\n /// The service types that the plugin provides.\n public let services: [Service]\n /// An optional parameter that include any command line arguments\n /// that must be passed to the plugin binary when it is loaded.\n /// This parameter is used only when `servicesConfig.loadAtBoot` is `true`\n public let defaultArguments: [String]\n }\n\n /// Short description of the plugin surface. This will be displayed as the\n /// help-text for CLI plugins, and will be returned in API calls to view loaded\n /// plugins from the daemon.\n public let abstract: String\n\n /// Author of the plugin. This is solely metadata.\n public let author: String?\n\n /// Services configuration. Specify nil for a CLI plugin, and an empty array for\n /// that does not publish any XPC services.\n public let servicesConfig: ServicesConfig?\n}\n\nextension PluginConfig {\n public var isCLI: Bool { self.servicesConfig == nil }\n}\n\nextension PluginConfig {\n public init?(configURL: URL) throws {\n let fm = FileManager.default\n if !fm.fileExists(atPath: configURL.path) {\n return nil\n }\n\n guard let data = fm.contents(atPath: configURL.path) else {\n return nil\n }\n\n let decoder: JSONDecoder = JSONDecoder()\n self = try decoder.decode(PluginConfig.self, from: data)\n }\n}\n"], ["/container/Sources/ContainerPlugin/Plugin.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\n/// Value type that contains the plugin configuration, the parsed name of the\n/// plugin and whether a CLI surface for the plugin was found.\npublic struct Plugin: Sendable, Codable {\n private static let machServicePrefix = \"com.apple.container.\"\n\n /// Pathname to installation directory for plugins.\n public let binaryURL: URL\n\n /// Configuration for the plugin.\n public let config: PluginConfig\n\n public init(binaryURL: URL, config: PluginConfig) {\n self.binaryURL = binaryURL\n self.config = config\n }\n}\n\nextension Plugin {\n public var name: String { binaryURL.lastPathComponent }\n\n public var shouldBoot: Bool {\n guard let config = self.config.servicesConfig else {\n return false\n }\n\n return config.loadAtBoot\n }\n\n public func getLaunchdLabel(instanceId: String? = nil) -> String {\n // Use the plugin name for the launchd label.\n guard let instanceId else {\n return \"\\(Self.machServicePrefix)\\(self.name)\"\n }\n return \"\\(Self.machServicePrefix)\\(self.name).\\(instanceId)\"\n }\n\n public func getMachServices(instanceId: String? = nil) -> [String] {\n // Use the service type for the mach service.\n guard let config = self.config.servicesConfig else {\n return []\n }\n var services = [String]()\n for service in config.services {\n let serviceName: String\n if let instanceId {\n serviceName = \"\\(Self.machServicePrefix)\\(service.type.rawValue).\\(name).\\(instanceId)\"\n } else {\n serviceName = \"\\(Self.machServicePrefix)\\(service.type.rawValue).\\(name)\"\n }\n services.append(serviceName)\n }\n return services\n }\n\n public func getMachService(instanceId: String? = nil, type: PluginConfig.DaemonPluginType) -> String? {\n guard hasType(type) else {\n return nil\n }\n\n guard let instanceId else {\n return \"\\(Self.machServicePrefix)\\(type.rawValue).\\(name)\"\n }\n return \"\\(Self.machServicePrefix)\\(type.rawValue).\\(name).\\(instanceId)\"\n }\n\n public func hasType(_ type: PluginConfig.DaemonPluginType) -> Bool {\n guard let config = self.config.servicesConfig else {\n return false\n }\n\n guard !(config.services.filter { $0.type == type }.isEmpty) else {\n return false\n }\n\n return true\n }\n}\n\nextension Plugin {\n public func exec(args: [String]) throws {\n var args = args\n let executable = self.binaryURL.path\n args[0] = executable\n let argv = args.map { strdup($0) } + [nil]\n guard execvp(executable, argv) != -1 else {\n throw POSIXError.fromErrno()\n }\n fatalError(\"unreachable\")\n }\n\n func helpText(padding: Int) -> String {\n guard !self.name.isEmpty else {\n return \"\"\n }\n let namePadded = name.padding(toLength: padding, withPad: \" \", startingAt: 0)\n return \" \" + namePadded + self.config.abstract\n }\n}\n"], ["/container/Sources/SocketForwarder/TCPForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\n\npublic struct TCPForwarder: SocketForwarder {\n private let proxyAddress: SocketAddress\n\n private let serverAddress: SocketAddress\n\n private let eventLoopGroup: any EventLoopGroup\n\n private let log: Logger?\n\n public init(\n proxyAddress: SocketAddress,\n serverAddress: SocketAddress,\n eventLoopGroup: any EventLoopGroup,\n log: Logger? = nil\n ) throws {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.log = log\n }\n\n public func run() throws -> EventLoopFuture {\n self.log?.trace(\"frontend - creating listener\")\n\n let bootstrap = ServerBootstrap(group: self.eventLoopGroup)\n .serverChannelOption(ChannelOptions.socket(.init(SOL_SOCKET), .init(SO_REUSEADDR)), value: 1)\n .childChannelOption(ChannelOptions.socket(.init(SOL_SOCKET), .init(SO_REUSEADDR)), value: 1)\n .childChannelInitializer { channel in\n channel.eventLoop.makeCompletedFuture {\n try channel.pipeline.syncOperations.addHandler(\n ConnectHandler(serverAddress: self.serverAddress, log: log)\n )\n }\n }\n\n return\n bootstrap\n .bind(to: self.proxyAddress)\n .flatMap { $0.eventLoop.makeSucceededFuture(SocketForwarderResult(channel: $0)) }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkState.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct NetworkStatus: Codable, Sendable {\n /// The address allocated for the network if no subnet was specified at\n /// creation time; otherwise, the subnet from the configuration.\n public let address: String\n /// The gateway IPv4 address.\n public let gateway: String\n\n public init(\n address: String,\n gateway: String\n ) {\n self.address = address\n self.gateway = gateway\n }\n\n}\n\n/// The configuration and runtime attributes for a network.\npublic enum NetworkState: Codable, Sendable {\n // The network has been configured.\n case created(NetworkConfiguration)\n // The network is running.\n case running(NetworkConfiguration, NetworkStatus)\n\n public var state: String {\n switch self {\n case .created: \"created\"\n case .running: \"running\"\n }\n }\n\n public var id: String {\n switch self {\n case .created(let configuration): configuration.id\n case .running(let configuration, _): configuration.id\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImageTag.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\n\nextension Application {\n struct ImageTag: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"tag\",\n abstract: \"Tag an image\")\n\n @Argument(help: \"SOURCE_IMAGE[:TAG]\")\n var source: String\n\n @Argument(help: \"TARGET_IMAGE[:TAG]\")\n var target: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let existing = try await ClientImage.get(reference: source)\n let targetReference = try ClientImage.normalizeReference(target)\n try await existing.tag(new: targetReference)\n print(\"Image \\(source) tagged as \\(target)\")\n }\n }\n}\n"], ["/container/Sources/ContainerClient/SandboxSnapshot.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\n\n/// A snapshot of a sandbox and its resources.\npublic struct SandboxSnapshot: Codable, Sendable {\n /// The runtime status of the sandbox.\n public let status: RuntimeStatus\n /// Network attachments for the sandbox.\n public let networks: [Attachment]\n /// Containers placed in the sandbox.\n public let containers: [ContainerSnapshot]\n\n public init(\n status: RuntimeStatus,\n networks: [Attachment],\n containers: [ContainerSnapshot]\n ) {\n self.status = status\n self.networks = networks\n self.containers = containers\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildStdio.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIO\n\nactor BuildStdio: BuildPipelineHandler {\n public let quiet: Bool\n public let handle: FileHandle\n\n init(quiet: Bool = false, output: FileHandle = FileHandle.standardError) throws {\n self.quiet = quiet\n self.handle = output\n }\n\n nonisolated func accept(_ packet: ServerStream) throws -> Bool {\n guard let _ = packet.getIO() else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard !quiet else {\n return\n }\n guard let io = packet.getIO() else {\n throw Error.ioMissing\n }\n if let cmdString = try TerminalCommand().json() {\n var response = ClientStream()\n response.buildID = packet.buildID\n response.command = .init()\n response.command.id = packet.buildID\n response.command.command = cmdString\n sender.yield(response)\n }\n handle.write(io.data)\n }\n}\n\nextension BuildStdio {\n enum Error: Swift.Error, CustomStringConvertible {\n case ioMissing\n case invalidContinuation\n var description: String {\n switch self {\n case .ioMissing:\n return \"io field missing in packet\"\n case .invalidContinuation:\n return \"continuation could not created\"\n }\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressTaskCoordinator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that represents a task whose progress is being monitored.\npublic struct ProgressTask: Sendable, Equatable {\n private var id = UUID()\n private var coordinator: ProgressTaskCoordinator\n\n init(manager: ProgressTaskCoordinator) {\n self.coordinator = manager\n }\n\n static public func == (lhs: ProgressTask, rhs: ProgressTask) -> Bool {\n lhs.id == rhs.id\n }\n\n /// Returns `true` if this task is the currently active task, `false` otherwise.\n public func isCurrent() async -> Bool {\n guard let currentTask = await coordinator.currentTask else {\n return false\n }\n return currentTask == self\n }\n}\n\n/// A type that coordinates progress tasks to ignore updates from completed tasks.\npublic actor ProgressTaskCoordinator {\n var currentTask: ProgressTask?\n\n /// Creates an instance of `ProgressTaskCoordinator`.\n public init() {}\n\n /// Returns a new task that should be monitored for progress updates.\n public func startTask() -> ProgressTask {\n let newTask = ProgressTask(manager: self)\n currentTask = newTask\n return newTask\n }\n\n /// Performs cleanup when the monitored tasks complete.\n public func finish() {\n currentTask = nil\n }\n\n /// Returns a handler that updates the progress of a given task.\n /// - Parameters:\n /// - task: The task whose progress is being updated.\n /// - progressUpdate: The handler to invoke when progress updates are received.\n public static func handler(for task: ProgressTask, from progressUpdate: @escaping ProgressUpdateHandler) -> ProgressUpdateHandler {\n { events in\n // Ignore updates from completed tasks.\n if await task.isCurrent() {\n await progressUpdate(events)\n }\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ContentStoreService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\npublic actor ContentStoreService {\n private let log: Logger\n private let contentStore: LocalContentStore\n private let root: URL\n\n public init(root: URL, log: Logger) throws {\n try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)\n self.root = root.appendingPathComponent(\"content\")\n self.contentStore = try LocalContentStore(path: self.root)\n self.log = log\n }\n\n public func get(digest: String) async throws -> URL? {\n self.log.trace(\"ContentStoreService: \\(#function) digest \\(digest)\")\n return try await self.contentStore.get(digest: digest)?.path\n }\n\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n self.log.debug(\"ContentStoreService: \\(#function) digests \\(digests)\")\n return try await self.contentStore.delete(digests: digests)\n }\n\n @discardableResult\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n self.log.debug(\"ContentStoreService: \\(#function) digests \\(keeping)\")\n return try await self.contentStore.delete(keeping: keeping)\n }\n\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n self.log.debug(\"ContentStoreService: \\(#function)\")\n return try await self.contentStore.newIngestSession()\n }\n\n public func completeIngestSession(_ id: String) async throws -> [String] {\n self.log.debug(\"ContentStoreService: \\(#function) id \\(id)\")\n return try await self.contentStore.completeIngestSession(id)\n }\n\n public func cancelIngestSession(_ id: String) async throws {\n self.log.debug(\"ContentStoreService: \\(#function) id \\(id)\")\n return try await self.contentStore.cancelIngestSession(id)\n }\n}\n"], ["/container/Sources/ContainerClient/Measurement+Parse.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nprivate let units: [Character: UnitInformationStorage] = [\n \"b\": .bytes,\n \"k\": .kibibytes,\n \"m\": .mebibytes,\n \"g\": .gibibytes,\n \"t\": .tebibytes,\n \"p\": .pebibytes,\n]\n\nextension Measurement {\n public enum ParseError: Swift.Error, CustomStringConvertible {\n case invalidSize\n case invalidSymbol(String)\n\n public var description: String {\n switch self {\n case .invalidSize:\n return \"invalid size\"\n case .invalidSymbol(let symbol):\n return \"invalid symbol: \\(symbol)\"\n }\n }\n }\n\n /// parse the provided string into a measurement that is able to be converted to various byte sizes\n public static func parse(parsing: String) throws -> Measurement {\n let check = \"01234567890. \"\n let i = parsing.lastIndex {\n check.contains($0)\n }\n guard let i else {\n throw ParseError.invalidSize\n }\n let after = parsing.index(after: i)\n let rawValue = parsing[..(value: value, unit: unit)\n }\n\n static func parseUnit(_ unit: String) throws -> Character {\n let s = unit.dropFirst()\n switch s {\n case \"\", \"b\", \"ib\":\n return unit.first ?? \"b\"\n default:\n throw ParseError.invalidSymbol(unit)\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Configuration parameters for network creation.\npublic struct NetworkConfiguration: Codable, Sendable, Identifiable {\n /// A unique identifier for the network\n public let id: String\n\n /// The network type\n public let mode: NetworkMode\n\n /// The preferred CIDR address for the subnet, if specified\n public let subnet: String?\n\n /// Creates a network configuration\n public init(\n id: String,\n mode: NetworkMode,\n subnet: String? = nil\n ) {\n self.id = id\n self.mode = mode\n self.subnet = subnet\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.grpc.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n// DO NOT EDIT.\n// swift-format-ignore-file\n//\n// Generated by the protocol buffer compiler.\n// Source: Builder.proto\n//\nimport GRPC\nimport NIO\nimport NIOConcurrencyHelpers\nimport SwiftProtobuf\n\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// Usage: instantiate `Com_Apple_Container_Build_V1_BuilderClient`, then call methods of this protocol to make API calls.\npublic protocol Com_Apple_Container_Build_V1_BuilderClientProtocol: GRPCClient {\n var serviceName: String { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? { get }\n\n func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func performBuild(\n callOptions: CallOptions?,\n handler: @escaping (Com_Apple_Container_Build_V1_ServerStream) -> Void\n ) -> BidirectionalStreamingCall\n\n func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n}\n\nextension Com_Apple_Container_Build_V1_BuilderClientProtocol {\n public var serviceName: String {\n return \"com.apple.container.build.v1.Builder\"\n }\n\n /// Create a build request.\n ///\n /// - Parameters:\n /// - request: Request to send to CreateBuild.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n ///\n /// Callers should use the `send` method on the returned object to send messages\n /// to the server. The caller should send an `.end` after the final message has been sent.\n ///\n /// - Parameters:\n /// - callOptions: Call options.\n /// - handler: A closure called when each response is received from the server.\n /// - Returns: A `ClientStreamingCall` with futures for the metadata and status.\n public func performBuild(\n callOptions: CallOptions? = nil,\n handler: @escaping (Com_Apple_Container_Build_V1_ServerStream) -> Void\n ) -> BidirectionalStreamingCall {\n return self.makeBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n handler: handler\n )\n }\n\n /// Unary call to Info\n ///\n /// - Parameters:\n /// - request: Request to send to Info.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(*, deprecated)\nextension Com_Apple_Container_Build_V1_BuilderClient: @unchecked Sendable {}\n\n@available(*, deprecated, renamed: \"Com_Apple_Container_Build_V1_BuilderNIOClient\")\npublic final class Com_Apple_Container_Build_V1_BuilderClient: Com_Apple_Container_Build_V1_BuilderClientProtocol {\n private let lock = Lock()\n private var _defaultCallOptions: CallOptions\n private var _interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n public let channel: GRPCChannel\n public var defaultCallOptions: CallOptions {\n get { self.lock.withLock { return self._defaultCallOptions } }\n set { self.lock.withLockVoid { self._defaultCallOptions = newValue } }\n }\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? {\n get { self.lock.withLock { return self._interceptors } }\n set { self.lock.withLockVoid { self._interceptors = newValue } }\n }\n\n /// Creates a client for the com.apple.container.build.v1.Builder service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self._defaultCallOptions = defaultCallOptions\n self._interceptors = interceptors\n }\n}\n\npublic struct Com_Apple_Container_Build_V1_BuilderNIOClient: Com_Apple_Container_Build_V1_BuilderClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n\n /// Creates a client for the com.apple.container.build.v1.Builder service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol: GRPCClient {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? { get }\n\n func makeCreateBuildCall(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makePerformBuildCall(\n callOptions: CallOptions?\n ) -> GRPCAsyncBidirectionalStreamingCall\n\n func makeInfoCall(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Container_Build_V1_BuilderClientMetadata.serviceDescriptor\n }\n\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? {\n return nil\n }\n\n public func makeCreateBuildCall(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n public func makePerformBuildCall(\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncBidirectionalStreamingCall {\n return self.makeAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func makeInfoCall(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Container_Build_V1_CreateBuildResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n public func performBuild(\n _ requests: RequestStream,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncResponseStream where RequestStream: Sequence, RequestStream.Element == Com_Apple_Container_Build_V1_ClientStream {\n return self.performAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n requests: requests,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func performBuild(\n _ requests: RequestStream,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncResponseStream where RequestStream: AsyncSequence & Sendable, RequestStream.Element == Com_Apple_Container_Build_V1_ClientStream {\n return self.performAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n requests: requests,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Container_Build_V1_InfoResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic struct Com_Apple_Container_Build_V1_BuilderAsyncClient: Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\npublic protocol Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when invoking 'createBuild'.\n func makeCreateBuildInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'performBuild'.\n func makePerformBuildInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'info'.\n func makeInfoInterceptors() -> [ClientInterceptor]\n}\n\npublic enum Com_Apple_Container_Build_V1_BuilderClientMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"Builder\",\n fullName: \"com.apple.container.build.v1.Builder\",\n methods: [\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild,\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild,\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info,\n ]\n )\n\n public enum Methods {\n public static let createBuild = GRPCMethodDescriptor(\n name: \"CreateBuild\",\n path: \"/com.apple.container.build.v1.Builder/CreateBuild\",\n type: GRPCCallType.unary\n )\n\n public static let performBuild = GRPCMethodDescriptor(\n name: \"PerformBuild\",\n path: \"/com.apple.container.build.v1.Builder/PerformBuild\",\n type: GRPCCallType.bidirectionalStreaming\n )\n\n public static let info = GRPCMethodDescriptor(\n name: \"Info\",\n path: \"/com.apple.container.build.v1.Builder/Info\",\n type: GRPCCallType.unary\n )\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// To build a server, implement a class that conforms to this protocol.\npublic protocol Com_Apple_Container_Build_V1_BuilderProvider: CallHandlerProvider {\n var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? { get }\n\n /// Create a build request.\n func createBuild(request: Com_Apple_Container_Build_V1_CreateBuildRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n func performBuild(context: StreamingResponseCallContext) -> EventLoopFuture<(StreamEvent) -> Void>\n\n func info(request: Com_Apple_Container_Build_V1_InfoRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n}\n\nextension Com_Apple_Container_Build_V1_BuilderProvider {\n public var serviceName: Substring {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor.fullName[...]\n }\n\n /// Determines, calls and returns the appropriate request handler, depending on the request's method.\n /// Returns nil for methods not handled by this service.\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"CreateBuild\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? [],\n userFunction: self.createBuild(request:context:)\n )\n\n case \"PerformBuild\":\n return BidirectionalStreamingServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n observerFactory: self.performBuild(context:)\n )\n\n case \"Info\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeInfoInterceptors() ?? [],\n userFunction: self.info(request:context:)\n )\n\n default:\n return nil\n }\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// To implement a server, implement an object which conforms to this protocol.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Container_Build_V1_BuilderAsyncProvider: CallHandlerProvider, Sendable {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? { get }\n\n /// Create a build request.\n func createBuild(\n request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Container_Build_V1_CreateBuildResponse\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n func performBuild(\n requestStream: GRPCAsyncRequestStream,\n responseStream: GRPCAsyncResponseStreamWriter,\n context: GRPCAsyncServerCallContext\n ) async throws\n\n func info(\n request: Com_Apple_Container_Build_V1_InfoRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Container_Build_V1_InfoResponse\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncProvider {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor\n }\n\n public var serviceName: Substring {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor.fullName[...]\n }\n\n public var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? {\n return nil\n }\n\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"CreateBuild\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? [],\n wrapping: { try await self.createBuild(request: $0, context: $1) }\n )\n\n case \"PerformBuild\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n wrapping: { try await self.performBuild(requestStream: $0, responseStream: $1, context: $2) }\n )\n\n case \"Info\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeInfoInterceptors() ?? [],\n wrapping: { try await self.info(request: $0, context: $1) }\n )\n\n default:\n return nil\n }\n }\n}\n\npublic protocol Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when handling 'createBuild'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCreateBuildInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'performBuild'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makePerformBuildInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'info'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeInfoInterceptors() -> [ServerInterceptor]\n}\n\npublic enum Com_Apple_Container_Build_V1_BuilderServerMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"Builder\",\n fullName: \"com.apple.container.build.v1.Builder\",\n methods: [\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.createBuild,\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.performBuild,\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.info,\n ]\n )\n\n public enum Methods {\n public static let createBuild = GRPCMethodDescriptor(\n name: \"CreateBuild\",\n path: \"/com.apple.container.build.v1.Builder/CreateBuild\",\n type: GRPCCallType.unary\n )\n\n public static let performBuild = GRPCMethodDescriptor(\n name: \"PerformBuild\",\n path: \"/com.apple.container.build.v1.Builder/PerformBuild\",\n type: GRPCCallType.bidirectionalStreaming\n )\n\n public static let info = GRPCMethodDescriptor(\n name: \"Info\",\n path: \"/com.apple.container.build.v1.Builder/Info\",\n type: GRPCCallType.unary\n )\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePrune.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\n\nextension Application {\n struct ImagePrune: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"prune\",\n abstract: \"Remove unreferenced and dangling images\")\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let (_, size) = try await ClientImage.pruneImages()\n let formatter = ByteCountFormatter()\n let freed = formatter.string(fromByteCount: Int64(size))\n print(\"Cleaned unreferenced images and snapshots\")\n print(\"Reclaimed \\(freed) in disk space\")\n }\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/HostTableResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\n\n/// Handler that uses table lookup to resolve hostnames.\npublic struct HostTableResolver: DNSHandler {\n public let hosts4: [String: IPv4]\n private let ttl: UInt32\n\n public init(hosts4: [String: IPv4], ttl: UInt32 = 300) {\n self.hosts4 = hosts4\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n let record: ResourceRecord?\n switch question.type {\n case ResourceRecordType.host:\n record = answerHost(question: question)\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n\n guard let record else {\n return nil\n }\n\n return Message(\n id: query.id,\n type: .response,\n returnCode: .noError,\n questions: query.questions,\n answers: [record]\n )\n }\n\n private func answerHost(question: Question) -> ResourceRecord? {\n guard let ip = hosts4[question.name] else {\n return nil\n }\n\n return HostRecord(name: question.name, ttl: ttl, ip: ip)\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ImageDetail.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationOCI\n\npublic struct ImageDetail: Codable {\n public let name: String\n public let index: Descriptor\n public let variants: [Variants]\n\n public struct Variants: Codable {\n public let platform: Platform\n public let config: ContainerizationOCI.Image\n public let size: Int64\n\n init(platform: Platform, size: Int64, config: ContainerizationOCI.Image) {\n self.platform = platform\n self.config = config\n self.size = size\n }\n }\n\n init(name: String, index: Descriptor, variants: [Variants]) {\n self.name = name\n self.index = index\n self.variants = variants\n }\n}\n\nextension ClientImage {\n public func details() async throws -> ImageDetail {\n let indexDescriptor = self.descriptor\n let reference = self.reference\n var variants: [ImageDetail.Variants] = []\n for desc in try await self.index().manifests {\n guard let platform = desc.platform else {\n continue\n }\n let config: ContainerizationOCI.Image\n let manifest: ContainerizationOCI.Manifest\n do {\n config = try await self.config(for: platform)\n manifest = try await self.manifest(for: platform)\n } catch {\n continue\n }\n let size = desc.size + manifest.config.size + manifest.layers.reduce(0, { (l, r) in l + r.size })\n variants.append(.init(platform: platform, size: size, config: config))\n }\n return ImageDetail(name: reference, index: indexDescriptor, variants: variants)\n }\n}\n"], ["/container/Sources/CLI/Container/ProcessUtils.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n static func ensureRunning(container: ClientContainer) throws {\n if container.status != .running {\n throw ContainerizationError(.invalidState, message: \"container \\(container.id) is not running\")\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientDefaults.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CVersion\nimport ContainerizationError\nimport Foundation\n\npublic enum ClientDefaults {\n private static let userDefaultDomain = \"com.apple.container.defaults\"\n\n public enum Keys: String {\n case defaultBuilderImage = \"image.builder\"\n case defaultDNSDomain = \"dns.domain\"\n case defaultRegistryDomain = \"registry.domain\"\n case defaultInitImage = \"image.init\"\n case defaultKernelURL = \"kernel.url\"\n case defaultKernelBinaryPath = \"kernel.binaryPath\"\n case buildRosetta = \"build.rosetta\"\n }\n\n public static func set(value: String, key: ClientDefaults.Keys) {\n udSuite.set(value, forKey: key.rawValue)\n }\n\n public static func unset(key: ClientDefaults.Keys) {\n udSuite.removeObject(forKey: key.rawValue)\n }\n\n public static func get(key: ClientDefaults.Keys) -> String {\n let current = udSuite.string(forKey: key.rawValue)\n return current ?? key.defaultValue\n }\n\n public static func getOptional(key: ClientDefaults.Keys) -> String? {\n udSuite.string(forKey: key.rawValue)\n }\n\n public static func setBool(value: Bool, key: ClientDefaults.Keys) {\n udSuite.set(value, forKey: key.rawValue)\n }\n\n public static func getBool(key: ClientDefaults.Keys) -> Bool? {\n guard udSuite.object(forKey: key.rawValue) != nil else { return nil }\n return udSuite.bool(forKey: key.rawValue)\n }\n\n private static var udSuite: UserDefaults {\n guard let ud = UserDefaults.init(suiteName: self.userDefaultDomain) else {\n fatalError(\"Failed to initialize UserDefaults for domain \\(self.userDefaultDomain)\")\n }\n return ud\n }\n}\n\nextension ClientDefaults.Keys {\n fileprivate var defaultValue: String {\n switch self {\n case .defaultKernelURL:\n return \"https://github.com/kata-containers/kata-containers/releases/download/3.17.0/kata-static-3.17.0-arm64.tar.xz\"\n case .defaultKernelBinaryPath:\n return \"opt/kata/share/kata-containers/vmlinux-6.12.28-153\"\n case .defaultBuilderImage:\n let tag = String(cString: get_container_builder_shim_version())\n return \"ghcr.io/apple/container-builder-shim/builder:\\(tag)\"\n case .defaultDNSDomain:\n return \"test\"\n case .defaultRegistryDomain:\n return \"docker.io\"\n case .defaultInitImage:\n let tag = String(cString: get_swift_containerization_version())\n guard tag != \"latest\" else {\n return \"vminit:latest\"\n }\n return \"ghcr.io/apple/containerization/vminit:\\(tag)\"\n case .buildRosetta:\n // This is a boolean key, not used with the string get() method\n return \"true\"\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A configuration for displaying a progress bar.\npublic struct ProgressConfig: Sendable {\n /// The file handle for progress updates.\n let terminal: FileHandle\n /// The initial description of the progress bar.\n let initialDescription: String\n /// The initial additional description of the progress bar.\n let initialSubDescription: String\n /// The initial items name (e.g., \"files\").\n let initialItemsName: String\n /// A flag indicating whether to show a spinner (e.g., \"⠋\").\n /// The spinner is hidden when a progress bar is shown.\n public let showSpinner: Bool\n /// A flag indicating whether to show tasks and total tasks (e.g., \"[1]\" or \"[1/3]\").\n public let showTasks: Bool\n /// A flag indicating whether to show the description (e.g., \"Downloading...\").\n public let showDescription: Bool\n /// A flag indicating whether to show a percentage (e.g., \"100%\").\n /// The percentage is hidden when no total size and total items are set.\n public let showPercent: Bool\n /// A flag indicating whether to show a progress bar (e.g., \"|███ |\").\n /// The progress bar is hidden when no total size and total items are set.\n public let showProgressBar: Bool\n /// A flag indicating whether to show items and total items (e.g., \"(22 it)\" or \"(22/22 it)\").\n public let showItems: Bool\n /// A flag indicating whether to show a size and a total size (e.g., \"(22 MB)\" or \"(22/22 MB)\").\n public let showSize: Bool\n /// A flag indicating whether to show a speed (e.g., \"(4.834 MB/s)\").\n /// The speed is combined with the size and total size (e.g., \"(22/22 MB, 4.834 MB/s)\").\n /// The speed is hidden when no total size is set.\n public let showSpeed: Bool\n /// A flag indicating whether to show the elapsed time (e.g., \"[4s]\").\n public let showTime: Bool\n /// The flag indicating whether to ignore small size values (less than 1 MB). For example, this may help to avoid reaching 100% after downloading metadata before downloading content.\n public let ignoreSmallSize: Bool\n /// The initial total tasks of the progress bar.\n let initialTotalTasks: Int?\n /// The initial total size of the progress bar.\n let initialTotalSize: Int64?\n /// The initial total items of the progress bar.\n let initialTotalItems: Int?\n /// The width of the progress bar in characters.\n public let width: Int\n /// The theme of the progress bar.\n public let theme: ProgressTheme\n /// The flag indicating whether to clear the progress bar before resetting the cursor.\n public let clearOnFinish: Bool\n /// The flag indicating whether to update the progress bar.\n public let disableProgressUpdates: Bool\n /// Creates a new instance of `ProgressConfig`.\n /// - Parameters:\n /// - terminal: The file handle for progress updates. The default value is `FileHandle.standardError`.\n /// - description: The initial description of the progress bar. The default value is `\"\"`.\n /// - subDescription: The initial additional description of the progress bar. The default value is `\"\"`.\n /// - itemsName: The initial items name. The default value is `\"it\"`.\n /// - showSpinner: A flag indicating whether to show a spinner. The default value is `true`.\n /// - showTasks: A flag indicating whether to show tasks and total tasks. The default value is `false`.\n /// - showDescription: A flag indicating whether to show the description. The default value is `true`.\n /// - showPercent: A flag indicating whether to show a percentage. The default value is `true`.\n /// - showProgressBar: A flag indicating whether to show a progress bar. The default value is `false`.\n /// - showItems: A flag indicating whether to show items and a total items. The default value is `false`.\n /// - showSize: A flag indicating whether to show a size and a total size. The default value is `true`.\n /// - showSpeed: A flag indicating whether to show a speed. The default value is `true`.\n /// - showTime: A flag indicating whether to show the elapsed time. The default value is `true`.\n /// - ignoreSmallSize: A flag indicating whether to ignore small size values. The default value is `false`.\n /// - totalTasks: The initial total tasks of the progress bar. The default value is `nil`.\n /// - totalItems: The initial total items of the progress bar. The default value is `nil`.\n /// - totalSize: The initial total size of the progress bar. The default value is `nil`.\n /// - width: The width of the progress bar in characters. The default value is `120`.\n /// - theme: The theme of the progress bar. The default value is `nil`.\n /// - clearOnFinish: The flag indicating whether to clear the progress bar before resetting the cursor. The default is `true`.\n /// - disableProgressUpdates: The flag indicating whether to update the progress bar. The default is `false`.\n public init(\n terminal: FileHandle = .standardError,\n description: String = \"\",\n subDescription: String = \"\",\n itemsName: String = \"it\",\n showSpinner: Bool = true,\n showTasks: Bool = false,\n showDescription: Bool = true,\n showPercent: Bool = true,\n showProgressBar: Bool = false,\n showItems: Bool = false,\n showSize: Bool = true,\n showSpeed: Bool = true,\n showTime: Bool = true,\n ignoreSmallSize: Bool = false,\n totalTasks: Int? = nil,\n totalItems: Int? = nil,\n totalSize: Int64? = nil,\n width: Int = 120,\n theme: ProgressTheme? = nil,\n clearOnFinish: Bool = true,\n disableProgressUpdates: Bool = false\n ) throws {\n if let totalTasks {\n guard totalTasks > 0 else {\n throw Error.invalid(\"totalTasks must be greater than zero\")\n }\n }\n if let totalItems {\n guard totalItems > 0 else {\n throw Error.invalid(\"totalItems must be greater than zero\")\n }\n }\n if let totalSize {\n guard totalSize > 0 else {\n throw Error.invalid(\"totalSize must be greater than zero\")\n }\n }\n\n self.terminal = terminal\n self.initialDescription = description\n self.initialSubDescription = subDescription\n self.initialItemsName = itemsName\n\n self.showSpinner = showSpinner\n self.showTasks = showTasks\n self.showDescription = showDescription\n self.showPercent = showPercent\n self.showProgressBar = showProgressBar\n self.showItems = showItems\n self.showSize = showSize\n self.showSpeed = showSpeed\n self.showTime = showTime\n\n self.ignoreSmallSize = ignoreSmallSize\n self.initialTotalTasks = totalTasks\n self.initialTotalItems = totalItems\n self.initialTotalSize = totalSize\n\n self.width = width\n self.theme = theme ?? DefaultProgressTheme()\n self.clearOnFinish = clearOnFinish\n self.disableProgressUpdates = disableProgressUpdates\n }\n}\n\nextension ProgressConfig {\n /// An enumeration of errors that can occur when creating a `ProgressConfig`.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalid(String)\n\n /// The description of the error.\n public var description: String {\n switch self {\n case .invalid(let reason):\n return \"Failed to validate config (\\(reason))\"\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Registry/Logout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\n\nextension Application {\n struct Logout: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: \"Log out from a registry\")\n\n @Argument(help: \"Registry server name\")\n var registry: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let keychain = KeychainHelper(id: Constants.keychainID)\n let r = Reference.resolveDomain(domain: registry)\n try keychain.delete(domain: r)\n }\n }\n}\n"], ["/container/Sources/ContainerLog/OSLogHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\nimport Logging\nimport os\n\nimport struct Logging.Logger\n\npublic struct OSLogHandler: LogHandler {\n private let logger: os.Logger\n\n public var logLevel: Logger.Level = .info\n private var formattedMetadata: String?\n\n public var metadata = Logger.Metadata() {\n didSet {\n self.formattedMetadata = self.formatMetadata(self.metadata)\n }\n }\n\n public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {\n get {\n self.metadata[metadataKey]\n }\n set {\n self.metadata[metadataKey] = newValue\n }\n }\n\n public init(label: String, category: String) {\n self.logger = os.Logger(subsystem: label, category: category)\n }\n}\n\nextension OSLogHandler {\n public func log(\n level: Logger.Level,\n message: Logger.Message,\n metadata: Logger.Metadata?,\n source: String,\n file: String,\n function: String,\n line: UInt\n ) {\n var formattedMetadata = self.formattedMetadata\n if let metadataOverride = metadata, !metadataOverride.isEmpty {\n formattedMetadata = self.formatMetadata(\n self.metadata.merging(metadataOverride) {\n $1\n }\n )\n }\n\n var finalMessage = message.description\n if let formattedMetadata {\n finalMessage += \" \" + formattedMetadata\n }\n\n self.logger.log(\n level: level.toOSLogLevel(),\n \"\\(finalMessage, privacy: .public)\"\n )\n }\n\n private func formatMetadata(_ metadata: Logger.Metadata) -> String? {\n if metadata.isEmpty {\n return nil\n }\n return metadata.map {\n \"[\\($0)=\\($1)]\"\n }.joined(separator: \" \")\n }\n}\n\nextension Logger.Level {\n func toOSLogLevel() -> OSLogType {\n switch self {\n case .debug, .trace:\n return .debug\n case .info:\n return .info\n case .notice:\n return .default\n case .error, .warning:\n return .error\n case .critical:\n return .fault\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+Terminal.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nenum EscapeSequence {\n static let hideCursor = \"\\u{001B}[?25l\"\n static let showCursor = \"\\u{001B}[?25h\"\n static let moveUp = \"\\u{001B}[1A\"\n}\n\nextension ProgressBar {\n private var terminalWidth: Int {\n guard\n let terminalHandle = term,\n let terminal = try? Terminal(descriptor: terminalHandle.fileDescriptor)\n else {\n return 0\n }\n\n let terminalWidth = (try? Int(terminal.size.width)) ?? 0\n return terminalWidth\n }\n\n /// Clears the progress bar and resets the cursor.\n public func clearAndResetCursor() {\n clear()\n resetCursor()\n }\n\n /// Clears the progress bar.\n public func clear() {\n displayText(\"\")\n }\n\n /// Resets the cursor.\n public func resetCursor() {\n display(EscapeSequence.showCursor)\n }\n\n func display(_ text: String) {\n guard let term else {\n return\n }\n termQueue.sync {\n try? term.write(contentsOf: Data(text.utf8))\n try? term.synchronize()\n }\n }\n\n func displayText(_ text: String, terminating: String = \"\\r\") {\n var text = text\n\n // Clears previously printed characters if the new string is shorter.\n text += String(repeating: \" \", count: max(printedWidth - text.count, 0))\n printedWidth = text.count\n state.withLock {\n $0.output = text\n }\n\n // Clears previously printed lines.\n var lines = \"\"\n if terminating.hasSuffix(\"\\r\") && terminalWidth > 0 {\n let lineCount = (text.count - 1) / terminalWidth\n for _ in 0.. String {\n var output = \"\"\n let maxLengths = self.maxLength()\n\n for rowIndex in 0.. [Int: Int] {\n var output: [Int: Int] = [:]\n for row in self.rows {\n for (i, column) in row.enumerated() {\n let currentMax = output[i] ?? 0\n output[i] = (column.count > currentMax) ? column.count : currentMax\n }\n }\n return output\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+Add.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension ProgressBar {\n /// A handler function to update the progress bar.\n /// - Parameter events: The events to handle.\n public func handler(_ events: [ProgressUpdateEvent]) {\n for event in events {\n switch event {\n case .setDescription(let description):\n set(description: description)\n case .setSubDescription(let subDescription):\n set(subDescription: subDescription)\n case .setItemsName(let itemsName):\n set(itemsName: itemsName)\n case .addTasks(let tasks):\n add(tasks: tasks)\n case .setTasks(let tasks):\n set(tasks: tasks)\n case .addTotalTasks(let totalTasks):\n add(totalTasks: totalTasks)\n case .setTotalTasks(let totalTasks):\n set(totalTasks: totalTasks)\n case .addSize(let size):\n add(size: size)\n case .setSize(let size):\n set(size: size)\n case .addTotalSize(let totalSize):\n add(totalSize: totalSize)\n case .setTotalSize(let totalSize):\n set(totalSize: totalSize)\n case .addItems(let items):\n add(items: items)\n case .setItems(let items):\n set(items: items)\n case .addTotalItems(let totalItems):\n add(totalItems: totalItems)\n case .setTotalItems(let totalItems):\n set(totalItems: totalItems)\n case .custom:\n // Custom events are handled by the client.\n break\n }\n }\n }\n\n /// Performs a check to see if the progress bar should be finished.\n public func checkIfFinished() {\n let state = self.state.withLock { $0 }\n\n var finished = true\n var defined = false\n if let totalTasks = state.totalTasks, totalTasks > 0 {\n // For tasks, we're showing the current task rather than the number of completed tasks.\n finished = finished && state.tasks == totalTasks\n defined = true\n }\n if let totalItems = state.totalItems, totalItems > 0 {\n finished = finished && state.items == totalItems\n defined = true\n }\n if let totalSize = state.totalSize, totalSize > 0 {\n finished = finished && state.size == totalSize\n defined = true\n }\n if defined && finished {\n finish()\n }\n }\n\n /// Sets the current tasks.\n /// - Parameter newTasks: The current tasks to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(tasks newTasks: Int, render: Bool = true) {\n state.withLock { $0.tasks = newTasks }\n if render {\n self.render()\n }\n checkIfFinished()\n }\n\n /// Performs an addition to the current tasks.\n /// - Parameter delta: The tasks to add to the current tasks.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(tasks delta: Int, render: Bool = true) {\n state.withLock {\n let newTasks = $0.tasks + delta\n $0.tasks = newTasks\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total tasks.\n /// - Parameter newTotalTasks: The total tasks to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalTasks newTotalTasks: Int, render: Bool = true) {\n state.withLock { $0.totalTasks = newTotalTasks }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total tasks.\n /// - Parameter delta: The tasks to add to the total tasks.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalTasks delta: Int, render: Bool = true) {\n state.withLock {\n let totalTasks = $0.totalTasks ?? 0\n let newTotalTasks = totalTasks + delta\n $0.totalTasks = newTotalTasks\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the items name.\n /// - Parameter newItemsName: The current items to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(itemsName newItemsName: String, render: Bool = true) {\n state.withLock { $0.itemsName = newItemsName }\n if render {\n self.render()\n }\n }\n\n /// Sets the current items.\n /// - Parameter newItems: The current items to set.\n public func set(items newItems: Int, render: Bool = true) {\n state.withLock { $0.items = newItems }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the current items.\n /// - Parameter delta: The items to add to the current items.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(items delta: Int, render: Bool = true) {\n state.withLock {\n let newItems = $0.items + delta\n $0.items = newItems\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total items.\n /// - Parameter newTotalItems: The total items to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalItems newTotalItems: Int, render: Bool = true) {\n state.withLock { $0.totalItems = newTotalItems }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total items.\n /// - Parameter delta: The items to add to the total items.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalItems delta: Int, render: Bool = true) {\n state.withLock {\n let totalItems = $0.totalItems ?? 0\n let newTotalItems = totalItems + delta\n $0.totalItems = newTotalItems\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the current size.\n /// - Parameter newSize: The current size to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(size newSize: Int64, render: Bool = true) {\n state.withLock { $0.size = newSize }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the current size.\n /// - Parameter delta: The size to add to the current size.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(size delta: Int64, render: Bool = true) {\n state.withLock {\n let newSize = $0.size + delta\n $0.size = newSize\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total size.\n /// - Parameter newTotalSize: The total size to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalSize newTotalSize: Int64, render: Bool = true) {\n state.withLock { $0.totalSize = newTotalSize }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total size.\n /// - Parameter delta: The size to add to the total size.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalSize delta: Int64, render: Bool = true) {\n state.withLock {\n let totalSize = $0.totalSize ?? 0\n let newTotalSize = totalSize + delta\n $0.totalSize = newTotalSize\n }\n if render {\n self.render()\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/Filesystem.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Options to pass to a mount call.\npublic typealias MountOptions = [String]\n\nextension MountOptions {\n /// Returns true if the Filesystem should be consumed as read-only.\n public var readonly: Bool {\n self.contains(\"ro\")\n }\n}\n\n/// A host filesystem that will be attached to the sandbox for use.\n///\n/// A filesystem will be mounted automatically when starting the sandbox\n/// or container.\npublic struct Filesystem: Sendable, Codable {\n /// Type of caching to perform at the host level.\n public enum CacheMode: Sendable, Codable {\n case on\n case off\n case auto\n }\n\n /// Sync mode to perform at the host level.\n public enum SyncMode: Sendable, Codable {\n case full\n case fsync\n case nosync\n }\n\n /// The type of filesystem attachment for the sandbox.\n public enum FSType: Sendable, Codable, Equatable {\n package enum VirtiofsType: String, Sendable, Codable, Equatable {\n // This is a virtiofs share for the rootfs of a sandbox.\n case rootfs\n // Data share. This is what all virtiofs shares for anything besides\n // the rootfs for a sandbox will be.\n case data\n }\n\n case block(format: String, cache: CacheMode, sync: SyncMode)\n case virtiofs\n case tmpfs\n }\n\n /// Type of the filesystem.\n public var type: FSType\n /// Source of the filesystem.\n public var source: String\n /// Destination where the filesystem should be mounted.\n public var destination: String\n /// Mount options applied when mounting the filesystem.\n public var options: MountOptions\n\n public init() {\n self.type = .tmpfs\n self.source = \"\"\n self.destination = \"\"\n self.options = []\n }\n\n public init(type: FSType, source: String, destination: String, options: MountOptions) {\n self.type = type\n self.source = source\n self.destination = destination\n self.options = options\n }\n\n /// A block based filesystem.\n public static func block(\n format: String, source: String, destination: String, options: MountOptions, cache: CacheMode = .auto,\n sync: SyncMode = .full\n ) -> Filesystem {\n .init(\n type: .block(format: format, cache: cache, sync: sync),\n source: URL(fileURLWithPath: source).absolutePath(),\n destination: destination,\n options: options\n )\n }\n\n /// A vritiofs backed filesystem providing a directory.\n public static func virtiofs(source: String, destination: String, options: MountOptions) -> Filesystem {\n .init(\n type: .virtiofs,\n source: URL(fileURLWithPath: source).absolutePath(),\n destination: destination,\n options: options\n )\n }\n\n public static func tmpfs(destination: String, options: MountOptions) -> Filesystem {\n .init(\n type: .tmpfs,\n source: \"tmpfs\",\n destination: destination,\n options: options\n )\n }\n\n /// Returns true if the Filesystem is backed by a block device.\n public var isBlock: Bool {\n switch type {\n case .block(_, _, _): true\n default: false\n }\n }\n\n /// Returns true if the Filesystem is backed by a in-memory mount type.\n public var isTmpfs: Bool {\n switch type {\n case .tmpfs: true\n default: false\n }\n }\n\n /// Returns true if the Filesystem is backed by virtioFS.\n public var isVirtiofs: Bool {\n switch type {\n case .virtiofs: true\n default: false\n }\n }\n\n /// Clone the Filesystem to the provided path.\n ///\n /// This uses `clonefile` to provide a copy-on-write copy of the Filesystem.\n public func clone(to: String) throws -> Self {\n let fm = FileManager.default\n let src = self.source\n try fm.copyItem(atPath: src, toPath: to)\n return .init(type: self.type, source: to, destination: self.destination, options: self.options)\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginFactory.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\nprivate let configFilename: String = \"config.json\"\n\n/// Describes the configuration and binary file locations for a plugin.\npublic protocol PluginFactory: Sendable {\n /// Create a plugin conforming to the layout, if possible.\n func create(installURL: URL) throws -> Plugin?\n}\n\n/// Default layout which uses a Unix-like structure.\npublic struct DefaultPluginFactory: PluginFactory {\n public init() {}\n\n public func create(installURL: URL) throws -> Plugin? {\n let fm = FileManager.default\n\n let configURL = installURL.appending(path: configFilename)\n guard fm.fileExists(atPath: configURL.path) else {\n return nil\n }\n\n guard let config = try PluginConfig(configURL: configURL) else {\n return nil\n }\n\n let name = installURL.lastPathComponent\n let binaryURL = installURL.appending(path: \"bin\").appending(path: name)\n guard fm.fileExists(atPath: binaryURL.path) else {\n return nil\n }\n\n return Plugin(binaryURL: binaryURL, config: config)\n }\n}\n\n/// Layout which uses a macOS application bundle structure.\npublic struct AppBundlePluginFactory: PluginFactory {\n private static let appSuffix = \".app\"\n\n public init() {}\n\n public func create(installURL: URL) throws -> Plugin? {\n let fm = FileManager.default\n\n let configURL =\n installURL\n .appending(path: \"Contents\")\n .appending(path: \"Resources\")\n .appending(path: configFilename)\n guard fm.fileExists(atPath: configURL.path) else {\n return nil\n }\n\n guard let config = try PluginConfig(configURL: configURL) else {\n return nil\n }\n\n let appName = installURL.lastPathComponent\n guard appName.hasSuffix(Self.appSuffix) else {\n return nil\n }\n let name = String(appName.dropLast(Self.appSuffix.count))\n let binaryURL =\n installURL\n .appending(path: \"Contents\")\n .appending(path: \"MacOS\")\n .appending(path: name)\n guard fm.fileExists(atPath: binaryURL.path) else {\n return nil\n }\n\n return Plugin(binaryURL: binaryURL, config: config)\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/NxDomainResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\n\n/// Handler that returns NXDOMAIN for all hostnames.\npublic struct NxDomainResolver: DNSHandler {\n private let ttl: UInt32\n\n public init(ttl: UInt32 = 300) {\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n switch question.type {\n case ResourceRecordType.host:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .nonExistentDomain,\n questions: query.questions,\n answers: []\n )\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/IsolatedInterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\n\n/// Isolated container network interface strategy. This strategy prohibits\n/// container to container networking, but it is the only approach that\n/// works for macOS Sequoia.\nstruct IsolatedInterfaceStrategy: InterfaceStrategy {\n public func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) -> Interface {\n let gateway = interfaceIndex == 0 ? attachment.gateway : nil\n return NATInterface(address: attachment.address, gateway: gateway)\n }\n}\n"], ["/container/Sources/SocketForwarder/LRUCache.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nstruct KeyExistsError: Error {}\n\nclass LRUCache {\n private class Node {\n fileprivate var prev: Node?\n fileprivate var next: Node?\n fileprivate let key: K\n fileprivate let value: V\n\n init(key: K, value: V) {\n self.prev = nil\n self.next = nil\n self.key = key\n self.value = value\n }\n }\n\n private let size: UInt\n private var head: Node?\n private var tail: Node?\n private var members: [K: Node]\n\n init(size: UInt) {\n self.size = size\n self.head = nil\n self.tail = nil\n self.members = [:]\n }\n\n var count: Int { members.count }\n\n func get(_ key: K) -> V? {\n guard let node = members[key] else {\n return nil\n }\n listRemove(node: node)\n listInsert(node: node, after: tail)\n return node.value\n }\n\n func put(key: K, value: V) -> (K, V)? {\n let node = Node(key: key, value: value)\n var evicted: (K, V)? = nil\n\n if let existingNode = members[key] {\n // evict the replaced node\n listRemove(node: existingNode)\n evicted = (existingNode.key, existingNode.value)\n } else if self.count >= self.size {\n // evict the least recently used node\n evicted = evict()\n }\n\n // insert the new node and return any evicted node\n members[key] = node\n listInsert(node: node, after: tail)\n return evicted\n }\n\n private func evict() -> (K, V)? {\n guard let head else {\n return nil\n }\n let ret = (head.key, head.value)\n listRemove(node: head)\n members.removeValue(forKey: head.key)\n return ret\n }\n\n private func listRemove(node: Node) {\n if let prev = node.prev {\n prev.next = node.next\n } else {\n head = node.next\n }\n if let next = node.next {\n next.prev = node.prev\n } else {\n tail = node.prev\n }\n }\n\n private func listInsert(node: Node, after: Node?) {\n let before: Node?\n if let after {\n before = after.next\n after.next = node\n } else {\n before = head\n head = node\n }\n\n if let before {\n before.prev = node\n } else {\n tail = node\n }\n\n node.prev = after\n node.next = before\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+State.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension ProgressBar {\n /// A configuration struct for the progress bar.\n public struct State {\n /// A flag indicating whether the progress bar is finished.\n public var finished = false\n var iteration = 0\n private let speedInterval: DispatchTimeInterval = .seconds(1)\n\n var description: String\n var subDescription: String\n var itemsName: String\n\n var tasks: Int\n var totalTasks: Int?\n\n var items: Int\n var totalItems: Int?\n\n private var sizeUpdateTime: DispatchTime?\n private var sizeUpdateValue: Int64 = 0\n var size: Int64 {\n didSet {\n calculateSizeSpeed()\n }\n }\n var totalSize: Int64?\n private var sizeUpdateSpeed: String?\n var sizeSpeed: String? {\n guard sizeUpdateTime == nil || sizeUpdateTime! > .now() - speedInterval - speedInterval else {\n return Int64(0).formattedSizeSpeed(from: startTime)\n }\n return sizeUpdateSpeed\n }\n var averageSizeSpeed: String {\n size.formattedSizeSpeed(from: startTime)\n }\n\n var percent: String {\n var value = 0\n if let totalSize, totalSize > 0 {\n value = Int(size * 100 / totalSize)\n } else if let totalItems, totalItems > 0 {\n value = Int(items * 100 / totalItems)\n }\n value = min(value, 100)\n return \"\\(value)%\"\n }\n\n var startTime: DispatchTime\n var output = \"\"\n\n init(\n description: String = \"\", subDescription: String = \"\", itemsName: String = \"\", tasks: Int = 0, totalTasks: Int? = nil, items: Int = 0, totalItems: Int? = nil,\n size: Int64 = 0, totalSize: Int64? = nil, startTime: DispatchTime = .now()\n ) {\n self.description = description\n self.subDescription = subDescription\n self.itemsName = itemsName\n self.tasks = tasks\n self.totalTasks = totalTasks\n self.items = items\n self.totalItems = totalItems\n self.size = size\n self.totalSize = totalSize\n self.startTime = startTime\n }\n\n private mutating func calculateSizeSpeed() {\n if sizeUpdateTime == nil || sizeUpdateTime! < .now() - speedInterval {\n let partSize = size - sizeUpdateValue\n let partStartTime = sizeUpdateTime ?? startTime\n let partSizeSpeed = partSize.formattedSizeSpeed(from: partStartTime)\n self.sizeUpdateSpeed = partSizeSpeed\n\n sizeUpdateTime = .now()\n sizeUpdateValue = size\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/XPC+.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\n/// Keys for XPC fields.\npublic enum XPCKeys: String {\n /// Route key.\n case route\n /// Container array key.\n case containers\n /// ID key.\n case id\n // ID for a process.\n case processIdentifier\n /// Container configuration key.\n case containerConfig\n /// Container options key.\n case containerOptions\n /// Vsock port number key.\n case port\n /// Exit code for a process\n case exitCode\n /// An event that occurred in a container\n case containerEvent\n /// Error key.\n case error\n /// FD to a container resource key.\n case fd\n /// FDs pointing to container logs key.\n case logs\n /// Options for stopping a container key.\n case stopOptions\n /// Plugins\n case pluginName\n case plugins\n case plugin\n\n /// Health check request.\n case ping\n\n /// Process request keys.\n case signal\n case snapshot\n case stdin\n case stdout\n case stderr\n case status\n case width\n case height\n case processConfig\n\n /// Update progress\n case progressUpdateEndpoint\n case progressUpdateSetDescription\n case progressUpdateSetSubDescription\n case progressUpdateSetItemsName\n case progressUpdateAddTasks\n case progressUpdateSetTasks\n case progressUpdateAddTotalTasks\n case progressUpdateSetTotalTasks\n case progressUpdateAddItems\n case progressUpdateSetItems\n case progressUpdateAddTotalItems\n case progressUpdateSetTotalItems\n case progressUpdateAddSize\n case progressUpdateSetSize\n case progressUpdateAddTotalSize\n case progressUpdateSetTotalSize\n\n /// Network\n case networkId\n case networkConfig\n case networkState\n case networkStates\n\n /// Kernel\n case kernel\n case kernelTarURL\n case kernelFilePath\n case systemPlatform\n}\n\npublic enum XPCRoute: String {\n case listContainer\n case createContainer\n case deleteContainer\n case containerLogs\n case containerEvent\n\n case pluginLoad\n case pluginGet\n case pluginRestart\n case pluginUnload\n case pluginList\n\n case networkCreate\n case networkDelete\n case networkList\n\n case ping\n\n case installKernel\n case getDefaultKernel\n}\n\nextension XPCMessage {\n public init(route: XPCRoute) {\n self.init(route: route.rawValue)\n }\n\n public func data(key: XPCKeys) -> Data? {\n data(key: key.rawValue)\n }\n\n public func dataNoCopy(key: XPCKeys) -> Data? {\n dataNoCopy(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Data) {\n set(key: key.rawValue, value: value)\n }\n\n public func string(key: XPCKeys) -> String? {\n string(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: String) {\n set(key: key.rawValue, value: value)\n }\n\n public func bool(key: XPCKeys) -> Bool {\n bool(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Bool) {\n set(key: key.rawValue, value: value)\n }\n\n public func uint64(key: XPCKeys) -> UInt64 {\n uint64(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: UInt64) {\n set(key: key.rawValue, value: value)\n }\n\n public func int64(key: XPCKeys) -> Int64 {\n int64(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Int64) {\n set(key: key.rawValue, value: value)\n }\n\n public func int(key: XPCKeys) -> Int {\n Int(int64(key: key.rawValue))\n }\n\n public func set(key: XPCKeys, value: Int) {\n set(key: key.rawValue, value: Int64(value))\n }\n\n public func fileHandle(key: XPCKeys) -> FileHandle? {\n fileHandle(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: FileHandle) {\n set(key: key.rawValue, value: value)\n }\n\n public func fileHandles(key: XPCKeys) -> [FileHandle]? {\n fileHandles(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: [FileHandle]) throws {\n try set(key: key.rawValue, value: value)\n }\n\n public func endpoint(key: XPCKeys) -> xpc_endpoint_t? {\n endpoint(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: xpc_endpoint_t) {\n set(key: key.rawValue, value: value)\n }\n}\n\n#endif\n"], ["/container/Sources/CLI/System/SystemDNS.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct SystemDNS: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"dns\",\n abstract: \"Manage local DNS domains\",\n subcommands: [\n DNSCreate.self,\n DNSDelete.self,\n DNSList.self,\n DNSDefault.self,\n ]\n )\n }\n}\n"], ["/container/Sources/ContainerClient/ProgressUpdateService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\n/// A service that sends progress updates to the client.\npublic actor ProgressUpdateService {\n private let endpointConnection: xpc_connection_t\n\n /// Creates a new instance for sending progress updates to the client.\n /// - Parameter message: The XPC message that contains the endpoint to connect to.\n public init?(message: XPCMessage) {\n guard let progressUpdateEndpoint = message.endpoint(key: .progressUpdateEndpoint) else {\n return nil\n }\n endpointConnection = xpc_connection_create_from_endpoint(progressUpdateEndpoint)\n xpc_connection_set_event_handler(endpointConnection) { _ in }\n // This connection will be closed by the client.\n xpc_connection_activate(endpointConnection)\n }\n\n /// Performs a progress update.\n /// - Parameter events: The events that represent the update.\n public func handler(_ events: [ProgressUpdateEvent]) async {\n let object = xpc_dictionary_create(nil, nil, 0)\n let replyMessage = XPCMessage(object: object)\n for event in events {\n switch event {\n case .setDescription(let description):\n replyMessage.set(key: .progressUpdateSetDescription, value: description)\n case .setSubDescription(let subDescription):\n replyMessage.set(key: .progressUpdateSetSubDescription, value: subDescription)\n case .setItemsName(let itemsName):\n replyMessage.set(key: .progressUpdateSetItemsName, value: itemsName)\n case .addTasks(let tasks):\n replyMessage.set(key: .progressUpdateAddTasks, value: tasks)\n case .setTasks(let tasks):\n replyMessage.set(key: .progressUpdateSetTasks, value: tasks)\n case .addTotalTasks(let totalTasks):\n replyMessage.set(key: .progressUpdateAddTotalTasks, value: totalTasks)\n case .setTotalTasks(let totalTasks):\n replyMessage.set(key: .progressUpdateSetTotalTasks, value: totalTasks)\n case .addSize(let size):\n replyMessage.set(key: .progressUpdateAddSize, value: size)\n case .setSize(let size):\n replyMessage.set(key: .progressUpdateSetSize, value: size)\n case .addTotalSize(let totalSize):\n replyMessage.set(key: .progressUpdateAddTotalSize, value: totalSize)\n case .setTotalSize(let totalSize):\n replyMessage.set(key: .progressUpdateSetTotalSize, value: totalSize)\n case .addItems(let items):\n replyMessage.set(key: .progressUpdateAddItems, value: items)\n case .setItems(let items):\n replyMessage.set(key: .progressUpdateSetItems, value: items)\n case .addTotalItems(let totalItems):\n replyMessage.set(key: .progressUpdateAddTotalItems, value: totalItems)\n case .setTotalItems(let totalItems):\n replyMessage.set(key: .progressUpdateSetTotalItems, value: totalItems)\n case .custom(_):\n // Unsupported progress update event in XPC communication.\n break\n }\n }\n xpc_connection_send_message(endpointConnection, replyMessage.underlying)\n }\n}\n"], ["/container/Sources/ContainerPlugin/LaunchPlist.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\n\npublic struct LaunchPlist: Encodable {\n public enum Domain: String, Codable {\n case Aqua\n case Background\n case System\n }\n\n public let label: String\n public let arguments: [String]\n\n public let environment: [String: String]?\n public let cwd: String?\n public let username: String?\n public let groupname: String?\n public let limitLoadToSessionType: [Domain]?\n public let runAtLoad: Bool?\n public let stdin: String?\n public let stdout: String?\n public let stderr: String?\n public let disabled: Bool?\n public let program: String?\n public let keepAlive: Bool?\n public let machServices: [String: Bool]?\n public let waitForDebugger: Bool?\n\n enum CodingKeys: String, CodingKey {\n case label = \"Label\"\n case arguments = \"ProgramArguments\"\n case environment = \"EnvironmentVariables\"\n case cwd = \"WorkingDirectory\"\n case username = \"UserName\"\n case groupname = \"GroupName\"\n case limitLoadToSessionType = \"LimitLoadToSessionType\"\n case runAtLoad = \"RunAtLoad\"\n case stdin = \"StandardInPath\"\n case stdout = \"StandardOutPath\"\n case stderr = \"StandardErrorPath\"\n case disabled = \"Disabled\"\n case program = \"Program\"\n case keepAlive = \"KeepAlive\"\n case machServices = \"MachServices\"\n case waitForDebugger = \"WaitForDebugger\"\n }\n\n public init(\n label: String,\n arguments: [String],\n environment: [String: String]? = nil,\n cwd: String? = nil,\n username: String? = nil,\n groupname: String? = nil,\n limitLoadToSessionType: [Domain]? = nil,\n runAtLoad: Bool? = nil,\n stdin: String? = nil,\n stdout: String? = nil,\n stderr: String? = nil,\n disabled: Bool? = nil,\n program: String? = nil,\n keepAlive: Bool? = nil,\n machServices: [String]? = nil,\n waitForDebugger: Bool? = nil\n ) {\n self.label = label\n self.arguments = arguments\n self.environment = environment\n self.cwd = cwd\n self.username = username\n self.groupname = groupname\n self.limitLoadToSessionType = limitLoadToSessionType\n self.runAtLoad = runAtLoad\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n self.disabled = disabled\n self.program = program\n self.keepAlive = keepAlive\n self.waitForDebugger = waitForDebugger\n if let services = machServices {\n var machServices: [String: Bool] = [:]\n for service in services {\n machServices[service] = true\n }\n self.machServices = machServices\n } else {\n self.machServices = nil\n }\n }\n}\n\nextension LaunchPlist {\n public func encode() throws -> Data {\n let enc = PropertyListEncoder()\n enc.outputFormat = .xml\n return try enc.encode(self)\n }\n}\n#endif\n"], ["/container/Sources/Services/ContainerNetworkService/Network.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\n\n/// Defines common characteristics and operations for a network.\npublic protocol Network: Sendable {\n // Contains network attributes while the network is running\n var state: NetworkState { get async }\n\n // Use implementation-dependent network attributes\n nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws\n\n // Start the network\n func start() async throws\n}\n"], ["/container/Sources/CLI/Container/ContainersCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct ContainersCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"containers\",\n abstract: \"Manage containers\",\n subcommands: [\n ContainerCreate.self,\n ContainerDelete.self,\n ContainerExec.self,\n ContainerInspect.self,\n ContainerKill.self,\n ContainerList.self,\n ContainerLogs.self,\n ContainerStart.self,\n ContainerStop.self,\n ],\n aliases: [\"container\", \"c\"]\n )\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ProcessConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Configuration data for an executable Process.\npublic struct ProcessConfiguration: Sendable, Codable {\n /// The on disk path to the executable binary.\n public var executable: String\n /// Arguments passed to the Process.\n public var arguments: [String]\n /// Environment variables for the Process.\n public var environment: [String]\n /// The current working directory (cwd) for the Process.\n public var workingDirectory: String\n /// A boolean value indicating if a Terminal or PTY device should\n /// be attached to the Process's Standard I/O.\n public var terminal: Bool\n /// The User a Process should execute under.\n public var user: User\n /// Supplemental groups for the Process.\n public var supplementalGroups: [UInt32]\n /// Rlimits for the Process.\n public var rlimits: [Rlimit]\n\n /// Rlimits for Processes.\n public struct Rlimit: Sendable, Codable {\n /// The Rlimit type of the Process.\n ///\n /// Values include standard Rlimit resource types, i.e. RLIMIT_NPROC, RLIMIT_NOFILE, ...\n public let limit: String\n /// The soft limit of the Process\n public let soft: UInt64\n /// The hard or max limit of the Process.\n public let hard: UInt64\n\n public init(limit: String, soft: UInt64, hard: UInt64) {\n self.limit = limit\n self.soft = soft\n self.hard = hard\n }\n }\n\n /// The User information for a Process.\n public enum User: Sendable, Codable, CustomStringConvertible {\n /// Given the raw user string of the form or or lookup the uid/gid within\n /// the container before setting it for the Process.\n case raw(userString: String)\n /// Set the provided uid/gid for the Process.\n case id(uid: UInt32, gid: UInt32)\n\n public var description: String {\n switch self {\n case .id(let uid, let gid):\n return \"\\(uid):\\(gid)\"\n case .raw(let name):\n return name\n }\n }\n }\n\n public init(\n executable: String,\n arguments: [String],\n environment: [String],\n workingDirectory: String = \"/\",\n terminal: Bool = false,\n user: User = .id(uid: 0, gid: 0),\n supplementalGroups: [UInt32] = [],\n rlimits: [Rlimit] = []\n ) {\n self.executable = executable\n self.arguments = arguments\n self.environment = environment\n self.workingDirectory = workingDirectory\n self.terminal = terminal\n self.user = user\n self.supplementalGroups = supplementalGroups\n self.rlimits = rlimits\n }\n}\n"], ["/container/Sources/ContainerClient/String+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension String {\n public func fromISO8601DateString(to: String) -> String? {\n if let date = fromISO8601Date() {\n let dateformatTo = DateFormatter()\n dateformatTo.dateFormat = to\n return dateformatTo.string(from: date)\n }\n return nil\n }\n\n public func fromISO8601Date() -> Date? {\n let iso8601DateFormatter = ISO8601DateFormatter()\n iso8601DateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]\n return iso8601DateFormatter.date(from: self)\n }\n\n public func isAbsolutePath() -> Bool {\n self.starts(with: \"/\")\n }\n\n /// Trim all `char` characters from the left side of the string. Stops when encountering a character that\n /// doesn't match `char`.\n mutating public func trimLeft(char: Character) {\n if self.isEmpty {\n return\n }\n var trimTo = 0\n for c in self {\n if char != c {\n break\n }\n trimTo += 1\n }\n if trimTo != 0 {\n let index = self.index(self.startIndex, offsetBy: trimTo)\n self = String(self[index...])\n }\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\n\nextension Application {\n struct DNSList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List local DNS domains\",\n aliases: [\"ls\"]\n )\n\n func run() async throws {\n let resolver: HostDNSResolver = HostDNSResolver()\n let domains = resolver.listDomains()\n print(domains.joined(separator: \"\\n\"))\n }\n\n }\n}\n"], ["/container/Sources/CLI/Image/ImagesCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct ImagesCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"images\",\n abstract: \"Manage images\",\n subcommands: [\n ImageInspect.self,\n ImageList.self,\n ImageLoad.self,\n ImagePrune.self,\n ImagePull.self,\n ImagePush.self,\n ImageRemove.self,\n ImageSave.self,\n ImageTag.self,\n ],\n aliases: [\"image\", \"i\"]\n )\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildAPI+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationOCI\n\npublic typealias IO = Com_Apple_Container_Build_V1_IO\npublic typealias InfoRequest = Com_Apple_Container_Build_V1_InfoRequest\npublic typealias InfoResponse = Com_Apple_Container_Build_V1_InfoResponse\npublic typealias ClientStream = Com_Apple_Container_Build_V1_ClientStream\npublic typealias ServerStream = Com_Apple_Container_Build_V1_ServerStream\npublic typealias ImageTransfer = Com_Apple_Container_Build_V1_ImageTransfer\npublic typealias BuildTransfer = Com_Apple_Container_Build_V1_BuildTransfer\npublic typealias BuilderClient = Com_Apple_Container_Build_V1_BuilderNIOClient\npublic typealias BuilderClientAsync = Com_Apple_Container_Build_V1_BuilderAsyncClient\npublic typealias BuilderClientProtocol = Com_Apple_Container_Build_V1_BuilderClientProtocol\npublic typealias BuilderClientAsyncProtocol = Com_Apple_Container_Build_V1_BuilderAsyncClient\n\nextension BuildTransfer {\n func stage() -> String? {\n let stage = self.metadata[\"stage\"]\n return stage == \"\" ? nil : stage\n }\n\n func method() -> String? {\n let method = self.metadata[\"method\"]\n return method == \"\" ? nil : method\n }\n\n func includePatterns() -> [String]? {\n guard let includePatternsString = self.metadata[\"include-patterns\"] else {\n return nil\n }\n return includePatternsString == \"\" ? nil : includePatternsString.components(separatedBy: \",\")\n }\n\n func followPaths() -> [String]? {\n guard let followPathString = self.metadata[\"followpaths\"] else {\n return nil\n }\n return followPathString == \"\" ? nil : followPathString.components(separatedBy: \",\")\n }\n\n func mode() -> String? {\n self.metadata[\"mode\"]\n }\n\n func size() -> Int? {\n guard let sizeStr = self.metadata[\"size\"] else {\n return nil\n }\n return sizeStr == \"\" ? nil : Int(sizeStr)\n }\n\n func offset() -> UInt64? {\n guard let offsetStr = self.metadata[\"offset\"] else {\n return nil\n }\n return offsetStr == \"\" ? nil : UInt64(offsetStr)\n }\n\n func len() -> Int? {\n guard let lenStr = self.metadata[\"length\"] else {\n return nil\n }\n return lenStr == \"\" ? nil : Int(lenStr)\n }\n}\n\nextension ImageTransfer {\n func stage() -> String? {\n self.metadata[\"stage\"]\n }\n\n func method() -> String? {\n self.metadata[\"method\"]\n }\n\n func ref() -> String? {\n self.metadata[\"ref\"]\n }\n\n func platform() throws -> Platform? {\n let metadata = self.metadata\n guard let platform = metadata[\"platform\"] else {\n return nil\n }\n return try Platform(from: platform)\n }\n\n func mode() -> String? {\n self.metadata[\"mode\"]\n }\n\n func size() -> Int? {\n let metadata = self.metadata\n guard let sizeStr = metadata[\"size\"] else {\n return nil\n }\n return Int(sizeStr)\n }\n\n func len() -> Int? {\n let metadata = self.metadata\n guard let lenStr = metadata[\"length\"] else {\n return nil\n }\n return Int(lenStr)\n }\n\n func offset() -> UInt64? {\n let metadata = self.metadata\n guard let offsetStr = metadata[\"offset\"] else {\n return nil\n }\n return UInt64(offsetStr)\n }\n}\n\nextension ServerStream {\n func getImageTransfer() -> ImageTransfer? {\n if case .imageTransfer(let v) = self.packetType {\n return v\n }\n return nil\n }\n\n func getBuildTransfer() -> BuildTransfer? {\n if case .buildTransfer(let v) = self.packetType {\n return v\n }\n return nil\n }\n\n func getIO() -> IO? {\n if case .io(let v) = self.packetType {\n return v\n }\n return nil\n }\n}\n"], ["/container/Sources/CLI/System/SystemCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct SystemCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"system\",\n abstract: \"Manage system components\",\n subcommands: [\n SystemDNS.self,\n SystemLogs.self,\n SystemStart.self,\n SystemStop.self,\n SystemStatus.self,\n SystemKernel.self,\n ],\n aliases: [\"s\"]\n )\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum NetworkRoutes: String {\n /// Return the current state of the network.\n case state = \"com.apple.container.network/state\"\n /// Allocates parameters for attaching a sandbox to the network.\n case allocate = \"com.apple.container.network/allocate\"\n /// Deallocates parameters for attaching a sandbox to the network.\n case deallocate = \"com.apple.container.network/deallocate\"\n /// Disables the allocator if no sandboxes are attached.\n case disableAllocator = \"com.apple.container.network/disableAllocator\"\n /// Retrieves the allocation for a hostname.\n case lookup = \"com.apple.container.network/lookup\"\n}\n"], ["/container/Sources/CLI/Registry/RegistryCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct RegistryCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"registry\",\n abstract: \"Manage registry configurations\",\n subcommands: [\n Login.self,\n Logout.self,\n RegistryDefault.self,\n ],\n aliases: [\"r\"]\n )\n }\n}\n"], ["/container/Sources/DNSServer/Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport DNS\nimport Foundation\n\npublic typealias Message = DNS.Message\npublic typealias ResourceRecord = DNS.ResourceRecord\npublic typealias HostRecord = DNS.HostRecord\npublic typealias IPv4 = DNS.IPv4\npublic typealias IPv6 = DNS.IPv6\npublic typealias ReturnCode = DNS.ReturnCode\n\npublic enum DNSResolverError: Swift.Error, CustomStringConvertible {\n case serverError(_ msg: String)\n case invalidHandlerSpec(_ spec: String)\n case unsupportedHandlerType(_ t: String)\n case invalidIP(_ v: String)\n case invalidHandlerOption(_ v: String)\n case handlerConfigError(_ msg: String)\n\n public var description: String {\n switch self {\n case .serverError(let msg):\n return \"server error: \\(msg)\"\n case .invalidHandlerSpec(let msg):\n return \"invalid handler spec: \\(msg)\"\n case .unsupportedHandlerType(let t):\n return \"unsupported handler type specified: \\(t)\"\n case .invalidIP(let ip):\n return \"invalid IP specified: \\(ip)\"\n case .invalidHandlerOption(let v):\n return \"invalid handler option specified: \\(v)\"\n case .handlerConfigError(let msg):\n return \"error configuring handler: \\(msg)\"\n }\n }\n}\n"], ["/container/Sources/CLI/Builder/Builder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct BuilderCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"builder\",\n abstract: \"Manage an image builder instance\",\n subcommands: [\n BuilderStart.self,\n BuilderStatus.self,\n BuilderStop.self,\n BuilderDelete.self,\n ])\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/CompositeResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Delegates a query sequentially to handlers until one provides a response.\npublic struct CompositeResolver: DNSHandler {\n private let handlers: [DNSHandler]\n\n public init(handlers: [DNSHandler]) {\n self.handlers = handlers\n }\n\n public func answer(query: Message) async throws -> Message? {\n for handler in self.handlers {\n if let response = try await handler.answer(query: query) {\n return response\n }\n }\n\n return nil\n }\n}\n"], ["/container/Sources/TerminalProgress/Int+Formatted.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Int {\n func formattedTime() -> String {\n let secondsInMinute = 60\n let secondsInHour = secondsInMinute * 60\n let secondsInDay = secondsInHour * 24\n\n let days = self / secondsInDay\n let hours = (self % secondsInDay) / secondsInHour\n let minutes = (self % secondsInHour) / secondsInMinute\n let seconds = self % secondsInMinute\n\n var components = [String]()\n if days > 0 {\n components.append(\"\\(days)d\")\n }\n if hours > 0 || days > 0 {\n components.append(\"\\(hours)h\")\n }\n if minutes > 0 || hours > 0 || days > 0 {\n components.append(\"\\(minutes)m\")\n }\n components.append(\"\\(seconds)s\")\n return components.joined(separator: \" \")\n }\n\n func formattedNumber() -> String {\n let formatter = NumberFormatter()\n formatter.numberStyle = .decimal\n guard let formattedNumber = formatter.string(from: NSNumber(value: self)) else {\n return \"\"\n }\n return formattedNumber\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkMode.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Networking mode that applies to client containers.\npublic enum NetworkMode: String, Codable, Sendable {\n /// NAT networking mode.\n /// Containers do not have routable IPs, and the host performs network\n /// address translation to allow containers to reach external services.\n case nat = \"nat\"\n}\n\nextension NetworkMode {\n public init() {\n self = .nat\n }\n\n public init?(_ value: String) {\n switch value.lowercased() {\n case \"nat\": self = .nat\n default: return nil\n }\n }\n}\n"], ["/container/Sources/SocketForwarder/GlueHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIOCore\n\nfinal class GlueHandler {\n\n private var partner: GlueHandler?\n\n private var context: ChannelHandlerContext?\n\n private var pendingRead: Bool = false\n\n private init() {}\n}\n\nextension GlueHandler {\n static func matchedPair() -> (GlueHandler, GlueHandler) {\n let first = GlueHandler()\n let second = GlueHandler()\n\n first.partner = second\n second.partner = first\n\n return (first, second)\n }\n}\n\nextension GlueHandler {\n private func partnerWrite(_ data: NIOAny) {\n self.context?.write(data, promise: nil)\n }\n\n private func partnerFlush() {\n self.context?.flush()\n }\n\n private func partnerWriteEOF() {\n self.context?.close(mode: .output, promise: nil)\n }\n\n private func partnerCloseFull() {\n self.context?.close(promise: nil)\n }\n\n private func partnerBecameWritable() {\n if self.pendingRead {\n self.pendingRead = false\n self.context?.read()\n }\n }\n\n private var partnerWritable: Bool {\n self.context?.channel.isWritable ?? false\n }\n}\n\nextension GlueHandler: ChannelDuplexHandler {\n typealias InboundIn = NIOAny\n typealias OutboundIn = NIOAny\n typealias OutboundOut = NIOAny\n\n func handlerAdded(context: ChannelHandlerContext) {\n self.context = context\n }\n\n func handlerRemoved(context: ChannelHandlerContext) {\n self.context = nil\n self.partner = nil\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n self.partner?.partnerWrite(data)\n }\n\n func channelReadComplete(context: ChannelHandlerContext) {\n self.partner?.partnerFlush()\n }\n\n func channelInactive(context: ChannelHandlerContext) {\n self.partner?.partnerCloseFull()\n }\n\n func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {\n if let event = event as? ChannelEvent, case .inputClosed = event {\n // We have read EOF.\n self.partner?.partnerWriteEOF()\n }\n }\n\n func errorCaught(context: ChannelHandlerContext, error: Error) {\n self.partner?.partnerCloseFull()\n }\n\n func channelWritabilityChanged(context: ChannelHandlerContext) {\n if context.channel.isWritable {\n self.partner?.partnerBecameWritable()\n }\n }\n\n func read(context: ChannelHandlerContext) {\n if let partner = self.partner, partner.partnerWritable {\n context.read()\n } else {\n self.pendingRead = true\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemKernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct SystemKernel: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kernel\",\n abstract: \"Manage the default kernel configuration\",\n subcommands: [\n KernelSet.self\n ]\n )\n }\n}\n"], ["/container/Sources/ContainerClient/Core/PublishPort.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The network protocols available for port forwarding.\npublic enum PublishProtocol: String, Sendable, Codable {\n case tcp = \"tcp\"\n case udp = \"udp\"\n\n /// Initialize a protocol with to default value, `.tcp`.\n public init() {\n self = .tcp\n }\n\n /// Initialize a protocol value from the provided string.\n public init?(_ value: String) {\n switch value.lowercased() {\n case \"tcp\": self = .tcp\n case \"udp\": self = .udp\n default: return nil\n }\n }\n}\n\n/// Specifies internet port forwarding from host to container.\npublic struct PublishPort: Sendable, Codable {\n /// The IP address of the proxy listener on the host\n public let hostAddress: String\n\n /// The port number of the proxy listener on the host\n public let hostPort: Int\n\n /// The port number of the container listener\n public let containerPort: Int\n\n /// The network protocol for the proxy\n public let proto: PublishProtocol\n\n /// Creates a new port forwarding specification.\n public init(hostAddress: String, hostPort: Int, containerPort: Int, proto: PublishProtocol) {\n self.hostAddress = hostAddress\n self.hostPort = hostPort\n self.containerPort = containerPort\n self.proto = proto\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/Attachment.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A snapshot of a network interface allocated to a sandbox.\npublic struct Attachment: Codable, Sendable {\n /// The network ID associated with the attachment.\n public let network: String\n /// The hostname associated with the attachment.\n public let hostname: String\n /// The subnet CIDR, where the address is the container interface IPv4 address.\n public let address: String\n /// The IPv4 gateway address.\n public let gateway: String\n\n public init(network: String, hostname: String, address: String, gateway: String) {\n self.network = network\n self.hostname = hostname\n self.address = address\n self.gateway = gateway\n }\n}\n"], ["/container/Sources/ContainerPlugin/CommandLine+Executable.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension CommandLine {\n public static var executablePathUrl: URL {\n /// _NSGetExecutablePath with a zero-length buffer returns the needed buffer length\n var bufferSize: Int32 = 0\n var buffer = [CChar](repeating: 0, count: Int(bufferSize))\n _ = _NSGetExecutablePath(&buffer, &bufferSize)\n\n /// Create the buffer and get the path\n buffer = [CChar](repeating: 0, count: Int(bufferSize))\n guard _NSGetExecutablePath(&buffer, &bufferSize) == 0 else {\n fatalError(\"UNEXPECTED: failed to get executable path\")\n }\n\n /// Return the path with the executable file component removed the last component and\n let executablePath = String(cString: &buffer)\n return URL(filePath: executablePath)\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientHealthCheck.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Foundation\n\npublic enum ClientHealthCheck {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n}\n\nextension ClientHealthCheck {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public static func ping(timeout: Duration? = .seconds(5)) async throws {\n let client = Self.newClient()\n let request = XPCMessage(route: .ping)\n try await client.send(request, responseTimeout: timeout)\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum NetworkKeys: String {\n case additionalData\n case allocatorDisabled\n case attachment\n case hostname\n case network\n case state\n}\n"], ["/container/Sources/ContainerClient/Core/ImageDescription.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\n\n/// A type that represents an OCI image that can be used with sandboxes or containers.\npublic struct ImageDescription: Sendable, Codable {\n /// The public reference/name of the image.\n public let reference: String\n /// The descriptor of the image.\n public let descriptor: Descriptor\n\n public var digest: String { descriptor.digest }\n public var mediaType: String { descriptor.mediaType }\n\n public init(reference: String, descriptor: Descriptor) {\n self.reference = reference\n self.descriptor = descriptor\n }\n}\n"], ["/container/Sources/SocketForwarder/SocketForwarderResult.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIO\n\npublic struct SocketForwarderResult: Sendable {\n private let channel: any Channel\n\n public init(channel: Channel) {\n self.channel = channel\n }\n\n public var proxyAddress: SocketAddress? { self.channel.localAddress }\n\n public func close() {\n self.channel.eventLoop.execute {\n _ = channel.close()\n }\n }\n\n public func wait() async throws {\n try await self.channel.closeFuture.get()\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressTheme.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A theme for progress bar.\npublic protocol ProgressTheme: Sendable {\n /// The icons used to represent a spinner.\n var spinner: [String] { get }\n /// The icon used to represent a progress bar.\n var bar: String { get }\n /// The icon used to indicate that a progress bar finished.\n var done: String { get }\n}\n\npublic struct DefaultProgressTheme: ProgressTheme {\n public let spinner = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"]\n public let bar = \"█\"\n public let done = \"✔\"\n}\n\nextension ProgressTheme {\n func getSpinnerIcon(_ iteration: Int) -> String {\n spinner[iteration % spinner.count]\n }\n}\n"], ["/container/Sources/APIServer/HealthCheck/HealthCheckHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport Logging\n\nactor HealthCheckHarness {\n private let log: Logger\n\n public init(log: Logger) {\n self.log = log\n }\n\n @Sendable\n func ping(_ message: XPCMessage) async -> XPCMessage {\n message.reply()\n }\n}\n"], ["/container/Sources/TerminalProgress/Int64+Formatted.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Int64 {\n func formattedSize() -> String {\n let formattedSize = ByteCountFormatter.string(fromByteCount: self, countStyle: .binary)\n return formattedSize\n }\n\n func formattedSizeSpeed(from startTime: DispatchTime) -> String {\n let elapsedTimeNanoseconds = DispatchTime.now().uptimeNanoseconds - startTime.uptimeNanoseconds\n let elapsedTimeSeconds = Double(elapsedTimeNanoseconds) / 1_000_000_000\n guard elapsedTimeSeconds > 0 else {\n return \"0 B/s\"\n }\n\n let speed = Double(self) / elapsedTimeSeconds\n let formattedSpeed = ByteCountFormatter.string(fromByteCount: Int64(speed), countStyle: .binary)\n return \"\\(formattedSpeed)/s\"\n }\n}\n"], ["/container/Sources/TerminalProgress/StandardError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct StandardError {\n func write(_ string: String) {\n if let data = string.data(using: .utf8) {\n FileHandle.standardError.write(data)\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/TerminalCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct TerminalCommand: Codable {\n let commandType: String\n let code: String\n let rows: UInt16\n let cols: UInt16\n\n enum CodingKeys: String, CodingKey {\n case commandType = \"command_type\"\n case code\n case rows\n case cols\n }\n\n init(rows: UInt16, cols: UInt16) {\n self.commandType = \"terminal\"\n self.code = \"winch\"\n self.rows = rows\n self.cols = cols\n }\n\n init() {\n self.commandType = \"terminal\"\n self.code = \"ack\"\n self.rows = 0\n self.cols = 0\n }\n\n func json() throws -> String? {\n let encoder = JSONEncoder()\n let data = try encoder.encode(self)\n return data.base64EncodedString().trimmingCharacters(in: CharacterSet(charactersIn: \"=\"))\n }\n}\n"], ["/container/Sources/ContainerClient/Array+Dedupe.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension Array where Element: Hashable {\n func dedupe() -> [Element] {\n var elems = Set()\n return filter { elems.insert($0).inserted }\n }\n}\n"], ["/container/Sources/CLI/Codable+JSON.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\nextension [any Codable] {\n func jsonArray() throws -> String {\n \"[\\(try self.map { String(data: try JSONEncoder().encode($0), encoding: .utf8)! }.joined(separator: \",\"))]\"\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/ImageServiceXPCKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\n/// Keys for XPC fields.\npublic enum ImagesServiceXPCKeys: String {\n case fd\n /// FDs pointing to container logs key.\n case logs\n /// Path to a file on disk key.\n case filePath\n\n /// Images\n case imageReference\n case imageNewReference\n case imageDescription\n case imageDescriptions\n case filesystem\n case ociPlatform\n case insecureFlag\n case garbageCollect\n\n /// ContentStore\n case digest\n case digests\n case directory\n case contentPath\n case size\n case ingestSessionId\n}\n\nextension XPCMessage {\n public func set(key: ImagesServiceXPCKeys, value: String) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: UInt64) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: Data) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: Bool) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func string(key: ImagesServiceXPCKeys) -> String? {\n self.string(key: key.rawValue)\n }\n\n public func data(key: ImagesServiceXPCKeys) -> Data? {\n self.data(key: key.rawValue)\n }\n\n public func dataNoCopy(key: ImagesServiceXPCKeys) -> Data? {\n self.dataNoCopy(key: key.rawValue)\n }\n\n public func uint64(key: ImagesServiceXPCKeys) -> UInt64 {\n self.uint64(key: key.rawValue)\n }\n\n public func bool(key: ImagesServiceXPCKeys) -> Bool {\n self.bool(key: key.rawValue)\n }\n}\n\n#endif\n"], ["/container/Sources/Services/ContainerImagesService/Client/ImageServiceXPCRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\npublic enum ImagesServiceXPCRoute: String {\n case imageList\n case imagePull\n case imagePush\n case imageTag\n case imageBuild\n case imageDelete\n case imageSave\n case imageLoad\n case imagePrune\n\n case contentGet\n case contentDelete\n case contentClean\n case contentIngestStart\n case contentIngestComplete\n case contentIngestCancel\n\n case imageUnpack\n case snapshotDelete\n case snapshotGet\n}\n\nextension XPCMessage {\n public init(route: ImagesServiceXPCRoute) {\n self.init(route: route.rawValue)\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerClient/Core/ContainerCreateOptions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct ContainerCreateOptions: Codable, Sendable {\n public let autoRemove: Bool\n\n public init(autoRemove: Bool) {\n self.autoRemove = autoRemove\n }\n\n public static let `default` = ContainerCreateOptions(autoRemove: false)\n\n}\n"], ["/container/Sources/ContainerClient/Core/PublishSocket.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\n/// Represents a socket that should be published from container to host.\npublic struct PublishSocket: Sendable, Codable {\n /// The path to the socket in the container.\n public var containerPath: URL\n\n /// The path where the socket should appear on the host.\n public var hostPath: URL\n\n /// File permissions for the socket on the host.\n public var permissions: FilePermissions?\n\n public init(\n containerPath: URL,\n hostPath: URL,\n permissions: FilePermissions? = nil\n ) {\n self.containerPath = containerPath\n self.hostPath = hostPath\n self.permissions = permissions\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerStopOptions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct ContainerStopOptions: Sendable, Codable {\n public let timeoutInSeconds: Int32\n public let signal: Int32\n\n public static let `default` = ContainerStopOptions(\n timeoutInSeconds: 5,\n signal: SIGTERM\n )\n\n public init(timeoutInSeconds: Int32, signal: Int32) {\n self.timeoutInSeconds = timeoutInSeconds\n self.signal = signal\n }\n}\n"], ["/container/Sources/DNSServer/DNSHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Protocol for implementing custom DNS handlers.\npublic protocol DNSHandler {\n /// Attempt to answer a DNS query\n /// - Parameter query: the query message\n /// - Throws: a server failure occurred during the query\n /// - Returns: The response message for the query, or nil if the request\n /// is not within the scope of the handler.\n func answer(query: Message) async throws -> Message?\n}\n"], ["/container/Sources/TerminalProgress/ProgressUpdate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum ProgressUpdateEvent: Sendable {\n case setDescription(String)\n case setSubDescription(String)\n case setItemsName(String)\n case addTasks(Int)\n case setTasks(Int)\n case addTotalTasks(Int)\n case setTotalTasks(Int)\n case addItems(Int)\n case setItems(Int)\n case addTotalItems(Int)\n case setTotalItems(Int)\n case addSize(Int64)\n case setSize(Int64)\n case addTotalSize(Int64)\n case setTotalSize(Int64)\n case custom(String)\n}\n\npublic typealias ProgressUpdateHandler = @Sendable (_ events: [ProgressUpdateEvent]) async -> Void\n\npublic protocol ProgressAdapter {\n associatedtype T\n static func handler(from progressUpdate: ProgressUpdateHandler?) -> (@Sendable ([T]) async -> Void)?\n}\n"], ["/container/Sources/ContainerClient/Arch.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum Arch: String {\n case arm64, amd64\n\n public static func hostArchitecture() -> Arch {\n #if arch(arm64)\n return .arm64\n #elseif arch(x86_64)\n return .amd64\n #endif\n }\n}\n"], ["/container/Sources/ContainerClient/ContainerEvents.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\npublic enum ContainerEvent: Sendable, Codable {\n case containerStart(id: String)\n case containerExit(id: String, exitCode: Int64)\n}\n"], ["/container/Sources/Services/ContainerNetworkService/UserDefaults+Container.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension UserDefaults {\n public static let appSuiteName = \"com.apple.container.defaults\"\n}\n"], ["/container/Sources/SocketForwarder/SocketForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIO\n\npublic protocol SocketForwarder: Sendable {\n func run() throws -> EventLoopFuture\n}\n"], ["/container/Sources/ContainerClient/SandboxRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum SandboxRoutes: String {\n /// Bootstrap the sandbox instance and create the init process.\n case bootstrap = \"com.apple.container.sandbox/bootstrap\"\n /// Create a process in the sandbox.\n case createProcess = \"com.apple.container.sandbox/createProcess\"\n /// Start a process in the sandbox.\n case start = \"com.apple.container.sandbox/start\"\n /// Stop the sandbox.\n case stop = \"com.apple.container.sandbox/stop\"\n /// Return the current state of the sandbox.\n case state = \"com.apple.container.sandbox/state\"\n /// Kill a process in the sandbox.\n case kill = \"com.apple.container.sandbox/kill\"\n /// Resize the pty of a process in the sandbox.\n case resize = \"com.apple.container.sandbox/resize\"\n /// Wait on a process in the sandbox.\n case wait = \"com.apple.container.sandbox/wait\"\n /// Execute a new process in the sandbox.\n case exec = \"com.apple.container.sandbox/exec\"\n /// Dial a vsock port in the sandbox.\n case dial = \"com.apple.container.sandbox/dial\"\n}\n"], ["/container/Sources/ContainerClient/Core/Constants.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum Constants {\n public static let keychainID = \"com.apple.container\"\n}\n"], ["/container/Sources/ContainerClient/Core/RuntimeStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Runtime status for a sandbox or container.\npublic enum RuntimeStatus: String, CaseIterable, Sendable, Codable {\n /// The object is in an unknown status.\n case unknown\n /// The object is currently stopped.\n case stopped\n /// The object is currently running.\n case running\n /// The object is currently stopping.\n case stopping\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:21:52", "created_task_model": "DeepSeek-R1", "function_skeleton": "func validate ( ) throws { }", "code_description": "This code segment functions to: Enforce mutual exclusivity between specifying individual items and a complete set via flags while ensuring at least one selection method is provided."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\n mutating func validate() throws {\n if all && !networkNames.isEmpty {\n throw ValidationError(\"Cannot specify both --all and network names.\")\n }\n \n if !all && networkNames.isEmpty {\n throw ValidationError(\"Must specify either --all or at least one network name.\")\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 03-22-12"}, "editdistance_info": {"edit_distance": 24.4186, "calculate_time": "2025-08-21 03:22:12", "true_code_clean": "func validate() throws {\n if networkNames.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no networks specified and --all not supplied\")\n }\n if networkNames.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument,\n message: \"explicitly supplied network name(s) conflict with the --all flag\"\n )\n }\n }", "predict_code_clean": "mutating func validate() throws {\n if all && !networkNames.isEmpty {\n throw ValidationError(\"Cannot specify both --all and network names.\")\n }\n if !all && networkNames.isEmpty {\n throw ValidationError(\"Must specify either --all or at least one network name.\")\n }\n }"}} {"repo_name": "container", "file_name": "/container/Sources/CLI/Container/ContainerLogs.swift", "inference_info": {"prefix_code": "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Darwin\nimport Dispatch\nimport Foundation\n\nextension Application {\n struct ContainerLogs: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"logs\",\n abstract: \"Fetch container stdio or boot logs\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Flag(name: .shortAndLong, help: \"Follow log output\")\n var follow: Bool = false\n\n @Flag(name: .long, help: \"Display the boot log for the container instead of stdio\")\n var boot: Bool = false\n\n @Option(name: [.customShort(\"n\")], help: \"Number of lines to show from the end of the logs. If not provided this will print all of the logs\")\n var numLines: Int?\n\n @Argument(help: \"Container to fetch logs for\")\n var container: String\n\n ", "suffix_code": "\n\n private static func tail(\n fh: FileHandle,\n n: Int?,\n follow: Bool\n ) async throws {\n if let n {\n var buffer = Data()\n let size = try fh.seekToEnd()\n var offset = size\n var lines: [String] = []\n\n while offset > 0, lines.count < n {\n let readSize = min(1024, offset)\n offset -= readSize\n try fh.seek(toOffset: offset)\n\n let data = fh.readData(ofLength: Int(readSize))\n buffer.insert(contentsOf: data, at: 0)\n\n if let chunk = String(data: buffer, encoding: .utf8) {\n lines = chunk.components(separatedBy: .newlines)\n lines = lines.filter { !$0.isEmpty }\n }\n }\n\n lines = Array(lines.suffix(n))\n for line in lines {\n print(line)\n }\n } else {\n // Fast path if all they want is the full file.\n guard let data = try fh.readToEnd() else {\n // Seems you get nil if it's a zero byte read, or you\n // try and read from dev/null.\n return\n }\n guard let str = String(data: data, encoding: .utf8) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to convert container logs to utf8\"\n )\n }\n print(str.trimmingCharacters(in: .newlines))\n }\n\n fflush(stdout)\n if follow {\n setbuf(stdout, nil)\n try await Self.followFile(fh: fh)\n }\n }\n\n private static func followFile(fh: FileHandle) async throws {\n _ = try fh.seekToEnd()\n let stream = AsyncStream { cont in\n fh.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n // Triggers on container restart - can exit here as well\n do {\n _ = try fh.seekToEnd() // To continue streaming existing truncated log files\n } catch {\n fh.readabilityHandler = nil\n cont.finish()\n return\n }\n }\n if let str = String(data: data, encoding: .utf8), !str.isEmpty {\n var lines = str.components(separatedBy: .newlines)\n lines = lines.filter { !$0.isEmpty }\n for line in lines {\n cont.yield(line)\n }\n }\n }\n }\n\n for await line in stream {\n print(line)\n }\n }\n }\n}\n", "middle_code": "func run() async throws {\n do {\n let container = try await ClientContainer.get(id: container)\n let fhs = try await container.logs()\n let fileHandle = boot ? fhs[1] : fhs[0]\n try await Self.tail(\n fh: fileHandle,\n n: numLines,\n follow: follow\n )\n } catch {\n throw ContainerizationError(\n .invalidArgument,\n message: \"failed to fetch container logs for \\(container): \\(error)\"\n )\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/container/Sources/CLI/RunCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Foundation\nimport NIOCore\nimport NIOPosix\nimport TerminalProgress\n\nextension Application {\n struct ContainerRunCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"run\",\n abstract: \"Run a container\")\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var resourceFlags: Flags.Resource\n\n @OptionGroup\n var managementFlags: Flags.Management\n\n @OptionGroup\n var registryFlags: Flags.Registry\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Argument(help: \"Image name\")\n var image: String\n\n @Argument(parsing: .captureForPassthrough, help: \"Container init process arguments\")\n var arguments: [String] = []\n\n func run() async throws {\n var exitCode: Int32 = 127\n let id = Utility.createContainerID(name: self.managementFlags.name)\n\n var progressConfig: ProgressConfig\n if progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 6\n )\n }\n\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n try Utility.validEntityName(id)\n\n // Check if container with id already exists.\n let existing = try? await ClientContainer.get(id: id)\n guard existing == nil else {\n throw ContainerizationError(\n .exists,\n message: \"container with id \\(id) already exists\"\n )\n }\n\n let ck = try await Utility.containerConfigFromFlags(\n id: id,\n image: image,\n arguments: arguments,\n process: processFlags,\n management: managementFlags,\n resource: resourceFlags,\n registry: registryFlags,\n progressUpdate: progress.handler\n )\n\n progress.set(description: \"Starting container\")\n\n let options = ContainerCreateOptions(autoRemove: managementFlags.remove)\n let container = try await ClientContainer.create(\n configuration: ck.0,\n options: options,\n kernel: ck.1\n )\n\n let detach = self.managementFlags.detach\n\n let process = try await container.bootstrap()\n progress.finish()\n\n do {\n let io = try ProcessIO.create(\n tty: self.processFlags.tty,\n interactive: self.processFlags.interactive,\n detach: detach\n )\n\n if !self.managementFlags.cidfile.isEmpty {\n let path = self.managementFlags.cidfile\n let data = id.data(using: .utf8)\n var attributes = [FileAttributeKey: Any]()\n attributes[.posixPermissions] = 0o644\n let success = FileManager.default.createFile(\n atPath: path,\n contents: data,\n attributes: attributes\n )\n guard success else {\n throw ContainerizationError(\n .internalError, message: \"failed to create cidfile at \\(path): \\(errno)\")\n }\n }\n\n if detach {\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n print(id)\n return\n }\n\n if !self.processFlags.tty {\n var handler = SignalThreshold(threshold: 3, signals: [SIGINT, SIGTERM])\n handler.start {\n print(\"Received 3 SIGINT/SIGTERM's, forcefully exiting.\")\n Darwin.exit(1)\n }\n }\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to run container: \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n\nstruct ProcessIO {\n let stdin: Pipe?\n let stdout: Pipe?\n let stderr: Pipe?\n var ioTracker: IoTracker?\n\n struct IoTracker {\n let stream: AsyncStream\n let cont: AsyncStream.Continuation\n let configuredStreams: Int\n }\n\n let stdio: [FileHandle?]\n\n let console: Terminal?\n\n func closeAfterStart() throws {\n try stdin?.fileHandleForReading.close()\n try stdout?.fileHandleForWriting.close()\n try stderr?.fileHandleForWriting.close()\n }\n\n func close() throws {\n try console?.reset()\n }\n\n static func create(tty: Bool, interactive: Bool, detach: Bool) throws -> ProcessIO {\n let current: Terminal? = try {\n if !tty || !interactive {\n return nil\n }\n let current = try Terminal.current\n try current.setraw()\n return current\n }()\n\n var stdio = [FileHandle?](repeating: nil, count: 3)\n\n let stdin: Pipe? = {\n if !interactive && !tty {\n return nil\n }\n return Pipe()\n }()\n\n if let stdin {\n if interactive {\n let pin = FileHandle.standardInput\n let stdinOSFile = OSFile(fd: pin.fileDescriptor)\n let pipeOSFile = OSFile(fd: stdin.fileHandleForWriting.fileDescriptor)\n try stdinOSFile.makeNonBlocking()\n nonisolated(unsafe) let buf = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n\n pin.readabilityHandler = { _ in\n Self.streamStdin(\n from: stdinOSFile,\n to: pipeOSFile,\n buffer: buf,\n ) {\n pin.readabilityHandler = nil\n buf.deallocate()\n try? stdin.fileHandleForWriting.close()\n }\n }\n }\n stdio[0] = stdin.fileHandleForReading\n }\n\n let stdout: Pipe? = {\n if detach {\n return nil\n }\n return Pipe()\n }()\n\n var configuredStreams = 0\n let (stream, cc) = AsyncStream.makeStream()\n if let stdout {\n configuredStreams += 1\n let pout: FileHandle = {\n if let current {\n return current.handle\n }\n return .standardOutput\n }()\n\n let rout = stdout.fileHandleForReading\n rout.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n rout.readabilityHandler = nil\n cc.yield()\n return\n }\n try! pout.write(contentsOf: data)\n }\n stdio[1] = stdout.fileHandleForWriting\n }\n\n let stderr: Pipe? = {\n if detach || tty {\n return nil\n }\n return Pipe()\n }()\n if let stderr {\n configuredStreams += 1\n let perr: FileHandle = .standardError\n let rerr = stderr.fileHandleForReading\n rerr.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n rerr.readabilityHandler = nil\n cc.yield()\n return\n }\n try! perr.write(contentsOf: data)\n }\n stdio[2] = stderr.fileHandleForWriting\n }\n\n var ioTracker: IoTracker? = nil\n if configuredStreams > 0 {\n ioTracker = .init(stream: stream, cont: cc, configuredStreams: configuredStreams)\n }\n\n return .init(\n stdin: stdin,\n stdout: stdout,\n stderr: stderr,\n ioTracker: ioTracker,\n stdio: stdio,\n console: current\n )\n }\n\n static func streamStdin(\n from: OSFile,\n to: OSFile,\n buffer: UnsafeMutableBufferPointer,\n onErrorOrEOF: () -> Void,\n ) {\n while true {\n let (bytesRead, action) = from.read(buffer)\n if bytesRead > 0 {\n let view = UnsafeMutableBufferPointer(\n start: buffer.baseAddress,\n count: bytesRead\n )\n\n let (bytesWritten, _) = to.write(view)\n if bytesWritten != bytesRead {\n onErrorOrEOF()\n return\n }\n }\n\n switch action {\n case .error(_), .eof, .brokenPipe:\n onErrorOrEOF()\n return\n case .again:\n return\n case .success:\n break\n }\n }\n }\n\n public func wait() async throws {\n guard let ioTracker = self.ioTracker else {\n return\n }\n do {\n try await Timeout.run(seconds: 3) {\n var counter = ioTracker.configuredStreams\n for await _ in ioTracker.stream {\n counter -= 1\n if counter == 0 {\n ioTracker.cont.finish()\n break\n }\n }\n }\n } catch {\n log.error(\"Timeout waiting for IO to complete : \\(error)\")\n throw error\n }\n }\n}\n\nstruct OSFile: Sendable {\n private let fd: Int32\n\n enum IOAction: Equatable {\n case eof\n case again\n case success\n case brokenPipe\n case error(_ errno: Int32)\n }\n\n init(fd: Int32) {\n self.fd = fd\n }\n\n init(handle: FileHandle) {\n self.fd = handle.fileDescriptor\n }\n\n func makeNonBlocking() throws {\n let flags = fcntl(fd, F_GETFL)\n guard flags != -1 else {\n throw POSIXError.fromErrno()\n }\n\n if fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1 {\n throw POSIXError.fromErrno()\n }\n }\n\n func write(_ buffer: UnsafeMutableBufferPointer) -> (wrote: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesWrote: Int = 0\n while true {\n let n = Darwin.write(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesWrote),\n buffer.count - bytesWrote\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesWrote, .again)\n }\n return (bytesWrote, .error(errno))\n }\n\n if n == 0 {\n return (bytesWrote, .brokenPipe)\n }\n\n bytesWrote += n\n if bytesWrote < buffer.count {\n continue\n }\n return (bytesWrote, .success)\n }\n }\n\n func read(_ buffer: UnsafeMutableBufferPointer) -> (read: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesRead: Int = 0\n while true {\n let n = Darwin.read(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesRead),\n buffer.count - bytesRead\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesRead, .again)\n }\n return (bytesRead, .error(errno))\n }\n\n if n == 0 {\n return (bytesRead, .eof)\n }\n\n bytesRead += n\n if bytesRead < buffer.count {\n continue\n }\n return (bytesRead, .success)\n }\n }\n}\n"], ["/container/Sources/CLI/BuildCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerBuild\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport NIO\nimport TerminalProgress\n\nextension Application {\n struct BuildCommand: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"build\"\n config.abstract = \"Build an image from a Dockerfile\"\n config._superCommandName = \"container\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64 = 2\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n var memory: String = \"2048MB\"\n\n @Option(name: .long, help: ArgumentHelp(\"Set build-time variables\", valueName: \"key=val\"))\n var buildArg: [String] = []\n\n @Argument(help: \"Build directory\")\n var contextDir: String = \".\"\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Path to Dockerfile\", valueName: \"path\"))\n var file: String = \"Dockerfile\"\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Set a label\", valueName: \"key=val\"))\n var label: [String] = []\n\n @Flag(name: .long, help: \"Do not use cache\")\n var noCache: Bool = false\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Output configuration for the build\", valueName: \"value\"))\n var output: [String] = {\n [\"type=oci\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Cache imports for the build\", valueName: \"value\", visibility: .hidden))\n var cacheIn: [String] = {\n []\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Cache exports for the build\", valueName: \"value\", visibility: .hidden))\n var cacheOut: [String] = {\n []\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"set the build architecture\", valueName: \"value\"))\n var arch: [String] = {\n [\"arm64\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"set the build os\", valueName: \"value\"))\n var os: [String] = {\n [\"linux\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Progress type - one of [auto|plain|tty]\", valueName: \"type\"))\n var progress: String = \"auto\"\n\n @Option(name: .long, help: ArgumentHelp(\"Builder-shim vsock port\", valueName: \"port\"))\n var vsockPort: UInt32 = 8088\n\n @Option(name: [.customShort(\"t\"), .customLong(\"tag\")], help: ArgumentHelp(\"Name for the built image\", valueName: \"name\"))\n var targetImageName: String = UUID().uuidString.lowercased()\n\n @Option(name: .long, help: ArgumentHelp(\"Set the target build stage\", valueName: \"stage\"))\n var target: String = \"\"\n\n @Flag(name: .shortAndLong, help: \"Suppress build output\")\n var quiet: Bool = false\n\n func run() async throws {\n do {\n let timeout: Duration = .seconds(300)\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Dialing builder\")\n\n let builder: Builder? = try await withThrowingTaskGroup(of: Builder.self) { group in\n defer {\n group.cancelAll()\n }\n\n group.addTask {\n while true {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n let fh = try await container.dial(self.vsockPort)\n\n let threadGroup: MultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n let b = try Builder(socket: fh, group: threadGroup)\n\n // If this call succeeds, then BuildKit is running.\n let _ = try await b.info()\n return b\n } catch {\n // If we get here, \"Dialing builder\" is shown for such a short period\n // of time that it's invisible to the user.\n progress.set(tasks: 0)\n progress.set(totalTasks: 3)\n\n try await BuilderStart.start(\n cpus: self.cpus,\n memory: self.memory,\n progressUpdate: progress.handler\n )\n\n // wait (seconds) for builder to start listening on vsock\n try await Task.sleep(for: .seconds(5))\n continue\n }\n }\n }\n\n group.addTask {\n try await Task.sleep(for: timeout)\n throw ValidationError(\n \"\"\"\n Timeout waiting for connection to builder\n \"\"\"\n )\n }\n\n return try await group.next()\n }\n\n guard let builder else {\n throw ValidationError(\"builder is not running\")\n }\n\n let dockerfile = try Data(contentsOf: URL(filePath: file))\n let exportPath = Application.appRoot.appendingPathComponent(\".build\")\n\n let buildID = UUID().uuidString\n let tempURL = exportPath.appendingPathComponent(buildID)\n try FileManager.default.createDirectory(at: tempURL, withIntermediateDirectories: true, attributes: nil)\n defer {\n try? FileManager.default.removeItem(at: tempURL)\n }\n\n let imageName: String = try {\n let parsedReference = try Reference.parse(targetImageName)\n parsedReference.normalize()\n return parsedReference.description\n }()\n\n var terminal: Terminal?\n switch self.progress {\n case \"tty\":\n terminal = try Terminal(descriptor: STDERR_FILENO)\n case \"auto\":\n terminal = try? Terminal(descriptor: STDERR_FILENO)\n case \"plain\":\n terminal = nil\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid progress mode \\(self.progress)\")\n }\n\n defer { terminal?.tryReset() }\n\n let exports: [Builder.BuildExport] = try output.map { output in\n var exp = try Builder.BuildExport(from: output)\n if exp.destination == nil {\n exp.destination = tempURL.appendingPathComponent(\"out.tar\")\n }\n return exp\n }\n\n try await withThrowingTaskGroup(of: Void.self) { [terminal] group in\n defer {\n group.cancelAll()\n }\n group.addTask {\n let handler = AsyncSignalHandler.create(notify: [SIGTERM, SIGINT, SIGUSR1, SIGUSR2])\n for await sig in handler.signals {\n throw ContainerizationError(.interrupted, message: \"exiting on signal \\(sig)\")\n }\n }\n let platforms: [Platform] = try {\n var results: [Platform] = []\n for o in self.os {\n for a in self.arch {\n guard let platform = try? Platform(from: \"\\(o)/\\(a)\") else {\n throw ValidationError(\"invalid os/architecture combination \\(o)/\\(a)\")\n }\n results.append(platform)\n }\n }\n return results\n }()\n group.addTask { [terminal] in\n let config = ContainerBuild.Builder.BuildConfig(\n buildID: buildID,\n contentStore: RemoteContentStoreClient(),\n buildArgs: buildArg,\n contextDir: contextDir,\n dockerfile: dockerfile,\n labels: label,\n noCache: noCache,\n platforms: platforms,\n terminal: terminal,\n tag: imageName,\n target: target,\n quiet: quiet,\n exports: exports,\n cacheIn: cacheIn,\n cacheOut: cacheOut\n )\n progress.finish()\n\n try await builder.build(config)\n }\n\n try await group.next()\n }\n\n let unpackProgressConfig = try ProgressConfig(\n description: \"Unpacking built image\",\n itemsName: \"entries\",\n showTasks: exports.count > 1,\n totalTasks: exports.count\n )\n let unpackProgress = ProgressBar(config: unpackProgressConfig)\n defer {\n unpackProgress.finish()\n }\n unpackProgress.start()\n\n var finalMessage = \"Successfully built \\(imageName)\"\n let taskManager = ProgressTaskCoordinator()\n // Currently, only a single export can be specified.\n for exp in exports {\n unpackProgress.add(tasks: 1)\n let unpackTask = await taskManager.startTask()\n switch exp.type {\n case \"oci\":\n try Task.checkCancellation()\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let loaded = try await ClientImage.load(from: dest.absolutePath())\n\n for image in loaded {\n try Task.checkCancellation()\n try await image.unpack(platform: nil, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: unpackProgress.handler))\n }\n case \"tar\":\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let tarURL = tempURL.appendingPathComponent(\"out.tar\")\n try FileManager.default.moveItem(at: tarURL, to: dest)\n finalMessage = \"Successfully exported to \\(dest.absolutePath())\"\n case \"local\":\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let localDir = tempURL.appendingPathComponent(\"local\")\n\n guard FileManager.default.fileExists(atPath: localDir.path) else {\n throw ContainerizationError(.invalidArgument, message: \"expected local output not found\")\n }\n try FileManager.default.copyItem(at: localDir, to: dest)\n finalMessage = \"Successfully exported to \\(dest.absolutePath())\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid exporter \\(exp.rawValue)\")\n }\n }\n await taskManager.finish()\n unpackProgress.finish()\n print(finalMessage)\n } catch {\n throw NSError(domain: \"Build\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"\\(error)\"])\n }\n }\n\n func validate() throws {\n guard FileManager.default.fileExists(atPath: file) else {\n throw ValidationError(\"Dockerfile does not exist at path: \\(file)\")\n }\n guard FileManager.default.fileExists(atPath: contextDir) else {\n throw ValidationError(\"context dir does not exist \\(contextDir)\")\n }\n guard let _ = try? Reference.parse(targetImageName) else {\n throw ValidationError(\"invalid reference \\(targetImageName)\")\n }\n }\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/SandboxService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\nimport SocketForwarder\n\nimport struct ContainerizationOCI.Mount\nimport struct ContainerizationOCI.Process\n\n/// An XPC service that manages the lifecycle of a single VM-backed container.\npublic actor SandboxService {\n private let root: URL\n private let interfaceStrategy: InterfaceStrategy\n private var container: ContainerInfo?\n private let monitor: ExitMonitor\n private let eventLoopGroup: any EventLoopGroup\n private var waiters: [String: [CheckedContinuation]] = [:]\n private let lock: AsyncLock = AsyncLock()\n private let log: Logging.Logger\n private var state: State = .created\n private var processes: [String: ProcessInfo] = [:]\n private var socketForwarders: [SocketForwarderResult] = []\n\n /// Create an instance with a bundle that describes the container.\n ///\n /// - Parameters:\n /// - root: The file URL for the bundle root.\n /// - interfaceStrategy: The strategy for producing network interface\n /// objects for each network to which the container attaches.\n /// - log: The destination for log messages.\n public init(root: URL, interfaceStrategy: InterfaceStrategy, eventLoopGroup: any EventLoopGroup, log: Logger) {\n self.root = root\n self.interfaceStrategy = interfaceStrategy\n self.log = log\n self.monitor = ExitMonitor(log: log)\n self.eventLoopGroup = eventLoopGroup\n }\n\n /// Start the VM and the guest agent process for a container.\n ///\n /// - Parameters:\n /// - message: An XPC message with no parameters.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func bootstrap(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`bootstrap` xpc handler\")\n return try await self.lock.withLock { _ in\n guard await self.state == .created else {\n throw ContainerizationError(\n .invalidState,\n message: \"container expected to be in created state, got: \\(await self.state)\"\n )\n }\n\n let bundle = ContainerClient.Bundle(path: self.root)\n try bundle.createLogFile()\n\n let vmm = VZVirtualMachineManager(\n kernel: try bundle.kernel,\n initialFilesystem: bundle.initialFilesystem.asMount,\n bootlog: bundle.bootlog.path,\n logger: self.log\n )\n var config = try bundle.configuration\n let container = LinuxContainer(\n config.id,\n rootfs: try bundle.containerRootfs.asMount,\n vmm: vmm,\n logger: self.log\n )\n\n // dynamically configure the DNS nameserver from a network if no explicit configuration\n if let dns = config.dns, dns.nameservers.isEmpty {\n if let nameserver = try await self.getDefaultNameserver(networks: config.networks) {\n config.dns = ContainerConfiguration.DNSConfiguration(\n nameservers: [nameserver],\n domain: dns.domain,\n searchDomains: dns.searchDomains,\n options: dns.options\n )\n }\n }\n\n try await self.configureContainer(container: container, config: config)\n\n let fqdn: String\n if let hostname = config.hostname {\n if let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName),\n let dnsDomain = suite.string(forKey: \"dns.domain\"),\n !hostname.contains(\".\")\n {\n // TODO: Make the suiteName a constant defined in ClientDefaults and use that.\n // This will need some re-working of dependencies between SandboxService and Client\n fqdn = \"\\(hostname).\\(dnsDomain).\"\n } else {\n fqdn = \"\\(hostname).\"\n }\n } else {\n fqdn = config.id\n }\n\n var attachments: [Attachment] = []\n for index in 0.. XPCMessage {\n self.log.info(\"`start` xpc handler\")\n return try await self.lock.withLock { lock in\n let id = try message.id()\n let stdio = message.stdio()\n let containerInfo = try await self.getContainer()\n let containerId = containerInfo.container.id\n if id == containerId {\n try await self.startInitProcess(stdio: stdio, lock: lock)\n await self.setState(.running)\n try await self.sendContainerEvent(.containerStart(id: id))\n } else {\n try await self.startExecProcess(processId: id, stdio: stdio, lock: lock)\n }\n return message.reply()\n }\n }\n\n private func startInitProcess(stdio: [FileHandle?], lock: AsyncLock.Context) async throws {\n let info = try self.getContainer()\n let container = info.container\n let bundle = info.bundle\n let id = container.id\n guard self.state == .booted else {\n throw ContainerizationError(\n .invalidState,\n message: \"container expected to be in booted state, got: \\(self.state)\"\n )\n }\n let containerLog = try FileHandle(forWritingTo: bundle.containerLog)\n let config = info.config\n let stdout = {\n if let h = stdio[1] {\n return MultiWriter(handles: [h, containerLog])\n }\n return MultiWriter(handles: [containerLog])\n }()\n let stderr: MultiWriter? = {\n if !config.initProcess.terminal {\n if let h = stdio[2] {\n return MultiWriter(handles: [h, containerLog])\n }\n return MultiWriter(handles: [containerLog])\n }\n return nil\n }()\n if let h = stdio[0] {\n container.stdin = h\n }\n container.stdout = stdout\n if let stderr {\n container.stderr = stderr\n }\n self.setState(.starting)\n do {\n try await container.start()\n let waitFunc: ExitMonitor.WaitHandler = {\n let code = try await container.wait()\n if let out = stdio[1] {\n try self.closeHandle(out.fileDescriptor)\n }\n if let err = stdio[2] {\n try self.closeHandle(err.fileDescriptor)\n }\n return code\n }\n try await self.monitor.track(id: id, waitingOn: waitFunc)\n } catch {\n try? await self.cleanupContainer()\n self.setState(.created)\n try await self.sendContainerEvent(.containerExit(id: id, exitCode: -1))\n throw error\n }\n }\n\n private func startExecProcess(processId id: String, stdio: [FileHandle?], lock: AsyncLock.Context) async throws {\n let container = try self.getContainer().container\n guard let processInfo = self.processes[id] else {\n throw ContainerizationError(.notFound, message: \"Process with id \\(id)\")\n }\n let ociConfig = self.configureProcessConfig(config: processInfo.config)\n let stdin: ReaderStream? = {\n if let h = stdio[0] {\n return h\n }\n return nil\n }()\n let process = try await container.exec(\n id,\n configuration: ociConfig,\n stdin: stdin,\n stdout: stdio[1],\n stderr: stdio[2]\n )\n try self.setUnderlyingProcess(id, process)\n try await process.start()\n let waitFunc: ExitMonitor.WaitHandler = {\n let code = try await process.wait()\n if let out = stdio[1] {\n try self.closeHandle(out.fileDescriptor)\n }\n if let err = stdio[2] {\n try self.closeHandle(err.fileDescriptor)\n }\n return code\n }\n try await self.monitor.track(id: id, waitingOn: waitFunc)\n }\n\n private func startSocketForwarders(containerIpAddress: String, publishedPorts: [PublishPort]) async throws {\n var forwarders: [SocketForwarderResult] = []\n try await withThrowingTaskGroup(of: SocketForwarderResult.self) { group in\n for publishedPort in publishedPorts {\n let proxyAddress = try SocketAddress(ipAddress: publishedPort.hostAddress, port: Int(publishedPort.hostPort))\n let serverAddress = try SocketAddress(ipAddress: containerIpAddress, port: Int(publishedPort.containerPort))\n log.info(\n \"creating forwarder for\",\n metadata: [\n \"proxy\": \"\\(proxyAddress)\",\n \"server\": \"\\(serverAddress)\",\n \"protocol\": \"\\(publishedPort.proto)\",\n ])\n group.addTask {\n let forwarder: SocketForwarder\n switch publishedPort.proto {\n case .tcp:\n forwarder = try TCPForwarder(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: self.log\n )\n case .udp:\n forwarder = try UDPForwarder(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: self.log\n )\n }\n return try await forwarder.run().get()\n }\n }\n for try await result in group {\n forwarders.append(result)\n }\n }\n\n self.socketForwarders = forwarders\n }\n\n private func stopSocketForwarders() async {\n log.info(\"closing forwarders\")\n for forwarder in self.socketForwarders {\n forwarder.close()\n try? await forwarder.wait()\n }\n log.info(\"closed forwarders\")\n }\n\n /// Create a process inside the virtual machine for the container.\n ///\n /// Use this procedure to run ad hoc processes in the virtual\n /// machine (`container exec`).\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: A client identifier for the process.\n /// - processConfig: JSON serialization of the `ProcessConfiguration`\n /// containing the process attributes.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func createProcess(_ message: XPCMessage) async throws -> XPCMessage {\n log.info(\"`createProcess` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped(_), .starting, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot exec: container is not running\"\n )\n case .running, .booted:\n let id = try message.id()\n let config = try message.processConfig()\n await self.addNewProcess(id, config)\n try await self.monitor.registerProcess(\n id: id,\n onExit: { id, code in\n guard let process = await self.processes[id]?.process else {\n throw ContainerizationError(.invalidState, message: \"ProcessInfo missing for process \\(id)\")\n }\n for cc in await self.waiters[id] ?? [] {\n cc.resume(returning: code)\n }\n await self.removeWaiters(for: id)\n try await process.delete()\n try await self.setProcessState(id: id, state: .stopped(code))\n })\n return message.reply()\n }\n }\n }\n\n /// Return the state for the sandbox and its containers.\n ///\n /// - Parameters:\n /// - message: An XPC message with no parameters.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - snapshot: The JSON serialization of the `SandboxSnapshot`\n /// that contains the state information.\n @Sendable\n public func state(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`state` xpc handler\")\n var status: RuntimeStatus = .unknown\n var networks: [Attachment] = []\n var cs: ContainerSnapshot?\n\n switch state {\n case .created, .stopped(_), .starting, .booted:\n status = .stopped\n case .stopping:\n status = .stopping\n case .running:\n let ctr = try getContainer()\n\n status = .running\n networks = ctr.attachments\n cs = ContainerSnapshot(\n configuration: ctr.config,\n status: RuntimeStatus.running,\n networks: networks\n )\n }\n\n let reply = message.reply()\n try reply.setState(\n .init(\n status: status,\n networks: networks,\n containers: cs != nil ? [cs!] : []\n )\n )\n return reply\n }\n\n /// Stop the container workload, any ad hoc processes, and the underlying\n /// virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - stopOptions: JSON serialization of `ContainerStopOptions`\n /// that modify stop behavior.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func stop(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`stop` xpc handler\")\n let reply = try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .stopped(_), .created, .stopping:\n return message.reply()\n case .starting:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot stop: container is not running\"\n )\n case .running, .booted:\n let ctr = try await getContainer()\n let stopOptions = try message.stopOptions()\n do {\n try await gracefulStopContainer(\n ctr.container,\n stopOpts: stopOptions\n )\n } catch {\n log.notice(\"failed to stop sandbox gracefully: \\(error)\")\n }\n await setState(.stopping)\n return message.reply()\n }\n }\n do {\n try await cleanupContainer()\n } catch {\n self.log.error(\"failed to cleanup container: \\(error)\")\n }\n return reply\n }\n\n /// Signal a process running in the virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n /// - signal: The signal value.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func kill(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`kill` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped, .starting, .booted, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot kill: container is not running\"\n )\n case .running:\n let ctr = try await getContainer()\n let id = try message.id()\n if id != ctr.container.id {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) does not exist\")\n }\n\n guard let proc = processInfo.process else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not started\")\n }\n try await proc.kill(Int32(try message.signal()))\n return message.reply()\n }\n\n // TODO: fix underlying signal value to int64\n try await ctr.container.kill(Int32(try message.signal()))\n return message.reply()\n }\n }\n }\n\n /// Resize the terminal for a process.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n /// - width: The terminal width.\n /// - height: The terminal height.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func resize(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`resize` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped, .starting, .booted, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot resize: container is not running\"\n )\n case .running:\n let id = try message.id()\n let ctr = try await getContainer()\n let width = message.uint64(key: .width)\n let height = message.uint64(key: .height)\n if id != ctr.container.id {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) does not exist\")\n }\n\n guard let proc = processInfo.process else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not started\")\n }\n\n try await proc.resize(to: .init(width: UInt16(width), height: UInt16(height)))\n return message.reply()\n }\n\n try await ctr.container.resize(to: .init(width: UInt16(width), height: UInt16(height)))\n return message.reply()\n }\n }\n }\n\n /// Wait for a process.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - exitCode: The exit code for the process.\n @Sendable\n public func wait(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`wait` xpc handler\")\n guard let id = message.string(key: .id) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing id in wait xpc message\")\n }\n\n let cachedCode: Int32? = try await self.lock.withLock { _ in\n let ctrInfo = try await self.getContainer()\n let ctr = ctrInfo.container\n if id == ctr.id {\n switch await self.state {\n case .stopped(let code):\n return code\n default:\n break\n }\n } else {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.notFound, message: \"Process with id \\(id)\")\n }\n switch processInfo.state {\n case .stopped(let code):\n return code\n default:\n break\n }\n }\n return nil\n }\n if let cachedCode {\n let reply = message.reply()\n reply.set(key: .exitCode, value: Int64(cachedCode))\n return reply\n }\n\n let exitCode = await withCheckedContinuation { cc in\n // Is this safe since we are in an actor? :(\n self.addWaiter(id: id, cont: cc)\n }\n let reply = message.reply()\n reply.set(key: .exitCode, value: Int64(exitCode))\n return reply\n }\n\n /// Dial a vsock port on the virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - port: The port number.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - fd: The file descriptor for the vsock.\n @Sendable\n public func dial(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`dial` xpc handler\")\n switch self.state {\n case .starting, .created, .stopped, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot dial: container is not running\"\n )\n case .running, .booted:\n let port = message.uint64(key: .port)\n guard port > 0 else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"no vsock port supplied for dial\"\n )\n }\n\n let ctr = try getContainer()\n let fh = try await ctr.container.dialVsock(port: UInt32(port))\n\n let reply = message.reply()\n reply.set(key: .fd, value: fh)\n return reply\n }\n }\n\n private func onContainerExit(id: String, code: Int32) async throws {\n self.log.info(\"init process exited with: \\(code)\")\n\n try await self.lock.withLock { [self] _ in\n let ctrInfo = try await getContainer()\n let ctr = ctrInfo.container\n // Did someone explicitly call stop and we're already\n // cleaning up?\n switch await self.state {\n case .stopped(_):\n return\n default:\n break\n }\n\n do {\n try await ctr.stop()\n } catch {\n log.notice(\"failed to stop sandbox gracefully: \\(error)\")\n }\n\n do {\n try await cleanupContainer()\n } catch {\n self.log.error(\"failed to cleanup container: \\(error)\")\n }\n await setState(.stopped(code))\n let waiters = await self.waiters[id] ?? []\n for cc in waiters {\n cc.resume(returning: code)\n }\n await self.removeWaiters(for: id)\n try await self.sendContainerEvent(.containerExit(id: id, exitCode: Int64(code)))\n exit(code)\n }\n }\n\n private func configureContainer(container: LinuxContainer, config: ContainerConfiguration) throws {\n container.cpus = config.resources.cpus\n container.memoryInBytes = config.resources.memoryInBytes\n container.rosetta = config.rosetta\n container.sysctl = config.sysctls.reduce(into: [String: String]()) {\n $0[$1.key] = $1.value\n }\n\n for mount in config.mounts {\n if try mount.isSocket() {\n let socket = UnixSocketConfiguration(\n source: URL(filePath: mount.source),\n destination: URL(filePath: mount.destination)\n )\n container.sockets.append(socket)\n } else {\n container.mounts.append(mount.asMount)\n }\n }\n\n for publishedSocket in config.publishedSockets {\n let socketConfig = UnixSocketConfiguration(\n source: publishedSocket.containerPath,\n destination: publishedSocket.hostPath,\n permissions: publishedSocket.permissions,\n direction: .outOf\n )\n container.sockets.append(socketConfig)\n }\n\n container.hostname = config.hostname ?? config.id\n\n if let dns = config.dns {\n container.dns = DNS(\n nameservers: dns.nameservers, domain: dns.domain,\n searchDomains: dns.searchDomains, options: dns.options)\n }\n\n configureInitialProcess(container: container, process: config.initProcess)\n }\n\n private func getDefaultNameserver(networks: [String]) async throws -> String? {\n for network in networks {\n let client = NetworkClient(id: network)\n let state = try await client.state()\n guard case .running(_, let status) = state else {\n continue\n }\n return status.gateway\n }\n\n return nil\n }\n\n private func configureInitialProcess(container: LinuxContainer, process: ProcessConfiguration) {\n container.arguments = [process.executable] + process.arguments\n container.environment = modifyingEnvironment(process)\n container.terminal = process.terminal\n container.workingDirectory = process.workingDirectory\n container.rlimits = process.rlimits.map {\n .init(type: $0.limit, hard: $0.hard, soft: $0.soft)\n }\n switch process.user {\n case .raw(let name):\n container.user = .init(\n uid: 0,\n gid: 0,\n umask: nil,\n additionalGids: process.supplementalGroups,\n username: name\n )\n case .id(let uid, let gid):\n container.user = .init(\n uid: uid,\n gid: gid,\n umask: nil,\n additionalGids: process.supplementalGroups,\n username: \"\"\n )\n }\n }\n\n private nonisolated func configureProcessConfig(config: ProcessConfiguration) -> ContainerizationOCI.Process {\n var proc = ContainerizationOCI.Process()\n proc.args = [config.executable] + config.arguments\n proc.env = modifyingEnvironment(config)\n proc.terminal = config.terminal\n proc.cwd = config.workingDirectory\n proc.rlimits = config.rlimits.map {\n .init(type: $0.limit, hard: $0.hard, soft: $0.soft)\n }\n switch config.user {\n case .raw(let name):\n proc.user = .init(\n uid: 0,\n gid: 0,\n umask: nil,\n additionalGids: config.supplementalGroups,\n username: name\n )\n case .id(let uid, let gid):\n proc.user = .init(\n uid: uid,\n gid: gid,\n umask: nil,\n additionalGids: config.supplementalGroups,\n username: \"\"\n )\n }\n\n return proc\n }\n\n private nonisolated func closeHandle(_ handle: Int32) throws {\n guard close(handle) == 0 else {\n guard let errCode = POSIXErrorCode(rawValue: errno) else {\n fatalError(\"failed to convert errno to POSIXErrorCode\")\n }\n throw POSIXError(errCode)\n }\n }\n\n private nonisolated func modifyingEnvironment(_ config: ProcessConfiguration) -> [String] {\n guard config.terminal else {\n return config.environment\n }\n // Prepend the TERM env var. If the user has it specified our value will be overridden.\n return [\"TERM=xterm\"] + config.environment\n }\n\n private func getContainer() throws -> ContainerInfo {\n guard let container else {\n throw ContainerizationError(\n .invalidState,\n message: \"no container found\"\n )\n }\n return container\n }\n\n private func gracefulStopContainer(_ lc: LinuxContainer, stopOpts: ContainerStopOptions) async throws {\n // Try and gracefully shut down the process. Even if this succeeds we need to power off\n // the vm, but we should try this first always.\n do {\n try await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n try await lc.wait()\n }\n group.addTask {\n try await lc.kill(stopOpts.signal)\n try await Task.sleep(for: .seconds(stopOpts.timeoutInSeconds))\n try await lc.kill(SIGKILL)\n }\n try await group.next()\n group.cancelAll()\n }\n } catch {}\n // Now actually bring down the vm.\n try await lc.stop()\n }\n\n private func cleanupContainer() async throws {\n // Give back our lovely IP(s)\n await self.stopSocketForwarders()\n let containerInfo = try self.getContainer()\n for attachment in containerInfo.attachments {\n let client = NetworkClient(id: attachment.network)\n do {\n try await client.deallocate(hostname: attachment.hostname)\n } catch {\n self.log.error(\"failed to deallocate hostname \\(attachment.hostname) on network \\(attachment.network): \\(error)\")\n }\n }\n }\n\n private func sendContainerEvent(_ event: ContainerEvent) async throws {\n let serviceIdentifier = \"com.apple.container.apiserver\"\n let client = XPCClient(service: serviceIdentifier)\n let message = XPCMessage(route: .containerEvent)\n\n let data = try JSONEncoder().encode(event)\n message.set(key: .containerEvent, value: data)\n try await client.send(message)\n }\n\n}\n\nextension XPCMessage {\n fileprivate func signal() throws -> Int64 {\n self.int64(key: .signal)\n }\n\n fileprivate func stopOptions() throws -> ContainerStopOptions {\n guard let data = self.dataNoCopy(key: .stopOptions) else {\n throw ContainerizationError(.invalidArgument, message: \"empty StopOptions\")\n }\n return try JSONDecoder().decode(ContainerStopOptions.self, from: data)\n }\n\n fileprivate func setState(_ state: SandboxSnapshot) throws {\n let data = try JSONEncoder().encode(state)\n self.set(key: .snapshot, value: data)\n }\n\n fileprivate func stdio() -> [FileHandle?] {\n var handles = [FileHandle?](repeating: nil, count: 3)\n if let stdin = self.fileHandle(key: .stdin) {\n handles[0] = stdin\n }\n if let stdout = self.fileHandle(key: .stdout) {\n handles[1] = stdout\n }\n if let stderr = self.fileHandle(key: .stderr) {\n handles[2] = stderr\n }\n return handles\n }\n\n fileprivate func setFileHandle(_ handle: FileHandle) {\n self.set(key: .fd, value: handle)\n }\n\n fileprivate func processConfig() throws -> ProcessConfiguration {\n guard let data = self.dataNoCopy(key: .processConfig) else {\n throw ContainerizationError(.invalidArgument, message: \"empty process configuration\")\n }\n return try JSONDecoder().decode(ProcessConfiguration.self, from: data)\n }\n}\n\nextension ContainerClient.Bundle {\n /// The pathname for the workload log file.\n public var containerLog: URL {\n path.appendingPathComponent(\"stdio.log\")\n }\n\n func createLogFile() throws {\n // Create the log file we'll write stdio to.\n // O_TRUNC resolves a log delay issue on restarted containers by force-updating internal state\n let fd = Darwin.open(self.containerLog.path, O_CREAT | O_RDONLY | O_TRUNC, 0o644)\n guard fd > 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n close(fd)\n }\n}\n\nextension Filesystem {\n var asMount: Containerization.Mount {\n switch self.type {\n case .tmpfs:\n return .any(\n type: \"tmpfs\",\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n case .virtiofs:\n return .share(\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n case .block(let format, _, _):\n return .block(\n format: format,\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n }\n }\n\n func isSocket() throws -> Bool {\n if !self.isVirtiofs {\n return false\n }\n let info = try File.info(self.source)\n return info.isSocket\n }\n}\n\nstruct MultiWriter: Writer {\n let handles: [FileHandle]\n\n func write(_ data: Data) throws {\n for handle in self.handles {\n try handle.write(contentsOf: data)\n }\n }\n}\n\nextension FileHandle: @retroactive ReaderStream, @retroactive Writer {\n public func write(_ data: Data) throws {\n try self.write(contentsOf: data)\n }\n\n public func stream() -> AsyncStream {\n .init { cont in\n self.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n self.readabilityHandler = nil\n cont.finish()\n return\n }\n cont.yield(data)\n }\n }\n }\n}\n\n// MARK: State handler helpers\n\nextension SandboxService {\n private func addWaiter(id: String, cont: CheckedContinuation) {\n var current = self.waiters[id] ?? []\n current.append(cont)\n self.waiters[id] = current\n }\n\n private func removeWaiters(for id: String) {\n self.waiters[id] = []\n }\n\n private func setUnderlyingProcess(_ id: String, _ process: LinuxProcess) throws {\n guard var info = self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not found\")\n }\n info.process = process\n self.processes[id] = info\n }\n\n private func setProcessState(id: String, state: State) throws {\n guard var info = self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not found\")\n }\n info.state = state\n self.processes[id] = info\n }\n\n private func setContainer(_ info: ContainerInfo) {\n self.container = info\n }\n\n private func addNewProcess(_ id: String, _ config: ProcessConfiguration) {\n self.processes[id] = ProcessInfo(config: config, process: nil, state: .created)\n }\n\n private struct ProcessInfo {\n let config: ProcessConfiguration\n var process: LinuxProcess?\n var state: State\n }\n\n private struct ContainerInfo {\n let container: LinuxContainer\n let config: ContainerConfiguration\n let attachments: [Attachment]\n let bundle: ContainerClient.Bundle\n }\n\n public enum State: Sendable, Equatable {\n case created\n case booted\n case starting\n case running\n case stopping\n case stopped(Int32)\n }\n\n func setState(_ new: State) {\n self.state = new\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct ContainerDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete one or more containers\",\n aliases: [\"rm\"])\n\n @Flag(name: .shortAndLong, help: \"Force the removal of one or more running containers\")\n var force = false\n\n @Flag(name: .shortAndLong, help: \"Remove all containers\")\n var all = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Container IDs/names\")\n var containerIDs: [String] = []\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument,\n message: \"explicitly supplied container ID(s) conflict with the --all flag\"\n )\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n var containers = [ClientContainer]()\n\n if all {\n containers = try await ClientContainer.list()\n } else {\n let ctrs = try await ClientContainer.list()\n containers = ctrs.filter { c in\n set.contains(c.id)\n }\n // If one of the containers requested isn't present, let's throw. We don't need to do\n // this for --all as --all should be perfectly usable with no containers to remove; otherwise,\n // it'd be quite clunky.\n if containers.count != set.count {\n let missing = set.filter { id in\n !containers.contains { c in\n c.id == id\n }\n }\n throw ContainerizationError(\n .notFound,\n message: \"failed to delete one or more containers: \\(missing)\"\n )\n }\n }\n\n var failed = [String]()\n let force = self.force\n let all = self.all\n try await withThrowingTaskGroup(of: ClientContainer?.self) { group in\n for container in containers {\n group.addTask {\n do {\n // First we need to find if the container supports auto-remove\n // and if so we need to skip deletion.\n if container.status == .running {\n if !force {\n // We don't want to error if the user just wants all containers deleted.\n // It's implied we'll skip containers we can't actually delete.\n if all {\n return nil\n }\n throw ContainerizationError(.invalidState, message: \"container is running\")\n }\n let stopOpts = ContainerStopOptions(\n timeoutInSeconds: 5,\n signal: SIGKILL\n )\n try await container.stop(opts: stopOpts)\n }\n try await container.delete()\n print(container.id)\n return nil\n } catch {\n log.error(\"failed to delete container \\(container.id): \\(error)\")\n return container\n }\n }\n }\n\n for try await ctr in group {\n guard let ctr else {\n continue\n }\n failed.append(ctr.id)\n }\n }\n\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"delete failed for one or more containers: \\(failed)\")\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct NetworkDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete one or more networks\",\n aliases: [\"rm\"])\n\n @Flag(name: .shortAndLong, help: \"Remove all networks\")\n var all = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Network names\")\n var networkNames: [String] = []\n\n func validate() throws {\n if networkNames.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no networks specified and --all not supplied\")\n }\n if networkNames.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument,\n message: \"explicitly supplied network name(s) conflict with the --all flag\"\n )\n }\n }\n\n mutating func run() async throws {\n let uniqueNetworkNames = Set(networkNames)\n let networks: [NetworkState]\n\n if all {\n networks = try await ClientNetwork.list()\n } else {\n networks = try await ClientNetwork.list()\n .filter { c in\n uniqueNetworkNames.contains(c.id)\n }\n\n // If one of the networks requested isn't present lets throw. We don't need to do\n // this for --all as --all should be perfectly usable with no networks to remove,\n // otherwise it'd be quite clunky.\n if networks.count != uniqueNetworkNames.count {\n let missing = uniqueNetworkNames.filter { id in\n !networks.contains { n in\n n.id == id\n }\n }\n throw ContainerizationError(\n .notFound,\n message: \"failed to delete one or more networks: \\(missing)\"\n )\n }\n }\n\n if uniqueNetworkNames.contains(ClientNetwork.defaultNetworkName) {\n throw ContainerizationError(\n .invalidArgument,\n message: \"cannot delete the default network\"\n )\n }\n\n var failed = [String]()\n try await withThrowingTaskGroup(of: NetworkState?.self) { group in\n for network in networks {\n group.addTask {\n do {\n // delete atomically disables the IP allocator, then deletes\n // the allocator disable fails if any IPs are still in use\n try await ClientNetwork.delete(id: network.id)\n print(network.id)\n return nil\n } catch {\n log.error(\"failed to delete network \\(network.id): \\(error)\")\n return network\n }\n }\n }\n\n for try await network in group {\n guard let network else {\n continue\n }\n failed.append(network.id)\n }\n }\n\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"delete failed for one or more networks: \\(failed)\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginLoader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\npublic struct PluginLoader: Sendable {\n // A path on disk managed by the PluginLoader, where it stores\n // runtime data for loaded plugins. This includes the launchd plists\n // and logs files.\n private let defaultPluginResourcePath: URL\n\n private let pluginDirectories: [URL]\n\n private let pluginFactories: [PluginFactory]\n\n private let log: Logger?\n\n public typealias PluginQualifier = ((Plugin) -> Bool)\n\n public init(pluginDirectories: [URL], pluginFactories: [PluginFactory], defaultResourcePath: URL, log: Logger? = nil) {\n self.pluginDirectories = pluginDirectories\n self.pluginFactories = pluginFactories\n self.log = log\n self.defaultPluginResourcePath = defaultResourcePath\n }\n\n static public func defaultPluginResourcePath(root: URL) -> URL {\n root.appending(path: \"plugin-state\")\n }\n\n static public func userPluginsDir(root: URL) -> URL {\n root\n .appending(path: \"libexec\")\n .appending(path: \"container-plugins\")\n .resolvingSymlinksInPath()\n }\n}\n\nextension PluginLoader {\n public func alterCLIHelpText(original: String) -> String {\n var plugins = findPlugins()\n plugins = plugins.filter { $0.config.isCLI }\n guard !plugins.isEmpty else {\n return original\n }\n\n var lines = original.split(separator: \"\\n\").map { String($0) }\n\n let sectionHeader = \"PLUGINS:\"\n lines.append(sectionHeader)\n\n for plugin in plugins {\n let helpText = plugin.helpText(padding: 24)\n lines.append(helpText)\n }\n\n return lines.joined(separator: \"\\n\")\n }\n\n public func findPlugins() -> [Plugin] {\n let fm = FileManager.default\n\n var pluginNames = Set()\n var plugins: [Plugin] = []\n\n for pluginDir in pluginDirectories {\n if !fm.fileExists(atPath: pluginDir.path) {\n continue\n }\n\n guard\n var dirs = try? fm.contentsOfDirectory(\n at: pluginDir,\n includingPropertiesForKeys: [.isDirectoryKey],\n options: .skipsHiddenFiles\n )\n else {\n continue\n }\n dirs = dirs.filter {\n $0.isDirectory\n }\n\n for installURL in dirs {\n do {\n guard\n let plugin = try\n (pluginFactories.compactMap {\n try $0.create(installURL: installURL)\n }.first)\n else {\n log?.warning(\n \"Not installing plugin with missing configuration\",\n metadata: [\n \"path\": \"\\(installURL.path)\"\n ]\n )\n continue\n }\n\n guard !pluginNames.contains(plugin.name) else {\n log?.warning(\n \"Not installing shadowed plugin\",\n metadata: [\n \"path\": \"\\(installURL.path)\",\n \"name\": \"\\(plugin.name)\",\n ])\n continue\n }\n\n plugins.append(plugin)\n pluginNames.insert(plugin.name)\n } catch {\n log?.warning(\n \"Not installing plugin with invalid configuration\",\n metadata: [\n \"path\": \"\\(installURL.path)\",\n \"error\": \"\\(error)\",\n ]\n )\n }\n }\n }\n\n return plugins\n }\n\n public func findPlugin(name: String, log: Logger? = nil) -> Plugin? {\n do {\n return\n try pluginDirectories\n .compactMap { installURL in\n try pluginFactories.compactMap { try $0.create(installURL: installURL.appending(path: name)) }.first\n }\n .first\n } catch {\n log?.warning(\n \"Not installing plugin with invalid configuration\",\n metadata: [\n \"name\": \"\\(name)\",\n \"error\": \"\\(error)\",\n ]\n )\n return nil\n }\n }\n}\n\nextension PluginLoader {\n public func registerWithLaunchd(\n plugin: Plugin,\n rootURL: URL? = nil,\n args: [String]? = nil,\n instanceId: String? = nil\n ) throws {\n // We only care about loading plugins that have a service\n // to expose; otherwise, they may just be CLI commands.\n guard let serviceConfig = plugin.config.servicesConfig else {\n return\n }\n\n let id = plugin.getLaunchdLabel(instanceId: instanceId)\n log?.info(\"Registering plugin\", metadata: [\"id\": \"\\(id)\"])\n let rootURL = rootURL ?? self.defaultPluginResourcePath.appending(path: plugin.name)\n try FileManager.default.createDirectory(at: rootURL, withIntermediateDirectories: true)\n let env = ProcessInfo.processInfo.environment.filter { key, _ in\n key.hasPrefix(\"CONTAINER_\")\n }\n let logUrl = rootURL.appendingPathComponent(\"service.log\")\n let plist = LaunchPlist(\n label: id,\n arguments: [plugin.binaryURL.path] + (args ?? serviceConfig.defaultArguments),\n environment: env,\n limitLoadToSessionType: [.Aqua, .Background, .System],\n runAtLoad: serviceConfig.runAtLoad,\n stdout: logUrl.path,\n stderr: logUrl.path,\n machServices: plugin.getMachServices(instanceId: instanceId)\n )\n\n let plistUrl = rootURL.appendingPathComponent(\"service.plist\")\n let data = try plist.encode()\n try data.write(to: plistUrl)\n try ServiceManager.register(plistPath: plistUrl.path)\n }\n\n public func deregisterWithLaunchd(plugin: Plugin, instanceId: String? = nil) throws {\n // We only care about loading plugins that have a service\n // to expose; otherwise, they may just be CLI commands.\n guard plugin.config.servicesConfig != nil else {\n return\n }\n let domain = try ServiceManager.getDomainString()\n let label = \"\\(domain)/\\(plugin.getLaunchdLabel(instanceId: instanceId))\"\n log?.info(\"Deregistering plugin\", metadata: [\"id\": \"\\(plugin.getLaunchdLabel())\"])\n try ServiceManager.deregister(fullServiceLabel: label)\n }\n}\n"], ["/container/Sources/CLI/Application.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerPlugin\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport TerminalProgress\n\n// `log` is updated only once in the `validate()` method.\nnonisolated(unsafe) var log = {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"CLI\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n log.logLevel = .debug\n return log\n}()\n\n@main\nstruct Application: AsyncParsableCommand {\n @OptionGroup\n var global: Flags.Global\n\n static let configuration = CommandConfiguration(\n commandName: \"container\",\n abstract: \"A container platform for macOS\",\n version: releaseVersion(),\n subcommands: [\n DefaultCommand.self\n ],\n groupedSubcommands: [\n CommandGroup(\n name: \"Container\",\n subcommands: [\n ContainerCreate.self,\n ContainerDelete.self,\n ContainerExec.self,\n ContainerInspect.self,\n ContainerKill.self,\n ContainerList.self,\n ContainerLogs.self,\n ContainerRunCommand.self,\n ContainerStart.self,\n ContainerStop.self,\n ]\n ),\n CommandGroup(\n name: \"Image\",\n subcommands: [\n BuildCommand.self,\n ImagesCommand.self,\n RegistryCommand.self,\n ]\n ),\n CommandGroup(\n name: \"Other\",\n subcommands: Self.otherCommands()\n ),\n ],\n // Hidden command to handle plugins on unrecognized input.\n defaultSubcommand: DefaultCommand.self\n )\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n static let pluginLoader: PluginLoader = {\n let installRoot = CommandLine.executablePathUrl\n .deletingLastPathComponent()\n .appendingPathComponent(\"..\")\n .standardized\n let pluginsURL = PluginLoader.userPluginsDir(root: installRoot)\n var directoryExists: ObjCBool = false\n _ = FileManager.default.fileExists(atPath: pluginsURL.path, isDirectory: &directoryExists)\n let userPluginsURL = directoryExists.boolValue ? pluginsURL : nil\n\n // plugins built into the application installed as a macOS app bundle\n let appBundlePluginsURL = Bundle.main.resourceURL?.appending(path: \"plugins\")\n\n // plugins built into the application installed as a Unix-like application\n let installRootPluginsURL =\n installRoot\n .appendingPathComponent(\"libexec\")\n .appendingPathComponent(\"container\")\n .appendingPathComponent(\"plugins\")\n .standardized\n\n let pluginDirectories = [\n userPluginsURL,\n appBundlePluginsURL,\n installRootPluginsURL,\n ].compactMap { $0 }\n\n let pluginFactories = [\n DefaultPluginFactory()\n ]\n\n let statePath = PluginLoader.defaultPluginResourcePath(root: Self.appRoot)\n try! FileManager.default.createDirectory(at: statePath, withIntermediateDirectories: true)\n return PluginLoader(pluginDirectories: pluginDirectories, pluginFactories: pluginFactories, defaultResourcePath: statePath, log: log)\n }()\n\n public static func main() async throws {\n restoreCursorAtExit()\n\n #if DEBUG\n let warning = \"Running debug build. Performance may be degraded.\"\n let formattedWarning = \"\\u{001B}[33mWarning!\\u{001B}[0m \\(warning)\\n\"\n let warningData = Data(formattedWarning.utf8)\n FileHandle.standardError.write(warningData)\n #endif\n\n let fullArgs = CommandLine.arguments\n let args = Array(fullArgs.dropFirst())\n\n do {\n // container -> defaultHelpCommand\n var command = try Application.parseAsRoot(args)\n if var asyncCommand = command as? AsyncParsableCommand {\n try await asyncCommand.run()\n } else {\n try command.run()\n }\n } catch {\n // Regular ol `command` with no args will get caught by DefaultCommand. --help\n // on the root command will land here.\n let containsHelp = fullArgs.contains(\"-h\") || fullArgs.contains(\"--help\")\n if fullArgs.count <= 2 && containsHelp {\n Self.printModifiedHelpText()\n return\n }\n let errorAsString: String = String(describing: error)\n if errorAsString.contains(\"XPC connection error\") {\n let modifiedError = ContainerizationError(.interrupted, message: \"\\(error)\\nEnsure container system service has been started with `container system start`.\")\n Application.exit(withError: modifiedError)\n } else {\n Application.exit(withError: error)\n }\n }\n }\n\n static func handleProcess(io: ProcessIO, process: ClientProcess) async throws -> Int32 {\n let signals = AsyncSignalHandler.create(notify: Application.signalSet)\n return try await withThrowingTaskGroup(of: Int32?.self, returning: Int32.self) { group in\n let waitAdded = group.addTaskUnlessCancelled {\n let code = try await process.wait()\n try await io.wait()\n return code\n }\n\n guard waitAdded else {\n group.cancelAll()\n return -1\n }\n\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n\n if let current = io.console {\n let size = try current.size\n // It's supremely possible the process could've exited already. We shouldn't treat\n // this as fatal.\n try? await process.resize(size)\n _ = group.addTaskUnlessCancelled {\n let winchHandler = AsyncSignalHandler.create(notify: [SIGWINCH])\n for await _ in winchHandler.signals {\n do {\n try await process.resize(try current.size)\n } catch {\n log.error(\n \"failed to send terminal resize event\",\n metadata: [\n \"error\": \"\\(error)\"\n ]\n )\n }\n }\n return nil\n }\n } else {\n _ = group.addTaskUnlessCancelled {\n for await sig in signals.signals {\n do {\n try await process.kill(sig)\n } catch {\n log.error(\n \"failed to send signal\",\n metadata: [\n \"signal\": \"\\(sig)\",\n \"error\": \"\\(error)\",\n ]\n )\n }\n }\n return nil\n }\n }\n\n while true {\n let result = try await group.next()\n if result == nil {\n return -1\n }\n let status = result!\n if let status {\n group.cancelAll()\n return status\n }\n }\n return -1\n }\n }\n\n func validate() throws {\n // Not really a \"validation\", but a cheat to run this before\n // any of the commands do their business.\n let debugEnvVar = ProcessInfo.processInfo.environment[\"CONTAINER_DEBUG\"]\n if self.global.debug || debugEnvVar != nil {\n log.logLevel = .debug\n }\n // Ensure we're not running under Rosetta.\n if try isTranslated() {\n throw ValidationError(\n \"\"\"\n `container` is currently running under Rosetta Translation, which could be\n caused by your terminal application. Please ensure this is turned off.\n \"\"\"\n )\n }\n }\n\n private static func otherCommands() -> [any ParsableCommand.Type] {\n guard #available(macOS 26, *) else {\n return [\n BuilderCommand.self,\n SystemCommand.self,\n ]\n }\n\n return [\n BuilderCommand.self,\n NetworkCommand.self,\n SystemCommand.self,\n ]\n }\n\n private static func restoreCursorAtExit() {\n let signalHandler: @convention(c) (Int32) -> Void = { signal in\n let exitCode = ExitCode(signal + 128)\n Application.exit(withError: exitCode)\n }\n // Termination by Ctrl+C.\n signal(SIGINT, signalHandler)\n // Termination using `kill`.\n signal(SIGTERM, signalHandler)\n // Normal and explicit exit.\n atexit {\n if let progressConfig = try? ProgressConfig() {\n let progressBar = ProgressBar(config: progressConfig)\n progressBar.resetCursor()\n }\n }\n }\n}\n\nextension Application {\n // Because we support plugins, we need to modify the help text to display\n // any if we found some.\n static func printModifiedHelpText() {\n let altered = Self.pluginLoader.alterCLIHelpText(\n original: Application.helpMessage(for: Application.self)\n )\n print(altered)\n }\n\n enum ListFormat: String, CaseIterable, ExpressibleByArgument {\n case json\n case table\n }\n\n static let signalSet: [Int32] = [\n SIGTERM,\n SIGINT,\n SIGUSR1,\n SIGUSR2,\n SIGWINCH,\n ]\n\n func isTranslated() throws -> Bool {\n do {\n return try Sysctl.byName(\"sysctl.proc_translated\") == 1\n } catch let posixErr as POSIXError {\n if posixErr.code == .ENOENT {\n return false\n }\n throw posixErr\n }\n }\n\n private static func releaseVersion() -> String {\n var versionDetails: [String: String] = [\"build\": \"release\"]\n #if DEBUG\n versionDetails[\"build\"] = \"debug\"\n #endif\n let gitCommit = {\n let sha = get_git_commit().map { String(cString: $0) }\n guard let sha else {\n return \"unspecified\"\n }\n return String(sha.prefix(7))\n }()\n versionDetails[\"commit\"] = gitCommit\n let extras: String = versionDetails.map { \"\\($0): \\($1)\" }.sorted().joined(separator: \", \")\n\n let bundleVersion = (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String)\n let releaseVersion = bundleVersion ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n\n return \"container CLI version \\(releaseVersion) (\\(extras))\"\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerBuild\nimport ContainerClient\nimport ContainerNetworkService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct BuilderStart: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"start\"\n config._superCommandName = \"builder\"\n config.abstract = \"Start builder\"\n config.usage = \"\\nbuilder start [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64 = 2\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n public var memory: String = \"2048MB\"\n\n func run() async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n totalTasks: 4\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n try await Self.start(cpus: self.cpus, memory: self.memory, progressUpdate: progress.handler)\n progress.finish()\n }\n\n static func start(cpus: Int64?, memory: String?, progressUpdate: @escaping ProgressUpdateHandler) async throws {\n await progressUpdate([\n .setDescription(\"Fetching BuildKit image\"),\n .setItemsName(\"blobs\"),\n ])\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n\n let builderImage: String = ClientDefaults.get(key: .defaultBuilderImage)\n let exportsMount: String = Application.appRoot.appendingPathComponent(\".build\").absolutePath()\n\n if !FileManager.default.fileExists(atPath: exportsMount) {\n try FileManager.default.createDirectory(\n atPath: exportsMount,\n withIntermediateDirectories: true,\n attributes: nil\n )\n }\n\n let builderPlatform = ContainerizationOCI.Platform(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n\n let existingContainer = try? await ClientContainer.get(id: \"buildkit\")\n if let existingContainer {\n let existingImage = existingContainer.configuration.image.reference\n let existingResources = existingContainer.configuration.resources\n\n // Check if we need to recreate the builder due to different image\n let imageChanged = existingImage != builderImage\n let cpuChanged = {\n if let cpus {\n if existingResources.cpus != cpus {\n return true\n }\n }\n return false\n }()\n let memChanged = try {\n if let memory {\n let memoryInBytes = try Parser.resources(cpus: nil, memory: memory).memoryInBytes\n if existingResources.memoryInBytes != memoryInBytes {\n return true\n }\n }\n return false\n }()\n\n switch existingContainer.status {\n case .running:\n guard imageChanged || cpuChanged || memChanged else {\n // If image, mem and cpu are the same, continue using the existing builder\n return\n }\n // If they changed, stop and delete the existing builder\n try await existingContainer.stop()\n try await existingContainer.delete()\n case .stopped:\n // If the builder is stopped and matches our requirements, start it\n // Otherwise, delete it and create a new one\n guard imageChanged || cpuChanged || memChanged else {\n try await existingContainer.startBuildKit(progressUpdate, nil)\n return\n }\n try await existingContainer.delete()\n case .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"builder is stopping, please wait until it is fully stopped before proceeding\"\n )\n case .unknown:\n break\n }\n }\n\n let shimArguments: [String] = [\n \"--debug\",\n \"--vsock\",\n ]\n\n let id = \"buildkit\"\n try ContainerClient.Utility.validEntityName(id)\n\n let processConfig = ProcessConfiguration(\n executable: \"/usr/local/bin/container-builder-shim\",\n arguments: shimArguments,\n environment: [],\n workingDirectory: \"/\",\n terminal: false,\n user: .id(uid: 0, gid: 0)\n )\n\n let resources = try Parser.resources(\n cpus: cpus,\n memory: memory\n )\n\n let image = try await ClientImage.fetch(\n reference: builderImage,\n platform: builderPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progressUpdate)\n )\n // Unpack fetched image before use\n await progressUpdate([\n .setDescription(\"Unpacking BuildKit image\"),\n .setItemsName(\"entries\"),\n ])\n\n let unpackTask = await taskManager.startTask()\n _ = try await image.getCreateSnapshot(\n platform: builderPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progressUpdate)\n )\n let imageConfig = ImageDescription(\n reference: builderImage,\n descriptor: image.descriptor\n )\n\n var config = ContainerConfiguration(id: id, image: imageConfig, process: processConfig)\n config.resources = resources\n config.mounts = [\n .init(\n type: .tmpfs,\n source: \"\",\n destination: \"/run\",\n options: []\n ),\n .init(\n type: .virtiofs,\n source: exportsMount,\n destination: \"/var/lib/container-builder-shim/exports\",\n options: []\n ),\n ]\n // Enable Rosetta only if the user didn't ask to disable it\n config.rosetta = ClientDefaults.getBool(key: .buildRosetta) ?? true\n\n let network = try await ClientNetwork.get(id: ClientNetwork.defaultNetworkName)\n guard case .running(_, let networkStatus) = network else {\n throw ContainerizationError(.invalidState, message: \"default network is not running\")\n }\n config.networks = [network.id]\n let subnet = try CIDRAddress(networkStatus.address)\n let nameserver = IPv4Address(fromValue: subnet.lower.value + 1).description\n let nameservers = [nameserver]\n config.dns = ContainerConfiguration.DNSConfiguration(nameservers: nameservers)\n\n let kernel = try await {\n await progressUpdate([\n .setDescription(\"Fetching kernel\"),\n .setItemsName(\"binary\"),\n ])\n\n let kernel = try await ClientKernel.getDefaultKernel(for: .current)\n return kernel\n }()\n\n await progressUpdate([\n .setDescription(\"Starting BuildKit container\")\n ])\n\n let container = try await ClientContainer.create(\n configuration: config,\n options: .default,\n kernel: kernel\n )\n\n try await container.startBuildKit(progressUpdate, taskManager)\n }\n }\n}\n\n// MARK: - ClientContainer Extension for BuildKit\n\nextension ClientContainer {\n /// Starts the BuildKit process within the container\n /// This method handles bootstrapping the container and starting the BuildKit process\n fileprivate func startBuildKit(_ progress: @escaping ProgressUpdateHandler, _ taskManager: ProgressTaskCoordinator? = nil) async throws {\n do {\n let io = try ProcessIO.create(\n tty: false,\n interactive: false,\n detach: true\n )\n defer { try? io.close() }\n let process = try await bootstrap()\n _ = try await process.start(io.stdio)\n await taskManager?.finish()\n try io.closeAfterStart()\n log.debug(\"starting BuildKit and BuildKit-shim\")\n } catch {\n try? await stop()\n try? await delete()\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to start BuildKit: \\(error)\")\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Parser.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\npublic struct Parser {\n public static func memoryString(_ memory: String) throws -> Int64 {\n let ram = try Measurement.parse(parsing: memory)\n let mb = ram.converted(to: .mebibytes)\n return Int64(mb.value)\n }\n\n public static func user(\n user: String?, uid: UInt32?, gid: UInt32?,\n defaultUser: ProcessConfiguration.User = .id(uid: 0, gid: 0)\n ) -> (user: ProcessConfiguration.User, groups: [UInt32]) {\n\n var supplementalGroups: [UInt32] = []\n let user: ProcessConfiguration.User = {\n if let user = user, !user.isEmpty {\n return .raw(userString: user)\n }\n if let uid, let gid {\n return .id(uid: uid, gid: gid)\n }\n if uid == nil, gid == nil {\n // Neither uid nor gid is set. return the default user\n return defaultUser\n }\n // One of uid / gid is left unspecified. Set the user accordingly\n if let uid {\n return .raw(userString: \"\\(uid)\")\n }\n if let gid {\n supplementalGroups.append(gid)\n }\n return defaultUser\n }()\n return (user, supplementalGroups)\n }\n\n public static func platform(os: String, arch: String) -> ContainerizationOCI.Platform {\n .init(arch: arch, os: os)\n }\n\n public static func resources(cpus: Int64?, memory: String?) throws -> ContainerConfiguration.Resources {\n var resource = ContainerConfiguration.Resources()\n if let cpus {\n resource.cpus = Int(cpus)\n }\n if let memory {\n resource.memoryInBytes = try Parser.memoryString(memory).mib()\n }\n return resource\n }\n\n public static func allEnv(imageEnvs: [String], envFiles: [String], envs: [String]) throws -> [String] {\n var output: [String] = []\n output.append(contentsOf: Parser.env(envList: imageEnvs))\n for envFile in envFiles {\n let content = try Parser.envFile(path: envFile)\n output.append(contentsOf: content)\n }\n output.append(contentsOf: Parser.env(envList: envs))\n return output\n }\n\n static func envFile(path: String) throws -> [String] {\n guard FileManager.default.fileExists(atPath: path) else {\n throw ContainerizationError(.notFound, message: \"envfile at \\(path) not found\")\n }\n\n let data = try String(contentsOfFile: path, encoding: .utf8)\n let lines = data.components(separatedBy: .newlines)\n var envVars: [String] = []\n for line in lines {\n let line = line.trimmingCharacters(in: .whitespaces)\n if line.isEmpty {\n continue\n }\n if !line.hasPrefix(\"#\") {\n let keyVals = line.split(separator: \"=\")\n if keyVals.count != 2 {\n continue\n }\n let key = keyVals[0].trimmingCharacters(in: .whitespaces)\n let val = keyVals[1].trimmingCharacters(in: .whitespaces)\n if key.isEmpty || val.isEmpty {\n continue\n }\n envVars.append(\"\\(key)=\\(val)\")\n }\n }\n return envVars\n }\n\n static func env(envList: [String]) -> [String] {\n var envVar: [String] = []\n for env in envList {\n var env = env\n let parts = env.split(separator: \"=\", maxSplits: 2)\n if parts.count == 1 {\n guard let val = ProcessInfo.processInfo.environment[env] else {\n continue\n }\n env = \"\\(env)=\\(val)\"\n }\n envVar.append(env)\n }\n return envVar\n }\n\n static func labels(_ rawLabels: [String]) throws -> [String: String] {\n var result: [String: String] = [:]\n for label in rawLabels {\n if label.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"label cannot be an empty string\")\n }\n let parts = label.split(separator: \"=\", maxSplits: 2)\n switch parts.count {\n case 1:\n result[String(parts[0])] = \"\"\n case 2:\n result[String(parts[0])] = String(parts[1])\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid label format \\(label)\")\n }\n }\n return result\n }\n\n static func process(\n arguments: [String],\n processFlags: Flags.Process,\n managementFlags: Flags.Management,\n config: ContainerizationOCI.ImageConfig?\n ) throws -> ProcessConfiguration {\n\n let imageEnvVars = config?.env ?? []\n let envvars = try Parser.allEnv(imageEnvs: imageEnvVars, envFiles: processFlags.envFile, envs: processFlags.env)\n\n let workingDir: String = {\n if let cwd = processFlags.cwd {\n return cwd\n }\n if let cwd = config?.workingDir {\n return cwd\n }\n return \"/\"\n }()\n\n let processArguments: [String]? = {\n var result: [String] = []\n var hasEntrypointOverride: Bool = false\n // ensure the entrypoint is honored if it has been explicitly set by the user\n if let entrypoint = managementFlags.entryPoint, !entrypoint.isEmpty {\n result = [entrypoint]\n hasEntrypointOverride = true\n } else if let entrypoint = config?.entrypoint, !entrypoint.isEmpty {\n result = entrypoint\n }\n if !arguments.isEmpty {\n result.append(contentsOf: arguments)\n } else {\n if let cmd = config?.cmd, !hasEntrypointOverride, !cmd.isEmpty {\n result.append(contentsOf: cmd)\n }\n }\n return result.count > 0 ? result : nil\n }()\n\n guard let commandToRun = processArguments, commandToRun.count > 0 else {\n throw ContainerizationError(.invalidArgument, message: \"Command/Entrypoint not specified for container process\")\n }\n\n let defaultUser: ProcessConfiguration.User = {\n if let u = config?.user {\n return .raw(userString: u)\n }\n return .id(uid: 0, gid: 0)\n }()\n\n let (user, additionalGroups) = Parser.user(\n user: processFlags.user, uid: processFlags.uid,\n gid: processFlags.gid, defaultUser: defaultUser)\n\n return .init(\n executable: commandToRun.first!,\n arguments: [String](commandToRun.dropFirst()),\n environment: envvars,\n workingDirectory: workingDir,\n terminal: processFlags.tty,\n user: user,\n supplementalGroups: additionalGroups\n )\n }\n\n // MARK: Mounts\n\n static let mountTypes = [\n \"virtiofs\",\n \"bind\",\n \"tmpfs\",\n ]\n\n static let defaultDirectives = [\"type\": \"virtiofs\"]\n\n static func tmpfsMounts(_ mounts: [String]) throws -> [Filesystem] {\n var result: [Filesystem] = []\n let mounts = mounts.dedupe()\n for tmpfs in mounts {\n let fs = Filesystem.tmpfs(destination: tmpfs, options: [])\n try validateMount(fs)\n result.append(fs)\n }\n return result\n }\n\n static func mounts(_ rawMounts: [String]) throws -> [Filesystem] {\n var mounts: [Filesystem] = []\n let rawMounts = rawMounts.dedupe()\n for mount in rawMounts {\n let m = try Parser.mount(mount)\n try validateMount(m)\n mounts.append(m)\n }\n return mounts\n }\n\n static func mount(_ mount: String) throws -> Filesystem {\n let parts = mount.split(separator: \",\")\n if parts.count == 0 {\n throw ContainerizationError(.invalidArgument, message: \"invalid mount format: \\(mount)\")\n }\n var directives = defaultDirectives\n for part in parts {\n let keyVal = part.split(separator: \"=\", maxSplits: 2)\n var key = String(keyVal[0])\n var skipValue = false\n switch key {\n case \"type\", \"size\", \"mode\":\n break\n case \"source\", \"src\":\n key = \"source\"\n case \"destination\", \"dst\", \"target\":\n key = \"destination\"\n case \"readonly\", \"ro\":\n key = \"ro\"\n skipValue = true\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown directive \\(key) when parsing mount \\(mount)\")\n }\n var value = \"\"\n if !skipValue {\n if keyVal.count != 2 {\n throw ContainerizationError(.invalidArgument, message: \"invalid directive format missing value \\(part) in \\(mount)\")\n }\n value = String(keyVal[1])\n }\n directives[key] = value\n }\n\n var fs = Filesystem()\n for (key, val) in directives {\n var val = val\n let type = directives[\"type\"] ?? \"\"\n\n switch key {\n case \"type\":\n if val == \"bind\" {\n val = \"virtiofs\"\n }\n switch val {\n case \"virtiofs\":\n fs.type = Filesystem.FSType.virtiofs\n case \"tmpfs\":\n fs.type = Filesystem.FSType.tmpfs\n default:\n throw ContainerizationError(.invalidArgument, message: \"unsupported mount type \\(val)\")\n }\n\n case \"ro\":\n fs.options.append(\"ro\")\n case \"size\":\n if type != \"tmpfs\" {\n throw ContainerizationError(.invalidArgument, message: \"unsupported option size for \\(type) mount\")\n }\n var overflow: Bool\n var memory = try Parser.memoryString(val)\n (memory, overflow) = memory.multipliedReportingOverflow(by: 1024 * 1024)\n if overflow {\n throw ContainerizationError(.invalidArgument, message: \"overflow encountered when parsing memory string: \\(val)\")\n }\n let s = \"size=\\(memory)\"\n fs.options.append(s)\n case \"mode\":\n if type != \"tmpfs\" {\n throw ContainerizationError(.invalidArgument, message: \"unsupported option mode for \\(type) mount\")\n }\n let s = \"mode=\\(val)\"\n fs.options.append(s)\n case \"source\":\n let absPath = URL(filePath: val).absoluteURL.path\n switch type {\n case \"virtiofs\", \"bind\":\n fs.source = absPath\n case \"tmpfs\":\n throw ContainerizationError(.invalidArgument, message: \"cannot specify source for tmpfs mount\")\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown mount type \\(type)\")\n }\n case \"destination\":\n fs.destination = val\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown mount directive \\(key)\")\n }\n }\n return fs\n }\n\n static func volumes(_ rawVolumes: [String]) throws -> [Filesystem] {\n var mounts: [Filesystem] = []\n for volume in rawVolumes {\n let m = try Parser.volume(volume)\n try Parser.validateMount(m)\n mounts.append(m)\n }\n return mounts\n }\n\n private static func volume(_ volume: String) throws -> Filesystem {\n var vol = volume\n vol.trimLeft(char: \":\")\n\n let parts = vol.split(separator: \":\")\n switch parts.count {\n case 1:\n throw ContainerizationError(.invalidArgument, message: \"anonymous volumes are not supported\")\n case 2, 3:\n // Bind / volume mounts.\n let src = String(parts[0])\n let dst = String(parts[1])\n\n let abs = URL(filePath: src).absoluteURL.path\n if !FileManager.default.fileExists(atPath: abs) {\n throw ContainerizationError(.invalidArgument, message: \"named volumes are not supported\")\n }\n\n var fs = Filesystem.virtiofs(\n source: URL(fileURLWithPath: src).absolutePath(),\n destination: dst,\n options: []\n )\n if parts.count == 3 {\n fs.options = parts[2].split(separator: \",\").map { String($0) }\n }\n return fs\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid volume format \\(volume)\")\n }\n }\n\n static func validMountType(_ type: String) -> Bool {\n mountTypes.contains(type)\n }\n\n static func validateMount(_ mount: Filesystem) throws {\n if !mount.isTmpfs {\n if !mount.source.isAbsolutePath() {\n throw ContainerizationError(\n .invalidArgument, message: \"\\(mount.source) is not an absolute path on the host\")\n }\n if !FileManager.default.fileExists(atPath: mount.source) {\n throw ContainerizationError(.invalidArgument, message: \"file path '\\(mount.source)' does not exist\")\n }\n }\n\n if mount.destination.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"mount destination cannot be empty\")\n }\n }\n\n /// Parse --publish-port arguments into PublishPort objects\n /// The format of each argument is `[host-ip:]host-port:container-port[/protocol]`\n /// (e.g., \"127.0.0.1:8080:80/tcp\")\n ///\n /// - Parameter rawPublishPorts: Array of port arguments\n /// - Returns: Array of PublishPort objects\n /// - Throws: ContainerizationError if parsing fails\n static func publishPorts(_ rawPublishPorts: [String]) throws -> [PublishPort] {\n var sockets: [PublishPort] = []\n\n // Process each raw port string\n for socket in rawPublishPorts {\n let parsedSocket = try Parser.publishPort(socket)\n sockets.append(parsedSocket)\n }\n return sockets\n }\n\n // Parse a single `--publish-port` argument into a `PublishPort`.\n private static func publishPort(_ portText: String) throws -> PublishPort {\n let protoSplit = portText.split(separator: \"/\")\n let proto: PublishProtocol\n let addressAndPortText: String\n switch protoSplit.count {\n case 1:\n addressAndPortText = String(protoSplit[0])\n proto = .tcp\n case 2:\n addressAndPortText = String(protoSplit[0])\n let protoText = String(protoSplit[1])\n guard let parsedProto = PublishProtocol(protoText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish protocol: \\(protoText)\")\n }\n proto = parsedProto\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid publish value: \\(portText)\")\n }\n\n let hostAddress: String\n let hostPortText: String\n let containerPortText: String\n let parts = addressAndPortText.split(separator: \":\")\n switch parts.count {\n case 2:\n hostAddress = \"0.0.0.0\"\n hostPortText = String(parts[0])\n containerPortText = String(parts[1])\n case 3:\n hostAddress = String(parts[0])\n hostPortText = String(parts[1])\n containerPortText = String(parts[2])\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid publish address: \\(portText)\")\n }\n\n guard let hostPort = Int(hostPortText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish host port: \\(hostPortText)\")\n }\n\n guard let containerPort = Int(containerPortText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish container port: \\(containerPortText)\")\n }\n\n return PublishPort(\n hostAddress: hostAddress,\n hostPort: hostPort,\n containerPort: containerPort,\n proto: proto\n )\n }\n\n /// Parse --publish-socket arguments into PublishSocket objects\n /// The format of each argument is `host_path:container_path`\n /// (e.g., \"/tmp/docker.sock:/var/run/docker.sock\")\n ///\n /// - Parameter rawPublishSockets: Array of socket arguments\n /// - Returns: Array of PublishSocket objects\n /// - Throws: ContainerizationError if parsing fails or a path is invalid\n static func publishSockets(_ rawPublishSockets: [String]) throws -> [PublishSocket] {\n var sockets: [PublishSocket] = []\n\n // Process each raw socket string\n for socket in rawPublishSockets {\n let parsedSocket = try Parser.publishSocket(socket)\n sockets.append(parsedSocket)\n }\n return sockets\n }\n\n // Parse a single `--publish-socket`` argument into a `PublishSocket`.\n private static func publishSocket(_ socketText: String) throws -> PublishSocket {\n // Split by colon to two parts: [host_path, container_path]\n let parts = socketText.split(separator: \":\")\n\n switch parts.count {\n case 2:\n // Extract host and container paths\n let hostPath = String(parts[0])\n let containerPath = String(parts[1])\n\n // Validate paths are not empty\n if hostPath.isEmpty {\n throw ContainerizationError(\n .invalidArgument, message: \"host socket path cannot be empty\")\n }\n if containerPath.isEmpty {\n throw ContainerizationError(\n .invalidArgument, message: \"container socket path cannot be empty\")\n }\n\n // Ensure container path must start with /\n if !containerPath.hasPrefix(\"/\") {\n throw ContainerizationError(\n .invalidArgument,\n message: \"container socket path must be absolute: \\(containerPath)\")\n }\n\n // Convert host path to absolute path for consistency\n let hostURL = URL(fileURLWithPath: hostPath)\n let absoluteHostPath = hostURL.absoluteURL.path\n\n // Check if host socket already exists and might be in use\n if FileManager.default.fileExists(atPath: absoluteHostPath) {\n do {\n let attrs = try FileManager.default.attributesOfItem(atPath: absoluteHostPath)\n if let fileType = attrs[.type] as? FileAttributeType, fileType == .typeSocket {\n throw ContainerizationError(\n .invalidArgument,\n message: \"host socket \\(absoluteHostPath) already exists and may be in use\")\n }\n // If it exists but is not a socket, we can remove it and create socket\n try FileManager.default.removeItem(atPath: absoluteHostPath)\n } catch let error as ContainerizationError {\n throw error\n } catch {\n // For other file system errors, continue with creation\n }\n }\n\n // Create host directory if it doesn't exist\n let hostDir = hostURL.deletingLastPathComponent()\n if !FileManager.default.fileExists(atPath: hostDir.path) {\n try FileManager.default.createDirectory(\n at: hostDir, withIntermediateDirectories: true)\n }\n\n // Create and return PublishSocket object with validated paths\n return PublishSocket(\n containerPath: URL(fileURLWithPath: containerPath),\n hostPath: URL(fileURLWithPath: absoluteHostPath),\n permissions: nil\n )\n\n default:\n throw ContainerizationError(\n .invalidArgument,\n message:\n \"invalid publish-socket format \\(socketText). Expected: host_path:container_path\")\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension String {\n fileprivate var fs_cleaned: String {\n var value = self\n\n if value.hasPrefix(\"file://\") {\n value.removeFirst(\"file://\".count)\n }\n\n if value.count > 1 && value.last == \"/\" {\n value.removeLast()\n }\n\n return value.removingPercentEncoding ?? value\n }\n\n fileprivate var fs_components: [String] {\n var parts: [String] = []\n for segment in self.split(separator: \"/\", omittingEmptySubsequences: true) {\n switch segment {\n case \".\":\n continue\n case \"..\":\n if !parts.isEmpty { parts.removeLast() }\n default:\n parts.append(String(segment))\n }\n }\n return parts\n }\n\n fileprivate var fs_isAbsolute: Bool { first == \"/\" }\n}\n\nextension URL {\n var cleanPath: String {\n self.path.fs_cleaned\n }\n\n func parentOf(_ url: URL) -> Bool {\n let parentPath = self.absoluteURL.cleanPath\n let childPath = url.absoluteURL.cleanPath\n\n guard parentPath.fs_isAbsolute else {\n return true\n }\n\n let parentParts = parentPath.fs_components\n let childParts = childPath.fs_components\n\n guard parentParts.count <= childParts.count else { return false }\n return zip(parentParts, childParts).allSatisfy { $0 == $1 }\n }\n\n func relativeChildPath(to context: URL) throws -> String {\n guard context.parentOf(self) else {\n throw BuildFSSync.Error.pathIsNotChild(cleanPath, context.cleanPath)\n }\n\n let ctxParts = context.cleanPath.fs_components\n let selfParts = cleanPath.fs_components\n\n return selfParts.dropFirst(ctxParts.count).joined(separator: \"/\")\n }\n\n func relativePathFrom(from base: URL) -> String {\n let destParts = cleanPath.fs_components\n let baseParts = base.cleanPath.fs_components\n\n let common = zip(destParts, baseParts).prefix { $0 == $1 }.count\n guard common > 0 else { return cleanPath }\n\n let ups = Array(repeating: \"..\", count: baseParts.count - common)\n let remainder = destParts.dropFirst(common)\n return (ups + remainder).joined(separator: \"/\")\n }\n\n func zeroCopyReader(\n chunk: Int = 1024 * 1024,\n buffer: AsyncStream.Continuation.BufferingPolicy = .unbounded\n ) throws -> AsyncStream {\n\n let path = self.cleanPath\n let fd = open(path, O_RDONLY | O_NONBLOCK)\n guard fd >= 0 else { throw POSIXError.fromErrno() }\n\n let channel = DispatchIO(\n type: .stream,\n fileDescriptor: fd,\n queue: .global(qos: .userInitiated)\n ) { errno in\n close(fd)\n }\n\n channel.setLimit(highWater: chunk)\n return AsyncStream(bufferingPolicy: buffer) { continuation in\n\n channel.read(\n offset: 0, length: Int.max,\n queue: .global(qos: .userInitiated)\n ) { done, ddata, err in\n if err != 0 {\n continuation.finish()\n return\n }\n\n if let ddata, ddata.count > -1 {\n let data = Data(ddata)\n\n switch continuation.yield(data) {\n case .terminated:\n channel.close(flags: .stop)\n default: break\n }\n }\n\n if done {\n channel.close(flags: .stop)\n continuation.finish()\n }\n }\n }\n }\n\n func bufferedCopyReader(chunkSize: Int = 4 * 1024 * 1024) throws -> BufferedCopyReader {\n try BufferedCopyReader(url: self, chunkSize: chunkSize)\n }\n}\n\n/// A synchronous buffered reader that reads one chunk at a time from a file\n/// Uses a configurable buffer size (default 4MB) and only reads when nextChunk() is called\n/// Implements AsyncSequence for use with `for await` loops\npublic final class BufferedCopyReader: AsyncSequence {\n public typealias Element = Data\n public typealias AsyncIterator = BufferedCopyReaderIterator\n\n private let inputStream: InputStream\n private let chunkSize: Int\n private var isFinished: Bool = false\n private let reusableBuffer: UnsafeMutablePointer\n\n /// Initialize a buffered copy reader for the given URL\n /// - Parameters:\n /// - url: The file URL to read from\n /// - chunkSize: Size of each chunk to read (default: 4MB)\n public init(url: URL, chunkSize: Int = 4 * 1024 * 1024) throws {\n guard let stream = InputStream(url: url) else {\n throw CocoaError(.fileReadNoSuchFile)\n }\n self.inputStream = stream\n self.chunkSize = chunkSize\n self.reusableBuffer = UnsafeMutablePointer.allocate(capacity: chunkSize)\n self.inputStream.open()\n }\n\n deinit {\n inputStream.close()\n reusableBuffer.deallocate()\n }\n\n /// Create an async iterator for this sequence\n public func makeAsyncIterator() -> BufferedCopyReaderIterator {\n BufferedCopyReaderIterator(reader: self)\n }\n\n /// Read the next chunk of data from the file\n /// - Returns: Data chunk, or nil if end of file reached\n /// - Throws: Any file reading errors\n public func nextChunk() throws -> Data? {\n guard !isFinished else { return nil }\n\n // Read directly into our reusable buffer\n let bytesRead = inputStream.read(reusableBuffer, maxLength: chunkSize)\n\n // Check for errors\n if bytesRead < 0 {\n if let error = inputStream.streamError {\n throw error\n }\n throw CocoaError(.fileReadUnknown)\n }\n\n // If we read no data, we've reached the end\n if bytesRead == 0 {\n isFinished = true\n return nil\n }\n\n // If we read less than the chunk size, this is the last chunk\n if bytesRead < chunkSize {\n isFinished = true\n }\n\n // Create Data object only with the bytes actually read\n return Data(bytes: reusableBuffer, count: bytesRead)\n }\n\n /// Check if the reader has finished reading the file\n public var hasFinished: Bool {\n isFinished\n }\n\n /// Reset the reader to the beginning of the file\n /// Note: InputStream doesn't support seeking, so this recreates the stream\n /// - Throws: Any file opening errors\n public func reset() throws {\n inputStream.close()\n // Note: InputStream doesn't provide a way to get the original URL,\n // so reset functionality is limited. Consider removing this method\n // or storing the original URL if reset is needed.\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Reset not supported with InputStream-based implementation\"\n ])\n }\n\n /// Get the current file offset\n /// Note: InputStream doesn't provide offset information\n /// - Returns: Current position in the file\n /// - Throws: Unsupported operation error\n public func currentOffset() throws -> UInt64 {\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Offset tracking not supported with InputStream-based implementation\"\n ])\n }\n\n /// Seek to a specific offset in the file\n /// Note: InputStream doesn't support seeking\n /// - Parameter offset: The byte offset to seek to\n /// - Throws: Unsupported operation error\n public func seek(to offset: UInt64) throws {\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Seeking not supported with InputStream-based implementation\"\n ])\n }\n\n /// Close the input stream explicitly (called automatically in deinit)\n public func close() {\n inputStream.close()\n isFinished = true\n }\n}\n\n/// AsyncIteratorProtocol implementation for BufferedCopyReader\npublic struct BufferedCopyReaderIterator: AsyncIteratorProtocol {\n public typealias Element = Data\n\n private let reader: BufferedCopyReader\n\n init(reader: BufferedCopyReader) {\n self.reader = reader\n }\n\n /// Get the next chunk of data asynchronously\n /// - Returns: Next data chunk, or nil when finished\n /// - Throws: Any file reading errors\n public mutating func next() async throws -> Data? {\n // Yield control to allow other tasks to run, then read synchronously\n await Task.yield()\n return try reader.nextChunk()\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct ContainerStop: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"stop\",\n abstract: \"Stop one or more running containers\")\n\n @Flag(name: .shortAndLong, help: \"Stop all running containers\")\n var all = false\n\n @Option(name: .shortAndLong, help: \"Signal to send the container(s)\")\n var signal: String = \"SIGTERM\"\n\n @Option(name: .shortAndLong, help: \"Seconds to wait before killing the container(s)\")\n var time: Int32 = 5\n\n @Argument\n var containerIDs: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument, message: \"explicitly supplied container IDs conflicts with the --all flag\")\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n var containers = [ClientContainer]()\n if self.all {\n containers = try await ClientContainer.list()\n } else {\n containers = try await ClientContainer.list().filter { c in\n set.contains(c.id)\n }\n }\n\n let opts = ContainerStopOptions(\n timeoutInSeconds: self.time,\n signal: try Signals.parseSignal(self.signal)\n )\n let failed = try await Self.stopContainers(containers: containers, stopOptions: opts)\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"stop failed for one or more containers \\(failed.joined(separator: \",\"))\")\n }\n }\n\n static func stopContainers(containers: [ClientContainer], stopOptions: ContainerStopOptions) async throws -> [String] {\n var failed: [String] = []\n try await withThrowingTaskGroup(of: ClientContainer?.self) { group in\n for container in containers {\n group.addTask {\n do {\n try await container.stop(opts: stopOptions)\n print(container.id)\n return nil\n } catch {\n log.error(\"failed to stop container \\(container.id): \\(error)\")\n return container\n }\n }\n }\n\n for try await ctr in group {\n guard let ctr else {\n continue\n }\n failed.append(ctr.id)\n }\n }\n\n return failed\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemLogs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport OSLog\n\nextension Application {\n struct SystemLogs: AsyncParsableCommand {\n static let subsystem = \"com.apple.container\"\n\n static let configuration = CommandConfiguration(\n commandName: \"logs\",\n abstract: \"Fetch system logs for `container` services\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(\n name: .long,\n help: \"Fetch logs starting from the specified time period (minus the current time); supported formats: m, h, d\"\n )\n var last: String = \"5m\"\n\n @Flag(name: .shortAndLong, help: \"Follow log output\")\n var follow: Bool = false\n\n func run() async throws {\n let process = Process()\n let sigHandler = AsyncSignalHandler.create(notify: [SIGINT, SIGTERM])\n\n Task {\n for await _ in sigHandler.signals {\n process.terminate()\n Darwin.exit(0)\n }\n }\n\n do {\n var args = [\"log\"]\n args.append(self.follow ? \"stream\" : \"show\")\n args.append(contentsOf: [\"--info\", \"--debug\"])\n if !self.follow {\n args.append(contentsOf: [\"--last\", last])\n }\n args.append(contentsOf: [\"--predicate\", \"subsystem = 'com.apple.container'\"])\n\n process.launchPath = \"/usr/bin/env\"\n process.arguments = args\n\n process.standardOutput = FileHandle.standardOutput\n process.standardError = FileHandle.standardError\n\n try process.run()\n process.waitUntilExit()\n } catch {\n throw ContainerizationError(\n .invalidArgument,\n message: \"failed to system logs: \\(error)\"\n )\n }\n throw ArgumentParser.ExitCode(process.terminationStatus)\n }\n }\n}\n"], ["/container/Sources/CLI/Registry/Login.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Login: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: \"Login to a registry\"\n )\n\n @Option(name: .shortAndLong, help: \"Username\")\n var username: String = \"\"\n\n @Flag(help: \"Take the password from stdin\")\n var passwordStdin: Bool = false\n\n @Argument(help: \"Registry server name\")\n var server: String\n\n @OptionGroup\n var registry: Flags.Registry\n\n func run() async throws {\n var username = self.username\n var password = \"\"\n if passwordStdin {\n if username == \"\" {\n throw ContainerizationError(\n .invalidArgument, message: \"must provide --username with --password-stdin\")\n }\n guard let passwordData = try FileHandle.standardInput.readToEnd() else {\n throw ContainerizationError(.invalidArgument, message: \"failed to read password from stdin\")\n }\n password = String(decoding: passwordData, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)\n }\n let keychain = KeychainHelper(id: Constants.keychainID)\n if username == \"\" {\n username = try keychain.userPrompt(domain: server)\n }\n if password == \"\" {\n password = try keychain.passwordPrompt()\n print()\n }\n\n let server = Reference.resolveDomain(domain: server)\n let scheme = try RequestScheme(registry.scheme).schemeFor(host: server)\n let _url = \"\\(scheme)://\\(server)\"\n guard let url = URL(string: _url) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n guard let host = url.host else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid host \\(server)\")\n }\n\n let client = RegistryClient(\n host: host,\n scheme: scheme.rawValue,\n port: url.port,\n authentication: BasicAuthentication(username: username, password: password),\n retryOptions: .init(\n maxRetries: 10,\n retryInterval: 300_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n )\n try await client.ping()\n try keychain.save(domain: server, username: username, password: password)\n print(\"Login succeeded\")\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImageList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ListImageOptions: ParsableArguments {\n @Flag(name: .shortAndLong, help: \"Only output the image name\")\n var quiet = false\n\n @Flag(name: .shortAndLong, help: \"Verbose output\")\n var verbose = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n }\n\n struct ListImageImplementation {\n static private func createHeader() -> [[String]] {\n [[\"NAME\", \"TAG\", \"DIGEST\"]]\n }\n\n static private func createVerboseHeader() -> [[String]] {\n [[\"NAME\", \"TAG\", \"INDEX DIGEST\", \"OS\", \"ARCH\", \"VARIANT\", \"SIZE\", \"CREATED\", \"MANIFEST DIGEST\"]]\n }\n\n static private func printImagesVerbose(images: [ClientImage]) async throws {\n\n var rows = createVerboseHeader()\n for image in images {\n let formatter = ByteCountFormatter()\n for descriptor in try await image.index().manifests {\n // Don't list attestation manifests\n if let referenceType = descriptor.annotations?[\"vnd.docker.reference.type\"],\n referenceType == \"attestation-manifest\"\n {\n continue\n }\n\n guard let platform = descriptor.platform else {\n continue\n }\n\n let os = platform.os\n let arch = platform.architecture\n let variant = platform.variant ?? \"\"\n\n var config: ContainerizationOCI.Image\n var manifest: ContainerizationOCI.Manifest\n do {\n config = try await image.config(for: platform)\n manifest = try await image.manifest(for: platform)\n } catch {\n continue\n }\n\n let created = config.created ?? \"\"\n let size = descriptor.size + manifest.config.size + manifest.layers.reduce(0, { (l, r) in l + r.size })\n let formattedSize = formatter.string(fromByteCount: size)\n\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n let reference = try ContainerizationOCI.Reference.parse(processedReferenceString)\n let row = [\n reference.name,\n reference.tag ?? \"\",\n Utility.trimDigest(digest: image.descriptor.digest),\n os,\n arch,\n variant,\n formattedSize,\n created,\n Utility.trimDigest(digest: descriptor.digest),\n ]\n rows.append(row)\n }\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n\n static private func printImages(images: [ClientImage], format: ListFormat, options: ListImageOptions) async throws {\n var images = images\n images.sort {\n $0.reference < $1.reference\n }\n\n if format == .json {\n let data = try JSONEncoder().encode(images.map { $0.description })\n print(String(data: data, encoding: .utf8)!)\n return\n }\n\n if options.quiet {\n try images.forEach { image in\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n print(processedReferenceString)\n }\n return\n }\n\n if options.verbose {\n try await Self.printImagesVerbose(images: images)\n return\n }\n\n var rows = createHeader()\n for image in images {\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n let reference = try ContainerizationOCI.Reference.parse(processedReferenceString)\n rows.append([\n reference.name,\n reference.tag ?? \"\",\n Utility.trimDigest(digest: image.descriptor.digest),\n ])\n }\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n\n static func validate(options: ListImageOptions) throws {\n if options.quiet && options.verbose {\n throw ContainerizationError(.invalidArgument, message: \"Cannot use flag --quite and --verbose together\")\n }\n let modifier = options.quiet || options.verbose\n if modifier && options.format == .json {\n throw ContainerizationError(.invalidArgument, message: \"Cannot use flag --quite or --verbose along with --format json\")\n }\n }\n\n static func listImages(options: ListImageOptions) async throws {\n let images = try await ClientImage.list().filter { img in\n !Utility.isInfraImage(name: img.reference)\n }\n try await printImages(images: images, format: options.format, options: options)\n }\n }\n\n struct ImageList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List images\",\n aliases: [\"ls\"])\n\n @OptionGroup\n var options: ListImageOptions\n\n mutating func run() async throws {\n try ListImageImplementation.validate(options: options)\n try await ListImageImplementation.listImages(options: options)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Archiver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationArchive\nimport ContainerizationOS\nimport Foundation\n\npublic final class Archiver: Sendable {\n public struct ArchiveEntryInfo: Sendable {\n let pathOnHost: URL\n let pathInArchive: URL\n\n public init(pathOnHost: URL, pathInArchive: URL) {\n self.pathOnHost = pathOnHost\n self.pathInArchive = pathInArchive\n }\n }\n\n public static func compress(\n source: URL,\n destination: URL,\n followSymlinks: Bool = false,\n writerConfiguration: ArchiveWriterConfiguration = ArchiveWriterConfiguration(format: .paxRestricted, filter: .gzip),\n closure: (URL) -> ArchiveEntryInfo?\n ) throws {\n let source = source.standardizedFileURL\n let destination = destination.standardizedFileURL\n\n let fileManager = FileManager.default\n try? fileManager.removeItem(at: destination)\n\n do {\n let directory = destination.deletingLastPathComponent()\n try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)\n\n guard\n let enumerator = FileManager.default.enumerator(\n at: source,\n includingPropertiesForKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]\n )\n else {\n throw Error.fileDoesNotExist(source)\n }\n\n var entryInfo = [ArchiveEntryInfo]()\n if !source.isDirectory {\n if let info = closure(source) {\n entryInfo.append(info)\n }\n } else {\n while let url = enumerator.nextObject() as? URL {\n guard let info = closure(url) else {\n continue\n }\n entryInfo.append(info)\n }\n }\n\n let archiver = try ArchiveWriter(\n configuration: writerConfiguration\n )\n try archiver.open(file: destination)\n\n for info in entryInfo {\n guard let entry = try Self._createEntry(entryInfo: info) else {\n throw Error.failedToCreateEntry\n }\n try Self._compressFile(item: info.pathOnHost, entry: entry, archiver: archiver)\n }\n try archiver.finishEncoding()\n } catch {\n try? fileManager.removeItem(at: destination)\n throw error\n }\n }\n\n public static func uncompress(source: URL, destination: URL) throws {\n let source = source.standardizedFileURL\n let destination = destination.standardizedFileURL\n\n // TODO: ArchiveReader needs some enhancement to support buffered uncompression\n let reader = try ArchiveReader(\n format: .paxRestricted,\n filter: .gzip,\n file: source\n )\n\n for (entry, data) in reader {\n guard let path = entry.path else {\n continue\n }\n let uncompressPath = destination.appendingPathComponent(path)\n\n let fileManager = FileManager.default\n switch entry.fileType {\n case .blockSpecial, .characterSpecial, .socket:\n continue\n case .directory:\n try fileManager.createDirectory(\n at: uncompressPath,\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: entry.permissions\n ]\n )\n case .regular:\n try fileManager.createDirectory(\n at: uncompressPath.deletingLastPathComponent(),\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: 0o755\n ]\n )\n let success = fileManager.createFile(\n atPath: uncompressPath.path,\n contents: data,\n attributes: [\n FileAttributeKey.posixPermissions: entry.permissions\n ]\n )\n if !success {\n throw POSIXError.fromErrno()\n }\n try data.write(to: uncompressPath)\n case .symbolicLink:\n guard let target = entry.symlinkTarget else {\n continue\n }\n try fileManager.createDirectory(\n at: uncompressPath.deletingLastPathComponent(),\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: 0o755\n ]\n )\n try fileManager.createSymbolicLink(atPath: uncompressPath.path, withDestinationPath: target)\n continue\n default:\n continue\n }\n\n // FIXME: uid/gid for compress.\n try fileManager.setAttributes(\n [.posixPermissions: NSNumber(value: entry.permissions)],\n ofItemAtPath: uncompressPath.path\n )\n\n if let creationDate = entry.creationDate {\n try fileManager.setAttributes(\n [.creationDate: creationDate],\n ofItemAtPath: uncompressPath.path\n )\n }\n\n if let modificationDate = entry.modificationDate {\n try fileManager.setAttributes(\n [.modificationDate: modificationDate],\n ofItemAtPath: uncompressPath.path\n )\n }\n }\n }\n\n // MARK: private functions\n private static func _compressFile(item: URL, entry: WriteEntry, archiver: ArchiveWriter) throws {\n guard let stream = InputStream(url: item) else {\n return\n }\n\n let writer = archiver.makeTransactionWriter()\n\n let bufferSize = Int(1.mib())\n let readBuffer = UnsafeMutablePointer.allocate(capacity: bufferSize)\n\n stream.open()\n try writer.writeHeader(entry: entry)\n while true {\n let byteRead = stream.read(readBuffer, maxLength: bufferSize)\n if byteRead <= 0 {\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n try data.withUnsafeBytes { pointer in\n try writer.writeChunk(data: pointer)\n }\n }\n }\n stream.close()\n try writer.finish()\n }\n\n private static func _createEntry(entryInfo: ArchiveEntryInfo, pathPrefix: String = \"\") throws -> WriteEntry? {\n let entry = WriteEntry()\n let fileManager = FileManager.default\n let attributes = try fileManager.attributesOfItem(atPath: entryInfo.pathOnHost.path)\n\n if let fileType = attributes[.type] as? FileAttributeType {\n switch fileType {\n case .typeBlockSpecial, .typeCharacterSpecial, .typeSocket:\n return nil\n case .typeDirectory:\n entry.fileType = .directory\n case .typeRegular:\n entry.fileType = .regular\n case .typeSymbolicLink:\n entry.fileType = .symbolicLink\n let symlinkTarget = try fileManager.destinationOfSymbolicLink(atPath: entryInfo.pathOnHost.path)\n entry.symlinkTarget = symlinkTarget\n default:\n return nil\n }\n }\n if let posixPermissions = attributes[.posixPermissions] as? NSNumber {\n #if os(macOS)\n entry.permissions = posixPermissions.uint16Value\n #else\n entry.permissions = posixPermissions.uint32Value\n #endif\n }\n if let fileSize = attributes[.size] as? UInt64 {\n entry.size = Int64(fileSize)\n }\n if let uid = attributes[.ownerAccountID] as? NSNumber {\n entry.owner = uid.uint32Value\n }\n if let gid = attributes[.groupOwnerAccountID] as? NSNumber {\n entry.group = gid.uint32Value\n }\n if let creationDate = attributes[.creationDate] as? Date {\n entry.creationDate = creationDate\n }\n if let modificationDate = attributes[.modificationDate] as? Date {\n entry.modificationDate = modificationDate\n }\n\n let pathTrimmed = Self._trimPathPrefix(entryInfo.pathInArchive.relativePath, pathPrefix: pathPrefix)\n entry.path = pathTrimmed\n return entry\n }\n\n private static func _trimPathPrefix(_ path: String, pathPrefix: String) -> String {\n guard !path.isEmpty && !pathPrefix.isEmpty else {\n return path\n }\n\n let decodedPath = path.removingPercentEncoding ?? path\n\n guard decodedPath.hasPrefix(pathPrefix) else {\n return decodedPath\n }\n let trimmedPath = String(decodedPath.suffix(from: pathPrefix.endIndex))\n return trimmedPath\n }\n\n private static func _isSymbolicLink(_ path: URL) throws -> Bool {\n let resourceValues = try path.resourceValues(forKeys: [.isSymbolicLinkKey])\n if let isSymbolicLink = resourceValues.isSymbolicLink {\n if isSymbolicLink {\n return true\n }\n }\n return false\n }\n}\n\nextension Archiver {\n public enum Error: Swift.Error, CustomStringConvertible {\n case failedToCreateEntry\n case fileDoesNotExist(_ url: URL)\n\n public var description: String {\n switch self {\n case .failedToCreateEntry:\n return \"failed to create entry\"\n case .fileDoesNotExist(let url):\n return \"file \\(url.path) does not exist\"\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIO\nimport NIOHPACK\nimport NIOHTTP2\n\npublic struct Builder: Sendable {\n let client: BuilderClientProtocol\n let clientAsync: BuilderClientAsyncProtocol\n let group: EventLoopGroup\n let builderShimSocket: FileHandle\n let channel: GRPCChannel\n\n public init(socket: FileHandle, group: EventLoopGroup) throws {\n try socket.setSendBufSize(4 << 20)\n try socket.setRecvBufSize(2 << 20)\n var config = ClientConnection.Configuration.default(\n target: .connectedSocket(socket.fileDescriptor),\n eventLoopGroup: group\n )\n config.connectionIdleTimeout = TimeAmount(.seconds(600))\n config.connectionKeepalive = .init(\n interval: TimeAmount(.seconds(600)),\n timeout: TimeAmount(.seconds(500)),\n permitWithoutCalls: true\n )\n config.connectionBackoff = .init(\n initialBackoff: TimeInterval(1),\n maximumBackoff: TimeInterval(10)\n )\n config.callStartBehavior = .fastFailure\n config.httpMaxFrameSize = 8 << 10\n config.maximumReceiveMessageLength = 512 << 20\n config.httpTargetWindowSize = 16 << 10\n\n let channel = ClientConnection(configuration: config)\n self.channel = channel\n self.clientAsync = BuilderClientAsync(channel: channel)\n self.client = BuilderClient(channel: channel)\n self.group = group\n self.builderShimSocket = socket\n }\n\n public func info() throws -> InfoResponse {\n let resp = self.client.info(InfoRequest(), callOptions: CallOptions())\n return try resp.response.wait()\n }\n\n public func info() async throws -> InfoResponse {\n let opts = CallOptions(timeLimit: .timeout(.seconds(30)))\n return try await self.clientAsync.info(InfoRequest(), callOptions: opts)\n }\n\n // TODO\n // - Symlinks in build context dir\n // - cache-to, cache-from\n // - output (other than the default OCI image output, e.g., local, tar, Docker)\n public func build(_ config: BuildConfig) async throws {\n var continuation: AsyncStream.Continuation?\n let reqStream = AsyncStream { (cont: AsyncStream.Continuation) in\n continuation = cont\n }\n guard let continuation else {\n throw Error.invalidContinuation\n }\n\n defer {\n continuation.finish()\n }\n\n if let terminal = config.terminal {\n Task {\n let winchHandler = AsyncSignalHandler.create(notify: [SIGWINCH])\n let setWinch = { (rows: UInt16, cols: UInt16) in\n var winch = ClientStream()\n winch.command = .init()\n if let cmdString = try TerminalCommand(rows: rows, cols: cols).json() {\n winch.command.command = cmdString\n continuation.yield(winch)\n }\n }\n let size = try terminal.size\n var width = size.width\n var height = size.height\n try setWinch(height, width)\n\n for await _ in winchHandler.signals {\n let size = try terminal.size\n let cols = size.width\n let rows = size.height\n if cols != width || rows != height {\n width = cols\n height = rows\n try setWinch(height, width)\n }\n }\n }\n }\n\n let respStream = self.clientAsync.performBuild(reqStream, callOptions: try CallOptions(config))\n let pipeline = try await BuildPipeline(config)\n do {\n try await pipeline.run(sender: continuation, receiver: respStream)\n } catch Error.buildComplete {\n _ = channel.close()\n try await group.shutdownGracefully()\n return\n }\n }\n\n public struct BuildExport: Sendable {\n public let type: String\n public var destination: URL?\n public let additionalFields: [String: String]\n public let rawValue: String\n\n public init(type: String, destination: URL?, additionalFields: [String: String], rawValue: String) {\n self.type = type\n self.destination = destination\n self.additionalFields = additionalFields\n self.rawValue = rawValue\n }\n\n public init(from input: String) throws {\n var typeValue: String?\n var destinationValue: URL?\n var additionalFields: [String: String] = [:]\n\n let pairs = input.components(separatedBy: \",\")\n for pair in pairs {\n let parts = pair.components(separatedBy: \"=\")\n guard parts.count == 2 else { continue }\n\n let key = parts[0].trimmingCharacters(in: .whitespaces)\n let value = parts[1].trimmingCharacters(in: .whitespaces)\n\n switch key {\n case \"type\":\n typeValue = value\n case \"dest\":\n destinationValue = try Self.resolveDestination(dest: value)\n default:\n additionalFields[key] = value\n }\n }\n\n guard let type = typeValue else {\n throw Builder.Error.invalidExport(input, \"type field is required\")\n }\n\n switch type {\n case \"oci\":\n break\n case \"tar\":\n if destinationValue == nil {\n throw Builder.Error.invalidExport(input, \"dest field is required\")\n }\n case \"local\":\n if destinationValue == nil {\n throw Builder.Error.invalidExport(input, \"dest field is required\")\n }\n default:\n throw Builder.Error.invalidExport(input, \"unsupported output type\")\n }\n\n self.init(type: type, destination: destinationValue, additionalFields: additionalFields, rawValue: input)\n }\n\n public var stringValue: String {\n get throws {\n var components = [\"type=\\(type)\"]\n\n switch type {\n case \"oci\", \"tar\", \"local\":\n break // ignore destination\n default:\n throw Builder.Error.invalidExport(rawValue, \"unsupported output type\")\n }\n\n for (key, value) in additionalFields {\n components.append(\"\\(key)=\\(value)\")\n }\n\n return components.joined(separator: \",\")\n }\n }\n\n static func resolveDestination(dest: String) throws -> URL {\n let destination = URL(fileURLWithPath: dest)\n let fileManager = FileManager.default\n\n if fileManager.fileExists(atPath: destination.path) {\n let resourceValues = try destination.resourceValues(forKeys: [.isDirectoryKey])\n let isDir = resourceValues.isDirectory\n if isDir != nil && isDir == false {\n throw Builder.Error.invalidExport(dest, \"dest path already exists\")\n }\n\n var finalDestination = destination.appendingPathComponent(\"out.tar\")\n var index = 1\n while fileManager.fileExists(atPath: finalDestination.path) {\n let path = \"out.tar.\\(index)\"\n finalDestination = destination.appendingPathComponent(path)\n index += 1\n }\n return finalDestination\n } else {\n let parentDirectory = destination.deletingLastPathComponent()\n try? fileManager.createDirectory(at: parentDirectory, withIntermediateDirectories: true, attributes: nil)\n }\n\n return destination\n }\n }\n\n public struct BuildConfig: Sendable {\n public let buildID: String\n public let contentStore: ContentStore\n public let buildArgs: [String]\n public let contextDir: String\n public let dockerfile: Data\n public let labels: [String]\n public let noCache: Bool\n public let platforms: [Platform]\n public let terminal: Terminal?\n public let tag: String\n public let target: String\n public let quiet: Bool\n public let exports: [BuildExport]\n public let cacheIn: [String]\n public let cacheOut: [String]\n\n public init(\n buildID: String,\n contentStore: ContentStore,\n buildArgs: [String],\n contextDir: String,\n dockerfile: Data,\n labels: [String],\n noCache: Bool,\n platforms: [Platform],\n terminal: Terminal?,\n tag: String,\n target: String,\n quiet: Bool,\n exports: [BuildExport],\n cacheIn: [String],\n cacheOut: [String],\n ) {\n self.buildID = buildID\n self.contentStore = contentStore\n self.buildArgs = buildArgs\n self.contextDir = contextDir\n self.dockerfile = dockerfile\n self.labels = labels\n self.noCache = noCache\n self.platforms = platforms\n self.terminal = terminal\n self.tag = tag\n self.target = target\n self.quiet = quiet\n self.exports = exports\n self.cacheIn = cacheIn\n self.cacheOut = cacheOut\n }\n }\n}\n\nextension Builder {\n enum Error: Swift.Error, CustomStringConvertible {\n case invalidContinuation\n case buildComplete\n case invalidExport(String, String)\n\n var description: String {\n switch self {\n case .invalidContinuation:\n return \"continuation could not created\"\n case .buildComplete:\n return \"build completed\"\n case .invalidExport(let exp, let reason):\n return \"export entry \\(exp) is invalid: \\(reason)\"\n }\n }\n }\n}\n\nextension CallOptions {\n public init(_ config: Builder.BuildConfig) throws {\n var headers: [(String, String)] = [\n (\"build-id\", config.buildID),\n (\"context\", URL(filePath: config.contextDir).path(percentEncoded: false)),\n (\"dockerfile\", config.dockerfile.base64EncodedString()),\n (\"progress\", config.terminal != nil ? \"tty\" : \"plain\"),\n (\"tag\", config.tag),\n (\"target\", config.target),\n ]\n for platform in config.platforms {\n headers.append((\"platforms\", platform.description))\n }\n if config.noCache {\n headers.append((\"no-cache\", \"\"))\n }\n for label in config.labels {\n headers.append((\"labels\", label))\n }\n for buildArg in config.buildArgs {\n headers.append((\"build-args\", buildArg))\n }\n for output in config.exports {\n headers.append((\"outputs\", try output.stringValue))\n }\n for cacheIn in config.cacheIn {\n headers.append((\"cache-in\", cacheIn))\n }\n for cacheOut in config.cacheOut {\n headers.append((\"cache-out\", cacheOut))\n }\n\n self.init(\n customMetadata: HPACKHeaders(headers)\n )\n }\n}\n\nextension FileHandle {\n @discardableResult\n func setSendBufSize(_ bytes: Int) throws -> Int {\n try setSockOpt(\n level: SOL_SOCKET,\n name: SO_SNDBUF,\n value: bytes)\n return bytes\n }\n\n @discardableResult\n func setRecvBufSize(_ bytes: Int) throws -> Int {\n try setSockOpt(\n level: SOL_SOCKET,\n name: SO_RCVBUF,\n value: bytes)\n return bytes\n }\n\n private func setSockOpt(level: Int32, name: Int32, value: Int) throws {\n var v = Int32(value)\n let res = withUnsafePointer(to: &v) { ptr -> Int32 in\n ptr.withMemoryRebound(\n to: UInt8.self,\n capacity: MemoryLayout.size\n ) { raw in\n #if canImport(Darwin)\n return setsockopt(\n self.fileDescriptor,\n level, name,\n raw,\n socklen_t(MemoryLayout.size))\n #else\n fatalError(\"unsupported platform\")\n #endif\n }\n }\n if res == -1 {\n throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EPERM)\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct SystemStart: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Start `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Path to the `container-apiserver` binary\")\n var path: String = Bundle.main.executablePath ?? \"\"\n\n @Flag(name: .long, help: \"Enable debug logging for the runtime daemon.\")\n var debug = false\n\n @Flag(\n name: .long, inversion: .prefixedEnableDisable,\n help: \"Specify whether the default kernel should be installed or not. The default behavior is to prompt the user for a response.\")\n var kernelInstall: Bool?\n\n func run() async throws {\n // Without the true path to the binary in the plist, `container-apiserver` won't launch properly.\n let executableUrl = URL(filePath: path)\n .resolvingSymlinksInPath()\n .deletingLastPathComponent()\n .appendingPathComponent(\"container-apiserver\")\n\n var args = [executableUrl.absolutePath()]\n if debug {\n args.append(\"--debug\")\n }\n\n let apiServerDataUrl = appRoot.appending(path: \"apiserver\")\n try! FileManager.default.createDirectory(at: apiServerDataUrl, withIntermediateDirectories: true)\n let env = ProcessInfo.processInfo.environment.filter { key, _ in\n key.hasPrefix(\"CONTAINER_\")\n }\n\n let logURL = apiServerDataUrl.appending(path: \"apiserver.log\")\n let plist = LaunchPlist(\n label: \"com.apple.container.apiserver\",\n arguments: args,\n environment: env,\n limitLoadToSessionType: [.Aqua, .Background, .System],\n runAtLoad: true,\n stdout: logURL.path,\n stderr: logURL.path,\n machServices: [\"com.apple.container.apiserver\"]\n )\n\n let plistURL = apiServerDataUrl.appending(path: \"apiserver.plist\")\n let data = try plist.encode()\n try data.write(to: plistURL)\n\n try ServiceManager.register(plistPath: plistURL.path)\n\n // Now ping our friendly daemon. Fail if we don't get a response.\n do {\n print(\"Verifying apiserver is running...\")\n try await ClientHealthCheck.ping(timeout: .seconds(10))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get a response from apiserver: \\(error)\"\n )\n }\n\n if await !initImageExists() {\n try? await installInitialFilesystem()\n }\n\n guard await !kernelExists() else {\n return\n }\n try await installDefaultKernel()\n }\n\n private func installInitialFilesystem() async throws {\n let dep = Dependencies.initFs\n let pullCommand = ImagePull(reference: dep.source)\n print(\"Installing base container filesystem...\")\n do {\n try await pullCommand.run()\n } catch {\n log.error(\"Failed to install base container filesystem: \\(error)\")\n }\n }\n\n private func installDefaultKernel() async throws {\n let kernelDependency = Dependencies.kernel\n let defaultKernelURL = kernelDependency.source\n let defaultKernelBinaryPath = ClientDefaults.get(key: .defaultKernelBinaryPath)\n\n var shouldInstallKernel = false\n if kernelInstall == nil {\n print(\"No default kernel configured.\")\n print(\"Install the recommended default kernel from [\\(kernelDependency.source)]? [Y/n]: \", terminator: \"\")\n guard let read = readLine(strippingNewline: true) else {\n throw ContainerizationError(.internalError, message: \"Failed to read user input\")\n }\n guard read.lowercased() == \"y\" || read.count == 0 else {\n print(\"Please use the `container system kernel set --recommended` command to configure the default kernel\")\n return\n }\n shouldInstallKernel = true\n } else {\n shouldInstallKernel = kernelInstall ?? false\n }\n guard shouldInstallKernel else {\n return\n }\n print(\"Installing kernel...\")\n try await KernelSet.downloadAndInstallWithProgressBar(tarRemoteURL: defaultKernelURL, kernelFilePath: defaultKernelBinaryPath)\n }\n\n private func initImageExists() async -> Bool {\n do {\n let img = try await ClientImage.get(reference: Dependencies.initFs.source)\n let _ = try await img.getSnapshot(platform: .current)\n return true\n } catch {\n return false\n }\n }\n\n private func kernelExists() async -> Bool {\n do {\n try await ClientKernel.getDefaultKernel(for: .current)\n return true\n } catch {\n return false\n }\n }\n }\n\n private enum Dependencies: String {\n case kernel\n case initFs\n\n var source: String {\n switch self {\n case .initFs:\n return ClientDefaults.get(key: .defaultInitImage)\n case .kernel:\n return ClientDefaults.get(key: .defaultKernelURL)\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderStatus: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"status\"\n config._superCommandName = \"builder\"\n config.abstract = \"Print builder status\"\n config.usage = \"\\n\\t builder status [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Flag(name: .long, help: ArgumentHelp(\"Display detailed status in json format\"))\n var json: Bool = false\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n if json {\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.prettyPrinted, .sortedKeys]\n let jsonData = try encoder.encode(container)\n\n guard let jsonString = String(data: jsonData, encoding: .utf8) else {\n throw ContainerizationError(.internalError, message: \"failed to encode BuildKit container as json\")\n }\n print(jsonString)\n return\n }\n\n let image = container.configuration.image.reference\n let resources = container.configuration.resources\n let cpus = resources.cpus\n let memory = resources.memoryInBytes / (1024 * 1024) // bytes to MB\n let addr = \"\"\n\n print(\"ID IMAGE STATE ADDR CPUS MEMORY\")\n print(\"\\(container.id) \\(image) \\(container.status.rawValue.uppercased()) \\(addr) \\(cpus) \\(memory) MB\")\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n print(\"builder is not running\")\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildFSSync.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport ContainerClient\nimport ContainerizationArchive\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\n\nactor BuildFSSync: BuildPipelineHandler {\n let contextDir: URL\n\n init(_ contextDir: URL) throws {\n guard FileManager.default.fileExists(atPath: contextDir.cleanPath) else {\n throw Error.contextNotFound(contextDir.cleanPath)\n }\n guard try contextDir.isDir() else {\n throw Error.contextIsNotDirectory(contextDir.cleanPath)\n }\n\n self.contextDir = contextDir\n }\n\n nonisolated func accept(_ packet: ServerStream) throws -> Bool {\n guard let buildTransfer = packet.getBuildTransfer() else {\n return false\n }\n guard buildTransfer.stage() == \"fssync\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let buildTransfer = packet.getBuildTransfer() else {\n throw Error.buildTransferMissing\n }\n guard let method = buildTransfer.method() else {\n throw Error.methodMissing\n }\n switch try FSSyncMethod(method) {\n case .read:\n try await self.read(sender, buildTransfer, packet.buildID)\n case .info:\n try await self.info(sender, buildTransfer, packet.buildID)\n case .walk:\n try await self.walk(sender, buildTransfer, packet.buildID)\n }\n }\n\n func read(_ sender: AsyncStream.Continuation, _ packet: BuildTransfer, _ buildID: String) async throws {\n let offset: UInt64 = packet.offset() ?? 0\n let size: Int = packet.len() ?? 0\n var path: URL\n if packet.source.hasPrefix(\"/\") {\n path = URL(fileURLWithPath: packet.source).standardizedFileURL\n } else {\n path =\n contextDir\n .appendingPathComponent(packet.source)\n .standardizedFileURL\n }\n if !FileManager.default.fileExists(atPath: path.cleanPath) {\n path = URL(filePath: self.contextDir.cleanPath)\n path.append(components: packet.source.cleanPathComponent)\n }\n let data = try {\n if try path.isDir() {\n return Data()\n }\n let file = try LocalContent(path: path.standardizedFileURL)\n return try file.data(offset: offset, length: size) ?? Data()\n }()\n\n let transfer = try path.buildTransfer(id: packet.id, contextDir: self.contextDir, complete: true, data: data)\n var response = ClientStream()\n response.buildID = buildID\n response.buildTransfer = transfer\n response.packetType = .buildTransfer(transfer)\n sender.yield(response)\n }\n\n func info(_ sender: AsyncStream.Continuation, _ packet: BuildTransfer, _ buildID: String) async throws {\n let path: URL\n if packet.source.hasPrefix(\"/\") {\n path = URL(fileURLWithPath: packet.source).standardizedFileURL\n } else {\n path =\n contextDir\n .appendingPathComponent(packet.source)\n .standardizedFileURL\n }\n let transfer = try path.buildTransfer(id: packet.id, contextDir: self.contextDir, complete: true)\n var response = ClientStream()\n response.buildID = buildID\n response.buildTransfer = transfer\n response.packetType = .buildTransfer(transfer)\n sender.yield(response)\n }\n\n private struct DirEntry: Hashable {\n let url: URL\n let isDirectory: Bool\n let relativePath: String\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(relativePath)\n }\n\n static func == (lhs: DirEntry, rhs: DirEntry) -> Bool {\n lhs.relativePath == rhs.relativePath\n }\n }\n\n func walk(\n _ sender: AsyncStream.Continuation,\n _ packet: BuildTransfer,\n _ buildID: String\n ) async throws {\n let wantsTar = packet.mode() == \"tar\"\n\n var entries: [String: Set] = [:]\n let followPaths: [String] = packet.followPaths() ?? []\n\n let followPathsWalked = try walk(root: self.contextDir, includePatterns: followPaths)\n for url in followPathsWalked {\n guard self.contextDir.absoluteURL.cleanPath != url.absoluteURL.cleanPath else {\n continue\n }\n guard self.contextDir.parentOf(url) else {\n continue\n }\n\n let relPath = try url.relativeChildPath(to: contextDir)\n let parentPath = try url.deletingLastPathComponent().relativeChildPath(to: contextDir)\n let entry = DirEntry(url: url, isDirectory: url.hasDirectoryPath, relativePath: relPath)\n entries[parentPath, default: []].insert(entry)\n\n if url.isSymlink {\n let target: URL = url.resolvingSymlinksInPath()\n if self.contextDir.parentOf(target) {\n let relPath = try target.relativeChildPath(to: self.contextDir)\n let entry = DirEntry(url: target, isDirectory: target.hasDirectoryPath, relativePath: relPath)\n let parentPath: String = try target.deletingLastPathComponent().relativeChildPath(to: self.contextDir)\n entries[parentPath, default: []].insert(entry)\n }\n }\n }\n\n var fileOrder = [String]()\n try processDirectory(\"\", inputEntries: entries, processedPaths: &fileOrder)\n\n if !wantsTar {\n let fileInfos = try fileOrder.map { rel -> FileInfo in\n try FileInfo(path: contextDir.appendingPathComponent(rel), contextDir: contextDir)\n }\n\n let data = try JSONEncoder().encode(fileInfos)\n let transfer = BuildTransfer(\n id: packet.id,\n source: packet.source,\n complete: true,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"json\",\n ],\n data: data\n )\n var resp = ClientStream()\n resp.buildID = buildID\n resp.buildTransfer = transfer\n resp.packetType = .buildTransfer(transfer)\n sender.yield(resp)\n return\n }\n\n let tarURL = URL.temporaryDirectory\n .appendingPathComponent(UUID().uuidString + \".tar\")\n\n defer { try? FileManager.default.removeItem(at: tarURL) }\n\n let writerCfg = ArchiveWriterConfiguration(\n format: .paxRestricted,\n filter: .none)\n\n try Archiver.compress(\n source: contextDir,\n destination: tarURL,\n writerConfiguration: writerCfg\n ) { url in\n guard let rel = try? url.relativeChildPath(to: contextDir) else {\n return nil\n }\n\n guard let parent = try? url.deletingLastPathComponent().relativeChildPath(to: self.contextDir) else {\n return nil\n }\n\n guard let items = entries[parent] else {\n return nil\n }\n\n let include = items.contains { item in\n item.relativePath == rel\n }\n\n guard include else {\n return nil\n }\n\n return Archiver.ArchiveEntryInfo(\n pathOnHost: url,\n pathInArchive: URL(fileURLWithPath: rel))\n }\n\n for try await chunk in try tarURL.bufferedCopyReader() {\n let part = BuildTransfer(\n id: packet.id,\n source: tarURL.path,\n complete: false,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"tar\",\n ],\n data: chunk\n )\n var resp = ClientStream()\n resp.buildID = buildID\n resp.buildTransfer = part\n resp.packetType = .buildTransfer(part)\n sender.yield(resp)\n }\n\n let done = BuildTransfer(\n id: packet.id,\n source: tarURL.path,\n complete: true,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"tar\",\n ],\n data: Data()\n )\n\n var finalResp = ClientStream()\n finalResp.buildID = buildID\n finalResp.buildTransfer = done\n finalResp.packetType = .buildTransfer(done)\n sender.yield(finalResp)\n }\n\n func walk(root: URL, includePatterns: [String]) throws -> [URL] {\n let globber = Globber(root)\n\n for p in includePatterns {\n try globber.match(p)\n }\n return Array(globber.results)\n }\n\n private func processDirectory(\n _ currentDir: String,\n inputEntries: [String: Set],\n processedPaths: inout [String]\n ) throws {\n guard let entries = inputEntries[currentDir] else {\n return\n }\n\n // Sort purely by lexicographical order of relativePath\n let sortedEntries = entries.sorted { $0.relativePath < $1.relativePath }\n\n for entry in sortedEntries {\n processedPaths.append(entry.relativePath)\n\n if entry.isDirectory {\n try processDirectory(\n entry.relativePath,\n inputEntries: inputEntries,\n processedPaths: &processedPaths\n )\n }\n }\n }\n\n struct FileInfo: Codable {\n let name: String\n let modTime: String\n let mode: UInt32\n let size: UInt64\n let isDir: Bool\n let uid: UInt32\n let gid: UInt32\n let target: String\n\n init(path: URL, contextDir: URL) throws {\n if path.isSymlink {\n let target: URL = path.resolvingSymlinksInPath()\n if contextDir.parentOf(target) {\n self.target = target.relativePathFrom(from: path)\n } else {\n self.target = target.cleanPath\n }\n } else {\n self.target = \"\"\n }\n\n self.name = try path.relativeChildPath(to: contextDir)\n self.modTime = try path.modTime()\n self.mode = try path.mode()\n self.size = try path.size()\n self.isDir = path.hasDirectoryPath\n self.uid = 0\n self.gid = 0\n }\n }\n\n enum FSSyncMethod: String {\n case read = \"Read\"\n case info = \"Info\"\n case walk = \"Walk\"\n\n init(_ method: String) throws {\n switch method {\n case \"Read\":\n self = .read\n case \"Info\":\n self = .info\n case \"Walk\":\n self = .walk\n default:\n throw Error.unknownMethod(method)\n }\n }\n }\n}\n\nextension BuildFSSync {\n enum Error: Swift.Error, CustomStringConvertible, Equatable {\n case buildTransferMissing\n case methodMissing\n case unknownMethod(String)\n case contextNotFound(String)\n case contextIsNotDirectory(String)\n case couldNotDetermineFileSize(String)\n case couldNotDetermineModTime(String)\n case couldNotDetermineFileMode(String)\n case invalidOffsetSizeForFile(String, UInt64, Int)\n case couldNotDetermineUID(String)\n case couldNotDetermineGID(String)\n case pathIsNotChild(String, String)\n\n var description: String {\n switch self {\n case .buildTransferMissing:\n return \"buildTransfer field missing in packet\"\n case .methodMissing:\n return \"method is missing in request\"\n case .unknownMethod(let m):\n return \"unknown content-store method \\(m)\"\n case .contextNotFound(let path):\n return \"context dir \\(path) not found\"\n case .contextIsNotDirectory(let path):\n return \"context \\(path) not a directory\"\n case .couldNotDetermineFileSize(let path):\n return \"could not determine size of file \\(path)\"\n case .couldNotDetermineModTime(let path):\n return \"could not determine last modified time of \\(path)\"\n case .couldNotDetermineFileMode(let path):\n return \"could not determine posix permissions (FileMode) of \\(path)\"\n case .invalidOffsetSizeForFile(let digest, let offset, let size):\n return \"invalid request for file: \\(digest) with offset: \\(offset) size: \\(size)\"\n case .couldNotDetermineUID(let path):\n return \"could not determine UID of file at path: \\(path)\"\n case .couldNotDetermineGID(let path):\n return \"could not determine GID of file at path: \\(path)\"\n case .pathIsNotChild(let path, let parent):\n return \"\\(path) is not a child of \\(parent)\"\n }\n }\n }\n}\n\nextension BuildTransfer {\n fileprivate init(id: String, source: String, complete: Bool, isDir: Bool, metadata: [String: String], data: Data? = nil) {\n self.init()\n self.id = id\n self.source = source\n self.direction = .outof\n self.complete = complete\n self.metadata = metadata\n self.isDirectory = isDir\n if let data {\n self.data = data\n }\n }\n}\n\nextension URL {\n fileprivate func size() throws -> UInt64 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let size = attrs[FileAttributeKey.size] as? UInt64 {\n return size\n }\n throw BuildFSSync.Error.couldNotDetermineFileSize(self.cleanPath)\n }\n\n fileprivate func modTime() throws -> String {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let date = attrs[FileAttributeKey.modificationDate] as? Date {\n return date.rfc3339()\n }\n throw BuildFSSync.Error.couldNotDetermineModTime(self.cleanPath)\n }\n\n fileprivate func isDir() throws -> Bool {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n guard let t = attrs[.type] as? FileAttributeType, t == .typeDirectory else {\n return false\n }\n return true\n }\n\n fileprivate func mode() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let mode = attrs[FileAttributeKey.posixPermissions] as? NSNumber {\n return mode.uint32Value\n }\n throw BuildFSSync.Error.couldNotDetermineFileMode(self.cleanPath)\n }\n\n fileprivate func uid() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let uid = attrs[.ownerAccountID] as? UInt32 {\n return uid\n }\n throw BuildFSSync.Error.couldNotDetermineUID(self.cleanPath)\n }\n\n fileprivate func gid() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let gid = attrs[.groupOwnerAccountID] as? UInt32 {\n return gid\n }\n throw BuildFSSync.Error.couldNotDetermineGID(self.cleanPath)\n }\n\n fileprivate func buildTransfer(\n id: String,\n contextDir: URL? = nil,\n complete: Bool = false,\n data: Data = Data()\n ) throws -> BuildTransfer {\n let p = try {\n if let contextDir { return try self.relativeChildPath(to: contextDir) }\n return self.cleanPath\n }()\n return BuildTransfer(\n id: id,\n source: String(p),\n complete: complete,\n isDir: try self.isDir(),\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": String(try self.mode()),\n \"size\": String(try self.size()),\n \"modified_at\": try self.modTime(),\n \"uid\": String(try self.uid()),\n \"gid\": String(try self.gid()),\n ],\n data: data\n )\n }\n}\n\nextension Date {\n fileprivate func rfc3339() -> String {\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"yyyy-MM-dd'T'HH:mm:ssZZZZZ\"\n dateFormatter.locale = Locale(identifier: \"en_US_POSIX\")\n dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // Adjust if necessary\n\n return dateFormatter.string(from: self)\n }\n}\n\nextension String {\n var cleanPathComponent: String {\n let trimmed = self.trimmingCharacters(in: CharacterSet(charactersIn: \"/\"))\n if let clean = trimmed.removingPercentEncoding {\n return clean\n }\n return trimmed\n }\n}\n"], ["/container/Sources/APIServer/APIServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerPlugin\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport DNSServer\nimport Foundation\nimport Logging\n\n@main\nstruct APIServer: AsyncParsableCommand {\n static let listenAddress = \"127.0.0.1\"\n static let dnsPort = 2053\n\n static let configuration = CommandConfiguration(\n commandName: \"container-apiserver\",\n abstract: \"Container management API server\",\n version: releaseVersion()\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .shortAndLong, help: \"Daemon root directory\")\n var root = Self.appRoot.path\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n func run() async throws {\n let commandName = Self.configuration.commandName ?? \"container-apiserver\"\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n do {\n log.info(\"configuring XPC server\")\n let root = URL(filePath: root)\n var routes = [XPCRoute: XPCServer.RouteHandler]()\n let pluginLoader = try initializePluginLoader(log: log)\n try await initializePlugins(pluginLoader: pluginLoader, log: log, routes: &routes)\n try initializeContainerService(root: root, pluginLoader: pluginLoader, log: log, routes: &routes)\n let networkService = try await initializeNetworkService(\n root: root,\n pluginLoader: pluginLoader,\n log: log,\n routes: &routes\n )\n initializeHealthCheckService(log: log, routes: &routes)\n try initializeKernelService(log: log, routes: &routes)\n\n let server = XPCServer(\n identifier: \"com.apple.container.apiserver\",\n routes: routes.reduce(\n into: [String: XPCServer.RouteHandler](),\n {\n $0[$1.key.rawValue] = $1.value\n }), log: log)\n\n await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n log.info(\"starting XPC server\")\n try await server.listen()\n }\n // start up host table DNS\n group.addTask {\n let hostsResolver = ContainerDNSHandler(networkService: networkService)\n let nxDomainResolver = NxDomainResolver()\n let compositeResolver = CompositeResolver(handlers: [hostsResolver, nxDomainResolver])\n let hostsQueryValidator = StandardQueryValidator(handler: compositeResolver)\n let dnsServer: DNSServer = DNSServer(handler: hostsQueryValidator, log: log)\n log.info(\n \"starting DNS host query resolver\",\n metadata: [\n \"host\": \"\\(Self.listenAddress)\",\n \"port\": \"\\(Self.dnsPort)\",\n ]\n )\n try await dnsServer.run(host: Self.listenAddress, port: Self.dnsPort)\n }\n }\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n APIServer.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"APIServer\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n return log\n }\n\n private func initializePluginLoader(log: Logger) throws -> PluginLoader {\n let installRoot = CommandLine.executablePathUrl\n .deletingLastPathComponent()\n .appendingPathComponent(\"..\")\n .standardized\n let pluginsURL = PluginLoader.userPluginsDir(root: installRoot)\n var directoryExists: ObjCBool = false\n _ = FileManager.default.fileExists(atPath: pluginsURL.path, isDirectory: &directoryExists)\n let userPluginsURL = directoryExists.boolValue ? pluginsURL : nil\n\n // plugins built into the application installed as a macOS app bundle\n let appBundlePluginsURL = Bundle.main.resourceURL?.appending(path: \"plugins\")\n\n // plugins built into the application installed as a Unix-like application\n let installRootPluginsURL =\n installRoot\n .appendingPathComponent(\"libexec\")\n .appendingPathComponent(\"container\")\n .appendingPathComponent(\"plugins\")\n .standardized\n\n let pluginDirectories = [\n userPluginsURL,\n appBundlePluginsURL,\n installRootPluginsURL,\n ].compactMap { $0 }\n\n let pluginFactories: [PluginFactory] = [\n DefaultPluginFactory(),\n AppBundlePluginFactory(),\n ]\n\n log.info(\"PLUGINS: \\(pluginDirectories)\")\n let statePath = PluginLoader.defaultPluginResourcePath(root: Self.appRoot)\n try FileManager.default.createDirectory(at: statePath, withIntermediateDirectories: true)\n return PluginLoader(pluginDirectories: pluginDirectories, pluginFactories: pluginFactories, defaultResourcePath: statePath, log: log)\n }\n\n // First load all of the plugins we can find. Then just expose\n // the handlers for clients to do whatever they want.\n private func initializePlugins(\n pluginLoader: PluginLoader,\n log: Logger,\n routes: inout [XPCRoute: XPCServer.RouteHandler]\n ) async throws {\n let bootPlugins = pluginLoader.findPlugins().filter { $0.shouldBoot }\n\n let service = PluginsService(pluginLoader: pluginLoader, log: log)\n try await service.loadAll(bootPlugins)\n\n let harness = PluginsHarness(service: service, log: log)\n routes[XPCRoute.pluginGet] = harness.get\n routes[XPCRoute.pluginList] = harness.list\n routes[XPCRoute.pluginLoad] = harness.load\n routes[XPCRoute.pluginUnload] = harness.unload\n routes[XPCRoute.pluginRestart] = harness.restart\n }\n\n private func initializeHealthCheckService(log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) {\n let svc = HealthCheckHarness(log: log)\n routes[XPCRoute.ping] = svc.ping\n }\n\n private func initializeKernelService(log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) throws {\n let svc = try KernelService(log: log, appRoot: Self.appRoot)\n let harness = KernelHarness(service: svc, log: log)\n routes[XPCRoute.installKernel] = harness.install\n routes[XPCRoute.getDefaultKernel] = harness.getDefaultKernel\n }\n\n private func initializeContainerService(root: URL, pluginLoader: PluginLoader, log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) throws {\n let service = try ContainersService(\n root: root,\n pluginLoader: pluginLoader,\n log: log\n )\n let harness = ContainersHarness(service: service, log: log)\n\n routes[XPCRoute.listContainer] = harness.list\n routes[XPCRoute.createContainer] = harness.create\n routes[XPCRoute.deleteContainer] = harness.delete\n routes[XPCRoute.containerLogs] = harness.logs\n routes[XPCRoute.containerEvent] = harness.eventHandler\n }\n\n private func initializeNetworkService(\n root: URL,\n pluginLoader: PluginLoader,\n log: Logger,\n routes: inout [XPCRoute: XPCServer.RouteHandler]\n ) async throws -> NetworksService {\n let resourceRoot = root.appendingPathComponent(\"networks\")\n let service = try await NetworksService(\n pluginLoader: pluginLoader,\n resourceRoot: resourceRoot,\n log: log\n )\n\n let defaultNetwork = try await service.list()\n .filter { $0.id == ClientNetwork.defaultNetworkName }\n .first\n if defaultNetwork == nil {\n let config = NetworkConfiguration(id: ClientNetwork.defaultNetworkName, mode: .nat)\n _ = try await service.create(configuration: config)\n }\n\n let harness = NetworksHarness(service: service, log: log)\n\n routes[XPCRoute.networkCreate] = harness.create\n routes[XPCRoute.networkDelete] = harness.delete\n routes[XPCRoute.networkList] = harness.list\n return service\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ContainerCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a new container\")\n\n @Argument(help: \"Image name\")\n var image: String\n\n @Argument(help: \"Container init process arguments\")\n var arguments: [String] = []\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var resourceFlags: Flags.Resource\n\n @OptionGroup\n var managementFlags: Flags.Management\n\n @OptionGroup\n var registryFlags: Flags.Registry\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 3\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let id = Utility.createContainerID(name: self.managementFlags.name)\n try Utility.validEntityName(id)\n\n let ck = try await Utility.containerConfigFromFlags(\n id: id,\n image: image,\n arguments: arguments,\n process: processFlags,\n management: managementFlags,\n resource: resourceFlags,\n registry: registryFlags,\n progressUpdate: progress.handler\n )\n\n let options = ContainerCreateOptions(autoRemove: managementFlags.remove)\n let container = try await ClientContainer.create(configuration: ck.0, options: options, kernel: ck.1)\n\n if !self.managementFlags.cidfile.isEmpty {\n let path = self.managementFlags.cidfile\n let data = container.id.data(using: .utf8)\n var attributes = [FileAttributeKey: Any]()\n attributes[.posixPermissions] = 0o644\n let success = FileManager.default.createFile(\n atPath: path,\n contents: data,\n attributes: attributes\n )\n guard success else {\n throw ContainerizationError(\n .internalError, message: \"failed to create cidfile at \\(path): \\(errno)\")\n }\n }\n progress.finish()\n\n print(container.id)\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationExtras\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ContainerList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List containers\",\n aliases: [\"ls\"])\n\n @Flag(name: .shortAndLong, help: \"Show stopped containers as well\")\n var all = false\n\n @Flag(name: .shortAndLong, help: \"Only output the container ID\")\n var quiet = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let containers = try await ClientContainer.list()\n try printContainers(containers: containers, format: format)\n }\n\n private func createHeader() -> [[String]] {\n [[\"ID\", \"IMAGE\", \"OS\", \"ARCH\", \"STATE\", \"ADDR\"]]\n }\n\n private func printContainers(containers: [ClientContainer], format: ListFormat) throws {\n if format == .json {\n let printables = containers.map {\n PrintableContainer($0)\n }\n let data = try JSONEncoder().encode(printables)\n print(String(data: data, encoding: .utf8)!)\n\n return\n }\n\n if self.quiet {\n containers.forEach {\n if !self.all && $0.status != .running {\n return\n }\n print($0.id)\n }\n return\n }\n\n var rows = createHeader()\n for container in containers {\n if !self.all && container.status != .running {\n continue\n }\n rows.append(container.asRow)\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n }\n}\n\nextension ClientContainer {\n var asRow: [String] {\n [\n self.id,\n self.configuration.image.reference,\n self.configuration.platform.os,\n self.configuration.platform.architecture,\n self.status.rawValue,\n self.networks.compactMap { try? CIDRAddress($0.address).address.description }.joined(separator: \",\"),\n ]\n }\n}\n\nstruct PrintableContainer: Codable {\n let status: RuntimeStatus\n let configuration: ContainerConfiguration\n let networks: [Attachment]\n\n init(_ container: ClientContainer) {\n self.status = container.status\n self.configuration = container.configuration\n self.networks = container.networks\n }\n}\n"], ["/container/Sources/APIServer/Containers/ContainersService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CVersion\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerSandboxService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ContainersService {\n private static let machServicePrefix = \"com.apple.container\"\n private static let launchdDomainString = try! ServiceManager.getDomainString()\n\n private let log: Logger\n private let containerRoot: URL\n private let pluginLoader: PluginLoader\n private let runtimePlugins: [Plugin]\n\n private let lock = AsyncLock()\n private var containers: [String: Item]\n\n struct Item: Sendable {\n let bundle: ContainerClient.Bundle\n var state: State\n\n enum State: Sendable {\n case dead\n case alive(SandboxClient)\n case exited(Int32)\n\n func isDead() -> Bool {\n switch self {\n case .dead: return true\n default: return false\n }\n }\n }\n }\n\n public init(root: URL, pluginLoader: PluginLoader, log: Logger) throws {\n let containerRoot = root.appendingPathComponent(\"containers\")\n try FileManager.default.createDirectory(at: containerRoot, withIntermediateDirectories: true)\n self.containerRoot = containerRoot\n self.pluginLoader = pluginLoader\n self.log = log\n self.runtimePlugins = pluginLoader.findPlugins().filter { $0.hasType(.runtime) }\n self.containers = try Self.loadAtBoot(root: containerRoot, loader: pluginLoader, log: log)\n }\n\n static func loadAtBoot(root: URL, loader: PluginLoader, log: Logger) throws -> [String: Item] {\n var directories = try FileManager.default.contentsOfDirectory(\n at: root,\n includingPropertiesForKeys: [.isDirectoryKey]\n )\n directories = directories.filter {\n $0.isDirectory\n }\n\n let runtimePlugins = loader.findPlugins().filter { $0.hasType(.runtime) }\n var results = [String: Item]()\n for dir in directories {\n do {\n let bundle = ContainerClient.Bundle(path: dir)\n let config = try bundle.configuration\n results[config.id] = .init(bundle: bundle, state: .dead)\n let plugin = runtimePlugins.first { $0.name == config.runtimeHandler }\n guard let plugin else {\n throw ContainerizationError(.internalError, message: \"Failed to find runtime plugin \\(config.runtimeHandler)\")\n }\n try Self.registerService(plugin: plugin, loader: loader, configuration: config, path: dir)\n } catch {\n try? FileManager.default.removeItem(at: dir)\n log.warning(\"failed to load container bundle at \\(dir.path)\")\n }\n }\n return results\n }\n\n private func setContainer(_ id: String, _ item: Item, context: AsyncLock.Context) async {\n self.containers[id] = item\n }\n\n /// List all containers registered with the service.\n public func list() async throws -> [ContainerSnapshot] {\n self.log.debug(\"\\(#function)\")\n return await lock.withLock { context in\n var snapshots = [ContainerSnapshot]()\n\n for (id, item) in await self.containers {\n do {\n let result = try await item.asSnapshot()\n snapshots.append(result.0)\n } catch {\n self.log.error(\"unable to load bundle for \\(id) \\(error)\")\n }\n }\n return snapshots\n }\n }\n\n /// Create a new container from the provided id and configuration.\n public func create(configuration: ContainerConfiguration, kernel: Kernel, options: ContainerCreateOptions) async throws {\n self.log.debug(\"\\(#function)\")\n\n let runtimePlugin = self.runtimePlugins.filter {\n $0.name == configuration.runtimeHandler\n }.first\n guard let runtimePlugin else {\n throw ContainerizationError(.notFound, message: \"unable to locate runtime plugin \\(configuration.runtimeHandler)\")\n }\n\n let path = self.containerRoot.appendingPathComponent(configuration.id)\n let systemPlatform = kernel.platform\n let initFs = try await getInitBlock(for: systemPlatform.ociPlatform())\n\n let bundle = try ContainerClient.Bundle.create(\n path: path,\n initialFilesystem: initFs,\n kernel: kernel,\n containerConfiguration: configuration\n )\n do {\n let containerImage = ClientImage(description: configuration.image)\n let imageFs = try await containerImage.getCreateSnapshot(platform: configuration.platform)\n try bundle.setContainerRootFs(cloning: imageFs)\n try bundle.write(filename: \"options.json\", value: options)\n\n try Self.registerService(\n plugin: runtimePlugin,\n loader: self.pluginLoader,\n configuration: configuration,\n path: path\n )\n } catch {\n do {\n try bundle.delete()\n } catch {\n self.log.error(\"failed to delete bundle for container \\(configuration.id): \\(error)\")\n }\n throw error\n }\n self.containers[configuration.id] = Item(bundle: bundle, state: .dead)\n }\n\n private func getInitBlock(for platform: Platform) async throws -> Filesystem {\n let initImage = try await ClientImage.fetch(reference: ClientImage.initImageRef, platform: platform)\n var fs = try await initImage.getCreateSnapshot(platform: platform)\n fs.options = [\"ro\"]\n return fs\n }\n\n private static func registerService(\n plugin: Plugin,\n loader: PluginLoader,\n configuration: ContainerConfiguration,\n path: URL\n ) throws {\n let args = [\n \"--root\", path.path,\n \"--uuid\", configuration.id,\n \"--debug\",\n ]\n try loader.registerWithLaunchd(\n plugin: plugin,\n rootURL: path,\n args: args,\n instanceId: configuration.id\n )\n }\n\n private func get(id: String, context: AsyncLock.Context) throws -> Item {\n try self._get(id: id)\n }\n\n private func _get(id: String) throws -> Item {\n let item = self.containers[id]\n guard let item else {\n throw ContainerizationError(\n .notFound,\n message: \"container with ID \\(id) not found\"\n )\n }\n return item\n }\n\n /// Delete a container and its resources.\n public func delete(id: String) async throws {\n self.log.debug(\"\\(#function)\")\n let item = try self._get(id: id)\n switch item.state {\n case .alive(let client):\n let state = try await client.state()\n if state.status == .running || state.status == .stopping {\n throw ContainerizationError(\n .invalidState,\n message: \"container \\(id) is not yet stopped and can not be deleted\"\n )\n }\n try self._cleanup(id: id, item: item)\n case .dead, .exited(_):\n try self._cleanup(id: id, item: item)\n }\n }\n\n private static func fullLaunchdServiceLabel(runtimeName: String, instanceId: String) -> String {\n \"\\(Self.launchdDomainString)/\\(Self.machServicePrefix).\\(runtimeName).\\(instanceId)\"\n }\n\n private func _cleanup(id: String, item: Item) throws {\n self.log.debug(\"\\(#function)\")\n let config = try item.bundle.configuration\n let label = Self.fullLaunchdServiceLabel(runtimeName: config.runtimeHandler, instanceId: id)\n try ServiceManager.deregister(fullServiceLabel: label)\n try item.bundle.delete()\n self.containers.removeValue(forKey: id)\n }\n\n private func _shutdown(id: String, item: Item) throws {\n let config = try item.bundle.configuration\n let label = Self.fullLaunchdServiceLabel(runtimeName: config.runtimeHandler, instanceId: id)\n try ServiceManager.kill(fullServiceLabel: label)\n }\n\n private func cleanup(id: String, item: Item, context: AsyncLock.Context) async throws {\n try self._cleanup(id: id, item: item)\n }\n\n private func containerProcessExitHandler(_ id: String, _ exitCode: Int32, context: AsyncLock.Context) async {\n self.log.info(\"Handling container \\(id) exit. Code \\(exitCode)\")\n do {\n var item = try self.get(id: id, context: context)\n switch item.state {\n case .dead, .exited(_):\n break\n case .alive(_):\n item.state = .exited(exitCode)\n await self.setContainer(id, item, context: context)\n }\n let options: ContainerCreateOptions = try item.bundle.load(filename: \"options.json\")\n if options.autoRemove {\n try await self.cleanup(id: id, item: item, context: context)\n }\n } catch {\n self.log.error(\n \"Failed to handle container exit\",\n metadata: [\n \"id\": .string(id),\n \"error\": .string(String(describing: error)),\n ])\n }\n }\n\n private func containerStartHandler(_ id: String, context: AsyncLock.Context) async throws {\n self.log.debug(\"\\(#function)\")\n self.log.info(\"Handling container \\(id) Start.\")\n do {\n var item = try self.get(id: id, context: context)\n let configuration = try item.bundle.configuration\n let client = SandboxClient(id: configuration.id, runtime: configuration.runtimeHandler)\n item.state = .alive(client)\n await self.setContainer(id, item, context: context)\n } catch {\n self.log.error(\n \"Failed to handle container start\",\n metadata: [\n \"id\": .string(id),\n \"error\": .string(String(describing: error)),\n ])\n }\n }\n}\n\nextension ContainersService {\n public func handleContainerEvents(event: ContainerEvent) async throws {\n self.log.debug(\"\\(#function)\")\n try await self.lock.withLock { context in\n switch event {\n case .containerExit(let id, let code):\n await self.containerProcessExitHandler(id, Int32(code), context: context)\n case .containerStart(let id):\n try await self.containerStartHandler(id, context: context)\n }\n }\n }\n\n /// Stop all containers inside the sandbox, aborting any processes currently\n /// executing inside the container, before stopping the underlying sandbox.\n public func stop(id: String, options: ContainerStopOptions) async throws {\n self.log.debug(\"\\(#function)\")\n try await lock.withLock { context in\n let item = try await self.get(id: id, context: context)\n switch item.state {\n case .dead, .exited(_):\n return\n case .alive(let client):\n try await client.stop(options: options)\n }\n }\n }\n\n public func logs(id: String) async throws -> [FileHandle] {\n self.log.debug(\"\\(#function)\")\n // Logs doesn't care if the container is running or not, just that\n // the bundle is there, and that the files actually exist.\n do {\n let item = try self._get(id: id)\n return [\n try FileHandle(forReadingFrom: item.bundle.containerLog),\n try FileHandle(forReadingFrom: item.bundle.bootlog),\n ]\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to open container logs: \\(error)\"\n )\n }\n }\n}\n\nextension ContainersService.Item {\n func asSnapshot() async throws -> (ContainerSnapshot, RuntimeStatus) {\n let config = try self.bundle.configuration\n\n switch self.state {\n case .dead, .exited(_):\n return (\n .init(\n configuration: config,\n status: RuntimeStatus.stopped,\n networks: []\n ), .stopped\n )\n case .alive(let client):\n let state = try await client.state()\n return (\n .init(\n configuration: config,\n status: state.status,\n networks: state.networks\n ), state.status\n )\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nextension Application {\n struct SystemStop: AsyncParsableCommand {\n private static let stopTimeoutSeconds: Int32 = 5\n private static let shutdownTimeoutSeconds: Int32 = 20\n\n static let configuration = CommandConfiguration(\n commandName: \"stop\",\n abstract: \"Stop all `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Launchd prefix for `container` services\")\n var prefix: String = \"com.apple.container.\"\n\n func run() async throws {\n let log = Logger(\n label: \"com.apple.container.cli\",\n factory: { label in\n StreamLogHandler.standardOutput(label: label)\n }\n )\n\n let launchdDomainString = try ServiceManager.getDomainString()\n let fullLabel = \"\\(launchdDomainString)/\\(prefix)apiserver\"\n\n log.info(\"stopping containers\", metadata: [\"stopTimeoutSeconds\": \"\\(Self.stopTimeoutSeconds)\"])\n do {\n let containers = try await ClientContainer.list()\n let signal = try Signals.parseSignal(\"SIGTERM\")\n let opts = ContainerStopOptions(timeoutInSeconds: Self.stopTimeoutSeconds, signal: signal)\n let failed = try await ContainerStop.stopContainers(containers: containers, stopOptions: opts)\n if !failed.isEmpty {\n log.warning(\"some containers could not be stopped gracefully\", metadata: [\"ids\": \"\\(failed)\"])\n }\n\n } catch {\n log.warning(\"failed to stop all containers\", metadata: [\"error\": \"\\(error)\"])\n }\n\n log.info(\"waiting for containers to exit\")\n do {\n for _ in 0.. 0 && all {\n throw ContainerizationError(.invalidArgument, message: \"explicitly supplied container IDs conflicts with the --all flag\")\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n\n var containers = try await ClientContainer.list().filter { c in\n c.status == .running\n }\n if !self.all {\n containers = containers.filter { c in\n set.contains(c.id)\n }\n }\n\n let signalNumber = try Signals.parseSignal(signal)\n\n var failed: [String] = []\n for container in containers {\n do {\n try await container.kill(signalNumber)\n print(container.id)\n } catch {\n log.error(\"failed to kill container \\(container.id): \\(error)\")\n failed.append(container.id)\n }\n }\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"kill failed for one or more containers\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildPipelineHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport GRPC\nimport NIO\n\nprotocol BuildPipelineHandler: Sendable {\n func accept(_ packet: ServerStream) throws -> Bool\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws\n}\n\npublic actor BuildPipeline {\n let handlers: [BuildPipelineHandler]\n public init(_ config: Builder.BuildConfig) async throws {\n self.handlers =\n [\n try BuildFSSync(URL(filePath: config.contextDir)),\n try BuildRemoteContentProxy(config.contentStore),\n try BuildImageResolver(config.contentStore),\n try BuildStdio(quiet: config.quiet, output: config.terminal?.handle ?? FileHandle.standardError),\n ]\n }\n\n public func run(\n sender: AsyncStream.Continuation,\n receiver: GRPCAsyncResponseStream\n ) async throws {\n defer { sender.finish() }\n try await untilFirstError { group in\n for try await packet in receiver {\n try Task.checkCancellation()\n for handler in self.handlers {\n try Task.checkCancellation()\n guard try handler.accept(packet) else {\n continue\n }\n try Task.checkCancellation()\n try await handler.handle(sender, packet)\n break\n }\n }\n }\n }\n\n /// untilFirstError() throws when any one of its submitted tasks fail.\n /// This is useful for asynchronous packet processing scenarios which\n /// have the following 3 requirements:\n /// - the packet should be processed without blocking I/O\n /// - the packet stream is never-ending\n /// - when the first task fails, the error needs to be propagated to the caller\n ///\n /// Usage:\n ///\n /// ```\n /// try await untilFirstError { group in\n /// for try await packet in receiver {\n /// group.addTask {\n /// try await handler.handle(sender, packet)\n /// }\n /// }\n /// }\n /// ```\n ///\n ///\n /// WithThrowingTaskGroup cannot accomplish this because it\n /// doesn't provide a mechanism to exit when one of the tasks fail\n /// before all the tasks have been added. i.e. it is more suitable for\n /// tasks that are limited. Here's a sample code where withThrowingTaskGroup\n /// doesn't solve the problem:\n ///\n /// ```\n /// withThrowingTaskGroup { group in\n /// for try await packet in receiver {\n /// group.addTask {\n /// /* process packet */\n /// }\n /// } /* this loop blocks forever waiting for more packets */\n /// try await group.next() /* this never gets called */\n /// }\n /// ```\n /// The above closure never returns even when a handler encounters an error\n /// because the blocking operation `try await group.next()` cannot be\n /// called while iterating over the receiver stream.\n private func untilFirstError(body: @Sendable @escaping (UntilFirstError) async throws -> Void) async throws {\n let group = try await UntilFirstError()\n var taskContinuation: AsyncStream>.Continuation?\n let tasks = AsyncStream> { continuation in\n taskContinuation = continuation\n }\n guard let taskContinuation else {\n throw NSError(\n domain: \"untilFirstError\",\n code: 1,\n userInfo: [NSLocalizedDescriptionKey: \"Failed to initialize task continuation\"])\n }\n defer { taskContinuation.finish() }\n let stream = AsyncStream { continuation in\n let processTasks = Task {\n let taskStream = await group.tasks()\n defer {\n continuation.finish()\n }\n for await item in taskStream {\n try Task.checkCancellation()\n let addedTask = Task {\n try Task.checkCancellation()\n do {\n try await item()\n } catch {\n continuation.yield(error)\n await group.continuation?.finish()\n throw error\n }\n }\n taskContinuation.yield(addedTask)\n }\n }\n taskContinuation.yield(processTasks)\n\n let mainTask = Task { @Sendable in\n defer {\n continuation.finish()\n processTasks.cancel()\n taskContinuation.finish()\n }\n do {\n try Task.checkCancellation()\n try await body(group)\n } catch {\n continuation.yield(error)\n await group.continuation?.finish()\n throw error\n }\n }\n taskContinuation.yield(mainTask)\n }\n\n // when the first handler fails, cancel all tasks and throw error\n for await item in stream {\n try Task.checkCancellation()\n Task {\n for await task in tasks {\n task.cancel()\n }\n }\n throw item\n }\n // if none of the handlers fail, wait for all subtasks to complete\n for await task in tasks {\n try Task.checkCancellation()\n try await task.value\n }\n }\n\n private actor UntilFirstError {\n var stream: AsyncStream<@Sendable () async throws -> Void>?\n var continuation: AsyncStream<@Sendable () async throws -> Void>.Continuation?\n\n init() async throws {\n self.stream = AsyncStream { cont in\n self.continuation = cont\n }\n guard let _ = continuation else {\n throw NSError()\n }\n }\n\n func addTask(body: @Sendable @escaping () async throws -> Void) {\n if !Task.isCancelled {\n self.continuation?.yield(body)\n }\n }\n\n func tasks() -> AsyncStream<@Sendable () async throws -> Void> {\n self.stream!\n }\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\nimport Logging\nimport os\nimport Synchronization\n\npublic struct XPCServer: Sendable {\n public typealias RouteHandler = @Sendable (XPCMessage) async throws -> XPCMessage\n\n private let routes: [String: RouteHandler]\n // Access to `connection` is protected by a lock\n private nonisolated(unsafe) let connection: xpc_connection_t\n private let lock = NSLock()\n\n let log: Logging.Logger\n\n public init(identifier: String, routes: [String: RouteHandler], log: Logging.Logger) {\n let connection = xpc_connection_create_mach_service(\n identifier,\n nil,\n UInt64(XPC_CONNECTION_MACH_SERVICE_LISTENER))\n\n self.routes = routes\n self.connection = connection\n self.log = log\n }\n\n public func listen() async throws {\n let connections = AsyncStream { cont in\n lock.withLock {\n xpc_connection_set_event_handler(self.connection) { object in\n switch xpc_get_type(object) {\n case XPC_TYPE_CONNECTION:\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n cont.yield(object)\n case XPC_TYPE_ERROR:\n if object.connectionError {\n cont.finish()\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(object))\")\n }\n }\n }\n }\n\n defer {\n lock.withLock {\n xpc_connection_cancel(self.connection)\n }\n }\n\n lock.withLock {\n xpc_connection_activate(self.connection)\n }\n try await withThrowingDiscardingTaskGroup { group in\n for await conn in connections {\n // `conn` isn't used concurrently.\n nonisolated(unsafe) let conn = conn\n let added = group.addTaskUnlessCancelled { @Sendable in\n try await self.handleClientConnection(connection: conn)\n xpc_connection_cancel(conn)\n }\n\n if !added {\n break\n }\n }\n\n group.cancelAll()\n }\n }\n\n func handleClientConnection(connection: xpc_connection_t) async throws {\n let replySent = Mutex(false)\n\n let objects = AsyncStream { cont in\n xpc_connection_set_event_handler(connection) { object in\n switch xpc_get_type(object) {\n case XPC_TYPE_DICTIONARY:\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n cont.yield(object)\n case XPC_TYPE_ERROR:\n if object.connectionError {\n cont.finish()\n }\n if !(replySent.withLock({ $0 }) && object.connectionClosed) {\n // When a xpc connection is closed, the framework sends a final XPC_ERROR_CONNECTION_INVALID message.\n // We can ignore this if we know we have already handled the request.\n self.log.error(\"xpc client handler connection error \\(object.errorDescription ?? \"no description\")\")\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(object))\")\n }\n }\n }\n defer {\n xpc_connection_cancel(connection)\n }\n\n xpc_connection_activate(connection)\n try await withThrowingDiscardingTaskGroup { group in\n // `connection` isn't used concurrently.\n nonisolated(unsafe) let connection = connection\n for await object in objects {\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n let added = group.addTaskUnlessCancelled { @Sendable in\n try await self.handleMessage(connection: connection, object: object)\n replySent.withLock { $0 = true }\n }\n if !added {\n break\n }\n }\n group.cancelAll()\n }\n }\n\n func handleMessage(connection: xpc_connection_t, object: xpc_object_t) async throws {\n guard let route = object.route else {\n log.error(\"empty route\")\n return\n }\n\n if let handler = routes[route] {\n let message = XPCMessage(object: object)\n do {\n let response = try await handler(message)\n xpc_connection_send_message(connection, response.underlying)\n } catch let error as ContainerizationError {\n let reply = message.reply()\n log.error(\"handler for \\(route) threw error \\(error)\")\n reply.set(error: error)\n xpc_connection_send_message(connection, reply.underlying)\n } catch {\n let reply = message.reply()\n log.error(\"handler for \\(route) threw error \\(error)\")\n let err = ContainerizationError(.unknown, message: String(describing: error))\n reply.set(error: err)\n xpc_connection_send_message(connection, reply.underlying)\n }\n }\n }\n}\n\nextension xpc_object_t {\n var route: String? {\n let croute = xpc_dictionary_get_string(self, XPCMessage.routeKey)\n guard let croute else {\n return nil\n }\n return String(cString: croute)\n }\n\n var connectionError: Bool {\n precondition(isError, \"Not an error\")\n return xpc_equal(self, XPC_ERROR_CONNECTION_INVALID) || xpc_equal(self, XPC_ERROR_CONNECTION_INTERRUPTED)\n }\n\n var connectionClosed: Bool {\n precondition(isError, \"Not an error\")\n return xpc_equal(self, XPC_ERROR_CONNECTION_INVALID)\n }\n\n var isError: Bool {\n xpc_get_type(self) == XPC_TYPE_ERROR\n }\n\n var errorDescription: String? {\n precondition(isError, \"Not an error\")\n let cstring = xpc_dictionary_get_string(self, XPC_ERROR_KEY_DESCRIPTION)\n guard let cstring else {\n return nil\n }\n return String(cString: cstring)\n }\n}\n\n#endif\n"], ["/container/Sources/Helpers/NetworkVmnet/NetworkVmnetHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\n@main\nstruct NetworkVmnetHelper: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"container-network-vmnet\",\n abstract: \"XPC service for managing a vmnet network\",\n version: releaseVersion(),\n subcommands: [\n Start.self\n ]\n )\n}\n\nextension NetworkVmnetHelper {\n struct Start: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Starts the network plugin\"\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .long, help: \"XPC service identifier\")\n var serviceIdentifier: String\n\n @Option(name: .shortAndLong, help: \"Network identifier\")\n var id: String\n\n @Option(name: .shortAndLong, help: \"CIDR address for the subnet\")\n var subnet: String?\n\n func run() async throws {\n let commandName = NetworkVmnetHelper._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n do {\n log.info(\"configuring XPC server\")\n let subnet = try self.subnet.map { try CIDRAddress($0) }\n let configuration = NetworkConfiguration(id: id, mode: .nat, subnet: subnet?.description)\n let network = try Self.createNetwork(configuration: configuration, log: log)\n try await network.start()\n let server = try await NetworkService(network: network, log: log)\n let xpc = XPCServer(\n identifier: serviceIdentifier,\n routes: [\n NetworkRoutes.state.rawValue: server.state,\n NetworkRoutes.allocate.rawValue: server.allocate,\n NetworkRoutes.deallocate.rawValue: server.deallocate,\n NetworkRoutes.lookup.rawValue: server.lookup,\n NetworkRoutes.disableAllocator.rawValue: server.disableAllocator,\n ],\n log: log\n )\n\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n NetworkVmnetHelper.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"NetworkVmnetHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n log[metadataKey: \"id\"] = \"\\(id)\"\n return log\n }\n\n private static func createNetwork(configuration: NetworkConfiguration, log: Logger) throws -> Network {\n guard #available(macOS 26, *) else {\n return try AllocationOnlyVmnetNetwork(configuration: configuration, log: log)\n }\n\n return try ReservedVmnetNetwork(configuration: configuration, log: log)\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SendableProperty\nimport Synchronization\n\n/// A progress bar that updates itself as tasks are completed.\npublic final class ProgressBar: Sendable {\n let config: ProgressConfig\n let state: Mutex\n @SendableProperty\n var printedWidth = 0\n let term: FileHandle?\n let termQueue = DispatchQueue(label: \"com.apple.container.ProgressBar\")\n private let standardError = StandardError()\n\n /// Returns `true` if the progress bar has finished.\n public var isFinished: Bool {\n state.withLock { $0.finished }\n }\n\n /// Creates a new progress bar.\n /// - Parameter config: The configuration for the progress bar.\n public init(config: ProgressConfig) {\n self.config = config\n term = isatty(config.terminal.fileDescriptor) == 1 ? config.terminal : nil\n let state = State(\n description: config.initialDescription, itemsName: config.initialItemsName, totalTasks: config.initialTotalTasks,\n totalItems: config.initialTotalItems,\n totalSize: config.initialTotalSize)\n self.state = Mutex(state)\n display(EscapeSequence.hideCursor)\n }\n\n deinit {\n clear()\n }\n\n /// Allows resetting the progress state.\n public func reset() {\n state.withLock {\n $0 = State(description: config.initialDescription)\n }\n }\n\n /// Allows resetting the progress state of the current task.\n public func resetCurrentTask() {\n state.withLock {\n $0 = State(description: $0.description, itemsName: $0.itemsName, tasks: $0.tasks, totalTasks: $0.totalTasks, startTime: $0.startTime)\n }\n }\n\n private func printFullDescription() {\n let (description, subDescription) = state.withLock { ($0.description, $0.subDescription) }\n\n if subDescription != \"\" {\n standardError.write(\"\\(description) \\(subDescription)\")\n } else {\n standardError.write(description)\n }\n }\n\n /// Updates the description of the progress bar and increments the tasks by one.\n /// - Parameter description: The description of the action being performed.\n public func set(description: String) {\n resetCurrentTask()\n\n state.withLock {\n $0.description = description\n $0.subDescription = \"\"\n $0.tasks += 1\n }\n if config.disableProgressUpdates {\n printFullDescription()\n }\n }\n\n /// Updates the additional description of the progress bar.\n /// - Parameter subDescription: The additional description of the action being performed.\n public func set(subDescription: String) {\n resetCurrentTask()\n\n state.withLock { $0.subDescription = subDescription }\n if config.disableProgressUpdates {\n printFullDescription()\n }\n }\n\n private func start(intervalSeconds: TimeInterval) async {\n if config.disableProgressUpdates && !state.withLock({ $0.description.isEmpty }) {\n printFullDescription()\n }\n\n while !state.withLock({ $0.finished }) {\n let intervalNanoseconds = UInt64(intervalSeconds * 1_000_000_000)\n render()\n state.withLock { $0.iteration += 1 }\n if (try? await Task.sleep(nanoseconds: intervalNanoseconds)) == nil {\n return\n }\n }\n }\n\n /// Starts an animation of the progress bar.\n /// - Parameter intervalSeconds: The time interval between updates in seconds.\n public func start(intervalSeconds: TimeInterval = 0.04) {\n Task(priority: .utility) {\n await start(intervalSeconds: intervalSeconds)\n }\n }\n\n /// Finishes the progress bar.\n public func finish() {\n guard !state.withLock({ $0.finished }) else {\n return\n }\n\n state.withLock { $0.finished = true }\n\n // The last render.\n render(force: true)\n\n if !config.disableProgressUpdates && !config.clearOnFinish {\n displayText(state.withLock { $0.output }, terminating: \"\\n\")\n }\n\n if config.clearOnFinish {\n clearAndResetCursor()\n } else {\n resetCursor()\n }\n // Allow printed output to flush.\n usleep(100_000)\n }\n}\n\nextension ProgressBar {\n private func secondsSinceStart() -> Int {\n let timeDifferenceNanoseconds = DispatchTime.now().uptimeNanoseconds - state.withLock { $0.startTime.uptimeNanoseconds }\n let timeDifferenceSeconds = Int(floor(Double(timeDifferenceNanoseconds) / 1_000_000_000))\n return timeDifferenceSeconds\n }\n\n func render(force: Bool = false) {\n guard term != nil && !config.disableProgressUpdates && (force || !state.withLock { $0.finished }) else {\n return\n }\n let output = draw()\n displayText(output)\n }\n\n func draw() -> String {\n let state = self.state.withLock { $0 }\n\n var components = [String]()\n if config.showSpinner && !config.showProgressBar {\n if !state.finished {\n let spinnerIcon = config.theme.getSpinnerIcon(state.iteration)\n components.append(\"\\(spinnerIcon)\")\n } else {\n components.append(\"\\(config.theme.done)\")\n }\n }\n\n if config.showTasks, let totalTasks = state.totalTasks {\n let tasks = min(state.tasks, totalTasks)\n components.append(\"[\\(tasks)/\\(totalTasks)]\")\n }\n\n if config.showDescription && !state.description.isEmpty {\n components.append(\"\\(state.description)\")\n if !state.subDescription.isEmpty {\n components.append(\"\\(state.subDescription)\")\n }\n }\n\n let allowProgress = !config.ignoreSmallSize || state.totalSize == nil || state.totalSize! > Int64(1024 * 1024)\n\n let value = state.totalSize != nil ? state.size : Int64(state.items)\n let total = state.totalSize ?? Int64(state.totalItems ?? 0)\n\n if config.showPercent && total > 0 && allowProgress {\n components.append(\"\\(state.finished ? \"100%\" : state.percent)\")\n }\n\n if config.showProgressBar, total > 0, allowProgress {\n let usedWidth = components.joined(separator: \" \").count + 45 /* the maximum number of characters we may need */\n let remainingWidth = max(config.width - usedWidth, 1 /* the minimum width of a progress bar */)\n let barLength = state.finished ? remainingWidth : Int(Int64(remainingWidth) * value / total)\n let barPaddingLength = remainingWidth - barLength\n let bar = \"\\(String(repeating: config.theme.bar, count: barLength))\\(String(repeating: \" \", count: barPaddingLength))\"\n components.append(\"|\\(bar)|\")\n }\n\n var additionalComponents = [String]()\n\n if config.showItems, state.items > 0 {\n var itemsName = \"\"\n if !state.itemsName.isEmpty {\n itemsName = \" \\(state.itemsName)\"\n }\n if state.finished {\n if let totalItems = state.totalItems {\n additionalComponents.append(\"\\(totalItems.formattedNumber())\\(itemsName)\")\n }\n } else {\n if let totalItems = state.totalItems {\n additionalComponents.append(\"\\(state.items.formattedNumber()) of \\(totalItems.formattedNumber())\\(itemsName)\")\n } else {\n additionalComponents.append(\"\\(state.items.formattedNumber())\\(itemsName)\")\n }\n }\n }\n\n if state.size > 0 && allowProgress {\n if state.finished {\n if config.showSize {\n if let totalSize = state.totalSize {\n var formattedTotalSize = totalSize.formattedSize()\n formattedTotalSize = adjustFormattedSize(formattedTotalSize)\n additionalComponents.append(formattedTotalSize)\n }\n }\n } else {\n var formattedCombinedSize = \"\"\n if config.showSize {\n var formattedSize = state.size.formattedSize()\n formattedSize = adjustFormattedSize(formattedSize)\n if let totalSize = state.totalSize {\n var formattedTotalSize = totalSize.formattedSize()\n formattedTotalSize = adjustFormattedSize(formattedTotalSize)\n formattedCombinedSize = combineSize(size: formattedSize, totalSize: formattedTotalSize)\n } else {\n formattedCombinedSize = formattedSize\n }\n }\n\n var formattedSpeed = \"\"\n if config.showSpeed {\n formattedSpeed = \"\\(state.sizeSpeed ?? state.averageSizeSpeed)\"\n formattedSpeed = adjustFormattedSize(formattedSpeed)\n }\n\n if config.showSize && config.showSpeed {\n additionalComponents.append(formattedCombinedSize)\n additionalComponents.append(formattedSpeed)\n } else if config.showSize {\n additionalComponents.append(formattedCombinedSize)\n } else if config.showSpeed {\n additionalComponents.append(formattedSpeed)\n }\n }\n }\n\n if additionalComponents.count > 0 {\n let joinedAdditionalComponents = additionalComponents.joined(separator: \", \")\n components.append(\"(\\(joinedAdditionalComponents))\")\n }\n\n if config.showTime {\n let timeDifferenceSeconds = secondsSinceStart()\n let formattedTime = timeDifferenceSeconds.formattedTime()\n components.append(\"[\\(formattedTime)]\")\n }\n\n return components.joined(separator: \" \")\n }\n\n private func adjustFormattedSize(_ size: String) -> String {\n // Ensure we always have one digit after the decimal point to prevent flickering.\n let zero = Int64(0).formattedSize()\n guard !size.contains(\".\"), let first = size.first, first.isNumber || !size.contains(zero) else {\n return size\n }\n var size = size\n for unit in [\"MB\", \"GB\", \"TB\"] {\n size = size.replacingOccurrences(of: \" \\(unit)\", with: \".0 \\(unit)\")\n }\n return size\n }\n\n private func combineSize(size: String, totalSize: String) -> String {\n let sizeComponents = size.split(separator: \" \", maxSplits: 1)\n let totalSizeComponents = totalSize.split(separator: \" \", maxSplits: 1)\n guard sizeComponents.count == 2, totalSizeComponents.count == 2 else {\n return \"\\(size)/\\(totalSize)\"\n }\n let sizeNumber = sizeComponents[0]\n let sizeUnit = sizeComponents[1]\n let totalSizeNumber = totalSizeComponents[0]\n let totalSizeUnit = totalSizeComponents[1]\n guard sizeUnit == totalSizeUnit else {\n return \"\\(size)/\\(totalSize)\"\n }\n return \"\\(sizeNumber)/\\(totalSizeNumber) \\(totalSizeUnit)\"\n }\n}\n"], ["/container/Sources/APIServer/Networks/NetworksService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerPersistence\nimport ContainerPlugin\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor NetworksService {\n private let resourceRoot: URL\n // FIXME: remove qualifier once we can update Containerization dependency.\n private let store: ContainerPersistence.FilesystemEntityStore\n private let pluginLoader: PluginLoader\n private let log: Logger\n private let networkPlugin: Plugin\n\n private var networkStates = [String: NetworkState]()\n private var busyNetworks = Set()\n\n public init(pluginLoader: PluginLoader, resourceRoot: URL, log: Logger) async throws {\n try FileManager.default.createDirectory(at: resourceRoot, withIntermediateDirectories: true)\n self.resourceRoot = resourceRoot\n self.store = try FilesystemEntityStore(path: resourceRoot, type: \"network\", log: log)\n self.pluginLoader = pluginLoader\n self.log = log\n\n let networkPlugin =\n pluginLoader\n .findPlugins()\n .filter { $0.hasType(.network) }\n .first\n guard let networkPlugin else {\n throw ContainerizationError(.internalError, message: \"cannot find network plugin\")\n }\n self.networkPlugin = networkPlugin\n\n let configurations = try await store.list()\n for configuration in configurations {\n do {\n try await registerService(configuration: configuration)\n } catch {\n log.error(\n \"failed to start network\",\n metadata: [\n \"id\": \"\\(configuration.id)\"\n ])\n }\n\n let client = NetworkClient(id: configuration.id)\n let networkState = try await client.state()\n networkStates[configuration.id] = networkState\n guard case .running = networkState else {\n log.error(\n \"network failed to start\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"state\": \"\\(networkState.state)\",\n ])\n return\n }\n }\n }\n\n /// List all networks registered with the service.\n public func list() async throws -> [NetworkState] {\n log.info(\"network service: list\")\n return networkStates.reduce(into: [NetworkState]()) {\n $0.append($1.value)\n }\n }\n\n /// Create a new network from the provided configuration.\n public func create(configuration: NetworkConfiguration) async throws -> NetworkState {\n guard !busyNetworks.contains(configuration.id) else {\n throw ContainerizationError(.exists, message: \"network \\(configuration.id) has a pending operation\")\n }\n\n busyNetworks.insert(configuration.id)\n defer { busyNetworks.remove(configuration.id) }\n\n log.info(\n \"network service: create\",\n metadata: [\n \"id\": \"\\(configuration.id)\"\n ])\n\n // Ensure the network doesn't already exist.\n guard networkStates[configuration.id] == nil else {\n throw ContainerizationError(.exists, message: \"network \\(configuration.id) already exists\")\n }\n\n // Create and start the network.\n try await registerService(configuration: configuration)\n let client = NetworkClient(id: configuration.id)\n let networkState = try await client.state()\n networkStates[configuration.id] = networkState\n\n // Persist the configuration data.\n do {\n try await store.create(configuration)\n return networkState\n } catch {\n networkStates.removeValue(forKey: configuration.id)\n do {\n try pluginLoader.deregisterWithLaunchd(plugin: networkPlugin, instanceId: configuration.id)\n } catch {\n log.error(\n \"failed to deregister network service after failed creation\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"error\": \"\\(error.localizedDescription)\",\n ])\n }\n\n throw error\n }\n }\n\n /// Delete a network.\n public func delete(id: String) async throws {\n guard !busyNetworks.contains(id) else {\n throw ContainerizationError(.exists, message: \"network \\(id) has a pending operation\")\n }\n\n busyNetworks.insert(id)\n defer { busyNetworks.remove(id) }\n\n log.info(\n \"network service: delete\",\n metadata: [\n \"id\": \"\\(id)\"\n ])\n if id == ClientNetwork.defaultNetworkName {\n throw ContainerizationError(.invalidArgument, message: \"cannot delete system subnet \\(ClientNetwork.defaultNetworkName)\")\n }\n\n guard let networkState = networkStates[id] else {\n throw ContainerizationError(.notFound, message: \"no network for id \\(id)\")\n }\n\n guard case .running = networkState else {\n throw ContainerizationError(.invalidState, message: \"cannot delete subnet \\(id) in state \\(networkState.state)\")\n }\n\n let client = NetworkClient(id: id)\n guard try await client.disableAllocator() else {\n throw ContainerizationError(.invalidState, message: \"cannot delete subnet \\(id) with containers attached\")\n }\n\n defer { networkStates.removeValue(forKey: id) }\n do {\n try pluginLoader.deregisterWithLaunchd(plugin: networkPlugin, instanceId: id)\n } catch {\n log.error(\n \"failed to deregister network service after failed creation\",\n metadata: [\n \"id\": \"\\(id)\",\n \"error\": \"\\(error.localizedDescription)\",\n ])\n }\n\n do {\n try await store.delete(id)\n } catch {\n throw ContainerizationError(.notFound, message: error.localizedDescription)\n }\n }\n\n /// Perform a hostname lookup on all networks.\n public func lookup(hostname: String) async throws -> Attachment? {\n for id in networkStates.keys {\n let client = NetworkClient(id: id)\n guard let allocation = try await client.lookup(hostname: hostname) else {\n continue\n }\n return allocation\n }\n return nil\n }\n\n private func registerService(configuration: NetworkConfiguration) async throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported network mode \\(configuration.mode.rawValue)\")\n }\n\n guard let serviceIdentifier = networkPlugin.getMachService(instanceId: configuration.id, type: .network) else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported network mode \\(configuration.mode.rawValue)\")\n }\n var args = [\n \"start\",\n \"--id\",\n configuration.id,\n \"--service-identifier\",\n serviceIdentifier,\n ]\n\n if let subnet = (try configuration.subnet.map { try CIDRAddress($0) }) {\n var existingCidrs: [CIDRAddress] = []\n for networkState in networkStates.values {\n if case .running(_, let status) = networkState {\n existingCidrs.append(try CIDRAddress(status.address))\n }\n }\n let overlap = existingCidrs.first { $0.overlaps(cidr: subnet) }\n if let overlap {\n throw ContainerizationError(.exists, message: \"subnet \\(subnet) overlaps an existing network with subnet \\(overlap)\")\n }\n\n args += [\"--subnet\", subnet.description]\n }\n\n try await pluginLoader.registerWithLaunchd(\n plugin: networkPlugin,\n rootURL: store.entityUrl(configuration.id),\n args: args,\n instanceId: configuration.id\n )\n }\n}\n"], ["/container/Sources/CLI/Image/ImageRemove.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct RemoveImageOptions: ParsableArguments {\n @Flag(name: .shortAndLong, help: \"Remove all images\")\n var all: Bool = false\n\n @Argument\n var images: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n }\n\n struct RemoveImageImplementation {\n static func validate(options: RemoveImageOptions) throws {\n if options.images.count == 0 && !options.all {\n throw ContainerizationError(.invalidArgument, message: \"no image specified and --all not supplied\")\n }\n if options.images.count > 0 && options.all {\n throw ContainerizationError(.invalidArgument, message: \"explicitly supplied images conflict with the --all flag\")\n }\n }\n\n static func removeImage(options: RemoveImageOptions) async throws {\n let (found, notFound) = try await {\n if options.all {\n let found = try await ClientImage.list()\n let notFound: [String] = []\n return (found, notFound)\n }\n return try await ClientImage.get(names: options.images)\n }()\n var failures: [String] = notFound\n var didDeleteAnyImage = false\n for image in found {\n guard !Utility.isInfraImage(name: image.reference) else {\n continue\n }\n do {\n try await ClientImage.delete(reference: image.reference, garbageCollect: false)\n print(image.reference)\n didDeleteAnyImage = true\n } catch {\n log.error(\"failed to remove \\(image.reference): \\(error)\")\n failures.append(image.reference)\n }\n }\n let (_, size) = try await ClientImage.pruneImages()\n let formatter = ByteCountFormatter()\n let freed = formatter.string(fromByteCount: Int64(size))\n\n if didDeleteAnyImage {\n print(\"Reclaimed \\(freed) in disk space\")\n }\n if failures.count > 0 {\n throw ContainerizationError(.internalError, message: \"failed to delete one or more images: \\(failures)\")\n }\n }\n }\n\n struct ImageRemove: AsyncParsableCommand {\n @OptionGroup\n var options: RemoveImageOptions\n\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Remove one or more images\",\n aliases: [\"rm\"])\n\n func validate() throws {\n try RemoveImageImplementation.validate(options: options)\n }\n\n mutating func run() async throws {\n try await RemoveImageImplementation.removeImage(options: options)\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/ServiceManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\npublic struct ServiceManager {\n private static func runLaunchctlCommand(args: [String]) throws -> Int32 {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = args\n\n let null = FileHandle.nullDevice\n launchctl.standardOutput = null\n launchctl.standardError = null\n\n try launchctl.run()\n launchctl.waitUntilExit()\n\n return launchctl.terminationStatus\n }\n\n /// Register a service by providing the path to a plist.\n public static func register(plistPath: String) throws {\n let domain = try Self.getDomainString()\n _ = try runLaunchctlCommand(args: [\"bootstrap\", domain, plistPath])\n }\n\n /// Deregister a service by a launchd label.\n public static func deregister(fullServiceLabel label: String) throws {\n _ = try runLaunchctlCommand(args: [\"bootout\", label])\n }\n\n /// Restart a service by a launchd label.\n public static func kickstart(fullServiceLabel label: String) throws {\n _ = try runLaunchctlCommand(args: [\"kickstart\", \"-k\", label])\n }\n\n /// Send a signal to a service by a launchd label.\n public static func kill(fullServiceLabel label: String, signal: Int32 = 15) throws {\n _ = try runLaunchctlCommand(args: [\"kill\", \"\\(signal)\", label])\n }\n\n /// Retrieve labels for all loaded launch units.\n public static func enumerate() throws -> [String] {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = [\"list\"]\n\n let stdoutPipe = Pipe()\n let stderrPipe = Pipe()\n launchctl.standardOutput = stdoutPipe\n launchctl.standardError = stderrPipe\n\n try launchctl.run()\n let outputData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()\n let stderrData = stderrPipe.fileHandleForReading.readDataToEndOfFile()\n launchctl.waitUntilExit()\n let status = launchctl.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(\n .internalError, message: \"Command `launchctl list` failed with status \\(status). Message: \\(String(data: stderrData, encoding: .utf8) ?? \"No error message\")\")\n }\n\n guard let outputText = String(data: outputData, encoding: .utf8) else {\n throw ContainerizationError(\n .internalError, message: \"Could not decode output of command `launchctl list`. Message: \\(String(data: stderrData, encoding: .utf8) ?? \"No error message\")\")\n }\n\n // The third field of each line of launchctl list output is the label\n return outputText.split { $0.isNewline }\n .map { String($0).split { $0.isWhitespace } }\n .filter { $0.count >= 3 }\n .map { String($0[2]) }\n }\n\n /// Check if a service has been registered or not.\n public static func isRegistered(fullServiceLabel label: String) throws -> Bool {\n let exitStatus = try runLaunchctlCommand(args: [\"list\", label])\n return exitStatus == 0\n }\n\n private static func getLaunchdSessionType() throws -> String {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = [\"managername\"]\n\n let null = FileHandle.nullDevice\n let stdoutPipe = Pipe()\n launchctl.standardOutput = stdoutPipe\n launchctl.standardError = null\n\n try launchctl.run()\n let outputData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()\n launchctl.waitUntilExit()\n let status = launchctl.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(.internalError, message: \"Command `launchctl managername` failed with status \\(status)\")\n }\n guard let outputText = String(data: outputData, encoding: .utf8) else {\n throw ContainerizationError(.internalError, message: \"Could not decode output of command `launchctl managername`\")\n }\n return outputText.trimmingCharacters(in: .whitespacesAndNewlines)\n }\n\n public static func getDomainString() throws -> String {\n let currentSessionType = try getLaunchdSessionType()\n switch currentSessionType {\n case LaunchPlist.Domain.System.rawValue:\n return LaunchPlist.Domain.System.rawValue.lowercased()\n case LaunchPlist.Domain.Background.rawValue:\n return \"user/\\(getuid())\"\n case LaunchPlist.Domain.Aqua.rawValue:\n return \"gui/\\(getuid())\"\n default:\n throw ContainerizationError(.internalError, message: \"Unsupported session type \\(currentSessionType)\")\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct ClientContainer: Sendable, Codable {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n\n private var sandboxClient: SandboxClient {\n SandboxClient(id: configuration.id, runtime: configuration.runtimeHandler)\n }\n\n /// Identifier of the container.\n public var id: String {\n configuration.id\n }\n\n public let status: RuntimeStatus\n\n /// Configured platform for the container.\n public var platform: ContainerizationOCI.Platform {\n configuration.platform\n }\n\n /// Configuration for the container.\n public let configuration: ContainerConfiguration\n\n /// Network allocated to the container.\n public let networks: [Attachment]\n\n package init(configuration: ContainerConfiguration) {\n self.configuration = configuration\n self.status = .stopped\n self.networks = []\n }\n\n init(snapshot: ContainerSnapshot) {\n self.configuration = snapshot.configuration\n self.status = snapshot.status\n self.networks = snapshot.networks\n }\n\n public var initProcess: ClientProcess {\n ClientProcessImpl(containerId: self.id, client: self.sandboxClient)\n }\n}\n\nextension ClientContainer {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n @discardableResult\n private static func xpcSend(\n client: XPCClient,\n message: XPCMessage,\n timeout: Duration? = .seconds(15)\n ) async throws -> XPCMessage {\n try await client.send(message, responseTimeout: timeout)\n }\n\n public static func create(\n configuration: ContainerConfiguration,\n options: ContainerCreateOptions = .default,\n kernel: Kernel\n ) async throws -> ClientContainer {\n do {\n let client = Self.newClient()\n let request = XPCMessage(route: .createContainer)\n\n let data = try JSONEncoder().encode(configuration)\n let kdata = try JSONEncoder().encode(kernel)\n let odata = try JSONEncoder().encode(options)\n request.set(key: .containerConfig, value: data)\n request.set(key: .kernel, value: kdata)\n request.set(key: .containerOptions, value: odata)\n\n try await xpcSend(client: client, message: request)\n return ClientContainer(configuration: configuration)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to create container\",\n cause: error\n )\n }\n }\n\n public static func list() async throws -> [ClientContainer] {\n do {\n let client = Self.newClient()\n let request = XPCMessage(route: .listContainer)\n\n let response = try await xpcSend(\n client: client,\n message: request,\n timeout: .seconds(10)\n )\n let data = response.dataNoCopy(key: .containers)\n guard let data else {\n return []\n }\n let configs = try JSONDecoder().decode([ContainerSnapshot].self, from: data)\n return configs.map { ClientContainer(snapshot: $0) }\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to list containers\",\n cause: error\n )\n }\n }\n\n /// Get the container for the provided id.\n public static func get(id: String) async throws -> ClientContainer {\n let containers = try await list()\n guard let container = containers.first(where: { $0.id == id }) else {\n throw ContainerizationError(\n .notFound,\n message: \"get failed: container \\(id) not found\"\n )\n }\n return container\n }\n}\n\nextension ClientContainer {\n public func bootstrap() async throws -> ClientProcess {\n let client = self.sandboxClient\n try await client.bootstrap()\n return ClientProcessImpl(containerId: self.id, client: self.sandboxClient)\n }\n\n /// Stop the container and all processes currently executing inside.\n public func stop(opts: ContainerStopOptions = ContainerStopOptions.default) async throws {\n do {\n let client = self.sandboxClient\n try await client.stop(options: opts)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to stop container\",\n cause: error\n )\n }\n }\n\n /// Delete the container along with any resources.\n public func delete() async throws {\n do {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .deleteContainer)\n request.set(key: .id, value: self.id)\n try await client.send(request)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to delete container\",\n cause: error\n )\n }\n }\n}\n\nextension ClientContainer {\n /// Execute a new process inside a running container.\n public func createProcess(id: String, configuration: ProcessConfiguration) async throws -> ClientProcess {\n do {\n let client = self.sandboxClient\n try await client.createProcess(id, config: configuration)\n return ClientProcessImpl(containerId: self.id, processId: id, client: client)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to exec in container\",\n cause: error\n )\n }\n }\n\n /// Send or \"kill\" a signal to the initial process of the container.\n /// Kill does not wait for the process to exit, it only delivers the signal.\n public func kill(_ signal: Int32) async throws {\n do {\n let client = self.sandboxClient\n try await client.kill(self.id, signal: Int64(signal))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill container \\(self.id)\",\n cause: error\n )\n }\n }\n\n public func logs() async throws -> [FileHandle] {\n do {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .containerLogs)\n request.set(key: .id, value: self.id)\n\n let response = try await client.send(request)\n let fds = response.fileHandles(key: .logs)\n guard let fds else {\n throw ContainerizationError(\n .internalError,\n message: \"No log fds returned\"\n )\n }\n return fds\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get logs for container \\(self.id)\",\n cause: error\n )\n }\n }\n\n public func dial(_ port: UInt32) async throws -> FileHandle {\n do {\n let client = self.sandboxClient\n return try await client.dial(port)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to dial \\(port) in container \\(self.id)\",\n cause: error\n )\n }\n }\n}\n"], ["/container/Sources/ContainerClient/HostDNSResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n/// Functions for managing local DNS domains for containers.\npublic struct HostDNSResolver {\n public static let defaultConfigPath = URL(filePath: \"/etc/resolver\")\n\n // prefix used to mark our files as /etc/resolver/{prefix}{domainName}\n private static let containerizationPrefix = \"containerization.\"\n\n private let configURL: URL\n\n public init(configURL: URL = Self.defaultConfigPath) {\n self.configURL = configURL\n }\n\n /// Creates a DNS resolver configuration file for domain resolved by the application.\n public func createDomain(name: String) throws {\n let path = self.configURL.appending(path: \"\\(Self.containerizationPrefix)\\(name)\").path\n let fm: FileManager = FileManager.default\n\n if fm.fileExists(atPath: self.configURL.path) {\n guard let isDir = try self.configURL.resourceValues(forKeys: [.isDirectoryKey]).isDirectory, isDir else {\n throw ContainerizationError(.invalidState, message: \"expected \\(self.configURL.path) to be a directory, but found a file\")\n }\n } else {\n try fm.createDirectory(at: self.configURL, withIntermediateDirectories: true)\n }\n\n guard !fm.fileExists(atPath: path) else {\n throw ContainerizationError(.exists, message: \"domain \\(name) already exists\")\n }\n\n let resolverText = \"\"\"\n domain \\(name)\n search \\(name)\n nameserver 127.0.0.1\n port 2053\n \"\"\"\n\n do {\n try resolverText.write(toFile: path, atomically: true, encoding: .utf8)\n } catch {\n throw ContainerizationError(.invalidState, message: \"failed to write resolver configuration for \\(name)\")\n }\n }\n\n /// Removes a DNS resolver configuration file for domain resolved by the application.\n public func deleteDomain(name: String) throws {\n let path = self.configURL.appending(path: \"\\(Self.containerizationPrefix)\\(name)\").path\n let fm = FileManager.default\n guard fm.fileExists(atPath: path) else {\n throw ContainerizationError(.notFound, message: \"domain \\(name) at \\(path) not found\")\n }\n\n do {\n try fm.removeItem(atPath: path)\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot delete domain (try sudo?)\")\n }\n }\n\n /// Lists application-created local DNS domains.\n public func listDomains() -> [String] {\n let fm: FileManager = FileManager.default\n guard\n let resolverPaths = try? fm.contentsOfDirectory(\n at: self.configURL,\n includingPropertiesForKeys: [.isDirectoryKey]\n )\n else {\n return []\n }\n\n return\n resolverPaths\n .filter { $0.lastPathComponent.starts(with: Self.containerizationPrefix) }\n .compactMap { try? getDomainFromResolver(url: $0) }\n .sorted()\n }\n\n /// Reinitializes the macOS DNS daemon.\n public static func reinitialize() throws {\n do {\n let kill = Foundation.Process()\n kill.executableURL = URL(fileURLWithPath: \"/usr/bin/killall\")\n kill.arguments = [\"-HUP\", \"mDNSResponder\"]\n\n let null = FileHandle.nullDevice\n kill.standardOutput = null\n kill.standardError = null\n\n try kill.run()\n kill.waitUntilExit()\n let status = kill.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(.internalError, message: \"mDNSResponder restart failed with status \\(status)\")\n }\n }\n }\n\n private func getDomainFromResolver(url: URL) throws -> String? {\n let text = try String(contentsOf: url, encoding: .utf8)\n for line in text.components(separatedBy: .newlines) {\n let trimmed = line.trimmingCharacters(in: .whitespaces)\n let components = trimmed.split(whereSeparator: { $0.isWhitespace })\n guard components.count == 2 else {\n continue\n }\n guard components[0] == \"domain\" else {\n continue\n }\n\n return String(components[1])\n }\n\n return nil\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerExec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct ContainerExec: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"exec\",\n abstract: \"Run a new command in a running container\")\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Running containers ID\")\n var containerID: String\n\n @Argument(parsing: .captureForPassthrough, help: \"New process arguments\")\n var arguments: [String]\n\n func run() async throws {\n var exitCode: Int32 = 127\n let container = try await ClientContainer.get(id: containerID)\n try ensureRunning(container: container)\n\n let stdin = self.processFlags.interactive\n let tty = self.processFlags.tty\n\n var config = container.configuration.initProcess\n config.executable = arguments.first!\n config.arguments = [String](self.arguments.dropFirst())\n config.terminal = tty\n config.environment.append(\n contentsOf: try Parser.allEnv(\n imageEnvs: [],\n envFiles: self.processFlags.envFile,\n envs: self.processFlags.env\n ))\n\n if let cwd = self.processFlags.cwd {\n config.workingDirectory = cwd\n }\n\n let defaultUser = config.user\n let (user, additionalGroups) = Parser.user(\n user: processFlags.user, uid: processFlags.uid,\n gid: processFlags.gid, defaultUser: defaultUser)\n config.user = user\n config.supplementalGroups.append(contentsOf: additionalGroups)\n\n do {\n let io = try ProcessIO.create(tty: tty, interactive: stdin, detach: false)\n\n if !self.processFlags.tty {\n var handler = SignalThreshold(threshold: 3, signals: [SIGINT, SIGTERM])\n handler.start {\n print(\"Received 3 SIGINT/SIGTERM's, forcefully exiting.\")\n Darwin.exit(1)\n }\n }\n\n let process = try await container.createProcess(\n id: UUID().uuidString.lowercased(),\n configuration: config)\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to exec process \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n"], ["/container/Sources/SocketForwarder/UDPForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\nimport Synchronization\n\n// Proxy backend for a single client address (clientIP, clientPort).\nprivate final class UDPProxyBackend: ChannelInboundHandler, Sendable {\n typealias InboundIn = AddressedEnvelope\n typealias OutboundOut = AddressedEnvelope\n\n private struct State {\n var queuedPayloads: Deque\n var channel: (any Channel)?\n }\n\n private let clientAddress: SocketAddress\n private let serverAddress: SocketAddress\n private let frontendChannel: any Channel\n private let log: Logger?\n private let state: Mutex\n\n init(clientAddress: SocketAddress, serverAddress: SocketAddress, frontendChannel: any Channel, log: Logger? = nil) {\n self.clientAddress = clientAddress\n self.serverAddress = serverAddress\n self.frontendChannel = frontendChannel\n self.log = log\n let state = State(queuedPayloads: Deque(), channel: nil)\n self.state = Mutex(state)\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n // relay data from server to client.\n let inbound = self.unwrapInboundIn(data)\n let outbound = OutboundOut(remoteAddress: self.clientAddress, data: inbound.data)\n self.log?.trace(\"backend - writing datagram to client\")\n _ = self.frontendChannel.writeAndFlush(outbound)\n }\n\n func channelActive(context: ChannelHandlerContext) {\n state.withLock {\n if !$0.queuedPayloads.isEmpty {\n self.log?.trace(\"backend - writing \\($0.queuedPayloads.count) queued datagrams to server\")\n while let queuedData = $0.queuedPayloads.popFirst() {\n let outbound: UDPProxyBackend.OutboundOut = OutboundOut(remoteAddress: self.serverAddress, data: queuedData)\n _ = context.channel.writeAndFlush(outbound)\n }\n }\n $0.channel = context.channel\n }\n }\n\n func write(data: ByteBuffer) {\n // change package remote address from proxy server to real server\n state.withLock {\n if let channel = $0.channel {\n // channel has been initialized, so relay any queued packets, along with this one to outbound\n self.log?.trace(\"backend - writing datagram to server\")\n let outbound: UDPProxyBackend.OutboundOut = OutboundOut(remoteAddress: self.serverAddress, data: data)\n _ = channel.writeAndFlush(outbound)\n } else {\n // channel is initializing, queue\n self.log?.trace(\"backend - queuing datagram\")\n $0.queuedPayloads.append(data)\n }\n }\n }\n\n func close() {\n state.withLock {\n guard let channel = $0.channel else {\n self.log?.warning(\"backend - close on inactive channel\")\n return\n }\n _ = channel.close()\n }\n }\n}\n\nprivate struct ProxyContext {\n public let proxy: UDPProxyBackend\n public let closeFuture: EventLoopFuture\n}\n\nprivate final class UDPProxyFrontend: ChannelInboundHandler, Sendable {\n typealias InboundIn = AddressedEnvelope\n typealias OutboundOut = AddressedEnvelope\n private let maxProxies = UInt(256)\n\n private let proxyAddress: SocketAddress\n private let serverAddress: SocketAddress\n private let eventLoopGroup: any EventLoopGroup\n private let log: Logger?\n\n private let proxies: Mutex>\n\n init(proxyAddress: SocketAddress, serverAddress: SocketAddress, eventLoopGroup: any EventLoopGroup, log: Logger? = nil) {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.proxies = Mutex(LRUCache(size: maxProxies))\n self.log = log\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n let inbound = self.unwrapInboundIn(data)\n\n guard let clientIP = inbound.remoteAddress.ipAddress else {\n log?.error(\"frontend - no client IP address in inbound payload\")\n return\n }\n\n guard let clientPort = inbound.remoteAddress.port else {\n log?.error(\"frontend - no client port in inbound payload\")\n return\n }\n\n let key = \"\\(clientIP):\\(clientPort)\"\n do {\n try proxies.withLock {\n if let context = $0.get(key) {\n context.proxy.write(data: inbound.data)\n } else {\n self.log?.trace(\"frontend - creating backend\")\n let proxy = UDPProxyBackend(\n clientAddress: inbound.remoteAddress,\n serverAddress: self.serverAddress,\n frontendChannel: context.channel,\n log: log\n )\n let proxyAddress = try SocketAddress(ipAddress: \"0.0.0.0\", port: 0)\n let proxyToServerFuture = DatagramBootstrap(group: self.eventLoopGroup)\n .channelInitializer {\n self.log?.trace(\"frontend - initializing backend\")\n return $0.pipeline.addHandler(proxy)\n }\n .bind(to: proxyAddress)\n .flatMap { $0.closeFuture }\n let context = ProxyContext(proxy: proxy, closeFuture: proxyToServerFuture)\n if let (_, evictedContext) = $0.put(key: key, value: context) {\n self.log?.trace(\"frontend - closing evicted backend\")\n evictedContext.proxy.close()\n }\n\n proxy.write(data: inbound.data)\n }\n }\n } catch {\n log?.error(\"server handler - backend channel creation failed with error: \\(error)\")\n return\n }\n }\n}\n\npublic struct UDPForwarder: SocketForwarder {\n private let proxyAddress: SocketAddress\n\n private let serverAddress: SocketAddress\n\n private let eventLoopGroup: any EventLoopGroup\n\n private let log: Logger?\n\n public init(\n proxyAddress: SocketAddress,\n serverAddress: SocketAddress,\n eventLoopGroup: any EventLoopGroup,\n log: Logger? = nil\n ) throws {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.log = log\n }\n\n public func run() throws -> EventLoopFuture {\n self.log?.trace(\"frontend - creating channel\")\n let proxyToServerHandler = UDPProxyFrontend(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: log\n )\n let bootstrap = DatagramBootstrap(group: self.eventLoopGroup)\n .channelInitializer { serverChannel in\n self.log?.trace(\"frontend - initializing channel\")\n return serverChannel.pipeline.addHandler(proxyToServerHandler)\n }\n return\n bootstrap\n .bind(to: proxyAddress)\n .flatMap { $0.eventLoop.makeSucceededFuture(SocketForwarderResult(channel: $0)) }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/SnapshotStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport TerminalProgress\n\npublic actor SnapshotStore {\n private static let snapshotFileName = \"snapshot\"\n private static let snapshotInfoFileName = \"snapshot-info\"\n private static let ingestDirName = \"ingest\"\n\n /// Return the Unpacker to use for a given image.\n /// If the given platform for the image cannot be unpacked return `nil`.\n public typealias UnpackStrategy = @Sendable (Containerization.Image, Platform) async throws -> Unpacker?\n\n public static let defaultUnpackStrategy: UnpackStrategy = { image, platform in\n guard platform.os == \"linux\" else {\n return nil\n }\n var minBlockSize = 512.gib()\n if image.reference == ClientDefaults.get(key: .defaultInitImage) {\n minBlockSize = 512.mib()\n }\n return EXT4Unpacker(blockSizeInBytes: minBlockSize)\n }\n\n let path: URL\n let fm = FileManager.default\n let ingestDir: URL\n let unpackStrategy: UnpackStrategy\n let log: Logger?\n\n public init(path: URL, unpackStrategy: @escaping UnpackStrategy, log: Logger?) throws {\n let root = path.appendingPathComponent(\"snapshots\")\n self.path = root\n self.ingestDir = self.path.appendingPathComponent(Self.ingestDirName)\n self.unpackStrategy = unpackStrategy\n self.log = log\n try self.fm.createDirectory(at: root, withIntermediateDirectories: true)\n try self.fm.createDirectory(at: self.ingestDir, withIntermediateDirectories: true)\n }\n\n public func unpack(image: Containerization.Image, platform: Platform? = nil, progressUpdate: ProgressUpdateHandler?) async throws {\n var toUnpack: [Descriptor] = []\n if let platform {\n let desc = try await image.descriptor(for: platform)\n toUnpack = [desc]\n } else {\n toUnpack = try await image.unpackableDescriptors()\n }\n\n let taskManager = ProgressTaskCoordinator()\n var taskUpdateProgress: ProgressUpdateHandler?\n\n for desc in toUnpack {\n try Task.checkCancellation()\n let snapshotDir = self.snapshotDir(desc)\n guard !self.fm.fileExists(atPath: snapshotDir.absolutePath()) else {\n // We have already unpacked this image + platform. Skip\n continue\n }\n guard let platform = desc.platform else {\n throw ContainerizationError(.internalError, message: \"Missing platform for descriptor \\(desc.digest)\")\n }\n guard let unpacker = try await self.unpackStrategy(image, platform) else {\n self.log?.warning(\"Skipping unpack for \\(image.reference) for platform \\(platform.description). No unpacker configured.\")\n continue\n }\n let currentSubTask = await taskManager.startTask()\n if let progressUpdate {\n let _taskUpdateProgress = ProgressTaskCoordinator.handler(for: currentSubTask, from: progressUpdate)\n await _taskUpdateProgress([\n .setSubDescription(\"for platform \\(platform.description)\")\n ])\n taskUpdateProgress = _taskUpdateProgress\n }\n\n let tempDir = try self.tempUnpackDir()\n\n let tempSnapshotPath = tempDir.appendingPathComponent(Self.snapshotFileName, isDirectory: false)\n let infoPath = tempDir.appendingPathComponent(Self.snapshotInfoFileName, isDirectory: false)\n do {\n let progress = ContainerizationProgressAdapter.handler(from: taskUpdateProgress)\n let mount = try await unpacker.unpack(image, for: platform, at: tempSnapshotPath, progress: progress)\n let fs = Filesystem.block(\n format: mount.type,\n source: self.snapshotPath(desc).absolutePath(),\n destination: mount.destination,\n options: mount.options\n )\n let snapshotInfo = try JSONEncoder().encode(fs)\n self.fm.createFile(atPath: infoPath.absolutePath(), contents: snapshotInfo)\n } catch {\n try? self.fm.removeItem(at: tempDir)\n throw error\n }\n do {\n try fm.moveItem(at: tempDir, to: snapshotDir)\n } catch let err as NSError {\n guard err.code == NSFileWriteFileExistsError else {\n throw err\n }\n try? self.fm.removeItem(at: tempDir)\n }\n }\n await taskManager.finish()\n }\n\n public func delete(for image: Containerization.Image, platform: Platform? = nil) async throws {\n var toDelete: [Descriptor] = []\n if let platform {\n let desc = try await image.descriptor(for: platform)\n toDelete.append(desc)\n } else {\n toDelete = try await image.unpackableDescriptors()\n }\n for desc in toDelete {\n let p = self.snapshotDir(desc)\n guard self.fm.fileExists(atPath: p.absolutePath()) else {\n continue\n }\n try self.fm.removeItem(at: p)\n }\n }\n\n public func get(for image: Containerization.Image, platform: Platform) async throws -> Filesystem {\n let desc = try await image.descriptor(for: platform)\n let infoPath = snapshotInfoPath(desc)\n let fsPath = snapshotPath(desc)\n\n guard self.fm.fileExists(atPath: infoPath.absolutePath()),\n self.fm.fileExists(atPath: fsPath.absolutePath())\n else {\n throw ContainerizationError(.notFound, message: \"image snapshot for \\(image.reference) with platform \\(platform.description)\")\n }\n let decoder = JSONDecoder()\n let data = try Data(contentsOf: infoPath)\n let fs = try decoder.decode(Filesystem.self, from: data)\n return fs\n }\n\n public func clean(keepingSnapshotsFor images: [Containerization.Image] = []) async throws -> UInt64 {\n var toKeep: [String] = [Self.ingestDirName]\n for image in images {\n for manifest in try await image.index().manifests {\n guard let platform = manifest.platform else {\n continue\n }\n let desc = try await image.descriptor(for: platform)\n toKeep.append(desc.digest.trimmingDigestPrefix)\n }\n }\n let all = try self.fm.contentsOfDirectory(at: self.path, includingPropertiesForKeys: [.totalFileAllocatedSizeKey]).map {\n $0.lastPathComponent\n }\n let delete = Set(all).subtracting(Set(toKeep))\n var deletedBytes: UInt64 = 0\n for dir in delete {\n let unpackedPath = self.path.appending(path: dir, directoryHint: .isDirectory)\n guard self.fm.fileExists(atPath: unpackedPath.absolutePath()) else {\n continue\n }\n deletedBytes += (try? self.fm.directorySize(dir: unpackedPath)) ?? 0\n try self.fm.removeItem(at: unpackedPath)\n }\n return deletedBytes\n }\n\n private func snapshotDir(_ desc: Descriptor) -> URL {\n let p = self.path.appendingPathComponent(desc.digest.trimmingDigestPrefix, isDirectory: true)\n return p\n }\n\n private func snapshotPath(_ desc: Descriptor) -> URL {\n let p = self.snapshotDir(desc)\n .appendingPathComponent(Self.snapshotFileName, isDirectory: false)\n return p\n }\n\n private func snapshotInfoPath(_ desc: Descriptor) -> URL {\n let p = self.snapshotDir(desc)\n .appendingPathComponent(Self.snapshotInfoFileName, isDirectory: false)\n return p\n }\n\n private func tempUnpackDir() throws -> URL {\n let uniqueDirectoryURL = ingestDir.appendingPathComponent(UUID().uuidString, isDirectory: true)\n try self.fm.createDirectory(at: uniqueDirectoryURL, withIntermediateDirectories: true, attributes: nil)\n return uniqueDirectoryURL\n }\n}\n\nextension FileManager {\n fileprivate func directorySize(dir: URL) throws -> UInt64 {\n var size = 0\n let resourceKeys: [URLResourceKey] = [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey]\n let contents = try self.contentsOfDirectory(\n at: dir,\n includingPropertiesForKeys: resourceKeys)\n\n for p in contents {\n let val = try p.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey])\n size += val.totalFileAllocatedSize ?? val.fileAllocatedSize ?? 0\n }\n return UInt64(size)\n }\n}\n\nextension Containerization.Image {\n fileprivate func unpackableDescriptors() async throws -> [Descriptor] {\n let index = try await self.index()\n return index.manifests.filter { desc in\n guard desc.platform != nil else {\n return false\n }\n if let referenceType = desc.annotations?[\"vnd.docker.reference.type\"], referenceType == \"attestation-manifest\" {\n return false\n }\n return true\n }\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCMessage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\n\n/// A message that can be pass across application boundaries via XPC.\npublic struct XPCMessage: Sendable {\n /// Defined message key storing the route value.\n public static let routeKey = \"com.apple.container.xpc.route\"\n /// Defined message key storing the error value.\n public static let errorKey = \"com.apple.container.xpc.error\"\n\n // Access to `object` is protected by a lock\n private nonisolated(unsafe) let object: xpc_object_t\n private let lock = NSLock()\n private let isErr: Bool\n\n /// The underlying xpc object that the message wraps.\n public var underlying: xpc_object_t {\n lock.withLock {\n object\n }\n }\n public var isErrorType: Bool { isErr }\n\n public init(object: xpc_object_t) {\n self.object = object\n self.isErr = xpc_get_type(self.object) == XPC_TYPE_ERROR\n }\n\n public init(route: String) {\n self.object = xpc_dictionary_create_empty()\n self.isErr = false\n xpc_dictionary_set_string(self.object, Self.routeKey, route)\n }\n}\n\nextension XPCMessage {\n public static func == (lhs: XPCMessage, rhs: xpc_object_t) -> Bool {\n xpc_equal(lhs.underlying, rhs)\n }\n\n public func reply() -> XPCMessage {\n lock.withLock {\n XPCMessage(object: xpc_dictionary_create_reply(object)!)\n }\n }\n\n public func errorKeyDescription() -> String? {\n guard self.isErr,\n let xpcErr = lock.withLock({\n xpc_dictionary_get_string(\n self.object,\n XPC_ERROR_KEY_DESCRIPTION\n )\n })\n else {\n return nil\n }\n return String(cString: xpcErr)\n }\n\n public func error() throws {\n let data = data(key: Self.errorKey)\n if let data {\n let item = try? JSONDecoder().decode(ContainerXPCError.self, from: data)\n precondition(item != nil, \"expected to receive a ContainerXPCXPCError\")\n\n throw ContainerizationError(item!.code, message: item!.message)\n }\n }\n\n public func set(error: ContainerizationError) {\n var message = error.message\n if let cause = error.cause {\n message += \" (cause: \\\"\\(cause)\\\")\"\n }\n let serializableError = ContainerXPCError(code: error.code.description, message: message)\n let data = try? JSONEncoder().encode(serializableError)\n precondition(data != nil)\n\n set(key: Self.errorKey, value: data!)\n }\n}\n\nstruct ContainerXPCError: Codable {\n let code: String\n let message: String\n}\n\nextension XPCMessage {\n public func data(key: String) -> Data? {\n var length: Int = 0\n let bytes = lock.withLock {\n xpc_dictionary_get_data(self.object, key, &length)\n }\n\n guard let bytes else {\n return nil\n }\n\n return Data(bytes: bytes, count: length)\n }\n\n /// dataNoCopy is similar to data, except the data is not copied\n /// to a new buffer. What this means in practice is the second the\n /// underlying xpc_object_t gets released by ARC the data will be\n /// released as well. This variant should be used when you know the\n /// data will be used before the object has no more references.\n public func dataNoCopy(key: String) -> Data? {\n var length: Int = 0\n let bytes = lock.withLock {\n xpc_dictionary_get_data(self.object, key, &length)\n }\n\n guard let bytes else {\n return nil\n }\n\n return Data(\n bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes),\n count: length,\n deallocator: .none\n )\n }\n\n public func set(key: String, value: Data) {\n value.withUnsafeBytes { ptr in\n if let addr = ptr.baseAddress {\n lock.withLock {\n xpc_dictionary_set_data(self.object, key, addr, value.count)\n }\n }\n }\n }\n\n public func string(key: String) -> String? {\n let _id = lock.withLock {\n xpc_dictionary_get_string(self.object, key)\n }\n if let _id {\n return String(cString: _id)\n }\n return nil\n }\n\n public func set(key: String, value: String) {\n lock.withLock {\n xpc_dictionary_set_string(self.object, key, value)\n }\n }\n\n public func bool(key: String) -> Bool {\n lock.withLock {\n xpc_dictionary_get_bool(self.object, key)\n }\n }\n\n public func set(key: String, value: Bool) {\n lock.withLock {\n xpc_dictionary_set_bool(self.object, key, value)\n }\n }\n\n public func uint64(key: String) -> UInt64 {\n lock.withLock {\n xpc_dictionary_get_uint64(self.object, key)\n }\n }\n\n public func set(key: String, value: UInt64) {\n lock.withLock {\n xpc_dictionary_set_uint64(self.object, key, value)\n }\n }\n\n public func int64(key: String) -> Int64 {\n lock.withLock {\n xpc_dictionary_get_int64(self.object, key)\n }\n }\n\n public func set(key: String, value: Int64) {\n lock.withLock {\n xpc_dictionary_set_int64(self.object, key, value)\n }\n }\n\n public func fileHandle(key: String) -> FileHandle? {\n let fd = lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n if let fd {\n let fd2 = xpc_fd_dup(fd)\n return FileHandle(fileDescriptor: fd2, closeOnDealloc: false)\n }\n return nil\n }\n\n public func set(key: String, value: FileHandle) {\n let fd = xpc_fd_create(value.fileDescriptor)\n close(value.fileDescriptor)\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, fd)\n }\n }\n\n public func fileHandles(key: String) -> [FileHandle]? {\n let fds = lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n if let fds {\n let fd1 = xpc_array_dup_fd(fds, 0)\n let fd2 = xpc_array_dup_fd(fds, 1)\n if fd1 == -1 || fd2 == -1 {\n return nil\n }\n return [\n FileHandle(fileDescriptor: fd1, closeOnDealloc: false),\n FileHandle(fileDescriptor: fd2, closeOnDealloc: false),\n ]\n }\n return nil\n }\n\n public func set(key: String, value: [FileHandle]) throws {\n let fdArray = xpc_array_create(nil, 0)\n for fh in value {\n guard let xpcFd = xpc_fd_create(fh.fileDescriptor) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to create xpc fd for \\(fh.fileDescriptor)\"\n )\n }\n xpc_array_append_value(fdArray, xpcFd)\n close(fh.fileDescriptor)\n }\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, fdArray)\n }\n }\n\n public func endpoint(key: String) -> xpc_endpoint_t? {\n lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n }\n\n public func set(key: String, value: xpc_endpoint_t) {\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, value)\n }\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerXPC/XPCClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\n\npublic struct XPCClient: Sendable {\n private nonisolated(unsafe) let connection: xpc_connection_t\n private let q: DispatchQueue?\n private let service: String\n\n public init(service: String, queue: DispatchQueue? = nil) {\n let connection = xpc_connection_create_mach_service(service, queue, 0)\n self.connection = connection\n self.q = queue\n self.service = service\n\n xpc_connection_set_event_handler(connection) { _ in }\n xpc_connection_set_target_queue(connection, self.q)\n xpc_connection_activate(connection)\n }\n}\n\nextension XPCClient {\n /// Close the underlying XPC connection.\n public func close() {\n xpc_connection_cancel(connection)\n }\n\n /// Returns the pid of process to which we have a connection.\n /// Note: `xpc_connection_get_pid` returns 0 if no activity\n /// has taken place on the connection prior to it being called.\n public func remotePid() -> pid_t {\n xpc_connection_get_pid(self.connection)\n }\n\n /// Send the provided message to the service.\n @discardableResult\n public func send(_ message: XPCMessage, responseTimeout: Duration? = nil) async throws -> XPCMessage {\n try await withThrowingTaskGroup(of: XPCMessage.self, returning: XPCMessage.self) { group in\n if let responseTimeout {\n group.addTask {\n try await Task.sleep(for: responseTimeout)\n let route = message.string(key: XPCMessage.routeKey) ?? \"nil\"\n throw ContainerizationError(.internalError, message: \"XPC timeout for request to \\(self.service)/\\(route)\")\n }\n }\n\n group.addTask {\n try await withCheckedThrowingContinuation { cont in\n xpc_connection_send_message_with_reply(self.connection, message.underlying, nil) { reply in\n do {\n let message = try self.parseReply(reply)\n cont.resume(returning: message)\n } catch {\n cont.resume(throwing: error)\n }\n }\n }\n }\n\n let response = try await group.next()\n // once one task has finished, cancel the rest.\n group.cancelAll()\n // we don't really care about the second error here\n // as it's most likely a `CancellationError`.\n try? await group.waitForAll()\n\n guard let response else {\n throw ContainerizationError(.invalidState, message: \"failed to receive XPC response\")\n }\n return response\n }\n }\n\n private func parseReply(_ reply: xpc_object_t) throws -> XPCMessage {\n switch xpc_get_type(reply) {\n case XPC_TYPE_ERROR:\n var code = ContainerizationError.Code.invalidState\n if reply.connectionError {\n code = .interrupted\n }\n throw ContainerizationError(\n code,\n message: \"XPC connection error: \\(reply.errorDescription ?? \"unknown\")\"\n )\n case XPC_TYPE_DICTIONARY:\n let message = XPCMessage(object: reply)\n // check errors from our protocol\n try message.error()\n return message\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(reply))\")\n }\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerClient/SandboxClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport TerminalProgress\n\n/// A client for interacting with a single sandbox.\npublic struct SandboxClient: Sendable, Codable {\n static let label = \"com.apple.container.runtime\"\n\n public static func machServiceLabel(runtime: String, id: String) -> String {\n \"\\(Self.label).\\(runtime).\\(id)\"\n }\n\n private var machServiceLabel: String {\n Self.machServiceLabel(runtime: runtime, id: id)\n }\n\n let id: String\n let runtime: String\n\n /// Create a container.\n public init(id: String, runtime: String) {\n self.id = id\n self.runtime = runtime\n }\n}\n\n// Runtime Methods\nextension SandboxClient {\n public func bootstrap() async throws {\n let request = XPCMessage(route: SandboxRoutes.bootstrap.rawValue)\n let client = createClient()\n defer { client.close() }\n\n try await client.send(request)\n }\n\n public func state() async throws -> SandboxSnapshot {\n let request = XPCMessage(route: SandboxRoutes.state.rawValue)\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.sandboxSnapshot()\n }\n\n public func createProcess(_ id: String, config: ProcessConfiguration) async throws {\n let request = XPCMessage(route: SandboxRoutes.createProcess.rawValue)\n request.set(key: .id, value: id)\n let data = try JSONEncoder().encode(config)\n request.set(key: .processConfig, value: data)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func startProcess(_ id: String, stdio: [FileHandle?]) async throws {\n let request = XPCMessage(route: SandboxRoutes.start.rawValue)\n for (i, h) in stdio.enumerated() {\n let key: XPCKeys = {\n switch i {\n case 0: .stdin\n case 1: .stdout\n case 2: .stderr\n default:\n fatalError(\"invalid fd \\(i)\")\n }\n }()\n\n if let h {\n request.set(key: key, value: h)\n }\n }\n request.set(key: .id, value: id)\n\n let client = createClient()\n defer { client.close() }\n\n try await client.send(request)\n }\n\n public func stop(options: ContainerStopOptions) async throws {\n let request = XPCMessage(route: SandboxRoutes.stop.rawValue)\n\n let data = try JSONEncoder().encode(options)\n request.set(key: .stopOptions, value: data)\n\n let client = createClient()\n defer { client.close() }\n let responseTimeout = Duration(.seconds(Int64(options.timeoutInSeconds + 1)))\n try await client.send(request, responseTimeout: responseTimeout)\n }\n\n public func kill(_ id: String, signal: Int64) async throws {\n let request = XPCMessage(route: SandboxRoutes.kill.rawValue)\n request.set(key: .id, value: id)\n request.set(key: .signal, value: signal)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func resize(_ id: String, size: Terminal.Size) async throws {\n let request = XPCMessage(route: SandboxRoutes.resize.rawValue)\n request.set(key: .id, value: id)\n request.set(key: .width, value: UInt64(size.width))\n request.set(key: .height, value: UInt64(size.height))\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func wait(_ id: String) async throws -> Int32 {\n let request = XPCMessage(route: SandboxRoutes.wait.rawValue)\n request.set(key: .id, value: id)\n\n let client = createClient()\n defer { client.close() }\n let response = try await client.send(request)\n let code = response.int64(key: .exitCode)\n return Int32(code)\n }\n\n public func dial(_ port: UInt32) async throws -> FileHandle {\n let request = XPCMessage(route: SandboxRoutes.dial.rawValue)\n request.set(key: .port, value: UInt64(port))\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n guard let fh = response.fileHandle(key: .fd) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get fd for vsock port \\(port)\"\n )\n }\n return fh\n }\n\n private func createClient() -> XPCClient {\n XPCClient(service: machServiceLabel)\n }\n}\n\nextension XPCMessage {\n public func id() throws -> String {\n let id = self.string(key: .id)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"No id\")\n }\n return id\n }\n\n func sandboxSnapshot() throws -> SandboxSnapshot {\n let data = self.dataNoCopy(key: .snapshot)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No state data returned\")\n }\n return try JSONDecoder().decode(SandboxSnapshot.self, from: data)\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationExtras\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct NetworkList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List networks\",\n aliases: [\"ls\"])\n\n @Flag(name: .shortAndLong, help: \"Only output the network name\")\n var quiet = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let networks = try await ClientNetwork.list()\n try printNetworks(networks: networks, format: format)\n }\n\n private func createHeader() -> [[String]] {\n [[\"NETWORK\", \"STATE\", \"SUBNET\"]]\n }\n\n private func printNetworks(networks: [NetworkState], format: ListFormat) throws {\n if format == .json {\n let printables = networks.map {\n PrintableNetwork($0)\n }\n let data = try JSONEncoder().encode(printables)\n print(String(data: data, encoding: .utf8)!)\n\n return\n }\n\n if self.quiet {\n networks.forEach {\n print($0.id)\n }\n return\n }\n\n var rows = createHeader()\n for network in networks {\n rows.append(network.asRow)\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n }\n}\n\nextension NetworkState {\n var asRow: [String] {\n switch self {\n case .created(_):\n return [self.id, self.state, \"none\"]\n case .running(_, let status):\n return [self.id, self.state, status.address]\n }\n }\n}\n\nstruct PrintableNetwork: Codable {\n let id: String\n let state: String\n let config: NetworkConfiguration\n let status: NetworkStatus?\n\n init(_ network: NetworkState) {\n self.id = network.id\n self.state = network.state\n switch network {\n case .created(let config):\n self.config = config\n self.status = nil\n case .running(let config, let status):\n self.config = config\n self.status = status\n }\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/RuntimeLinuxHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\nimport NIO\n\n@main\nstruct RuntimeLinuxHelper: AsyncParsableCommand {\n static let label = \"com.apple.container.runtime.container-runtime-linux\"\n\n static let configuration = CommandConfiguration(\n commandName: \"container-runtime-linux\",\n abstract: \"XPC Service for managing a Linux sandbox\",\n version: releaseVersion()\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .shortAndLong, help: \"Sandbox UUID\")\n var uuid: String\n\n @Option(name: .shortAndLong, help: \"Root directory for the sandbox\")\n var root: String\n\n var machServiceLabel: String {\n \"\\(Self.label).\\(uuid)\"\n }\n\n func run() async throws {\n let commandName = Self._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n do {\n try adjustLimits()\n signal(SIGPIPE, SIG_IGN)\n\n log.info(\"configuring XPC server\")\n let interfaceStrategy: any InterfaceStrategy\n if #available(macOS 26, *) {\n interfaceStrategy = NonisolatedInterfaceStrategy(log: log)\n } else {\n interfaceStrategy = IsolatedInterfaceStrategy()\n }\n let server = SandboxService(root: .init(fileURLWithPath: root), interfaceStrategy: interfaceStrategy, eventLoopGroup: eventLoopGroup, log: log)\n let xpc = XPCServer(\n identifier: machServiceLabel,\n routes: [\n SandboxRoutes.bootstrap.rawValue: server.bootstrap,\n SandboxRoutes.createProcess.rawValue: server.createProcess,\n SandboxRoutes.state.rawValue: server.state,\n SandboxRoutes.stop.rawValue: server.stop,\n SandboxRoutes.kill.rawValue: server.kill,\n SandboxRoutes.resize.rawValue: server.resize,\n SandboxRoutes.wait.rawValue: server.wait,\n SandboxRoutes.start.rawValue: server.startProcess,\n SandboxRoutes.dial.rawValue: server.dial,\n ],\n log: log\n )\n\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n try? await eventLoopGroup.shutdownGracefully()\n RuntimeLinuxHelper.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"RuntimeLinuxHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n log[metadataKey: \"uuid\"] = \"\\(uuid)\"\n return log\n }\n\n private func adjustLimits() throws {\n var limits = rlimit()\n guard getrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n limits.rlim_cur = 65536\n limits.rlim_max = 65536\n guard setrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderDelete: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"delete\"\n config._superCommandName = \"builder\"\n config.abstract = \"Delete builder\"\n config.usage = \"\\n\\t builder delete [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Flag(name: .shortAndLong, help: \"Force delete builder even if it is running\")\n var force = false\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n if container.status != .stopped {\n guard force else {\n throw ContainerizationError(.invalidState, message: \"BuildKit container is not stopped, use --force to override\")\n }\n try await container.stop()\n }\n try await container.delete()\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/DNSServer/DNSServer+Handle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport NIOCore\nimport NIOPosix\n\nextension DNSServer {\n /// Handles the DNS request.\n /// - Parameters:\n /// - outbound: The NIOAsyncChannelOutboundWriter for which to respond.\n /// - packet: The request packet.\n func handle(\n outbound: NIOAsyncChannelOutboundWriter>,\n packet: inout AddressedEnvelope\n ) async throws {\n let chunkSize = 512\n var data = Data()\n\n self.log?.debug(\"reading data\")\n while packet.data.readableBytes > 0 {\n if let chunk = packet.data.readBytes(length: min(chunkSize, packet.data.readableBytes)) {\n data.append(contentsOf: chunk)\n }\n }\n\n self.log?.debug(\"deserializing message\")\n let query = try Message(deserialize: data)\n self.log?.debug(\"processing query: \\(query.questions)\")\n\n // always send response\n let responseData: Data\n do {\n self.log?.debug(\"awaiting processing\")\n var response =\n try await handler.answer(query: query)\n ?? Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n\n // no responses\n if response.answers.isEmpty {\n response.returnCode = .nonExistentDomain\n }\n\n self.log?.debug(\"serializing response\")\n responseData = try response.serialize()\n } catch {\n self.log?.error(\"error processing message from \\(query): \\(error)\")\n let response = Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n responseData = try response.serialize()\n }\n\n self.log?.debug(\"sending response for \\(query.id)\")\n let rData = ByteBuffer(bytes: responseData)\n try? await outbound.write(AddressedEnvelope(remoteAddress: packet.remoteAddress, data: rData))\n\n self.log?.debug(\"processing done\")\n\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientImage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\n// MARK: ClientImage structure\n\npublic struct ClientImage: Sendable {\n private let contentStore: ContentStore = RemoteContentStoreClient()\n public let description: ImageDescription\n\n public var digest: String { description.digest }\n public var descriptor: Descriptor { description.descriptor }\n public var reference: String { description.reference }\n\n public init(description: ImageDescription) {\n self.description = description\n }\n\n /// Returns the underlying OCI index for the image.\n public func index() async throws -> Index {\n guard let content: Content = try await contentStore.get(digest: description.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(description.digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the manifest for the specified platform.\n public func manifest(for platform: Platform) async throws -> Manifest {\n let index = try await self.index()\n let desc = index.manifests.first { desc in\n desc.platform == platform\n }\n guard let desc else {\n throw ContainerizationError(.unsupported, message: \"Platform \\(platform.description)\")\n }\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the OCI config for the specified platform.\n public func config(for platform: Platform) async throws -> ContainerizationOCI.Image {\n let manifest = try await self.manifest(for: platform)\n let desc = manifest.config\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n return try content.decode()\n }\n}\n\n// MARK: ClientImage constants\n\nextension ClientImage {\n private static let serviceIdentifier = \"com.apple.container.core.container-core-images\"\n public static let initImageRef = ClientDefaults.get(key: .defaultInitImage)\n\n private static func newXPCClient() -> XPCClient {\n XPCClient(service: Self.serviceIdentifier)\n }\n\n private static func newRequest(_ route: ImagesServiceXPCRoute) -> XPCMessage {\n XPCMessage(route: route)\n }\n\n private static var defaultRegistryDomain: String {\n ClientDefaults.get(key: .defaultRegistryDomain)\n }\n}\n\n// MARK: Static methods\n\nextension ClientImage {\n private static let legacyDockerRegistryHost = \"docker.io\"\n private static let dockerRegistryHost = \"registry-1.docker.io\"\n private static let defaultDockerRegistryRepo = \"library\"\n\n public static func normalizeReference(_ ref: String) throws -> String {\n guard ref != Self.initImageRef else {\n // Don't modify the default init image reference.\n // This is to allow for easier local development against\n // an updated containerization.\n return ref\n }\n // Check if the input reference has a domain specified\n var updatedRawReference: String = ref\n let r = try Reference.parse(ref)\n if r.domain == nil {\n updatedRawReference = \"\\(Self.defaultRegistryDomain)/\\(ref)\"\n }\n\n let updatedReference = try Reference.parse(updatedRawReference)\n\n // Handle adding the :latest tag if it isn't specified,\n // as well as adding the \"library/\" repository if it isn't set only if the host is docker.io\n updatedReference.normalize()\n return updatedReference.description\n }\n\n public static func denormalizeReference(_ ref: String) throws -> String {\n var updatedRawReference: String = ref\n let r = try Reference.parse(ref)\n let defaultRegistry = Self.defaultRegistryDomain\n if r.domain == defaultRegistry {\n updatedRawReference = \"\\(r.path)\"\n if let tag = r.tag {\n updatedRawReference += \":\\(tag)\"\n } else if let digest = r.digest {\n updatedRawReference += \"@\\(digest)\"\n }\n if defaultRegistry == dockerRegistryHost || defaultRegistry == legacyDockerRegistryHost {\n updatedRawReference.trimPrefix(\"\\(defaultDockerRegistryRepo)/\")\n }\n }\n return updatedRawReference\n }\n\n public static func list() async throws -> [ClientImage] {\n let client = newXPCClient()\n let request = newRequest(.imageList)\n let response = try await client.send(request)\n\n let imageDescriptions = try response.imageDescriptions()\n return imageDescriptions.map { desc in\n ClientImage(description: desc)\n }\n }\n\n public static func get(names: [String]) async throws -> (images: [ClientImage], error: [String]) {\n let all = try await self.list()\n var errors: [String] = []\n var found: [ClientImage] = []\n for name in names {\n do {\n guard let img = try Self._search(reference: name, in: all) else {\n errors.append(name)\n continue\n }\n found.append(img)\n } catch {\n errors.append(name)\n }\n }\n return (found, errors)\n }\n\n public static func get(reference: String) async throws -> ClientImage {\n let all = try await self.list()\n guard let found = try self._search(reference: reference, in: all) else {\n throw ContainerizationError(.notFound, message: \"Image with reference \\(reference)\")\n }\n return found\n }\n\n private static func _search(reference: String, in all: [ClientImage]) throws -> ClientImage? {\n let locallyBuiltImage = try {\n // Check if we have an image whose index descriptor contains the image name\n // as an annotation. Prefer this in all cases, since these are locally built images.\n let r = try Reference.parse(reference)\n r.normalize()\n let withDefaultTag = r.description\n\n let localImageMatches = all.filter { $0.description.nameFromAnnotation() == withDefaultTag }\n guard localImageMatches.count > 1 else {\n return localImageMatches.first\n }\n // More than one image matched. Check against the tagged reference\n return localImageMatches.first { $0.reference == withDefaultTag }\n }()\n if let locallyBuiltImage {\n return locallyBuiltImage\n }\n // If we don't find a match, try matching `ImageDescription.name` against the given\n // input string, while also checking against its normalized form.\n // Return the first match.\n let normalizedReference = try Self.normalizeReference(reference)\n return all.first(where: { image in\n image.reference == reference || image.reference == normalizedReference\n })\n }\n\n public static func pull(reference: String, platform: Platform? = nil, scheme: RequestScheme = .auto, progressUpdate: ProgressUpdateHandler? = nil) async throws -> ClientImage {\n let client = newXPCClient()\n let request = newRequest(.imagePull)\n\n let reference = try self.normalizeReference(reference)\n guard let host = try Reference.parse(reference).domain else {\n throw ContainerizationError(.invalidArgument, message: \"Could not extract host from reference \\(reference)\")\n }\n\n request.set(key: .imageReference, value: reference)\n try request.set(platform: platform)\n\n let insecure = try scheme.schemeFor(host: host) == .http\n request.set(key: .insecureFlag, value: insecure)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n\n let response = try await client.send(request)\n let description = try response.imageDescription()\n let image = ClientImage(description: description)\n\n await progressUpdateClient?.finish()\n return image\n }\n\n public static func delete(reference: String, garbageCollect: Bool = false) async throws {\n let client = newXPCClient()\n let request = newRequest(.imageDelete)\n request.set(key: .imageReference, value: reference)\n request.set(key: .garbageCollect, value: garbageCollect)\n let _ = try await client.send(request)\n }\n\n public static func load(from tarFile: String) async throws -> [ClientImage] {\n let client = newXPCClient()\n let request = newRequest(.imageLoad)\n request.set(key: .filePath, value: tarFile)\n let reply = try await client.send(request)\n\n let loaded = try reply.imageDescriptions()\n return loaded.map { desc in\n ClientImage(description: desc)\n }\n }\n\n public static func pruneImages() async throws -> ([String], UInt64) {\n let client = newXPCClient()\n let request = newRequest(.imagePrune)\n let response = try await client.send(request)\n let digests = try response.digests()\n let size = response.uint64(key: .size)\n return (digests, size)\n }\n\n public static func fetch(reference: String, platform: Platform? = nil, scheme: RequestScheme = .auto, progressUpdate: ProgressUpdateHandler? = nil) async throws -> ClientImage\n {\n do {\n let match = try await self.get(reference: reference)\n if let platform {\n // The image exists, but we dont know if we have the right platform pulled\n // Check if we do, if not pull the requested platform\n _ = try await match.config(for: platform)\n }\n return match\n } catch let err as ContainerizationError {\n guard err.isCode(.notFound) else {\n throw err\n }\n return try await Self.pull(reference: reference, platform: platform, scheme: scheme, progressUpdate: progressUpdate)\n }\n }\n}\n\n// MARK: Instance methods\n\nextension ClientImage {\n public func push(platform: Platform? = nil, scheme: RequestScheme, progressUpdate: ProgressUpdateHandler?) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imagePush)\n\n guard let host = try Reference.parse(reference).domain else {\n throw ContainerizationError(.invalidArgument, message: \"Could not extract host from reference \\(reference)\")\n }\n request.set(key: .imageReference, value: reference)\n\n let insecure = try scheme.schemeFor(host: host) == .http\n request.set(key: .insecureFlag, value: insecure)\n\n try request.set(platform: platform)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n _ = try await client.send(request)\n await progressUpdateClient?.finish()\n }\n\n @discardableResult\n public func tag(new: String) async throws -> ClientImage {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageTag)\n request.set(key: .imageReference, value: self.description.reference)\n request.set(key: .imageNewReference, value: new)\n let reply = try await client.send(request)\n let description = try reply.imageDescription()\n return ClientImage(description: description)\n }\n\n // MARK: Snapshot Methods\n\n public func save(out: String, platform: Platform? = nil) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageSave)\n try request.set(description: self.description)\n request.set(key: .filePath, value: out)\n try request.set(platform: platform)\n let _ = try await client.send(request)\n }\n\n public func unpack(platform: Platform?, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageUnpack)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n\n try await client.send(request)\n\n await progressUpdateClient?.finish()\n }\n\n public func deleteSnapshot(platform: Platform?) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.snapshotDelete)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n try await client.send(request)\n }\n\n public func getSnapshot(platform: Platform) async throws -> Filesystem {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.snapshotGet)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n let response = try await client.send(request)\n let fs = try response.filesystem()\n return fs\n }\n\n @discardableResult\n public func getCreateSnapshot(platform: Platform, progressUpdate: ProgressUpdateHandler? = nil) async throws -> Filesystem {\n do {\n return try await self.getSnapshot(platform: platform)\n } catch let err as ContainerizationError {\n guard err.code == .notFound else {\n throw err\n }\n try await self.unpack(platform: platform, progressUpdate: progressUpdate)\n return try await self.getSnapshot(platform: platform)\n }\n }\n}\n\nextension XPCMessage {\n fileprivate func set(description: ImageDescription) throws {\n let descData = try JSONEncoder().encode(description)\n self.set(key: .imageDescription, value: descData)\n }\n\n fileprivate func set(descriptions: [ImageDescription]) throws {\n let descData = try JSONEncoder().encode(descriptions)\n self.set(key: .imageDescriptions, value: descData)\n }\n\n fileprivate func set(platform: Platform?) throws {\n guard let platform else {\n return\n }\n let platformData = try JSONEncoder().encode(platform)\n self.set(key: .ociPlatform, value: platformData)\n }\n\n fileprivate func imageDescription() throws -> ImageDescription {\n let responseData = self.dataNoCopy(key: .imageDescription)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"imageDescription not received\")\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: responseData)\n return description\n }\n\n fileprivate func imageDescriptions() throws -> [ImageDescription] {\n let responseData = self.dataNoCopy(key: .imageDescriptions)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"imageDescriptions not received\")\n }\n let descriptions = try JSONDecoder().decode([ImageDescription].self, from: responseData)\n return descriptions\n }\n\n fileprivate func filesystem() throws -> Filesystem {\n let responseData = self.dataNoCopy(key: .filesystem)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"filesystem not received\")\n }\n let fs = try JSONDecoder().decode(Filesystem.self, from: responseData)\n return fs\n }\n\n fileprivate func digests() throws -> [String] {\n let responseData = self.dataNoCopy(key: .digests)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"digests not received\")\n }\n let digests = try JSONDecoder().decode([String].self, from: responseData)\n return digests\n }\n}\n\nextension ImageDescription {\n fileprivate func nameFromAnnotation() -> String? {\n guard let annotations = self.descriptor.annotations else {\n return nil\n }\n guard let name = annotations[AnnotationKeys.containerizationImageName] else {\n return nil\n }\n return name\n }\n}\n"], ["/container/Sources/Helpers/Images/ImagesHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerImagesService\nimport ContainerImagesServiceClient\nimport ContainerLog\nimport ContainerXPC\nimport Containerization\nimport Foundation\nimport Logging\n\n@main\nstruct ImagesHelper: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"container-core-images\",\n abstract: \"XPC service for managing OCI images\",\n version: releaseVersion(),\n subcommands: [\n Start.self\n ]\n )\n}\n\nextension ImagesHelper {\n struct Start: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Starts the image plugin\"\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .long, help: \"XPC service prefix\")\n var serviceIdentifier: String = \"com.apple.container.core.container-core-images\"\n\n @Option(name: .shortAndLong, help: \"Daemon root directory\")\n var root = Self.appRoot.path\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n private static let unpackStrategy = SnapshotStore.defaultUnpackStrategy\n\n func run() async throws {\n let commandName = ImagesHelper._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n do {\n log.info(\"configuring XPC server\")\n let root = URL(filePath: root)\n var routes = [String: XPCServer.RouteHandler]()\n try self.initializeContentService(root: root, log: log, routes: &routes)\n try self.initializeImagesService(root: root, log: log, routes: &routes)\n let xpc = XPCServer(\n identifier: serviceIdentifier,\n routes: routes,\n log: log\n )\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n ImagesHelper.exit(withError: error)\n }\n }\n\n private func initializeImagesService(root: URL, log: Logger, routes: inout [String: XPCServer.RouteHandler]) throws {\n let contentStore = RemoteContentStoreClient()\n let imageStore = try ImageStore(path: root, contentStore: contentStore)\n let snapshotStore = try SnapshotStore(path: root, unpackStrategy: Self.unpackStrategy, log: log)\n let service = try ImagesService(contentStore: contentStore, imageStore: imageStore, snapshotStore: snapshotStore, log: log)\n let harness = ImagesServiceHarness(service: service, log: log)\n\n routes[ImagesServiceXPCRoute.imagePull.rawValue] = harness.pull\n routes[ImagesServiceXPCRoute.imageList.rawValue] = harness.list\n routes[ImagesServiceXPCRoute.imageDelete.rawValue] = harness.delete\n routes[ImagesServiceXPCRoute.imageTag.rawValue] = harness.tag\n routes[ImagesServiceXPCRoute.imagePush.rawValue] = harness.push\n routes[ImagesServiceXPCRoute.imageSave.rawValue] = harness.save\n routes[ImagesServiceXPCRoute.imageLoad.rawValue] = harness.load\n routes[ImagesServiceXPCRoute.imageUnpack.rawValue] = harness.unpack\n routes[ImagesServiceXPCRoute.imagePrune.rawValue] = harness.prune\n routes[ImagesServiceXPCRoute.snapshotDelete.rawValue] = harness.deleteSnapshot\n routes[ImagesServiceXPCRoute.snapshotGet.rawValue] = harness.getSnapshot\n }\n\n private func initializeContentService(root: URL, log: Logger, routes: inout [String: XPCServer.RouteHandler]) throws {\n let service = try ContentStoreService(root: root, log: log)\n let harness = ContentServiceHarness(service: service, log: log)\n\n routes[ImagesServiceXPCRoute.contentClean.rawValue] = harness.clean\n routes[ImagesServiceXPCRoute.contentGet.rawValue] = harness.get\n routes[ImagesServiceXPCRoute.contentDelete.rawValue] = harness.delete\n routes[ImagesServiceXPCRoute.contentIngestStart.rawValue] = harness.newIngestSession\n routes[ImagesServiceXPCRoute.contentIngestCancel.rawValue] = harness.cancelIngestSession\n routes[ImagesServiceXPCRoute.contentIngestComplete.rawValue] = harness.completeIngestSession\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"ImagesHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n return log\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/APIServer/Kernel/FileDownloader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\ninternal struct FileDownloader {\n public static func downloadFile(url: URL, to destination: URL, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let request = try HTTPClient.Request(url: url)\n\n let delegate = try FileDownloadDelegate(\n path: destination.path(),\n reportHead: {\n let expectedSizeString = $0.headers[\"Content-Length\"].first ?? \"\"\n if let expectedSize = Int64(expectedSizeString) {\n if let progressUpdate {\n Task {\n await progressUpdate([\n .addTotalSize(expectedSize)\n ])\n }\n }\n }\n },\n reportProgress: {\n let receivedBytes = Int64($0.receivedBytes)\n if let progressUpdate {\n Task {\n await progressUpdate([\n .setSize(receivedBytes)\n ])\n }\n }\n })\n\n let client = FileDownloader.createClient()\n _ = try await client.execute(request: request, delegate: delegate).get()\n try await client.shutdown()\n }\n\n private static func createClient() -> HTTPClient {\n var httpConfiguration = HTTPClient.Configuration()\n let proxyConfig: HTTPClient.Configuration.Proxy? = {\n let proxyEnv = ProcessInfo.processInfo.environment[\"HTTP_PROXY\"]\n guard let proxyEnv else {\n return nil\n }\n guard let url = URL(string: proxyEnv), let host = url.host(), let port = url.port else {\n return nil\n }\n return .server(host: host, port: port)\n }()\n httpConfiguration.proxy = proxyConfig\n return HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration)\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePull.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport TerminalProgress\n\nextension Application {\n struct ImagePull: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"pull\",\n abstract: \"Pull an image\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Argument var reference: String\n\n init() {}\n\n init(platform: String? = nil, scheme: String = \"auto\", reference: String, disableProgress: Bool = false) {\n self.global = Flags.Global()\n self.registry = Flags.Registry(scheme: scheme)\n self.progressFlags = Flags.Progress(disableProgressUpdates: disableProgress)\n self.platform = platform\n self.reference = reference\n }\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let scheme = try RequestScheme(registry.scheme)\n\n let processedReference = try ClientImage.normalizeReference(reference)\n\n var progressConfig: ProgressConfig\n if self.progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: self.progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 2\n )\n }\n\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Fetching image\")\n progress.set(itemsName: \"blobs\")\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n let image = try await ClientImage.pull(\n reference: processedReference, platform: p, scheme: scheme, progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progress.handler)\n )\n\n progress.set(description: \"Unpacking image\")\n progress.set(itemsName: \"entries\")\n let unpackTask = await taskManager.startTask()\n try await image.unpack(platform: p, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progress.handler))\n await taskManager.finish()\n progress.finish()\n }\n }\n}\n"], ["/container/Sources/CLI/Registry/RegistryDefault.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct RegistryDefault: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"default\",\n abstract: \"Manage the default image registry\",\n subcommands: [\n DefaultSetCommand.self,\n DefaultUnsetCommand.self,\n DefaultInspectCommand.self,\n ]\n )\n }\n\n struct DefaultSetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default registry\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @Argument\n var host: String\n\n func run() async throws {\n let scheme = try RequestScheme(registry.scheme).schemeFor(host: host)\n\n let _url = \"\\(scheme)://\\(host)\"\n guard let url = URL(string: _url), let domain = url.host() else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n let resolvedDomain = Reference.resolveDomain(domain: domain)\n let client = RegistryClient(host: resolvedDomain, scheme: scheme.rawValue, port: url.port)\n do {\n try await client.ping()\n } catch let err as RegistryClient.Error {\n switch err {\n case .invalidStatus(url: _, .unauthorized, _), .invalidStatus(url: _, .forbidden, _):\n break\n default:\n throw err\n }\n }\n ClientDefaults.set(value: host, key: .defaultRegistryDomain)\n print(\"Set default registry to \\(host)\")\n }\n }\n\n struct DefaultUnsetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"unset\",\n abstract: \"Unset the default registry\",\n aliases: [\"clear\"]\n )\n\n func run() async throws {\n ClientDefaults.unset(key: .defaultRegistryDomain)\n print(\"Unset the default registry domain\")\n }\n }\n\n struct DefaultInspectCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display the default registry domain\"\n )\n\n func run() async throws {\n print(ClientDefaults.get(key: .defaultRegistryDomain))\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildRemoteContentProxy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\n\nstruct BuildRemoteContentProxy: BuildPipelineHandler {\n let local: ContentStore\n\n public init(_ contentStore: ContentStore) throws {\n self.local = contentStore\n }\n\n func accept(_ packet: ServerStream) throws -> Bool {\n guard let imageTransfer = packet.getImageTransfer() else {\n return false\n }\n guard imageTransfer.stage() == \"content-store\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let imageTransfer = packet.getImageTransfer() else {\n throw Error.imageTransferMissing\n }\n\n guard let method = imageTransfer.method() else {\n throw Error.methodMissing\n }\n\n switch try ContentStoreMethod(method) {\n case .info:\n try await self.info(sender, imageTransfer, packet.buildID)\n case .readerAt:\n try await self.readerAt(sender, imageTransfer, packet.buildID)\n default:\n throw Error.unknownMethod(method)\n }\n }\n\n func info(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer, _ buildID: String) async throws {\n let descriptor = try await local.get(digest: packet.tag)\n let size = try descriptor?.size()\n let transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.info.rawValue,\n size: size\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n }\n\n func readerAt(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer, _ buildID: String) async throws {\n let digest = packet.descriptor.digest\n let offset: UInt64 = packet.offset() ?? 0\n let size: Int = packet.len() ?? 0\n guard let descriptor = try await local.get(digest: digest) else {\n throw Error.contentMissing\n }\n if offset == 0 && size == 0 { // Metadata request\n var transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.readerAt.rawValue,\n size: descriptor.size(),\n data: Data()\n )\n transfer.complete = true\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n return\n }\n guard let data = try descriptor.data(offset: offset, length: size) else {\n throw Error.invalidOffsetSizeForContent(packet.descriptor.digest, offset, size)\n }\n\n let transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.readerAt.rawValue,\n size: UInt64(data.count),\n data: data\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n }\n\n func delete(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.delete)\"])\n }\n\n func update(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.update)\"])\n }\n\n func walk(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.walk)\"])\n }\n\n enum ContentStoreMethod: String {\n case info = \"/containerd.services.content.v1.Content/Info\"\n case readerAt = \"/containerd.services.content.v1.Content/ReaderAt\"\n case delete = \"/containerd.services.content.v1.Content/Delete\"\n case update = \"/containerd.services.content.v1.Content/Update\"\n case walk = \"/containerd.services.content.v1.Content/Walk\"\n\n init(_ method: String) throws {\n guard let value = ContentStoreMethod(rawValue: method) else {\n throw Error.unknownMethod(method)\n }\n self = value\n }\n }\n}\n\nextension ImageTransfer {\n fileprivate init(id: String, digest: String, method: String, size: UInt64? = nil, data: Data = Data()) throws {\n self.init()\n self.id = id\n self.tag = digest\n self.metadata = [\n \"os\": \"linux\",\n \"stage\": \"content-store\",\n \"method\": method,\n ]\n if let size {\n self.metadata[\"size\"] = String(size)\n }\n self.complete = true\n self.direction = .into\n self.data = data\n }\n}\n\nextension BuildRemoteContentProxy {\n enum Error: Swift.Error, CustomStringConvertible {\n case imageTransferMissing\n case methodMissing\n case contentMissing\n case unknownMethod(String)\n case invalidOffsetSizeForContent(String, UInt64, Int)\n\n var description: String {\n switch self {\n case .imageTransferMissing:\n return \"imageTransfer is missing\"\n case .methodMissing:\n return \"method is missing in request\"\n case .contentMissing:\n return \"content cannot be found\"\n case .unknownMethod(let m):\n return \"unknown content-store method \\(m)\"\n case .invalidOffsetSizeForContent(let digest, let offset, let size):\n return \"invalid request for content: \\(digest) with offset: \\(offset) size: \\(size)\"\n }\n }\n }\n\n}\n"], ["/container/Sources/CLI/System/Kernel/KernelSet.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct KernelSet: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default kernel\"\n )\n\n @Option(name: .customLong(\"binary\"), help: \"Path to the binary to set as the default kernel. If used with --tar, this points to a location inside the tar\")\n var binaryPath: String? = nil\n\n @Option(name: .customLong(\"tar\"), help: \"Filesystem path or remote URL to a tar ball that contains the kernel to use\")\n var tarPath: String? = nil\n\n @Option(name: .customLong(\"arch\"), help: \"The architecture of the kernel binary. One of (amd64, arm64)\")\n var architecture: String = ContainerizationOCI.Platform.current.architecture.description\n\n @Flag(name: .customLong(\"recommended\"), help: \"Download and install the recommended kernel as the default. This flag ignores any other arguments\")\n var recommended: Bool = false\n\n func run() async throws {\n if recommended {\n let url = ClientDefaults.get(key: .defaultKernelURL)\n let path = ClientDefaults.get(key: .defaultKernelBinaryPath)\n print(\"Installing the recommended kernel from \\(url)...\")\n try await Self.downloadAndInstallWithProgressBar(tarRemoteURL: url, kernelFilePath: path)\n return\n }\n guard tarPath != nil else {\n return try await self.setKernelFromBinary()\n }\n try await self.setKernelFromTar()\n }\n\n private func setKernelFromBinary() async throws {\n guard let binaryPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--binary'\")\n }\n let absolutePath = URL(fileURLWithPath: binaryPath, relativeTo: .currentDirectory()).absoluteURL.absoluteString\n let platform = try getSystemPlatform()\n try await ClientKernel.installKernel(kernelFilePath: absolutePath, platform: platform)\n }\n\n private func setKernelFromTar() async throws {\n guard let binaryPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--binary'\")\n }\n guard let tarPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--tar\")\n }\n let platform = try getSystemPlatform()\n let localTarPath = URL(fileURLWithPath: tarPath, relativeTo: .currentDirectory()).absoluteString\n let fm = FileManager.default\n if fm.fileExists(atPath: localTarPath) {\n try await ClientKernel.installKernelFromTar(tarFile: localTarPath, kernelFilePath: binaryPath, platform: platform)\n return\n }\n guard let remoteURL = URL(string: tarPath) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid remote URL '\\(tarPath)' for argument '--tar'. Missing protocol?\")\n }\n try await Self.downloadAndInstallWithProgressBar(tarRemoteURL: remoteURL.absoluteString, kernelFilePath: binaryPath, platform: platform)\n }\n\n private func getSystemPlatform() throws -> SystemPlatform {\n switch architecture {\n case \"arm64\":\n return .linuxArm\n case \"amd64\":\n return .linuxAmd\n default:\n throw ContainerizationError(.unsupported, message: \"Unsupported architecture \\(architecture)\")\n }\n }\n\n public static func downloadAndInstallWithProgressBar(tarRemoteURL: String, kernelFilePath: String, platform: SystemPlatform = .current) async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n totalTasks: 2\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n try await ClientKernel.installKernelFromTar(tarFile: tarRemoteURL, kernelFilePath: kernelFilePath, platform: platform, progressUpdate: progress.handler)\n progress.finish()\n }\n\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+Terminal.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nenum EscapeSequence {\n static let hideCursor = \"\\u{001B}[?25l\"\n static let showCursor = \"\\u{001B}[?25h\"\n static let moveUp = \"\\u{001B}[1A\"\n}\n\nextension ProgressBar {\n private var terminalWidth: Int {\n guard\n let terminalHandle = term,\n let terminal = try? Terminal(descriptor: terminalHandle.fileDescriptor)\n else {\n return 0\n }\n\n let terminalWidth = (try? Int(terminal.size.width)) ?? 0\n return terminalWidth\n }\n\n /// Clears the progress bar and resets the cursor.\n public func clearAndResetCursor() {\n clear()\n resetCursor()\n }\n\n /// Clears the progress bar.\n public func clear() {\n displayText(\"\")\n }\n\n /// Resets the cursor.\n public func resetCursor() {\n display(EscapeSequence.showCursor)\n }\n\n func display(_ text: String) {\n guard let term else {\n return\n }\n termQueue.sync {\n try? term.write(contentsOf: Data(text.utf8))\n try? term.synchronize()\n }\n }\n\n func displayText(_ text: String, terminating: String = \"\\r\") {\n var text = text\n\n // Clears previously printed characters if the new string is shorter.\n text += String(repeating: \" \", count: max(printedWidth - text.count, 0))\n printedWidth = text.count\n state.withLock {\n $0.output = text\n }\n\n // Clears previously printed lines.\n var lines = \"\"\n if terminating.hasSuffix(\"\\r\") && terminalWidth > 0 {\n let lineCount = (text.count - 1) / terminalWidth\n for _ in 0.. {\n associatedtype T: Codable & Identifiable & Sendable\n\n func list() async throws -> [T]\n func create(_ entity: T) async throws\n func retrieve(_ id: String) async throws -> T?\n func update(_ entity: T) async throws\n func upsert(_ entity: T) async throws\n func delete(_ id: String) async throws\n}\n\npublic actor FilesystemEntityStore: EntityStore where T: Codable & Identifiable & Sendable {\n typealias Index = [String: T]\n\n private let path: URL\n private let type: String\n private var index: Index\n private let log: Logger\n private let encoder = JSONEncoder()\n\n public init(path: URL, type: String, log: Logger) throws {\n self.path = path\n self.type = type\n self.log = log\n self.index = try Self.load(path: path, log: log)\n }\n\n public func list() async throws -> [T] {\n Array(index.values)\n }\n\n public func create(_ entity: T) async throws {\n let metadataUrl = metadataUrl(entity.id)\n guard !FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.exists, message: \"Entity \\(entity.id) already exist\")\n }\n\n try FileManager.default.createDirectory(at: entityUrl(entity.id), withIntermediateDirectories: true)\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func retrieve(_ id: String) throws -> T? {\n index[id]\n }\n\n public func update(_ entity: T) async throws {\n let metadataUrl: URL = metadataUrl(entity.id)\n guard FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.notFound, message: \"Entity \\(entity.id) not found\")\n }\n\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func upsert(_ entity: T) async throws {\n let metadataUrl: URL = metadataUrl(entity.id)\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func delete(_ id: String) async throws {\n let metadataUrl = entityUrl(id)\n guard FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.notFound, message: \"entity \\(id) not found\")\n }\n try FileManager.default.removeItem(at: metadataUrl)\n index.removeValue(forKey: id)\n }\n\n public func entityUrl(_ id: String) -> URL {\n path.appendingPathComponent(id)\n }\n\n private static func load(path: URL, log: Logger) throws -> Index {\n let directories = try FileManager.default.contentsOfDirectory(at: path, includingPropertiesForKeys: nil)\n var index: FilesystemEntityStore.Index = Index()\n let decoder = JSONDecoder()\n\n for entityUrl in directories {\n do {\n let metadataUrl = entityUrl.appendingPathComponent(metadataFilename)\n let data = try Data(contentsOf: metadataUrl)\n let entity = try decoder.decode(T.self, from: data)\n index[entity.id] = entity\n } catch {\n log.warning(\n \"failed to load entity, ignoring\",\n metadata: [\n \"path\": \"\\(entityUrl)\"\n ])\n }\n }\n\n return index\n }\n\n private func metadataUrl(_ id: String) -> URL {\n entityUrl(id).appendingPathComponent(metadataFilename)\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePush.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport TerminalProgress\n\nextension Application {\n struct ImagePush: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"push\",\n abstract: \"Push an image\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Argument var reference: String\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let scheme = try RequestScheme(registry.scheme)\n let image = try await ClientImage.get(reference: reference)\n\n var progressConfig: ProgressConfig\n if progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n description: \"Pushing image \\(image.reference)\",\n itemsName: \"blobs\",\n showItems: true,\n showSpeed: false,\n ignoreSmallSize: true\n )\n }\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n _ = try await image.push(platform: p, scheme: scheme, progressUpdate: progress.handler)\n progress.finish()\n }\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderStop: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"stop\"\n config._superCommandName = \"builder\"\n config.abstract = \"Stop builder\"\n config.usage = \"\\n\\t builder stop\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n try await container.stop()\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n print(\"builder is not running\")\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Utility.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct Utility {\n private static let infraImages = [\n ClientDefaults.get(key: .defaultBuilderImage),\n ClientDefaults.get(key: .defaultInitImage),\n ]\n\n public static func createContainerID(name: String?) -> String {\n guard let name else {\n return UUID().uuidString.lowercased()\n }\n return name\n }\n\n public static func isInfraImage(name: String) -> Bool {\n for infraImage in infraImages {\n if name == infraImage {\n return true\n }\n }\n return false\n }\n\n public static func trimDigest(digest: String) -> String {\n var digest = digest\n digest.trimPrefix(\"sha256:\")\n if digest.count > 24 {\n digest = String(digest.prefix(24)) + \"...\"\n }\n return digest\n }\n\n public static func validEntityName(_ name: String) throws {\n let pattern = #\"^[a-zA-Z0-9][a-zA-Z0-9_.-]+$\"#\n let regex = try Regex(pattern)\n if try regex.firstMatch(in: name) == nil {\n throw ContainerizationError(.invalidArgument, message: \"invalid entity name \\(name)\")\n }\n }\n\n public static func containerConfigFromFlags(\n id: String,\n image: String,\n arguments: [String],\n process: Flags.Process,\n management: Flags.Management,\n resource: Flags.Resource,\n registry: Flags.Registry,\n progressUpdate: @escaping ProgressUpdateHandler\n ) async throws -> (ContainerConfiguration, Kernel) {\n let requestedPlatform = Parser.platform(os: management.os, arch: management.arch)\n let scheme = try RequestScheme(registry.scheme)\n\n await progressUpdate([\n .setDescription(\"Fetching image\"),\n .setItemsName(\"blobs\"),\n ])\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n let img = try await ClientImage.fetch(\n reference: image,\n platform: requestedPlatform,\n scheme: scheme,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progressUpdate)\n )\n\n // Unpack a fetched image before use\n await progressUpdate([\n .setDescription(\"Unpacking image\"),\n .setItemsName(\"entries\"),\n ])\n let unpackTask = await taskManager.startTask()\n try await img.getCreateSnapshot(\n platform: requestedPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progressUpdate))\n\n await progressUpdate([\n .setDescription(\"Fetching kernel\"),\n .setItemsName(\"binary\"),\n ])\n\n let kernel = try await self.getKernel(management: management)\n\n // Pull and unpack the initial filesystem\n await progressUpdate([\n .setDescription(\"Fetching init image\"),\n .setItemsName(\"blobs\"),\n ])\n let fetchInitTask = await taskManager.startTask()\n let initImage = try await ClientImage.fetch(\n reference: ClientImage.initImageRef, platform: .current, scheme: scheme,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchInitTask, from: progressUpdate))\n\n await progressUpdate([\n .setDescription(\"Unpacking init image\"),\n .setItemsName(\"entries\"),\n ])\n let unpackInitTask = await taskManager.startTask()\n _ = try await initImage.getCreateSnapshot(\n platform: .current,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackInitTask, from: progressUpdate))\n\n await taskManager.finish()\n\n let imageConfig = try await img.config(for: requestedPlatform).config\n let description = img.description\n let pc = try Parser.process(\n arguments: arguments,\n processFlags: process,\n managementFlags: management,\n config: imageConfig\n )\n\n var config = ContainerConfiguration(id: id, image: description, process: pc)\n config.platform = requestedPlatform\n config.hostname = id\n\n config.resources = try Parser.resources(\n cpus: resource.cpus,\n memory: resource.memory\n )\n\n let tmpfs = try Parser.tmpfsMounts(management.tmpFs)\n let volumes = try Parser.volumes(management.volumes)\n var mounts = try Parser.mounts(management.mounts)\n mounts.append(contentsOf: tmpfs)\n mounts.append(contentsOf: volumes)\n config.mounts = mounts\n\n if management.networks.isEmpty {\n config.networks = [ClientNetwork.defaultNetworkName]\n } else {\n // networks may only be specified for macOS 26+\n guard #available(macOS 26, *) else {\n throw ContainerizationError(.invalidArgument, message: \"non-default network configuration requires macOS 26 or newer\")\n }\n config.networks = management.networks\n }\n\n var networkStatuses: [NetworkStatus] = []\n for networkName in config.networks {\n let network: NetworkState = try await ClientNetwork.get(id: networkName)\n guard case .running(_, let networkStatus) = network else {\n throw ContainerizationError(.invalidState, message: \"network \\(networkName) is not running\")\n }\n networkStatuses.append(networkStatus)\n }\n\n if management.dnsDisabled {\n config.dns = nil\n } else {\n let domain = management.dnsDomain ?? ClientDefaults.getOptional(key: .defaultDNSDomain)\n config.dns = .init(\n nameservers: management.dnsNameservers,\n domain: domain,\n searchDomains: management.dnsSearchDomains,\n options: management.dnsOptions\n )\n }\n\n if Platform.current.architecture == \"arm64\" && requestedPlatform.architecture == \"amd64\" {\n config.rosetta = true\n }\n\n config.labels = try Parser.labels(management.labels)\n\n config.publishedPorts = try Parser.publishPorts(management.publishPorts)\n\n // Parse --publish-socket arguments and add to container configuration\n // to enable socket forwarding from container to host.\n config.publishedSockets = try Parser.publishSockets(management.publishSockets)\n\n return (config, kernel)\n }\n\n private static func getKernel(management: Flags.Management) async throws -> Kernel {\n // For the image itself we'll take the user input and try with it as we can do userspace\n // emulation for x86, but for the kernel we need it to match the hosts architecture.\n let s: SystemPlatform = .current\n if let userKernel = management.kernel {\n guard FileManager.default.fileExists(atPath: userKernel) else {\n throw ContainerizationError(.notFound, message: \"Kernel file not found at path \\(userKernel)\")\n }\n let p = URL(filePath: userKernel)\n return .init(path: p, platform: s)\n }\n return try await ClientKernel.getDefaultKernel(for: s)\n }\n}\n"], ["/container/Sources/ContainerClient/ProgressUpdateClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\n/// A client that can be used to receive progress updates from a service.\npublic actor ProgressUpdateClient {\n private var endpointConnection: xpc_connection_t?\n private var endpoint: xpc_endpoint_t?\n\n /// Creates a new client for receiving progress updates from a service.\n /// - Parameters:\n /// - progressUpdate: The handler to invoke when progress updates are received.\n /// - request: The XPC message to send the endpoint to connect to.\n public init(for progressUpdate: @escaping ProgressUpdateHandler, request: XPCMessage) async {\n createEndpoint(for: progressUpdate)\n setEndpoint(to: request)\n }\n\n /// Performs a connection setup for receiving progress updates.\n /// - Parameter progressUpdate: The handler to invoke when progress updates are received.\n private func createEndpoint(for progressUpdate: @escaping ProgressUpdateHandler) {\n let endpointConnection = xpc_connection_create(nil, nil)\n // Access to `reversedConnection` is protected by a lock\n nonisolated(unsafe) var reversedConnection: xpc_connection_t?\n let reversedConnectionLock = NSLock()\n xpc_connection_set_event_handler(endpointConnection) { connectionMessage in\n reversedConnectionLock.withLock {\n switch xpc_get_type(connectionMessage) {\n case XPC_TYPE_CONNECTION:\n reversedConnection = connectionMessage\n xpc_connection_set_event_handler(connectionMessage) { updateMessage in\n Self.handleProgressUpdate(updateMessage, progressUpdate: progressUpdate)\n }\n xpc_connection_activate(connectionMessage)\n case XPC_TYPE_ERROR:\n if let reversedConnectionUnwrapped = reversedConnection {\n xpc_connection_cancel(reversedConnectionUnwrapped)\n reversedConnection = nil\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(connectionMessage))\")\n }\n }\n }\n xpc_connection_activate(endpointConnection)\n\n self.endpointConnection = endpointConnection\n self.endpoint = xpc_endpoint_create(endpointConnection)\n }\n\n /// Performs a setup of the progress update endpoint.\n /// - Parameter request: The XPC message containing the endpoint to use.\n private func setEndpoint(to request: XPCMessage) {\n guard let endpoint else {\n return\n }\n request.set(key: .progressUpdateEndpoint, value: endpoint)\n }\n\n /// Performs cleanup of the created connection.\n public func finish() {\n if let endpointConnection {\n xpc_connection_cancel(endpointConnection)\n self.endpointConnection = nil\n }\n }\n\n private static func handleProgressUpdate(_ message: xpc_object_t, progressUpdate: @escaping ProgressUpdateHandler) {\n switch xpc_get_type(message) {\n case XPC_TYPE_DICTIONARY:\n let message = XPCMessage(object: message)\n handleProgressUpdate(message, progressUpdate: progressUpdate)\n case XPC_TYPE_ERROR:\n break\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(message))\")\n break\n }\n }\n\n private static func handleProgressUpdate(_ message: XPCMessage, progressUpdate: @escaping ProgressUpdateHandler) {\n var events = [ProgressUpdateEvent]()\n\n if let description = message.string(key: .progressUpdateSetDescription) {\n events.append(.setDescription(description))\n }\n if let subDescription = message.string(key: .progressUpdateSetSubDescription) {\n events.append(.setSubDescription(subDescription))\n }\n if let itemsName = message.string(key: .progressUpdateSetItemsName) {\n events.append(.setItemsName(itemsName))\n }\n var tasks = message.int(key: .progressUpdateAddTasks)\n if tasks != 0 {\n events.append(.addTasks(tasks))\n }\n tasks = message.int(key: .progressUpdateSetTasks)\n if tasks != 0 {\n events.append(.setTasks(tasks))\n }\n var totalTasks = message.int(key: .progressUpdateAddTotalTasks)\n if totalTasks != 0 {\n events.append(.addTotalTasks(totalTasks))\n }\n totalTasks = message.int(key: .progressUpdateSetTotalTasks)\n if totalTasks != 0 {\n events.append(.setTotalTasks(totalTasks))\n }\n var items = message.int(key: .progressUpdateAddItems)\n if items != 0 {\n events.append(.addItems(items))\n }\n items = message.int(key: .progressUpdateSetItems)\n if items != 0 {\n events.append(.setItems(items))\n }\n var totalItems = message.int(key: .progressUpdateAddTotalItems)\n if totalItems != 0 {\n events.append(.addTotalItems(totalItems))\n }\n totalItems = message.int(key: .progressUpdateSetTotalItems)\n if totalItems != 0 {\n events.append(.setTotalItems(totalItems))\n }\n var size = message.int64(key: .progressUpdateAddSize)\n if size != 0 {\n events.append(.addSize(size))\n }\n size = message.int64(key: .progressUpdateSetSize)\n if size != 0 {\n events.append(.setSize(size))\n }\n var totalSize = message.int64(key: .progressUpdateAddTotalSize)\n if totalSize != 0 {\n events.append(.addTotalSize(totalSize))\n }\n totalSize = message.int64(key: .progressUpdateSetTotalSize)\n if totalSize != 0 {\n events.append(.setTotalSize(totalSize))\n }\n\n Task {\n await progressUpdate(events)\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImageLoad.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ImageLoad: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"load\",\n abstract: \"Load images from an OCI compatible tar archive\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(\n name: .shortAndLong, help: \"Path to the tar archive to load images from\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var input: String\n\n func run() async throws {\n guard FileManager.default.fileExists(atPath: input) else {\n print(\"File does not exist \\(input)\")\n Application.exit(withError: ArgumentParser.ExitCode(1))\n }\n\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n totalTasks: 2\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Loading tar archive\")\n let loaded = try await ClientImage.load(from: input)\n\n let taskManager = ProgressTaskCoordinator()\n let unpackTask = await taskManager.startTask()\n progress.set(description: \"Unpacking image\")\n progress.set(itemsName: \"entries\")\n for image in loaded {\n try await image.unpack(platform: nil, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progress.handler))\n }\n await taskManager.finish()\n progress.finish()\n print(\"Loaded images:\")\n for image in loaded {\n print(image.reference)\n }\n }\n }\n}\n"], ["/container/Sources/DNSServer/DNSServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\nimport NIOCore\nimport NIOPosix\n\n/// Provides a DNS server.\n/// - Parameters:\n/// - host: The host address on which to listen.\n/// - port: The port for the server to listen.\npublic struct DNSServer {\n public var handler: DNSHandler\n let log: Logger?\n\n public init(\n handler: DNSHandler,\n log: Logger? = nil\n ) {\n self.handler = handler\n self.log = log\n }\n\n public func run(host: String, port: Int) async throws {\n // TODO: TCP server\n let srv = try await DatagramBootstrap(group: NIOSingletons.posixEventLoopGroup)\n .channelOption(.socketOption(.so_reuseaddr), value: 1)\n .bind(host: host, port: port)\n .flatMapThrowing { channel in\n try NIOAsyncChannel(\n wrappingChannelSynchronously: channel,\n configuration: NIOAsyncChannel.Configuration(\n inboundType: AddressedEnvelope.self,\n outboundType: AddressedEnvelope.self\n )\n )\n }\n .get()\n\n try await srv.executeThenClose { inbound, outbound in\n for try await var packet in inbound {\n try await self.handle(outbound: outbound, packet: &packet)\n }\n }\n }\n\n public func run(socketPath: String) async throws {\n // TODO: TCP server\n let srv = try await DatagramBootstrap(group: NIOSingletons.posixEventLoopGroup)\n .bind(unixDomainSocketPath: socketPath, cleanupExistingSocketFile: true)\n .flatMapThrowing { channel in\n try NIOAsyncChannel(\n wrappingChannelSynchronously: channel,\n configuration: NIOAsyncChannel.Configuration(\n inboundType: AddressedEnvelope.self,\n outboundType: AddressedEnvelope.self\n )\n )\n }\n .get()\n\n try await srv.executeThenClose { inbound, outbound in\n for try await var packet in inbound {\n log?.debug(\"received packet from \\(packet.remoteAddress)\")\n try await self.handle(outbound: outbound, packet: &packet)\n log?.debug(\"sent packet\")\n }\n }\n }\n\n public func stop() async throws {}\n}\n"], ["/container/Sources/CLI/Image/ImageSave.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ImageSave: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"save\",\n abstract: \"Save an image as an OCI compatible tar archive\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Option(\n name: .shortAndLong, help: \"Path to save the image tar archive\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var output: String\n\n @Argument var reference: String\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let progressConfig = try ProgressConfig(\n description: \"Saving image\"\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let image = try await ClientImage.get(reference: reference)\n try await image.save(out: output, platform: p)\n\n progress.finish()\n print(\"Image saved\")\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildImageResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\nimport Logging\n\nstruct BuildImageResolver: BuildPipelineHandler {\n let contentStore: ContentStore\n\n public init(_ contentStore: ContentStore) throws {\n self.contentStore = contentStore\n }\n\n func accept(_ packet: ServerStream) throws -> Bool {\n guard let imageTransfer = packet.getImageTransfer() else {\n return false\n }\n guard imageTransfer.stage() == \"resolver\" else {\n return false\n }\n guard imageTransfer.method() == \"/resolve\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let imageTransfer = packet.getImageTransfer() else {\n throw Error.imageTransferMissing\n }\n guard let ref = imageTransfer.ref() else {\n throw Error.tagMissing\n }\n\n guard let platform = try imageTransfer.platform() else {\n throw Error.platformMissing\n }\n\n let img = try await {\n guard let img = try? await ClientImage.pull(reference: ref, platform: platform) else {\n return try await ClientImage.fetch(reference: ref, platform: platform)\n }\n return img\n }()\n\n let index: Index = try await img.index()\n let buildID = packet.buildID\n let platforms = index.manifests.compactMap { $0.platform }\n for pl in platforms {\n if pl == platform {\n let manifest = try await img.manifest(for: pl)\n guard let ociImage: ContainerizationOCI.Image = try await self.contentStore.get(digest: manifest.config.digest) else {\n continue\n }\n let enc = JSONEncoder()\n let data = try enc.encode(ociImage)\n let transfer = try ImageTransfer(\n id: imageTransfer.id,\n digest: img.descriptor.digest,\n ref: ref,\n platform: platform.description,\n data: data\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n return\n }\n }\n throw Error.unknownPlatformForImage(platform.description, ref)\n }\n}\n\nextension ImageTransfer {\n fileprivate init(id: String, digest: String, ref: String, platform: String, data: Data) throws {\n self.init()\n self.id = id\n self.tag = digest\n self.metadata = [\n \"os\": \"linux\",\n \"stage\": \"resolver\",\n \"method\": \"/resolve\",\n \"ref\": ref,\n \"platform\": platform,\n ]\n self.complete = true\n self.direction = .into\n self.data = data\n }\n}\n\nextension BuildImageResolver {\n enum Error: Swift.Error, CustomStringConvertible {\n case imageTransferMissing\n case tagMissing\n case platformMissing\n case imageNameMissing\n case imageTagMissing\n case imageNotFound\n case indexDigestMissing(String)\n case unknownRegistry(String)\n case digestIsNotIndex(String)\n case digestIsNotManifest(String)\n case unknownPlatformForImage(String, String)\n\n var description: String {\n switch self {\n case .imageTransferMissing:\n return \"imageTransfer is missing\"\n case .tagMissing:\n return \"tag parameter missing in metadata\"\n case .platformMissing:\n return \"platform parameter missing in metadata\"\n case .imageNameMissing:\n return \"image name missing in $ref parameter\"\n case .imageTagMissing:\n return \"image tag missing in $ref parameter\"\n case .imageNotFound:\n return \"image not found\"\n case .indexDigestMissing(let ref):\n return \"index digest is missing for image: \\(ref)\"\n case .unknownRegistry(let registry):\n return \"registry \\(registry) is unknown\"\n case .digestIsNotIndex(let digest):\n return \"digest \\(digest) is not a descriptor to an index\"\n case .digestIsNotManifest(let digest):\n return \"digest \\(digest) is not a descriptor to a manifest\"\n case .unknownPlatformForImage(let platform, let ref):\n return \"platform \\(platform) for image \\(ref) not found\"\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientProcess.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport NIOCore\nimport NIOPosix\nimport TerminalProgress\n\n/// A protocol that defines the methods and data members available to a process\n/// started inside of a container.\npublic protocol ClientProcess: Sendable {\n /// Identifier for the process.\n var id: String { get }\n\n /// Start the underlying process inside of the container.\n func start(_ stdio: [FileHandle?]) async throws\n /// Send a terminal resize request to the process `id`.\n func resize(_ size: Terminal.Size) async throws\n /// Send or \"kill\" a signal to the process `id`.\n /// Kill does not wait for the process to exit, it only delivers the signal.\n func kill(_ signal: Int32) async throws\n /// Wait for the process `id` to complete and return its exit code.\n /// This method blocks until the process exits and the code is obtained.\n func wait() async throws -> Int32\n}\n\nstruct ClientProcessImpl: ClientProcess, Sendable {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n /// Identifier of the container.\n public let containerId: String\n\n private let client: SandboxClient\n\n /// Identifier of a process. That is running inside of a container.\n /// This field is nil if the process this objects refers to is the\n /// init process of the container.\n public let processId: String?\n\n public var id: String {\n processId ?? containerId\n }\n\n init(containerId: String, processId: String? = nil, client: SandboxClient) {\n self.containerId = containerId\n self.processId = processId\n self.client = client\n }\n\n /// Start the container and return the initial process.\n public func start(_ stdio: [FileHandle?]) async throws {\n do {\n let client = self.client\n try await client.startProcess(self.id, stdio: stdio)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to start container\",\n cause: error\n )\n }\n }\n\n public func kill(_ signal: Int32) async throws {\n do {\n\n let client = self.client\n try await client.kill(self.id, signal: Int64(signal))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill process\",\n cause: error\n )\n }\n }\n\n public func resize(_ size: ContainerizationOS.Terminal.Size) async throws {\n do {\n\n let client = self.client\n try await client.resize(self.id, size: size)\n\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to resize process\",\n cause: error\n )\n }\n }\n\n public func wait() async throws -> Int32 {\n do {\n let client = self.client\n return try await client.wait(self.id)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to wait on process\",\n cause: error\n )\n }\n }\n}\n"], ["/container/Sources/SocketForwarder/ConnectHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Logging\nimport NIOCore\nimport NIOPosix\n\nfinal class ConnectHandler {\n private var pendingBytes: [NIOAny]\n private let serverAddress: SocketAddress\n private var log: Logger? = nil\n\n init(serverAddress: SocketAddress, log: Logger?) {\n self.pendingBytes = []\n self.serverAddress = serverAddress\n self.log = log\n }\n}\n\nextension ConnectHandler: ChannelInboundHandler {\n typealias InboundIn = ByteBuffer\n typealias OutboundOut = ByteBuffer\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n if self.pendingBytes.isEmpty {\n self.connectToServer(context: context)\n }\n self.pendingBytes.append(data)\n }\n\n func handlerAdded(context: ChannelHandlerContext) {\n // Add logger metadata.\n self.log?[metadataKey: \"proxy\"] = \"\\(context.channel.localAddress?.description ?? \"none\")\"\n self.log?[metadataKey: \"server\"] = \"\\(context.channel.remoteAddress?.description ?? \"none\")\"\n }\n}\n\nextension ConnectHandler: RemovableChannelHandler {\n func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) {\n var didRead = false\n\n // We are being removed, and need to deliver any pending bytes we may have if we're upgrading.\n while self.pendingBytes.count > 0 {\n let data = self.pendingBytes.removeFirst()\n context.fireChannelRead(data)\n didRead = true\n }\n\n if didRead {\n context.fireChannelReadComplete()\n }\n\n self.log?.trace(\"backend - removing connect handler from pipeline\")\n context.leavePipeline(removalToken: removalToken)\n }\n}\n\nextension ConnectHandler {\n private func connectToServer(context: ChannelHandlerContext) {\n self.log?.trace(\"backend - connecting\")\n\n ClientBootstrap(group: context.eventLoop)\n .connect(to: serverAddress)\n .assumeIsolatedUnsafeUnchecked()\n .whenComplete { result in\n switch result {\n case .success(let channel):\n self.log?.trace(\"backend - connected\")\n self.glue(channel, context: context)\n case .failure(let error):\n self.log?.error(\"backend - connect failed: \\(error)\")\n context.close(promise: nil)\n context.fireErrorCaught(error)\n }\n }\n }\n\n private func glue(_ peerChannel: Channel, context: ChannelHandlerContext) {\n self.log?.trace(\"backend - gluing channels\")\n\n // Now we need to glue our channel and the peer channel together.\n let (localGlue, peerGlue) = GlueHandler.matchedPair()\n do {\n try context.channel.pipeline.syncOperations.addHandler(localGlue)\n try peerChannel.pipeline.syncOperations.addHandler(peerGlue)\n context.pipeline.syncOperations.removeHandler(self, promise: nil)\n } catch {\n // Close connected peer channel before closing our channel.\n peerChannel.close(mode: .all, promise: nil)\n context.close(promise: nil)\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ImageService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport Logging\nimport TerminalProgress\n\npublic actor ImagesService {\n public static let keychainID = \"com.apple.container\"\n\n private let log: Logger\n private let contentStore: ContentStore\n private let imageStore: ImageStore\n private let snapshotStore: SnapshotStore\n\n public init(contentStore: ContentStore, imageStore: ImageStore, snapshotStore: SnapshotStore, log: Logger) throws {\n self.contentStore = contentStore\n self.imageStore = imageStore\n self.snapshotStore = snapshotStore\n self.log = log\n }\n\n private func _list() async throws -> [Containerization.Image] {\n try await imageStore.list()\n }\n\n private func _get(_ reference: String) async throws -> Containerization.Image {\n try await imageStore.get(reference: reference)\n }\n\n private func _get(_ description: ImageDescription) async throws -> Containerization.Image {\n let exists = try await self._get(description.reference)\n guard exists.descriptor == description.descriptor else {\n throw ContainerizationError(.invalidState, message: \"Descriptor mismatch. Expected \\(description.descriptor), got \\(exists.descriptor)\")\n }\n return exists\n }\n\n public func list() async throws -> [ImageDescription] {\n self.log.info(\"ImagesService: \\(#function)\")\n return try await imageStore.list().map { $0.description.fromCZ }\n }\n\n public func pull(reference: String, platform: Platform?, insecure: Bool, progressUpdate: ProgressUpdateHandler?) async throws -> ImageDescription {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference), platform: \\(String(describing: platform)), insecure: \\(insecure)\")\n let img = try await Self.withAuthentication(ref: reference) { auth in\n try await self.imageStore.pull(\n reference: reference, platform: platform, insecure: insecure, auth: auth, progress: ContainerizationProgressAdapter.handler(from: progressUpdate))\n }\n guard let img else {\n throw ContainerizationError(.internalError, message: \"Failed to pull image \\(reference)\")\n }\n return img.description.fromCZ\n }\n\n public func push(reference: String, platform: Platform?, insecure: Bool, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference), platform: \\(String(describing: platform)), insecure: \\(insecure)\")\n try await Self.withAuthentication(ref: reference) { auth in\n try await self.imageStore.push(\n reference: reference, platform: platform, insecure: insecure, auth: auth, progress: ContainerizationProgressAdapter.handler(from: progressUpdate))\n }\n }\n\n public func tag(old: String, new: String) async throws -> ImageDescription {\n self.log.info(\"ImagesService: \\(#function) - old: \\(old), new: \\(new)\")\n let img = try await self.imageStore.tag(existing: old, new: new)\n return img.description.fromCZ\n }\n\n public func delete(reference: String, garbageCollect: Bool) async throws {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference)\")\n try await self.imageStore.delete(reference: reference, performCleanup: garbageCollect)\n }\n\n public func save(reference: String, out: URL, platform: Platform?) async throws {\n self.log.info(\"ImagesService: \\(#function) - reference: \\(reference) , platform: \\(String(describing: platform))\")\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try await self.imageStore.save(references: [reference], out: tempDir, platform: platform)\n let writer = try ArchiveWriter(format: .pax, filter: .none, file: out)\n try writer.archiveDirectory(tempDir)\n try writer.finishEncoding()\n }\n\n public func load(from tarFile: URL) async throws -> [ImageDescription] {\n self.log.info(\"ImagesService: \\(#function) from: \\(tarFile.absolutePath())\")\n let reader = try ArchiveReader(file: tarFile)\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try reader.extractContents(to: tempDir)\n let loaded = try await self.imageStore.load(from: tempDir)\n var images: [ImageDescription] = []\n for image in loaded {\n images.append(image.description.fromCZ)\n }\n return images\n }\n\n public func prune() async throws -> ([String], UInt64) {\n let images = try await self._list()\n let freedSnapshotBytes = try await self.snapshotStore.clean(keepingSnapshotsFor: images)\n let (deleted, freedContentBytes) = try await self.imageStore.prune()\n return (deleted, freedContentBytes + freedSnapshotBytes)\n }\n}\n\n// MARK: Image Snapshot Methods\n\nextension ImagesService {\n public func unpack(description: ImageDescription, platform: Platform?, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n try await self.snapshotStore.unpack(image: img, platform: platform, progressUpdate: progressUpdate)\n }\n\n public func deleteImageSnapshot(description: ImageDescription, platform: Platform?) async throws {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n try await self.snapshotStore.delete(for: img, platform: platform)\n }\n\n public func getImageSnapshot(description: ImageDescription, platform: Platform) async throws -> Filesystem {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n return try await self.snapshotStore.get(for: img, platform: platform)\n }\n}\n\n// MARK: Static Methods\n\nextension ImagesService {\n private static func withAuthentication(\n ref: String, _ body: @Sendable @escaping (_ auth: Authentication?) async throws -> T?\n ) async throws -> T? {\n var authentication: Authentication?\n let ref = try Reference.parse(ref)\n guard let host = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"No host specified in image reference: \\(ref)\")\n }\n authentication = Self.authenticationFromEnv(host: host)\n if let authentication {\n return try await body(authentication)\n }\n let keychain = KeychainHelper(id: Self.keychainID)\n do {\n authentication = try keychain.lookup(domain: host)\n } catch let err as KeychainHelper.Error {\n guard case .keyNotFound = err else {\n throw ContainerizationError(.internalError, message: \"Error querying keychain for \\(host)\", cause: err)\n }\n }\n do {\n return try await body(authentication)\n } catch let err as RegistryClient.Error {\n guard case .invalidStatus(_, let status, _) = err else {\n throw err\n }\n guard status == .unauthorized || status == .forbidden else {\n throw err\n }\n guard authentication != nil else {\n throw ContainerizationError(.internalError, message: \"\\(String(describing: err)). No credentials found for host \\(host)\")\n }\n throw err\n }\n }\n\n private static func authenticationFromEnv(host: String) -> Authentication? {\n let env = ProcessInfo.processInfo.environment\n guard env[\"CONTAINER_REGISTRY_HOST\"] == host else {\n return nil\n }\n guard let user = env[\"CONTAINER_REGISTRY_USER\"], let password = env[\"CONTAINER_REGISTRY_TOKEN\"] else {\n return nil\n }\n return BasicAuthentication(username: user, password: password)\n }\n}\n\nextension ImageDescription {\n public var toCZ: Containerization.Image.Description {\n .init(reference: self.reference, descriptor: self.descriptor)\n }\n}\n\nextension Containerization.Image.Description {\n public var fromCZ: ImageDescription {\n .init(\n reference: self.reference,\n descriptor: self.descriptor\n )\n }\n}\n"], ["/container/Sources/ContainerClient/Flags.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationError\nimport Foundation\n\npublic struct Flags {\n public struct Global: ParsableArguments {\n public init() {}\n\n @Flag(name: .long, help: \"Enable debug output [environment: CONTAINER_DEBUG]\")\n public var debug = false\n }\n\n public struct Process: ParsableArguments {\n public init() {}\n\n @Option(\n name: [.customLong(\"cwd\"), .customShort(\"w\"), .customLong(\"workdir\")],\n help: \"Current working directory for the container\")\n public var cwd: String?\n\n @Option(name: [.customLong(\"env\"), .customShort(\"e\")], help: \"Set environment variables\")\n public var env: [String] = []\n\n @Option(name: .customLong(\"env-file\"), help: \"Read in a file of environment variables\")\n public var envFile: [String] = []\n\n @Option(name: .customLong(\"uid\"), help: \"Set the uid for the process\")\n public var uid: UInt32?\n\n @Option(name: .customLong(\"gid\"), help: \"Set the gid for the process\")\n public var gid: UInt32?\n\n @Flag(name: [.customLong(\"interactive\"), .customShort(\"i\")], help: \"Keep Stdin open even if not attached\")\n public var interactive = false\n\n @Flag(name: [.customLong(\"tty\"), .customShort(\"t\")], help: \"Open a tty with the process\")\n public var tty = false\n\n @Option(name: [.customLong(\"user\"), .customShort(\"u\")], help: \"Set the user for the process\")\n public var user: String?\n }\n\n public struct Resource: ParsableArguments {\n public init() {}\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64?\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n public var memory: String?\n }\n\n public struct Registry: ParsableArguments {\n public init() {}\n\n public init(scheme: String) {\n self.scheme = scheme\n }\n\n @Option(help: \"Scheme to use when connecting to the container registry. One of (http, https, auto)\")\n public var scheme: String = \"auto\"\n }\n\n public struct Management: ParsableArguments {\n public init() {}\n\n @Flag(name: [.customLong(\"detach\"), .short], help: \"Run the container and detach from the process\")\n public var detach = false\n\n @Option(name: .customLong(\"entrypoint\"), help: \"Override the entrypoint of the image\")\n public var entryPoint: String?\n\n @Option(name: .customLong(\"mount\"), help: \"Add a mount to the container (type=<>,source=<>,target=<>,readonly)\")\n public var mounts: [String] = []\n\n @Option(name: [.customLong(\"publish\"), .short], help: \"Publish a port from container to host (format: [host-ip:]host-port:container-port[/protocol])\")\n public var publishPorts: [String] = []\n\n @Option(name: .customLong(\"publish-socket\"), help: \"Publish a socket from container to host (format: host_path:container_path)\")\n public var publishSockets: [String] = []\n\n @Option(name: .customLong(\"tmpfs\"), help: \"Add a tmpfs mount to the container at the given path\")\n public var tmpFs: [String] = []\n\n @Option(name: .customLong(\"name\"), help: \"Assign a name to the container. If excluded will be a generated UUID\")\n public var name: String?\n\n @Flag(name: [.customLong(\"remove\"), .customLong(\"rm\")], help: \"Remove the container after it stops\")\n public var remove = false\n\n @Option(name: .customLong(\"os\"), help: \"Set OS if image can target multiple operating systems\")\n public var os = \"linux\"\n\n @Option(\n name: [.customLong(\"arch\"), .short], help: \"Set arch if image can target multiple architectures\")\n public var arch: String = Arch.hostArchitecture().rawValue\n\n @Option(name: [.customLong(\"volume\"), .short], help: \"Bind mount a volume into the container\")\n public var volumes: [String] = []\n\n @Option(\n name: [.customLong(\"kernel\"), .short], help: \"Set a custom kernel path\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n public var kernel: String?\n\n @Option(name: [.customLong(\"network\")], help: \"Attach the container to a network\")\n public var networks: [String] = []\n\n @Option(name: .customLong(\"cidfile\"), help: \"Write the container ID to the path provided\")\n public var cidfile = \"\"\n\n @Flag(name: [.customLong(\"no-dns\")], help: \"Do not configure DNS in the container\")\n public var dnsDisabled = false\n\n @Option(name: .customLong(\"dns\"), help: \"DNS nameserver IP address\")\n public var dnsNameservers: [String] = []\n\n @Option(name: .customLong(\"dns-domain\"), help: \"Default DNS domain\")\n public var dnsDomain: String? = nil\n\n @Option(name: .customLong(\"dns-search\"), help: \"DNS search domains\")\n public var dnsSearchDomains: [String] = []\n\n @Option(name: .customLong(\"dns-option\"), help: \"DNS options\")\n public var dnsOptions: [String] = []\n\n @Option(name: [.customLong(\"label\"), .short], help: \"Add a key=value label to the container\")\n public var labels: [String] = []\n }\n\n public struct Progress: ParsableArguments {\n public init() {}\n\n public init(disableProgressUpdates: Bool) {\n self.disableProgressUpdates = disableProgressUpdates\n }\n\n @Flag(name: .customLong(\"disable-progress-updates\"), help: \"Disable progress bar updates\")\n public var disableProgressUpdates = false\n }\n}\n"], ["/container/Sources/CLI/Image/ImageInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ImageInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more images\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Images to inspect\")\n var images: [String]\n\n func run() async throws {\n var printable = [any Codable]()\n let result = try await ClientImage.get(names: images)\n let notFound = result.error\n for image in result.images {\n guard !Utility.isInfraImage(name: image.reference) else {\n continue\n }\n printable.append(try await image.details())\n }\n if printable.count > 0 {\n print(try printable.jsonArray())\n }\n if notFound.count > 0 {\n throw ContainerizationError(.notFound, message: \"Images: \\(notFound.joined(separator: \"\\n\"))\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildAPI+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationOCI\n\npublic typealias IO = Com_Apple_Container_Build_V1_IO\npublic typealias InfoRequest = Com_Apple_Container_Build_V1_InfoRequest\npublic typealias InfoResponse = Com_Apple_Container_Build_V1_InfoResponse\npublic typealias ClientStream = Com_Apple_Container_Build_V1_ClientStream\npublic typealias ServerStream = Com_Apple_Container_Build_V1_ServerStream\npublic typealias ImageTransfer = Com_Apple_Container_Build_V1_ImageTransfer\npublic typealias BuildTransfer = Com_Apple_Container_Build_V1_BuildTransfer\npublic typealias BuilderClient = Com_Apple_Container_Build_V1_BuilderNIOClient\npublic typealias BuilderClientAsync = Com_Apple_Container_Build_V1_BuilderAsyncClient\npublic typealias BuilderClientProtocol = Com_Apple_Container_Build_V1_BuilderClientProtocol\npublic typealias BuilderClientAsyncProtocol = Com_Apple_Container_Build_V1_BuilderAsyncClient\n\nextension BuildTransfer {\n func stage() -> String? {\n let stage = self.metadata[\"stage\"]\n return stage == \"\" ? nil : stage\n }\n\n func method() -> String? {\n let method = self.metadata[\"method\"]\n return method == \"\" ? nil : method\n }\n\n func includePatterns() -> [String]? {\n guard let includePatternsString = self.metadata[\"include-patterns\"] else {\n return nil\n }\n return includePatternsString == \"\" ? nil : includePatternsString.components(separatedBy: \",\")\n }\n\n func followPaths() -> [String]? {\n guard let followPathString = self.metadata[\"followpaths\"] else {\n return nil\n }\n return followPathString == \"\" ? nil : followPathString.components(separatedBy: \",\")\n }\n\n func mode() -> String? {\n self.metadata[\"mode\"]\n }\n\n func size() -> Int? {\n guard let sizeStr = self.metadata[\"size\"] else {\n return nil\n }\n return sizeStr == \"\" ? nil : Int(sizeStr)\n }\n\n func offset() -> UInt64? {\n guard let offsetStr = self.metadata[\"offset\"] else {\n return nil\n }\n return offsetStr == \"\" ? nil : UInt64(offsetStr)\n }\n\n func len() -> Int? {\n guard let lenStr = self.metadata[\"length\"] else {\n return nil\n }\n return lenStr == \"\" ? nil : Int(lenStr)\n }\n}\n\nextension ImageTransfer {\n func stage() -> String? {\n self.metadata[\"stage\"]\n }\n\n func method() -> String? {\n self.metadata[\"method\"]\n }\n\n func ref() -> String? {\n self.metadata[\"ref\"]\n }\n\n func platform() throws -> Platform? {\n let metadata = self.metadata\n guard let platform = metadata[\"platform\"] else {\n return nil\n }\n return try Platform(from: platform)\n }\n\n func mode() -> String? {\n self.metadata[\"mode\"]\n }\n\n func size() -> Int? {\n let metadata = self.metadata\n guard let sizeStr = metadata[\"size\"] else {\n return nil\n }\n return Int(sizeStr)\n }\n\n func len() -> Int? {\n let metadata = self.metadata\n guard let lenStr = metadata[\"length\"] else {\n return nil\n }\n return Int(lenStr)\n }\n\n func offset() -> UInt64? {\n let metadata = self.metadata\n guard let offsetStr = metadata[\"offset\"] else {\n return nil\n }\n return UInt64(offsetStr)\n }\n}\n\nextension ServerStream {\n func getImageTransfer() -> ImageTransfer? {\n if case .imageTransfer(let v) = self.packetType {\n return v\n }\n return nil\n }\n\n func getBuildTransfer() -> BuildTransfer? {\n if case .buildTransfer(let v) = self.packetType {\n return v\n }\n return nil\n }\n\n func getIO() -> IO? {\n if case .io(let v) = self.packetType {\n return v\n }\n return nil\n }\n}\n"], ["/container/Sources/ContainerClient/Core/Bundle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport Foundation\n\npublic struct Bundle: Sendable {\n private static let initfsFilename = \"initfs.ext4\"\n private static let kernelFilename = \"kernel.json\"\n private static let kernelBinaryFilename = \"kernel.bin\"\n private static let containerRootFsBlockFilename = \"rootfs.ext4\"\n private static let containerRootFsFilename = \"rootfs.json\"\n\n static let containerConfigFilename = \"config.json\"\n\n /// The path to the bundle.\n public let path: URL\n\n public init(path: URL) {\n self.path = path\n }\n\n public var bootlog: URL {\n self.path.appendingPathComponent(\"vminitd.log\")\n }\n\n private var containerRootfsBlock: URL {\n self.path.appendingPathComponent(Self.containerRootFsBlockFilename)\n }\n\n private var containerRootfsConfig: URL {\n self.path.appendingPathComponent(Self.containerRootFsFilename)\n }\n\n public var containerRootfs: Filesystem {\n get throws {\n let data = try Data(contentsOf: containerRootfsConfig)\n let fs = try JSONDecoder().decode(Filesystem.self, from: data)\n return fs\n }\n }\n\n /// Return the initial filesystem for a sandbox.\n public var initialFilesystem: Filesystem {\n .block(\n format: \"ext4\",\n source: self.path.appendingPathComponent(Self.initfsFilename).path,\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n\n public var kernel: Kernel {\n get throws {\n try load(path: self.path.appendingPathComponent(Self.kernelFilename))\n }\n }\n\n public var configuration: ContainerConfiguration {\n get throws {\n try load(path: self.path.appendingPathComponent(Self.containerConfigFilename))\n }\n }\n}\n\nextension Bundle {\n public static func create(\n path: URL,\n initialFilesystem: Filesystem,\n kernel: Kernel,\n containerConfiguration: ContainerConfiguration? = nil\n ) throws -> Bundle {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n let kbin = path.appendingPathComponent(Self.kernelBinaryFilename)\n try FileManager.default.copyItem(at: kernel.path, to: kbin)\n var k = kernel\n k.path = kbin\n try write(path.appendingPathComponent(Self.kernelFilename), value: k)\n\n switch initialFilesystem.type {\n case .block(let fmt, _, _):\n guard fmt == \"ext4\" else {\n fatalError(\"ext4 is the only supported format for initial filesystem\")\n }\n // when saving the Initial Filesystem to the bundle\n // discard any filesystem information and just persist\n // the block into the Bundle.\n _ = try initialFilesystem.clone(to: path.appendingPathComponent(Self.initfsFilename).path)\n default:\n fatalError(\"invalid filesystem type for initial filesystem\")\n }\n let bundle = Bundle(path: path)\n if let containerConfiguration {\n try bundle.write(filename: Self.containerConfigFilename, value: containerConfiguration)\n }\n return bundle\n }\n}\n\nextension Bundle {\n /// Set the value of the configuration for the Bundle.\n public func set(configuration: ContainerConfiguration) throws {\n try write(filename: Self.containerConfigFilename, value: configuration)\n }\n\n /// Return the full filepath for a named resource in the Bundle.\n public func filePath(for name: String) -> URL {\n path.appendingPathComponent(name)\n }\n\n public func setContainerRootFs(cloning fs: Filesystem) throws {\n let cloned = try fs.clone(to: self.containerRootfsBlock.absolutePath())\n let fsData = try JSONEncoder().encode(cloned)\n try fsData.write(to: self.containerRootfsConfig)\n }\n\n /// Delete the bundle and all of the resources contained inside.\n public func delete() throws {\n try FileManager.default.removeItem(at: self.path)\n }\n\n public func write(filename: String, value: Encodable) throws {\n try Self.write(self.path.appendingPathComponent(filename), value: value)\n }\n\n private static func write(_ path: URL, value: Encodable) throws {\n let data = try JSONEncoder().encode(value)\n try data.write(to: path)\n }\n\n public func load(filename: String) throws -> T where T: Decodable {\n try load(path: self.path.appendingPathComponent(filename))\n }\n\n private func load(path: URL) throws -> T where T: Decodable {\n let data = try Data(contentsOf: path)\n return try JSONDecoder().decode(T.self, from: data)\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/ReservedVmnetNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport Dispatch\nimport Foundation\nimport Logging\nimport SendableProperty\nimport SystemConfiguration\nimport XPC\nimport vmnet\n\n/// Creates a vmnet network with reservation APIs.\n@available(macOS 26, *)\npublic final class ReservedVmnetNetwork: Network {\n @SendablePropertyUnchecked\n private var _state: NetworkState\n private let log: Logger\n\n @SendableProperty\n private var network: vmnet_network_ref?\n @SendableProperty\n private var interface: interface_ref?\n private let networkLock = NSLock()\n\n /// Configure a bridge network that allows external system access using\n /// network address translation.\n public init(\n configuration: NetworkConfiguration,\n log: Logger\n ) throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.unsupported, message: \"invalid network mode \\(configuration.mode)\")\n }\n\n log.info(\"creating vmnet network\")\n self.log = log\n _state = .created(configuration)\n log.info(\"created vmnet network\")\n }\n\n public var state: NetworkState {\n get async { _state }\n }\n\n public nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws {\n try networkLock.withLock {\n try handler(network.map { try Self.serialize_network_ref(ref: $0) })\n }\n }\n\n public func start() async throws {\n guard case .created(let configuration) = _state else {\n throw ContainerizationError(.invalidArgument, message: \"cannot start network that is in \\(_state.state) state\")\n }\n\n try startNetwork(configuration: configuration, log: log)\n }\n\n private static func serialize_network_ref(ref: vmnet_network_ref) throws -> XPCMessage {\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let refObject = vmnet_network_copy_serialization(ref, &status) else {\n throw ContainerizationError(.invalidArgument, message: \"cannot serialize vmnet_network_ref to XPC object, status \\(status)\")\n }\n return XPCMessage(object: refObject)\n }\n\n private func startNetwork(configuration: NetworkConfiguration, log: Logger) throws {\n log.info(\n \"starting vmnet network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n ]\n )\n let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName)\n let subnetText = configuration.subnet ?? suite?.string(forKey: \"network.subnet\")\n\n // with the reservation API, subnet priority is CLI argument, UserDefault, auto\n let subnet = try subnetText.map { try CIDRAddress($0) }\n\n // set up the vmnet configuration\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let vmnetConfiguration = vmnet_network_configuration_create(vmnet.operating_modes_t.VMNET_SHARED_MODE, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet config with status \\(status)\")\n }\n\n vmnet_network_configuration_disable_dhcp(vmnetConfiguration)\n\n // set the subnet if the caller provided one\n if let subnet {\n let gateway = IPv4Address(fromValue: subnet.lower.value + 1)\n var gatewayAddr = in_addr()\n inet_pton(AF_INET, gateway.description, &gatewayAddr)\n let mask = IPv4Address(fromValue: subnet.prefixLength.prefixMask32)\n var maskAddr = in_addr()\n inet_pton(AF_INET, mask.description, &maskAddr)\n log.info(\n \"configuring vmnet subnet\",\n metadata: [\"cidr\": \"\\(subnet)\"]\n )\n let status = vmnet_network_configuration_set_ipv4_subnet(vmnetConfiguration, &gatewayAddr, &maskAddr)\n guard status == .VMNET_SUCCESS else {\n throw ContainerizationError(.internalError, message: \"failed to set subnet \\(subnet) for network \\(configuration.id)\")\n }\n }\n\n // reserve the network\n guard let network = vmnet_network_create(vmnetConfiguration, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet network with status \\(status)\")\n }\n self.network = network\n\n // retrieve the subnet since the caller may not have provided one\n var subnetAddr = in_addr()\n var maskAddr = in_addr()\n vmnet_network_get_ipv4_subnet(network, &subnetAddr, &maskAddr)\n let subnetValue = UInt32(bigEndian: subnetAddr.s_addr)\n let maskValue = UInt32(bigEndian: maskAddr.s_addr)\n let lower = IPv4Address(fromValue: subnetValue & maskValue)\n let upper = IPv4Address(fromValue: lower.value + ~maskValue)\n let runningSubnet = try CIDRAddress(lower: lower, upper: upper)\n let runningGateway = IPv4Address(fromValue: runningSubnet.lower.value + 1)\n self._state = .running(configuration, NetworkStatus(address: runningSubnet.description, gateway: runningGateway.description))\n log.info(\n \"started vmnet network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n \"cidr\": \"\\(runningSubnet)\",\n ]\n )\n }\n}\n"], ["/container/Sources/APIServer/Containers/ContainersHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nstruct ContainersHarness {\n let log: Logging.Logger\n let service: ContainersService\n\n init(service: ContainersService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let containers = try await service.list()\n let data = try JSONEncoder().encode(containers)\n\n let reply = message.reply()\n reply.set(key: .containers, value: data)\n return reply\n }\n\n @Sendable\n func create(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .containerConfig)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"container configuration cannot be empty\")\n }\n let kdata = message.dataNoCopy(key: .kernel)\n guard let kdata else {\n throw ContainerizationError(.invalidArgument, message: \"kernel cannot be empty\")\n }\n let odata = message.dataNoCopy(key: .containerOptions)\n var options: ContainerCreateOptions = .default\n if let odata {\n options = try JSONDecoder().decode(ContainerCreateOptions.self, from: odata)\n }\n let config = try JSONDecoder().decode(ContainerConfiguration.self, from: data)\n let kernel = try JSONDecoder().decode(Kernel.self, from: kdata)\n\n try await service.create(configuration: config, kernel: kernel, options: options)\n return message.reply()\n }\n\n @Sendable\n func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .id)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"id cannot be empty\")\n }\n try await service.delete(id: id)\n return message.reply()\n }\n\n @Sendable\n func logs(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .id)\n guard let id else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"id cannot be empty\"\n )\n }\n let fds = try await service.logs(id: id)\n let reply = message.reply()\n try reply.set(key: .logs, value: fds)\n return reply\n }\n\n @Sendable\n func eventHandler(_ message: XPCMessage) async throws -> XPCMessage {\n let event = try message.containerEvent()\n try await service.handleContainerEvents(event: event)\n return message.reply()\n }\n}\n\nextension XPCMessage {\n public func containerEvent() throws -> ContainerEvent {\n guard let data = self.dataNoCopy(key: .containerEvent) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing container event data\")\n }\n let event = try JSONDecoder().decode(ContainerEvent.self, from: data)\n return event\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.pb.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// DO NOT EDIT.\n// swift-format-ignore-file\n// swiftlint:disable all\n//\n// Generated by the Swift generator plugin for the protocol buffer compiler.\n// Source: Builder.proto\n//\n// For information on using the generated types, please see the documentation:\n// https://github.com/apple/swift-protobuf/\n\nimport Foundation\nimport SwiftProtobuf\n\n// If the compiler emits an error on this type, it is because this file\n// was generated by a version of the `protoc` Swift plug-in that is\n// incompatible with the version of SwiftProtobuf to which you are linking.\n// Please ensure that you are building against the same version of the API\n// that was used to generate this file.\nfileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {\n struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}\n typealias Version = _2\n}\n\npublic enum Com_Apple_Container_Build_V1_TransferDirection: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case into // = 0\n case outof // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .into\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .into\n case 1: self = .outof\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .into: return 0\n case .outof: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_TransferDirection] = [\n .into,\n .outof,\n ]\n\n}\n\n/// Standard input/output.\npublic enum Com_Apple_Container_Build_V1_Stdio: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case stdin // = 0\n case stdout // = 1\n case stderr // = 2\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .stdin\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .stdin\n case 1: self = .stdout\n case 2: self = .stderr\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .stdin: return 0\n case .stdout: return 1\n case .stderr: return 2\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_Stdio] = [\n .stdin,\n .stdout,\n .stderr,\n ]\n\n}\n\n/// Build error type.\npublic enum Com_Apple_Container_Build_V1_BuildErrorType: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case buildFailed // = 0\n case `internal` // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .buildFailed\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .buildFailed\n case 1: self = .internal\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .buildFailed: return 0\n case .internal: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_BuildErrorType] = [\n .buildFailed,\n .internal,\n ]\n\n}\n\npublic struct Com_Apple_Container_Build_V1_InfoRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_InfoResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_CreateBuildRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The name of the build stage.\n public var stageName: String = String()\n\n /// The tag of the image to be created.\n public var tag: String = String()\n\n /// Any additional metadata to be associated with the build.\n public var metadata: Dictionary = [:]\n\n /// Additional build arguments.\n public var buildArgs: [String] = []\n\n /// Enable debug logging.\n public var debug: Bool = false\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_CreateBuildResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String = String()\n\n /// Any additional metadata to be associated with the build.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_ClientStream: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String {\n get {return _storage._buildID}\n set {_uniqueStorage()._buildID = newValue}\n }\n\n /// The packet type.\n public var packetType: OneOf_PacketType? {\n get {return _storage._packetType}\n set {_uniqueStorage()._packetType = newValue}\n }\n\n public var signal: Com_Apple_Container_Build_V1_Signal {\n get {\n if case .signal(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_Signal()\n }\n set {_uniqueStorage()._packetType = .signal(newValue)}\n }\n\n public var command: Com_Apple_Container_Build_V1_Run {\n get {\n if case .command(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_Run()\n }\n set {_uniqueStorage()._packetType = .command(newValue)}\n }\n\n public var buildTransfer: Com_Apple_Container_Build_V1_BuildTransfer {\n get {\n if case .buildTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildTransfer()\n }\n set {_uniqueStorage()._packetType = .buildTransfer(newValue)}\n }\n\n public var imageTransfer: Com_Apple_Container_Build_V1_ImageTransfer {\n get {\n if case .imageTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_ImageTransfer()\n }\n set {_uniqueStorage()._packetType = .imageTransfer(newValue)}\n }\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n /// The packet type.\n public enum OneOf_PacketType: Equatable, Sendable {\n case signal(Com_Apple_Container_Build_V1_Signal)\n case command(Com_Apple_Container_Build_V1_Run)\n case buildTransfer(Com_Apple_Container_Build_V1_BuildTransfer)\n case imageTransfer(Com_Apple_Container_Build_V1_ImageTransfer)\n\n }\n\n public init() {}\n\n fileprivate var _storage = _StorageClass.defaultInstance\n}\n\npublic struct Com_Apple_Container_Build_V1_Signal: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A POSIX signal to send to the build process.\n /// Can be used for cancelling builds.\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_Run: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the execution.\n public var id: String = String()\n\n /// The type of command to execute.\n public var command: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_RunComplete: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the execution.\n public var id: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_BuildTransfer: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the transfer.\n public var id: String = String()\n\n /// The direction for transferring data (either to the server or from the\n /// server).\n public var direction: Com_Apple_Container_Build_V1_TransferDirection = .into\n\n /// The absolute path to the source from the server perspective.\n public var source: String {\n get {return _source ?? String()}\n set {_source = newValue}\n }\n /// Returns true if `source` has been explicitly set.\n public var hasSource: Bool {return self._source != nil}\n /// Clears the value of `source`. Subsequent reads from it will return its default value.\n public mutating func clearSource() {self._source = nil}\n\n /// The absolute path for the destination from the server perspective.\n public var destination: String {\n get {return _destination ?? String()}\n set {_destination = newValue}\n }\n /// Returns true if `destination` has been explicitly set.\n public var hasDestination: Bool {return self._destination != nil}\n /// Clears the value of `destination`. Subsequent reads from it will return its default value.\n public mutating func clearDestination() {self._destination = nil}\n\n /// The actual data bytes to be transferred.\n public var data: Data = Data()\n\n /// Signal to indicate that the transfer of data for the request has finished.\n public var complete: Bool = false\n\n /// Boolean to indicate if the content is a directory.\n public var isDirectory: Bool = false\n\n /// Metadata for the transfer.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _source: String? = nil\n fileprivate var _destination: String? = nil\n}\n\npublic struct Com_Apple_Container_Build_V1_ImageTransfer: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the transfer.\n public var id: String = String()\n\n /// The direction for transferring data (either to the server or from the\n /// server).\n public var direction: Com_Apple_Container_Build_V1_TransferDirection = .into\n\n /// The tag for the image.\n public var tag: String = String()\n\n /// The descriptor for the image content.\n public var descriptor: Com_Apple_Container_Build_V1_Descriptor {\n get {return _descriptor ?? Com_Apple_Container_Build_V1_Descriptor()}\n set {_descriptor = newValue}\n }\n /// Returns true if `descriptor` has been explicitly set.\n public var hasDescriptor: Bool {return self._descriptor != nil}\n /// Clears the value of `descriptor`. Subsequent reads from it will return its default value.\n public mutating func clearDescriptor() {self._descriptor = nil}\n\n /// The actual data bytes to be transferred.\n public var data: Data = Data()\n\n /// Signal to indicate that the transfer of data for the request has finished.\n public var complete: Bool = false\n\n /// Metadata for the image.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _descriptor: Com_Apple_Container_Build_V1_Descriptor? = nil\n}\n\npublic struct Com_Apple_Container_Build_V1_ServerStream: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String {\n get {return _storage._buildID}\n set {_uniqueStorage()._buildID = newValue}\n }\n\n /// The packet type.\n public var packetType: OneOf_PacketType? {\n get {return _storage._packetType}\n set {_uniqueStorage()._packetType = newValue}\n }\n\n public var io: Com_Apple_Container_Build_V1_IO {\n get {\n if case .io(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_IO()\n }\n set {_uniqueStorage()._packetType = .io(newValue)}\n }\n\n public var buildError: Com_Apple_Container_Build_V1_BuildError {\n get {\n if case .buildError(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildError()\n }\n set {_uniqueStorage()._packetType = .buildError(newValue)}\n }\n\n public var commandComplete: Com_Apple_Container_Build_V1_RunComplete {\n get {\n if case .commandComplete(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_RunComplete()\n }\n set {_uniqueStorage()._packetType = .commandComplete(newValue)}\n }\n\n public var buildTransfer: Com_Apple_Container_Build_V1_BuildTransfer {\n get {\n if case .buildTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildTransfer()\n }\n set {_uniqueStorage()._packetType = .buildTransfer(newValue)}\n }\n\n public var imageTransfer: Com_Apple_Container_Build_V1_ImageTransfer {\n get {\n if case .imageTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_ImageTransfer()\n }\n set {_uniqueStorage()._packetType = .imageTransfer(newValue)}\n }\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n /// The packet type.\n public enum OneOf_PacketType: Equatable, Sendable {\n case io(Com_Apple_Container_Build_V1_IO)\n case buildError(Com_Apple_Container_Build_V1_BuildError)\n case commandComplete(Com_Apple_Container_Build_V1_RunComplete)\n case buildTransfer(Com_Apple_Container_Build_V1_BuildTransfer)\n case imageTransfer(Com_Apple_Container_Build_V1_ImageTransfer)\n\n }\n\n public init() {}\n\n fileprivate var _storage = _StorageClass.defaultInstance\n}\n\npublic struct Com_Apple_Container_Build_V1_IO: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The type of IO.\n public var type: Com_Apple_Container_Build_V1_Stdio = .stdin\n\n /// The IO data bytes.\n public var data: Data = Data()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_BuildError: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The type of build error.\n public var type: Com_Apple_Container_Build_V1_BuildErrorType = .buildFailed\n\n /// Additional message for the build failure.\n public var message: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n/// OCI Platform metadata.\npublic struct Com_Apple_Container_Build_V1_Platform: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var architecture: String = String()\n\n public var os: String = String()\n\n public var osVersion: String = String()\n\n public var osFeatures: [String] = []\n\n public var variant: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n/// OCI Descriptor metadata.\npublic struct Com_Apple_Container_Build_V1_Descriptor: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var mediaType: String = String()\n\n public var digest: String = String()\n\n public var size: Int64 = 0\n\n public var urls: [String] = []\n\n public var annotations: Dictionary = [:]\n\n public var platform: Com_Apple_Container_Build_V1_Platform {\n get {return _platform ?? Com_Apple_Container_Build_V1_Platform()}\n set {_platform = newValue}\n }\n /// Returns true if `platform` has been explicitly set.\n public var hasPlatform: Bool {return self._platform != nil}\n /// Clears the value of `platform`. Subsequent reads from it will return its default value.\n public mutating func clearPlatform() {self._platform = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _platform: Com_Apple_Container_Build_V1_Platform? = nil\n}\n\n// MARK: - Code below here is support for the SwiftProtobuf runtime.\n\nfileprivate let _protobuf_package = \"com.apple.container.build.v1\"\n\nextension Com_Apple_Container_Build_V1_TransferDirection: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"INTO\"),\n 1: .same(proto: \"OUTOF\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_Stdio: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"STDIN\"),\n 1: .same(proto: \"STDOUT\"),\n 2: .same(proto: \"STDERR\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_BuildErrorType: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"BUILD_FAILED\"),\n 1: .same(proto: \"INTERNAL\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_InfoRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".InfoRequest\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_InfoRequest, rhs: Com_Apple_Container_Build_V1_InfoRequest) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_InfoResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".InfoResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_InfoResponse, rhs: Com_Apple_Container_Build_V1_InfoResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_CreateBuildRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateBuildRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"stage_name\"),\n 2: .same(proto: \"tag\"),\n 3: .same(proto: \"metadata\"),\n 4: .standard(proto: \"build_args\"),\n 5: .same(proto: \"debug\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.stageName) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.tag) }()\n case 3: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.buildArgs) }()\n case 5: try { try decoder.decodeSingularBoolField(value: &self.debug) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.stageName.isEmpty {\n try visitor.visitSingularStringField(value: self.stageName, fieldNumber: 1)\n }\n if !self.tag.isEmpty {\n try visitor.visitSingularStringField(value: self.tag, fieldNumber: 2)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 3)\n }\n if !self.buildArgs.isEmpty {\n try visitor.visitRepeatedStringField(value: self.buildArgs, fieldNumber: 4)\n }\n if self.debug != false {\n try visitor.visitSingularBoolField(value: self.debug, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_CreateBuildRequest, rhs: Com_Apple_Container_Build_V1_CreateBuildRequest) -> Bool {\n if lhs.stageName != rhs.stageName {return false}\n if lhs.tag != rhs.tag {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.buildArgs != rhs.buildArgs {return false}\n if lhs.debug != rhs.debug {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_CreateBuildResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateBuildResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.buildID) }()\n case 2: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.buildID.isEmpty {\n try visitor.visitSingularStringField(value: self.buildID, fieldNumber: 1)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_CreateBuildResponse, rhs: Com_Apple_Container_Build_V1_CreateBuildResponse) -> Bool {\n if lhs.buildID != rhs.buildID {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ClientStream: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ClientStream\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"signal\"),\n 3: .same(proto: \"command\"),\n 4: .standard(proto: \"build_transfer\"),\n 5: .standard(proto: \"image_transfer\"),\n ]\n\n fileprivate class _StorageClass {\n var _buildID: String = String()\n var _packetType: Com_Apple_Container_Build_V1_ClientStream.OneOf_PacketType?\n\n // This property is used as the initial default value for new instances of the type.\n // The type itself is protecting the reference to its storage via CoW semantics.\n // This will force a copy to be made of this reference when the first mutation occurs;\n // hence, it is safe to mark this as `nonisolated(unsafe)`.\n static nonisolated(unsafe) let defaultInstance = _StorageClass()\n\n private init() {}\n\n init(copying source: _StorageClass) {\n _buildID = source._buildID\n _packetType = source._packetType\n }\n }\n\n fileprivate mutating func _uniqueStorage() -> _StorageClass {\n if !isKnownUniquelyReferenced(&_storage) {\n _storage = _StorageClass(copying: _storage)\n }\n return _storage\n }\n\n public mutating func decodeMessage(decoder: inout D) throws {\n _ = _uniqueStorage()\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &_storage._buildID) }()\n case 2: try {\n var v: Com_Apple_Container_Build_V1_Signal?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .signal(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .signal(v)\n }\n }()\n case 3: try {\n var v: Com_Apple_Container_Build_V1_Run?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .command(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .command(v)\n }\n }()\n case 4: try {\n var v: Com_Apple_Container_Build_V1_BuildTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildTransfer(v)\n }\n }()\n case 5: try {\n var v: Com_Apple_Container_Build_V1_ImageTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .imageTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .imageTransfer(v)\n }\n }()\n default: break\n }\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !_storage._buildID.isEmpty {\n try visitor.visitSingularStringField(value: _storage._buildID, fieldNumber: 1)\n }\n switch _storage._packetType {\n case .signal?: try {\n guard case .signal(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 2)\n }()\n case .command?: try {\n guard case .command(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 3)\n }()\n case .buildTransfer?: try {\n guard case .buildTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n }()\n case .imageTransfer?: try {\n guard case .imageTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 5)\n }()\n case nil: break\n }\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ClientStream, rhs: Com_Apple_Container_Build_V1_ClientStream) -> Bool {\n if lhs._storage !== rhs._storage {\n let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in\n let _storage = _args.0\n let rhs_storage = _args.1\n if _storage._buildID != rhs_storage._buildID {return false}\n if _storage._packetType != rhs_storage._packetType {return false}\n return true\n }\n if !storagesAreEqual {return false}\n }\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Signal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Signal\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Signal, rhs: Com_Apple_Container_Build_V1_Signal) -> Bool {\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Run: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Run\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"command\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.command) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if !self.command.isEmpty {\n try visitor.visitSingularStringField(value: self.command, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Run, rhs: Com_Apple_Container_Build_V1_Run) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.command != rhs.command {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_RunComplete: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".RunComplete\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_RunComplete, rhs: Com_Apple_Container_Build_V1_RunComplete) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_BuildTransfer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".BuildTransfer\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"direction\"),\n 3: .same(proto: \"source\"),\n 4: .same(proto: \"destination\"),\n 5: .same(proto: \"data\"),\n 6: .same(proto: \"complete\"),\n 7: .standard(proto: \"is_directory\"),\n 8: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularEnumField(value: &self.direction) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._source) }()\n case 4: try { try decoder.decodeSingularStringField(value: &self._destination) }()\n case 5: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n case 6: try { try decoder.decodeSingularBoolField(value: &self.complete) }()\n case 7: try { try decoder.decodeSingularBoolField(value: &self.isDirectory) }()\n case 8: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.direction != .into {\n try visitor.visitSingularEnumField(value: self.direction, fieldNumber: 2)\n }\n try { if let v = self._source {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try { if let v = self._destination {\n try visitor.visitSingularStringField(value: v, fieldNumber: 4)\n } }()\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 5)\n }\n if self.complete != false {\n try visitor.visitSingularBoolField(value: self.complete, fieldNumber: 6)\n }\n if self.isDirectory != false {\n try visitor.visitSingularBoolField(value: self.isDirectory, fieldNumber: 7)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 8)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_BuildTransfer, rhs: Com_Apple_Container_Build_V1_BuildTransfer) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.direction != rhs.direction {return false}\n if lhs._source != rhs._source {return false}\n if lhs._destination != rhs._destination {return false}\n if lhs.data != rhs.data {return false}\n if lhs.complete != rhs.complete {return false}\n if lhs.isDirectory != rhs.isDirectory {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ImageTransfer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ImageTransfer\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"direction\"),\n 3: .same(proto: \"tag\"),\n 4: .same(proto: \"descriptor\"),\n 5: .same(proto: \"data\"),\n 6: .same(proto: \"complete\"),\n 7: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularEnumField(value: &self.direction) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.tag) }()\n case 4: try { try decoder.decodeSingularMessageField(value: &self._descriptor) }()\n case 5: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n case 6: try { try decoder.decodeSingularBoolField(value: &self.complete) }()\n case 7: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.direction != .into {\n try visitor.visitSingularEnumField(value: self.direction, fieldNumber: 2)\n }\n if !self.tag.isEmpty {\n try visitor.visitSingularStringField(value: self.tag, fieldNumber: 3)\n }\n try { if let v = self._descriptor {\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n } }()\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 5)\n }\n if self.complete != false {\n try visitor.visitSingularBoolField(value: self.complete, fieldNumber: 6)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 7)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ImageTransfer, rhs: Com_Apple_Container_Build_V1_ImageTransfer) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.direction != rhs.direction {return false}\n if lhs.tag != rhs.tag {return false}\n if lhs._descriptor != rhs._descriptor {return false}\n if lhs.data != rhs.data {return false}\n if lhs.complete != rhs.complete {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ServerStream: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ServerStream\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"io\"),\n 3: .standard(proto: \"build_error\"),\n 4: .standard(proto: \"command_complete\"),\n 5: .standard(proto: \"build_transfer\"),\n 6: .standard(proto: \"image_transfer\"),\n ]\n\n fileprivate class _StorageClass {\n var _buildID: String = String()\n var _packetType: Com_Apple_Container_Build_V1_ServerStream.OneOf_PacketType?\n\n // This property is used as the initial default value for new instances of the type.\n // The type itself is protecting the reference to its storage via CoW semantics.\n // This will force a copy to be made of this reference when the first mutation occurs;\n // hence, it is safe to mark this as `nonisolated(unsafe)`.\n static nonisolated(unsafe) let defaultInstance = _StorageClass()\n\n private init() {}\n\n init(copying source: _StorageClass) {\n _buildID = source._buildID\n _packetType = source._packetType\n }\n }\n\n fileprivate mutating func _uniqueStorage() -> _StorageClass {\n if !isKnownUniquelyReferenced(&_storage) {\n _storage = _StorageClass(copying: _storage)\n }\n return _storage\n }\n\n public mutating func decodeMessage(decoder: inout D) throws {\n _ = _uniqueStorage()\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &_storage._buildID) }()\n case 2: try {\n var v: Com_Apple_Container_Build_V1_IO?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .io(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .io(v)\n }\n }()\n case 3: try {\n var v: Com_Apple_Container_Build_V1_BuildError?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildError(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildError(v)\n }\n }()\n case 4: try {\n var v: Com_Apple_Container_Build_V1_RunComplete?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .commandComplete(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .commandComplete(v)\n }\n }()\n case 5: try {\n var v: Com_Apple_Container_Build_V1_BuildTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildTransfer(v)\n }\n }()\n case 6: try {\n var v: Com_Apple_Container_Build_V1_ImageTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .imageTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .imageTransfer(v)\n }\n }()\n default: break\n }\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !_storage._buildID.isEmpty {\n try visitor.visitSingularStringField(value: _storage._buildID, fieldNumber: 1)\n }\n switch _storage._packetType {\n case .io?: try {\n guard case .io(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 2)\n }()\n case .buildError?: try {\n guard case .buildError(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 3)\n }()\n case .commandComplete?: try {\n guard case .commandComplete(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n }()\n case .buildTransfer?: try {\n guard case .buildTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 5)\n }()\n case .imageTransfer?: try {\n guard case .imageTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 6)\n }()\n case nil: break\n }\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ServerStream, rhs: Com_Apple_Container_Build_V1_ServerStream) -> Bool {\n if lhs._storage !== rhs._storage {\n let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in\n let _storage = _args.0\n let rhs_storage = _args.1\n if _storage._buildID != rhs_storage._buildID {return false}\n if _storage._packetType != rhs_storage._packetType {return false}\n return true\n }\n if !storagesAreEqual {return false}\n }\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_IO: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IO\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"data\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularEnumField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.type != .stdin {\n try visitor.visitSingularEnumField(value: self.type, fieldNumber: 1)\n }\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_IO, rhs: Com_Apple_Container_Build_V1_IO) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.data != rhs.data {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_BuildError: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".BuildError\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"message\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularEnumField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.message) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.type != .buildFailed {\n try visitor.visitSingularEnumField(value: self.type, fieldNumber: 1)\n }\n if !self.message.isEmpty {\n try visitor.visitSingularStringField(value: self.message, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_BuildError, rhs: Com_Apple_Container_Build_V1_BuildError) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.message != rhs.message {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Platform: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Platform\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"architecture\"),\n 2: .same(proto: \"os\"),\n 3: .standard(proto: \"os_version\"),\n 4: .standard(proto: \"os_features\"),\n 5: .same(proto: \"variant\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.architecture) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.os) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.osVersion) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.osFeatures) }()\n case 5: try { try decoder.decodeSingularStringField(value: &self.variant) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.architecture.isEmpty {\n try visitor.visitSingularStringField(value: self.architecture, fieldNumber: 1)\n }\n if !self.os.isEmpty {\n try visitor.visitSingularStringField(value: self.os, fieldNumber: 2)\n }\n if !self.osVersion.isEmpty {\n try visitor.visitSingularStringField(value: self.osVersion, fieldNumber: 3)\n }\n if !self.osFeatures.isEmpty {\n try visitor.visitRepeatedStringField(value: self.osFeatures, fieldNumber: 4)\n }\n if !self.variant.isEmpty {\n try visitor.visitSingularStringField(value: self.variant, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Platform, rhs: Com_Apple_Container_Build_V1_Platform) -> Bool {\n if lhs.architecture != rhs.architecture {return false}\n if lhs.os != rhs.os {return false}\n if lhs.osVersion != rhs.osVersion {return false}\n if lhs.osFeatures != rhs.osFeatures {return false}\n if lhs.variant != rhs.variant {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Descriptor: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Descriptor\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"media_type\"),\n 2: .same(proto: \"digest\"),\n 3: .same(proto: \"size\"),\n 4: .same(proto: \"urls\"),\n 5: .same(proto: \"annotations\"),\n 6: .same(proto: \"platform\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.mediaType) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.digest) }()\n case 3: try { try decoder.decodeSingularInt64Field(value: &self.size) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.urls) }()\n case 5: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.annotations) }()\n case 6: try { try decoder.decodeSingularMessageField(value: &self._platform) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.mediaType.isEmpty {\n try visitor.visitSingularStringField(value: self.mediaType, fieldNumber: 1)\n }\n if !self.digest.isEmpty {\n try visitor.visitSingularStringField(value: self.digest, fieldNumber: 2)\n }\n if self.size != 0 {\n try visitor.visitSingularInt64Field(value: self.size, fieldNumber: 3)\n }\n if !self.urls.isEmpty {\n try visitor.visitRepeatedStringField(value: self.urls, fieldNumber: 4)\n }\n if !self.annotations.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.annotations, fieldNumber: 5)\n }\n try { if let v = self._platform {\n try visitor.visitSingularMessageField(value: v, fieldNumber: 6)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Descriptor, rhs: Com_Apple_Container_Build_V1_Descriptor) -> Bool {\n if lhs.mediaType != rhs.mediaType {return false}\n if lhs.digest != rhs.digest {return false}\n if lhs.size != rhs.size {return false}\n if lhs.urls != rhs.urls {return false}\n if lhs.annotations != rhs.annotations {return false}\n if lhs._platform != rhs._platform {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/RemoteContentStoreClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Crypto\nimport ContainerizationError\nimport Foundation\nimport ContainerizationOCI\nimport ContainerXPC\n\npublic struct RemoteContentStoreClient: ContentStore {\n private static let serviceIdentifier = \"com.apple.container.core.container-core-images\"\n private static let encoder = JSONEncoder()\n\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public init() {}\n\n private func _get(digest: String) async throws -> URL? {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentGet)\n request.set(key: .digest, value: digest)\n do {\n let response = try await client.send(request)\n guard let path = response.string(key: .contentPath) else {\n return nil\n }\n return URL(filePath: path)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return nil\n }\n throw error\n }\n }\n\n public func get(digest: String) async throws -> Content? {\n guard let url = try await self._get(digest: digest) else {\n return nil\n }\n return try LocalContent(path: url)\n }\n\n public func get(digest: String) async throws -> T? {\n guard let content: Content = try await self.get(digest: digest) else {\n return nil\n }\n return try content.decode()\n }\n\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentClean)\n\n let d = try Self.encoder.encode(keeping)\n request.set(key: .digests, value: d)\n let response = try await client.send(request)\n\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let deleted = try decoder.decode([String].self, from: data)\n let size = response.uint64(key: .size)\n return (deleted, size)\n }\n\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentDelete)\n\n let d = try Self.encoder.encode(digests)\n request.set(key: .digests, value: d)\n let response = try await client.send(request)\n\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let deleted = try decoder.decode([String].self, from: data)\n let size = response.uint64(key: .size)\n return (deleted, size)\n }\n\n @discardableResult\n public func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String] {\n let (id, tempPath) = try await self.newIngestSession()\n try await body(tempPath)\n return try await self.completeIngestSession(id)\n }\n\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestStart)\n let response = try await client.send(request)\n guard let id = response.string(key: .ingestSessionId) else {\n throw ContainerizationError.init(.internalError, message: \"failed create new ingest session\")\n }\n guard let dir = response.string(key: .directory) else {\n throw ContainerizationError.init(.internalError, message: \"failed create new ingest session\")\n }\n return (id, URL(filePath: dir))\n }\n\n @discardableResult\n public func completeIngestSession(_ id: String) async throws -> [String] {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestComplete)\n\n request.set(key: .ingestSessionId, value: id)\n\n let response = try await client.send(request)\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let ingested = try decoder.decode([String].self, from: data)\n return ingested\n }\n\n public func cancelIngestSession(_ id: String) async throws {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestCancel)\n request.set(key: .ingestSessionId, value: id)\n try await client.send(request)\n }\n}\n\n#endif\n"], ["/container/Sources/Services/ContainerImagesService/Server/ImagesServiceHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\npublic struct ImagesServiceHarness: Sendable {\n let log: Logging.Logger\n let service: ImagesService\n\n public init(service: ImagesService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n public func pull(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let insecure = message.bool(key: .insecureFlag)\n\n let progressUpdateService = ProgressUpdateService(message: message)\n let imageDescription = try await service.pull(reference: ref, platform: platform, insecure: insecure, progressUpdate: progressUpdateService?.handler)\n\n let imageData = try JSONEncoder().encode(imageDescription)\n let reply = message.reply()\n reply.set(key: .imageDescription, value: imageData)\n return reply\n }\n\n @Sendable\n public func push(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let insecure = message.bool(key: .insecureFlag)\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await service.push(reference: ref, platform: platform, insecure: insecure, progressUpdate: progressUpdateService?.handler)\n\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func tag(_ message: XPCMessage) async throws -> XPCMessage {\n let old = message.string(key: .imageReference)\n guard let old else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let new = message.string(key: .imageNewReference)\n guard let new else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing new image reference\"\n )\n }\n let newDescription = try await service.tag(old: old, new: new)\n let descData = try JSONEncoder().encode(newDescription)\n let reply = message.reply()\n reply.set(key: .imageDescription, value: descData)\n return reply\n }\n\n @Sendable\n public func list(_ message: XPCMessage) async throws -> XPCMessage {\n let images = try await service.list()\n let imageData = try JSONEncoder().encode(images)\n let reply = message.reply()\n reply.set(key: .imageDescriptions, value: imageData)\n return reply\n }\n\n @Sendable\n public func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let garbageCollect = message.bool(key: .garbageCollect)\n try await self.service.delete(reference: ref, garbageCollect: garbageCollect)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func save(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .imageDescription)\n guard let data else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let imageDescription = try JSONDecoder().decode(ImageDescription.self, from: data)\n\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let out = message.string(key: .filePath)\n guard let out else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing output file path\"\n )\n }\n try await service.save(reference: imageDescription.reference, out: URL(filePath: out), platform: platform)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func load(_ message: XPCMessage) async throws -> XPCMessage {\n let input = message.string(key: .filePath)\n guard let input else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing input file path\"\n )\n }\n let images = try await service.load(from: URL(filePath: input))\n let data = try JSONEncoder().encode(images)\n let reply = message.reply()\n reply.set(key: .imageDescriptions, value: data)\n return reply\n }\n\n @Sendable\n public func prune(_ message: XPCMessage) async throws -> XPCMessage {\n let (deleted, size) = try await service.prune()\n let reply = message.reply()\n let data = try JSONEncoder().encode(deleted)\n reply.set(key: .digests, value: data)\n reply.set(key: .size, value: size)\n return reply\n }\n}\n\n// MARK: Image Snapshot Methods\n\nextension ImagesServiceHarness {\n @Sendable\n public func unpack(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing Image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n var platform: Platform?\n if let platformData = message.dataNoCopy(key: .ociPlatform) {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await self.service.unpack(description: description, platform: platform, progressUpdate: progressUpdateService?.handler)\n\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func deleteSnapshot(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform?\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n try await self.service.deleteImageSnapshot(description: description, platform: platform)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func getSnapshot(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n let platformData = message.dataNoCopy(key: .ociPlatform)\n guard let platformData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing OCI platform\"\n )\n }\n let platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n let fs = try await self.service.getImageSnapshot(description: description, platform: platform)\n let fsData = try JSONEncoder().encode(fs)\n let reply = message.reply()\n reply.set(key: .filesystem, value: fsData)\n return reply\n }\n}\n"], ["/container/Sources/ContainerClient/ContainerizationProgressAdapter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport TerminalProgress\n\npublic enum ContainerizationProgressAdapter: ProgressAdapter {\n public static func handler(from progressUpdate: ProgressUpdateHandler?) -> ProgressHandler? {\n guard let progressUpdate else {\n return nil\n }\n return { events in\n var updateEvents = [ProgressUpdateEvent]()\n for event in events {\n if event.event == \"add-items\" {\n if let items = event.value as? Int {\n updateEvents.append(.addItems(items))\n }\n } else if event.event == \"add-total-items\" {\n if let totalItems = event.value as? Int {\n updateEvents.append(.addTotalItems(totalItems))\n }\n } else if event.event == \"add-size\" {\n if let size = event.value as? Int64 {\n updateEvents.append(.addSize(size))\n }\n } else if event.event == \"add-total-size\" {\n if let totalSize = event.value as? Int64 {\n updateEvents.append(.addTotalSize(totalSize))\n }\n }\n }\n await progressUpdate(updateEvents)\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nextension Application {\n struct SystemStatus: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"status\",\n abstract: \"Show the status of `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Launchd prefix for `container` services\")\n var prefix: String = \"com.apple.container.\"\n\n func run() async throws {\n let isRegistered = try ServiceManager.isRegistered(fullServiceLabel: \"\\(prefix)apiserver\")\n if !isRegistered {\n print(\"apiserver is not running and not registered with launchd\")\n Application.exit(withError: ExitCode(1))\n }\n\n // Now ping our friendly daemon. Fail after 10 seconds with no response.\n do {\n print(\"Verifying apiserver is running...\")\n try await ClientHealthCheck.ping(timeout: .seconds(10))\n print(\"apiserver is running\")\n } catch {\n print(\"apiserver is not running\")\n Application.exit(withError: ExitCode(1))\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/Globber.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic class Globber {\n let input: URL\n var results: Set = .init()\n\n public init(_ input: URL) {\n self.input = input\n }\n\n public func match(_ pattern: String) throws {\n let adjustedPattern =\n pattern\n .replacingOccurrences(of: #\"^\\./(?=.)\"#, with: \"\", options: .regularExpression)\n .replacingOccurrences(of: \"^\\\\.[/]?$\", with: \"*\", options: .regularExpression)\n .replacingOccurrences(of: \"\\\\*{2,}[/]\", with: \"*/**/\", options: .regularExpression)\n .replacingOccurrences(of: \"[/]\\\\*{2,}([^/])\", with: \"/**/*$1\", options: .regularExpression)\n .replacingOccurrences(of: \"^\\\\*{2,}([^/])\", with: \"**/*$1\", options: .regularExpression)\n\n for child in input.children {\n try self.match(input: child, components: adjustedPattern.split(separator: \"/\").map(String.init))\n }\n }\n\n private func match(input: URL, components: [String]) throws {\n if components.isEmpty {\n var dir = input.standardizedFileURL\n\n while dir != self.input.standardizedFileURL {\n results.insert(dir)\n guard dir.pathComponents.count > 1 else { break }\n dir.deleteLastPathComponent()\n }\n return input.childrenRecursive.forEach { results.insert($0) }\n }\n\n let head = components.first ?? \"\"\n let tail = components.tail\n\n if head == \"**\" {\n var tail: [String] = tail\n while tail.first == \"**\" {\n tail = tail.tail\n }\n try self.match(input: input, components: tail)\n for child in input.children {\n try self.match(input: child, components: components)\n }\n return\n }\n\n if try glob(input.lastPathComponent, head) {\n try self.match(input: input, components: tail)\n\n for child in input.children where try glob(child.lastPathComponent, tail.first ?? \"\") {\n try self.match(input: child, components: tail)\n }\n return\n }\n }\n\n func glob(_ input: String, _ pattern: String) throws -> Bool {\n let regexPattern =\n \"^\"\n + NSRegularExpression.escapedPattern(for: pattern)\n .replacingOccurrences(of: \"\\\\*\", with: \"[^/]*\")\n .replacingOccurrences(of: \"\\\\?\", with: \"[^/]\")\n .replacingOccurrences(of: \"[\\\\^\", with: \"[^\")\n .replacingOccurrences(of: \"\\\\[\", with: \"[\")\n .replacingOccurrences(of: \"\\\\]\", with: \"]\") + \"$\"\n\n // validate the regex pattern created\n let _ = try Regex(regexPattern)\n return input.range(of: regexPattern, options: .regularExpression) != nil\n }\n}\n\nextension URL {\n var children: [URL] {\n\n (try? FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil))\n ?? []\n }\n\n var childrenRecursive: [URL] {\n var results: [URL] = []\n if let enumerator = FileManager.default.enumerator(\n at: self, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey])\n {\n while let child = enumerator.nextObject() as? URL {\n results.append(child)\n }\n }\n return [self] + results\n }\n}\n\nextension [String] {\n var tail: [String] {\n if self.count <= 1 {\n return []\n }\n return Array(self.dropFirst())\n }\n}\n"], ["/container/Sources/ContainerClient/SignalThreshold.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\n\n// For a lot of programs, they don't install their own signal handlers for\n// SIGINT/SIGTERM which poses a somewhat fun problem for containers. Because\n// they're pid 1 (doesn't matter that it isn't in the \"root\" pid namespace)\n// the default actions for SIGINT and SIGTERM now are nops. So this type gives\n// us an opportunity to set a threshold for a certain number of signals received\n// so we can have an escape hatch for users to escape their horrific mistake\n// of cat'ing /dev/urandom by exit(1)'ing :)\npublic struct SignalThreshold {\n private let threshold: Int\n private let signals: [Int32]\n private var t: Task<(), Never>?\n\n public init(\n threshold: Int,\n signals: [Int32],\n ) {\n self.threshold = threshold\n self.signals = signals\n }\n\n // Start kicks off the signal watching. The passed in handler will\n // run only once upon passing the threshold number passed in the constructor.\n mutating public func start(handler: @Sendable @escaping () -> Void) {\n let signals = self.signals\n let threshold = self.threshold\n self.t = Task {\n var received = 0\n let signalHandler = AsyncSignalHandler.create(notify: signals)\n for await _ in signalHandler.signals {\n received += 1\n if received == threshold {\n handler()\n signalHandler.cancel()\n return\n }\n }\n }\n }\n\n public func stop() {\n self.t?.cancel()\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\npublic actor NetworkService: Sendable {\n private let network: any Network\n private let log: Logger?\n private var allocator: AttachmentAllocator\n\n /// Set up a network service for the specified network.\n public init(\n network: any Network,\n log: Logger? = nil\n ) async throws {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let subnet = try CIDRAddress(status.address)\n\n let size = Int(subnet.upper.value - subnet.lower.value - 3)\n self.allocator = try AttachmentAllocator(lower: subnet.lower.value + 2, size: size)\n self.network = network\n self.log = log\n }\n\n @Sendable\n public func state(_ message: XPCMessage) async throws -> XPCMessage {\n let reply = message.reply()\n let state = await network.state\n try reply.setState(state)\n return reply\n }\n\n @Sendable\n public func allocate(_ message: XPCMessage) async throws -> XPCMessage {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let hostname = try message.hostname()\n let index = try await allocator.allocate(hostname: hostname)\n let subnet = try CIDRAddress(status.address)\n let ip = IPv4Address(fromValue: index)\n let attachment = Attachment(\n network: state.id,\n hostname: hostname,\n address: try CIDRAddress(ip, prefixLength: subnet.prefixLength).description,\n gateway: status.gateway\n )\n log?.info(\n \"allocated attachment\",\n metadata: [\n \"hostname\": \"\\(hostname)\",\n \"address\": \"\\(attachment.address)\",\n \"gateway\": \"\\(attachment.gateway)\",\n ])\n let reply = message.reply()\n try reply.setAttachment(attachment)\n try network.withAdditionalData {\n if let additionalData = $0 {\n try reply.setAdditionalData(additionalData.underlying)\n }\n }\n return reply\n }\n\n @Sendable\n public func deallocate(_ message: XPCMessage) async throws -> XPCMessage {\n let hostname = try message.hostname()\n try await allocator.deallocate(hostname: hostname)\n log?.info(\"released attachments\", metadata: [\"hostname\": \"\\(hostname)\"])\n return message.reply()\n }\n\n @Sendable\n public func lookup(_ message: XPCMessage) async throws -> XPCMessage {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let hostname = try message.hostname()\n let index = try await allocator.lookup(hostname: hostname)\n let reply = message.reply()\n guard let index else {\n return reply\n }\n\n let address = IPv4Address(fromValue: index)\n let subnet = try CIDRAddress(status.address)\n let attachment = Attachment(\n network: state.id,\n hostname: hostname,\n address: try CIDRAddress(address, prefixLength: subnet.prefixLength).description,\n gateway: status.gateway\n )\n log?.debug(\n \"lookup attachment\",\n metadata: [\n \"hostname\": \"\\(hostname)\",\n \"address\": \"\\(address)\",\n ])\n try reply.setAttachment(attachment)\n return reply\n }\n\n @Sendable\n public func disableAllocator(_ message: XPCMessage) async throws -> XPCMessage {\n let success = await allocator.disableAllocator()\n log?.info(\"attempted allocator disable\", metadata: [\"success\": \"\\(success)\"])\n let reply = message.reply()\n reply.setAllocatorDisabled(success)\n return reply\n }\n}\n\nextension XPCMessage {\n fileprivate func setAdditionalData(_ additionalData: xpc_object_t) throws {\n xpc_dictionary_set_value(self.underlying, NetworkKeys.additionalData.rawValue, additionalData)\n }\n\n fileprivate func setAllocatorDisabled(_ allocatorDisabled: Bool) {\n self.set(key: NetworkKeys.allocatorDisabled.rawValue, value: allocatorDisabled)\n }\n\n fileprivate func setAttachment(_ attachment: Attachment) throws {\n let data = try JSONEncoder().encode(attachment)\n self.set(key: NetworkKeys.attachment.rawValue, value: data)\n }\n\n fileprivate func setState(_ state: NetworkState) throws {\n let data = try JSONEncoder().encode(state)\n self.set(key: NetworkKeys.state.rawValue, value: data)\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientKernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct ClientKernel {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n}\n\nextension ClientKernel {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public static func installKernel(kernelFilePath: String, platform: SystemPlatform) async throws {\n let client = newClient()\n let message = XPCMessage(route: .installKernel)\n\n message.set(key: .kernelFilePath, value: kernelFilePath)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n try await client.send(message)\n }\n\n public static func installKernelFromTar(tarFile: String, kernelFilePath: String, platform: SystemPlatform, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let client = newClient()\n let message = XPCMessage(route: .installKernel)\n\n message.set(key: .kernelTarURL, value: tarFile)\n message.set(key: .kernelFilePath, value: kernelFilePath)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: message)\n }\n\n try await client.send(message)\n await progressUpdateClient?.finish()\n }\n\n @discardableResult\n public static func getDefaultKernel(for platform: SystemPlatform) async throws -> Kernel {\n let client = newClient()\n let message = XPCMessage(route: .getDefaultKernel)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n do {\n let reply = try await client.send(message)\n guard let kData = reply.dataNoCopy(key: .kernel) else {\n throw ContainerizationError(.internalError, message: \"Missing kernel data from XPC response\")\n }\n\n let kernel = try JSONDecoder().decode(Kernel.self, from: kData)\n return kernel\n } catch let err as ContainerizationError {\n guard err.isCode(.notFound) else {\n throw err\n }\n throw ContainerizationError(\n .notFound, message: \"Default kernel not configured for architecture \\(platform.architecture). Please use the `container system kernel set` command to configure it\")\n }\n }\n}\n\nextension SystemPlatform {\n public static var current: SystemPlatform {\n switch Platform.current.architecture {\n case \"arm64\":\n return .linuxArm\n case \"amd64\":\n return .linuxAmd\n default:\n fatalError(\"Unknown architecture\")\n }\n }\n}\n"], ["/container/Sources/APIServer/Kernel/KernelService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\nimport TerminalProgress\n\nactor KernelService {\n private static let defaultKernelNamePrefix: String = \"default.kernel-\"\n\n private let log: Logger\n private let kernelDirectory: URL\n\n public init(log: Logger, appRoot: URL) throws {\n self.log = log\n self.kernelDirectory = appRoot.appending(path: \"kernels\")\n try FileManager.default.createDirectory(at: self.kernelDirectory, withIntermediateDirectories: true)\n }\n\n /// Copies a kernel binary from a local path on disk into the managed kernels directory\n /// as the default kernel for the provided platform.\n public func installKernel(kernelFile url: URL, platform: SystemPlatform = .linuxArm) throws {\n self.log.info(\"KernelService: \\(#function) - kernelFile: \\(url), platform: \\(String(describing: platform))\")\n let kFile = url.resolvingSymlinksInPath()\n let destPath = self.kernelDirectory.appendingPathComponent(kFile.lastPathComponent)\n try FileManager.default.copyItem(at: kFile, to: destPath)\n try Task.checkCancellation()\n do {\n try self.setDefaultKernel(name: kFile.lastPathComponent, platform: platform)\n } catch {\n try? FileManager.default.removeItem(at: destPath)\n throw error\n }\n }\n\n /// Copies a kernel binary from inside of tar file into the managed kernels directory\n /// as the default kernel for the provided platform.\n /// The parameter `tar` maybe a location to a local file on disk, or a remote URL.\n public func installKernelFrom(tar: URL, kernelFilePath: String, platform: SystemPlatform, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"KernelService: \\(#function) - tar: \\(tar), kernelFilePath: \\(kernelFilePath), platform: \\(String(describing: platform))\")\n\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n\n await progressUpdate?([\n .setDescription(\"Downloading kernel\")\n ])\n let taskManager = ProgressTaskCoordinator()\n let downloadTask = await taskManager.startTask()\n var tarFile = tar\n if !FileManager.default.fileExists(atPath: tar.absoluteString) {\n self.log.debug(\"KernelService: Downloading \\(tar)\")\n tarFile = tempDir.appendingPathComponent(tar.lastPathComponent)\n var downloadProgressUpdate: ProgressUpdateHandler?\n if let progressUpdate {\n downloadProgressUpdate = ProgressTaskCoordinator.handler(for: downloadTask, from: progressUpdate)\n }\n try await FileDownloader.downloadFile(url: tar, to: tarFile, progressUpdate: downloadProgressUpdate)\n }\n await taskManager.finish()\n\n await progressUpdate?([\n .setDescription(\"Unpacking kernel\")\n ])\n let archiveReader = try ArchiveReader(file: tarFile)\n let kernelFile = try archiveReader.extractFile(from: kernelFilePath, to: tempDir)\n try self.installKernel(kernelFile: kernelFile, platform: platform)\n\n if !FileManager.default.fileExists(atPath: tar.absoluteString) {\n try FileManager.default.removeItem(at: tarFile)\n }\n }\n\n private func setDefaultKernel(name: String, platform: SystemPlatform) throws {\n self.log.info(\"KernelService: \\(#function) - name: \\(name), platform: \\(String(describing: platform))\")\n let kernelPath = self.kernelDirectory.appendingPathComponent(name)\n guard FileManager.default.fileExists(atPath: kernelPath.path) else {\n throw ContainerizationError(.notFound, message: \"Kernel not found at \\(kernelPath)\")\n }\n let name = \"\\(Self.defaultKernelNamePrefix)\\(platform.architecture)\"\n let defaultKernelPath = self.kernelDirectory.appendingPathComponent(name)\n try? FileManager.default.removeItem(at: defaultKernelPath)\n try FileManager.default.createSymbolicLink(at: defaultKernelPath, withDestinationURL: kernelPath)\n }\n\n public func getDefaultKernel(platform: SystemPlatform = .linuxArm) async throws -> Kernel {\n self.log.info(\"KernelService: \\(#function) - platform: \\(String(describing: platform))\")\n let name = \"\\(Self.defaultKernelNamePrefix)\\(platform.architecture)\"\n let defaultKernelPath = self.kernelDirectory.appendingPathComponent(name).resolvingSymlinksInPath()\n guard FileManager.default.fileExists(atPath: defaultKernelPath.path) else {\n throw ContainerizationError(.notFound, message: \"Default kernel not found at \\(defaultKernelPath)\")\n }\n return Kernel(path: defaultKernelPath, platform: platform)\n }\n}\n\nextension ArchiveReader {\n fileprivate func extractFile(from: String, to directory: URL) throws -> URL {\n let (_, data) = try self.extractFile(path: from)\n try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)\n let fileName = URL(filePath: from).lastPathComponent\n let fileURL = directory.appendingPathComponent(fileName)\n try data.write(to: fileURL, options: .atomic)\n return fileURL\n }\n}\n"], ["/container/Sources/CLI/DefaultCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\n\nstruct DefaultCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: nil,\n shouldDisplay: false\n )\n\n @OptionGroup(visibility: .hidden)\n var global: Flags.Global\n\n @Argument(parsing: .captureForPassthrough)\n var remaining: [String] = []\n\n func run() async throws {\n // See if we have a possible plugin command.\n guard let command = remaining.first else {\n Application.printModifiedHelpText()\n return\n }\n\n // Check for edge cases and unknown options to match the behavior in the absence of plugins.\n if command.isEmpty {\n throw ValidationError(\"Unknown argument '\\(command)'\")\n } else if command.starts(with: \"-\") {\n throw ValidationError(\"Unknown option '\\(command)'\")\n }\n\n let pluginLoader = Application.pluginLoader\n guard let plugin = pluginLoader.findPlugin(name: command), plugin.config.isCLI else {\n throw ValidationError(\"failed to find plugin named container-\\(command)\")\n }\n // Exec performs execvp (with no fork).\n try plugin.exec(args: remaining)\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildStdio.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIO\n\nactor BuildStdio: BuildPipelineHandler {\n public let quiet: Bool\n public let handle: FileHandle\n\n init(quiet: Bool = false, output: FileHandle = FileHandle.standardError) throws {\n self.quiet = quiet\n self.handle = output\n }\n\n nonisolated func accept(_ packet: ServerStream) throws -> Bool {\n guard let _ = packet.getIO() else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard !quiet else {\n return\n }\n guard let io = packet.getIO() else {\n throw Error.ioMissing\n }\n if let cmdString = try TerminalCommand().json() {\n var response = ClientStream()\n response.buildID = packet.buildID\n response.command = .init()\n response.command.id = packet.buildID\n response.command.command = cmdString\n sender.yield(response)\n }\n handle.write(io.data)\n }\n}\n\nextension BuildStdio {\n enum Error: Swift.Error, CustomStringConvertible {\n case ioMissing\n case invalidContinuation\n var description: String {\n switch self {\n case .ioMissing:\n return \"io field missing in packet\"\n case .invalidContinuation:\n return \"continuation could not created\"\n }\n }\n }\n}\n"], ["/container/Sources/ContainerLog/OSLogHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\nimport Logging\nimport os\n\nimport struct Logging.Logger\n\npublic struct OSLogHandler: LogHandler {\n private let logger: os.Logger\n\n public var logLevel: Logger.Level = .info\n private var formattedMetadata: String?\n\n public var metadata = Logger.Metadata() {\n didSet {\n self.formattedMetadata = self.formatMetadata(self.metadata)\n }\n }\n\n public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {\n get {\n self.metadata[metadataKey]\n }\n set {\n self.metadata[metadataKey] = newValue\n }\n }\n\n public init(label: String, category: String) {\n self.logger = os.Logger(subsystem: label, category: category)\n }\n}\n\nextension OSLogHandler {\n public func log(\n level: Logger.Level,\n message: Logger.Message,\n metadata: Logger.Metadata?,\n source: String,\n file: String,\n function: String,\n line: UInt\n ) {\n var formattedMetadata = self.formattedMetadata\n if let metadataOverride = metadata, !metadataOverride.isEmpty {\n formattedMetadata = self.formatMetadata(\n self.metadata.merging(metadataOverride) {\n $1\n }\n )\n }\n\n var finalMessage = message.description\n if let formattedMetadata {\n finalMessage += \" \" + formattedMetadata\n }\n\n self.logger.log(\n level: level.toOSLogLevel(),\n \"\\(finalMessage, privacy: .public)\"\n )\n }\n\n private func formatMetadata(_ metadata: Logger.Metadata) -> String? {\n if metadata.isEmpty {\n return nil\n }\n return metadata.map {\n \"[\\($0)=\\($1)]\"\n }.joined(separator: \" \")\n }\n}\n\nextension Logger.Level {\n func toOSLogLevel() -> OSLogType {\n switch self {\n case .debug, .trace:\n return .debug\n case .info:\n return .info\n case .notice:\n return .default\n case .error, .warning:\n return .error\n case .critical:\n return .fault\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.grpc.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n// DO NOT EDIT.\n// swift-format-ignore-file\n//\n// Generated by the protocol buffer compiler.\n// Source: Builder.proto\n//\nimport GRPC\nimport NIO\nimport NIOConcurrencyHelpers\nimport SwiftProtobuf\n\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// Usage: instantiate `Com_Apple_Container_Build_V1_BuilderClient`, then call methods of this protocol to make API calls.\npublic protocol Com_Apple_Container_Build_V1_BuilderClientProtocol: GRPCClient {\n var serviceName: String { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? { get }\n\n func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func performBuild(\n callOptions: CallOptions?,\n handler: @escaping (Com_Apple_Container_Build_V1_ServerStream) -> Void\n ) -> BidirectionalStreamingCall\n\n func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n}\n\nextension Com_Apple_Container_Build_V1_BuilderClientProtocol {\n public var serviceName: String {\n return \"com.apple.container.build.v1.Builder\"\n }\n\n /// Create a build request.\n ///\n /// - Parameters:\n /// - request: Request to send to CreateBuild.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n ///\n /// Callers should use the `send` method on the returned object to send messages\n /// to the server. The caller should send an `.end` after the final message has been sent.\n ///\n /// - Parameters:\n /// - callOptions: Call options.\n /// - handler: A closure called when each response is received from the server.\n /// - Returns: A `ClientStreamingCall` with futures for the metadata and status.\n public func performBuild(\n callOptions: CallOptions? = nil,\n handler: @escaping (Com_Apple_Container_Build_V1_ServerStream) -> Void\n ) -> BidirectionalStreamingCall {\n return self.makeBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n handler: handler\n )\n }\n\n /// Unary call to Info\n ///\n /// - Parameters:\n /// - request: Request to send to Info.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(*, deprecated)\nextension Com_Apple_Container_Build_V1_BuilderClient: @unchecked Sendable {}\n\n@available(*, deprecated, renamed: \"Com_Apple_Container_Build_V1_BuilderNIOClient\")\npublic final class Com_Apple_Container_Build_V1_BuilderClient: Com_Apple_Container_Build_V1_BuilderClientProtocol {\n private let lock = Lock()\n private var _defaultCallOptions: CallOptions\n private var _interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n public let channel: GRPCChannel\n public var defaultCallOptions: CallOptions {\n get { self.lock.withLock { return self._defaultCallOptions } }\n set { self.lock.withLockVoid { self._defaultCallOptions = newValue } }\n }\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? {\n get { self.lock.withLock { return self._interceptors } }\n set { self.lock.withLockVoid { self._interceptors = newValue } }\n }\n\n /// Creates a client for the com.apple.container.build.v1.Builder service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self._defaultCallOptions = defaultCallOptions\n self._interceptors = interceptors\n }\n}\n\npublic struct Com_Apple_Container_Build_V1_BuilderNIOClient: Com_Apple_Container_Build_V1_BuilderClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n\n /// Creates a client for the com.apple.container.build.v1.Builder service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol: GRPCClient {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? { get }\n\n func makeCreateBuildCall(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makePerformBuildCall(\n callOptions: CallOptions?\n ) -> GRPCAsyncBidirectionalStreamingCall\n\n func makeInfoCall(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Container_Build_V1_BuilderClientMetadata.serviceDescriptor\n }\n\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? {\n return nil\n }\n\n public func makeCreateBuildCall(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n public func makePerformBuildCall(\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncBidirectionalStreamingCall {\n return self.makeAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func makeInfoCall(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Container_Build_V1_CreateBuildResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n public func performBuild(\n _ requests: RequestStream,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncResponseStream where RequestStream: Sequence, RequestStream.Element == Com_Apple_Container_Build_V1_ClientStream {\n return self.performAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n requests: requests,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func performBuild(\n _ requests: RequestStream,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncResponseStream where RequestStream: AsyncSequence & Sendable, RequestStream.Element == Com_Apple_Container_Build_V1_ClientStream {\n return self.performAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n requests: requests,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Container_Build_V1_InfoResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic struct Com_Apple_Container_Build_V1_BuilderAsyncClient: Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\npublic protocol Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when invoking 'createBuild'.\n func makeCreateBuildInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'performBuild'.\n func makePerformBuildInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'info'.\n func makeInfoInterceptors() -> [ClientInterceptor]\n}\n\npublic enum Com_Apple_Container_Build_V1_BuilderClientMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"Builder\",\n fullName: \"com.apple.container.build.v1.Builder\",\n methods: [\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild,\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild,\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info,\n ]\n )\n\n public enum Methods {\n public static let createBuild = GRPCMethodDescriptor(\n name: \"CreateBuild\",\n path: \"/com.apple.container.build.v1.Builder/CreateBuild\",\n type: GRPCCallType.unary\n )\n\n public static let performBuild = GRPCMethodDescriptor(\n name: \"PerformBuild\",\n path: \"/com.apple.container.build.v1.Builder/PerformBuild\",\n type: GRPCCallType.bidirectionalStreaming\n )\n\n public static let info = GRPCMethodDescriptor(\n name: \"Info\",\n path: \"/com.apple.container.build.v1.Builder/Info\",\n type: GRPCCallType.unary\n )\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// To build a server, implement a class that conforms to this protocol.\npublic protocol Com_Apple_Container_Build_V1_BuilderProvider: CallHandlerProvider {\n var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? { get }\n\n /// Create a build request.\n func createBuild(request: Com_Apple_Container_Build_V1_CreateBuildRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n func performBuild(context: StreamingResponseCallContext) -> EventLoopFuture<(StreamEvent) -> Void>\n\n func info(request: Com_Apple_Container_Build_V1_InfoRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n}\n\nextension Com_Apple_Container_Build_V1_BuilderProvider {\n public var serviceName: Substring {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor.fullName[...]\n }\n\n /// Determines, calls and returns the appropriate request handler, depending on the request's method.\n /// Returns nil for methods not handled by this service.\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"CreateBuild\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? [],\n userFunction: self.createBuild(request:context:)\n )\n\n case \"PerformBuild\":\n return BidirectionalStreamingServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n observerFactory: self.performBuild(context:)\n )\n\n case \"Info\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeInfoInterceptors() ?? [],\n userFunction: self.info(request:context:)\n )\n\n default:\n return nil\n }\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// To implement a server, implement an object which conforms to this protocol.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Container_Build_V1_BuilderAsyncProvider: CallHandlerProvider, Sendable {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? { get }\n\n /// Create a build request.\n func createBuild(\n request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Container_Build_V1_CreateBuildResponse\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n func performBuild(\n requestStream: GRPCAsyncRequestStream,\n responseStream: GRPCAsyncResponseStreamWriter,\n context: GRPCAsyncServerCallContext\n ) async throws\n\n func info(\n request: Com_Apple_Container_Build_V1_InfoRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Container_Build_V1_InfoResponse\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncProvider {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor\n }\n\n public var serviceName: Substring {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor.fullName[...]\n }\n\n public var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? {\n return nil\n }\n\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"CreateBuild\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? [],\n wrapping: { try await self.createBuild(request: $0, context: $1) }\n )\n\n case \"PerformBuild\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n wrapping: { try await self.performBuild(requestStream: $0, responseStream: $1, context: $2) }\n )\n\n case \"Info\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeInfoInterceptors() ?? [],\n wrapping: { try await self.info(request: $0, context: $1) }\n )\n\n default:\n return nil\n }\n }\n}\n\npublic protocol Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when handling 'createBuild'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCreateBuildInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'performBuild'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makePerformBuildInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'info'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeInfoInterceptors() -> [ServerInterceptor]\n}\n\npublic enum Com_Apple_Container_Build_V1_BuilderServerMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"Builder\",\n fullName: \"com.apple.container.build.v1.Builder\",\n methods: [\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.createBuild,\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.performBuild,\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.info,\n ]\n )\n\n public enum Methods {\n public static let createBuild = GRPCMethodDescriptor(\n name: \"CreateBuild\",\n path: \"/com.apple.container.build.v1.Builder/CreateBuild\",\n type: GRPCCallType.unary\n )\n\n public static let performBuild = GRPCMethodDescriptor(\n name: \"PerformBuild\",\n path: \"/com.apple.container.build.v1.Builder/PerformBuild\",\n type: GRPCCallType.bidirectionalStreaming\n )\n\n public static let info = GRPCMethodDescriptor(\n name: \"Info\",\n path: \"/com.apple.container.build.v1.Builder/Info\",\n type: GRPCCallType.unary\n )\n }\n}\n"], ["/container/Sources/SocketForwarder/TCPForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\n\npublic struct TCPForwarder: SocketForwarder {\n private let proxyAddress: SocketAddress\n\n private let serverAddress: SocketAddress\n\n private let eventLoopGroup: any EventLoopGroup\n\n private let log: Logger?\n\n public init(\n proxyAddress: SocketAddress,\n serverAddress: SocketAddress,\n eventLoopGroup: any EventLoopGroup,\n log: Logger? = nil\n ) throws {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.log = log\n }\n\n public func run() throws -> EventLoopFuture {\n self.log?.trace(\"frontend - creating listener\")\n\n let bootstrap = ServerBootstrap(group: self.eventLoopGroup)\n .serverChannelOption(ChannelOptions.socket(.init(SOL_SOCKET), .init(SO_REUSEADDR)), value: 1)\n .childChannelOption(ChannelOptions.socket(.init(SOL_SOCKET), .init(SO_REUSEADDR)), value: 1)\n .childChannelInitializer { channel in\n channel.eventLoop.makeCompletedFuture {\n try channel.pipeline.syncOperations.addHandler(\n ConnectHandler(serverAddress: self.serverAddress, log: log)\n )\n }\n }\n\n return\n bootstrap\n .bind(to: self.proxyAddress)\n .flatMap { $0.eventLoop.makeSucceededFuture(SocketForwarderResult(channel: $0)) }\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\n\nextension Application {\n struct DNSCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a local DNS domain for containers (must run as an administrator)\"\n )\n\n @Argument(help: \"the local domain name\")\n var domainName: String\n\n func run() async throws {\n let resolver: HostDNSResolver = HostDNSResolver()\n do {\n try resolver.createDomain(name: domainName)\n print(domainName)\n } catch let error as ContainerizationError {\n throw error\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot create domain (try sudo?)\")\n }\n\n do {\n try HostDNSResolver.reinitialize()\n } catch {\n throw ContainerizationError(.invalidState, message: \"mDNSResponder restart failed, run `sudo killall -HUP mDNSResponder` to deactivate domain\")\n }\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/AllocationOnlyVmnetNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\npublic actor AllocationOnlyVmnetNetwork: Network {\n private let log: Logger\n private var _state: NetworkState\n\n /// Configure a bridge network that allows external system access using\n /// network address translation.\n public init(\n configuration: NetworkConfiguration,\n log: Logger\n ) throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.unsupported, message: \"invalid network mode \\(configuration.mode)\")\n }\n\n guard configuration.subnet == nil else {\n throw ContainerizationError(.unsupported, message: \"subnet assignment is not yet implemented\")\n }\n\n self.log = log\n self._state = .created(configuration)\n }\n\n public var state: NetworkState {\n self._state\n }\n\n public nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws {\n try handler(nil)\n }\n\n public func start() async throws {\n guard case .created(let configuration) = _state else {\n throw ContainerizationError(.invalidState, message: \"cannot start network \\(_state.id) in \\(_state.state) state\")\n }\n var defaultSubnet = \"192.168.64.1/24\"\n\n log.info(\n \"starting allocation-only network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(NetworkMode.nat.rawValue)\",\n ]\n )\n\n if let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName) {\n // TODO: Make the suiteName a constant defined in ClientDefaults and use that.\n // This will need some re-working of dependencies between NetworkService and Client\n defaultSubnet = suite.string(forKey: \"network.subnet\") ?? defaultSubnet\n }\n\n let subnet = try CIDRAddress(defaultSubnet)\n let gateway = IPv4Address(fromValue: subnet.lower.value + 1)\n self._state = .running(configuration, NetworkStatus(address: subnet.description, gateway: gateway.description))\n log.info(\n \"started allocation-only network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n \"cidr\": \"\\(defaultSubnet)\",\n ]\n )\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/ExitMonitor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\n/// Track when long running work exits, and notify the caller via a callback.\npublic actor ExitMonitor {\n /// A callback that receives the client identifier and exit code.\n public typealias ExitCallback = @Sendable (String, Int32) async throws -> Void\n\n /// A function that waits for work to complete, returning an exit code.\n public typealias WaitHandler = @Sendable () async throws -> Int32\n\n /// Create a new monitor.\n ///\n /// - Parameters:\n /// - log: The destination for log messages.\n public init(log: Logger? = nil) {\n self.log = log\n }\n\n private var exitCallbacks: [String: ExitCallback] = [:]\n private var runningTasks: [String: Task] = [:]\n private let log: Logger?\n\n /// Remove tracked work from the monitor.\n ///\n /// - Parameters:\n /// - id: The client identifier for the tracked work.\n public func stopTracking(id: String) async {\n if let task = self.runningTasks[id] {\n task.cancel()\n }\n exitCallbacks.removeValue(forKey: id)\n runningTasks.removeValue(forKey: id)\n }\n\n /// Register long running work so that the monitor invokes\n /// a callback when the work completes.\n ///\n /// - Parameters:\n /// - id: The client identifier for the work.\n /// - onExit: The callback to invoke when the work completes.\n public func registerProcess(id: String, onExit: @escaping ExitCallback) async throws {\n guard self.exitCallbacks[id] == nil else {\n throw ContainerizationError(.invalidState, message: \"ExitMonitor already setup for process \\(id)\")\n }\n self.exitCallbacks[id] = onExit\n }\n\n /// Await the completion of previously registered item of work.\n ///\n /// - Parameters:\n /// - id: The client identifier for the work.\n /// - waitingOn: A function that waits for the work to complete,\n /// and then returns an exit code.\n public func track(id: String, waitingOn: @escaping WaitHandler) async throws {\n guard let onExit = self.exitCallbacks[id] else {\n throw ContainerizationError(.invalidState, message: \"ExitMonitor not setup for process \\(id)\")\n }\n guard self.runningTasks[id] == nil else {\n throw ContainerizationError(.invalidState, message: \"Already have a running task tracking process \\(id)\")\n }\n self.runningTasks[id] = Task {\n do {\n let exitStatus = try await waitingOn()\n try await onExit(id, exitStatus)\n } catch {\n self.log?.error(\"WaitHandler for \\(id) threw error \\(String(describing: error))\")\n try? await onExit(id, -1)\n }\n }\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct DNSDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete a local DNS domain (must run as an administrator)\",\n aliases: [\"rm\"]\n )\n\n @Argument(help: \"the local domain name\")\n var domainName: String\n\n func run() async throws {\n let resolver = HostDNSResolver()\n do {\n try resolver.deleteDomain(name: domainName)\n print(domainName)\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot create domain (try sudo?)\")\n }\n\n do {\n try HostDNSResolver.reinitialize()\n } catch {\n throw ContainerizationError(.invalidState, message: \"mDNSResponder restart failed, run `sudo killall -HUP mDNSResponder` to deactivate domain\")\n }\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A configuration for displaying a progress bar.\npublic struct ProgressConfig: Sendable {\n /// The file handle for progress updates.\n let terminal: FileHandle\n /// The initial description of the progress bar.\n let initialDescription: String\n /// The initial additional description of the progress bar.\n let initialSubDescription: String\n /// The initial items name (e.g., \"files\").\n let initialItemsName: String\n /// A flag indicating whether to show a spinner (e.g., \"⠋\").\n /// The spinner is hidden when a progress bar is shown.\n public let showSpinner: Bool\n /// A flag indicating whether to show tasks and total tasks (e.g., \"[1]\" or \"[1/3]\").\n public let showTasks: Bool\n /// A flag indicating whether to show the description (e.g., \"Downloading...\").\n public let showDescription: Bool\n /// A flag indicating whether to show a percentage (e.g., \"100%\").\n /// The percentage is hidden when no total size and total items are set.\n public let showPercent: Bool\n /// A flag indicating whether to show a progress bar (e.g., \"|███ |\").\n /// The progress bar is hidden when no total size and total items are set.\n public let showProgressBar: Bool\n /// A flag indicating whether to show items and total items (e.g., \"(22 it)\" or \"(22/22 it)\").\n public let showItems: Bool\n /// A flag indicating whether to show a size and a total size (e.g., \"(22 MB)\" or \"(22/22 MB)\").\n public let showSize: Bool\n /// A flag indicating whether to show a speed (e.g., \"(4.834 MB/s)\").\n /// The speed is combined with the size and total size (e.g., \"(22/22 MB, 4.834 MB/s)\").\n /// The speed is hidden when no total size is set.\n public let showSpeed: Bool\n /// A flag indicating whether to show the elapsed time (e.g., \"[4s]\").\n public let showTime: Bool\n /// The flag indicating whether to ignore small size values (less than 1 MB). For example, this may help to avoid reaching 100% after downloading metadata before downloading content.\n public let ignoreSmallSize: Bool\n /// The initial total tasks of the progress bar.\n let initialTotalTasks: Int?\n /// The initial total size of the progress bar.\n let initialTotalSize: Int64?\n /// The initial total items of the progress bar.\n let initialTotalItems: Int?\n /// The width of the progress bar in characters.\n public let width: Int\n /// The theme of the progress bar.\n public let theme: ProgressTheme\n /// The flag indicating whether to clear the progress bar before resetting the cursor.\n public let clearOnFinish: Bool\n /// The flag indicating whether to update the progress bar.\n public let disableProgressUpdates: Bool\n /// Creates a new instance of `ProgressConfig`.\n /// - Parameters:\n /// - terminal: The file handle for progress updates. The default value is `FileHandle.standardError`.\n /// - description: The initial description of the progress bar. The default value is `\"\"`.\n /// - subDescription: The initial additional description of the progress bar. The default value is `\"\"`.\n /// - itemsName: The initial items name. The default value is `\"it\"`.\n /// - showSpinner: A flag indicating whether to show a spinner. The default value is `true`.\n /// - showTasks: A flag indicating whether to show tasks and total tasks. The default value is `false`.\n /// - showDescription: A flag indicating whether to show the description. The default value is `true`.\n /// - showPercent: A flag indicating whether to show a percentage. The default value is `true`.\n /// - showProgressBar: A flag indicating whether to show a progress bar. The default value is `false`.\n /// - showItems: A flag indicating whether to show items and a total items. The default value is `false`.\n /// - showSize: A flag indicating whether to show a size and a total size. The default value is `true`.\n /// - showSpeed: A flag indicating whether to show a speed. The default value is `true`.\n /// - showTime: A flag indicating whether to show the elapsed time. The default value is `true`.\n /// - ignoreSmallSize: A flag indicating whether to ignore small size values. The default value is `false`.\n /// - totalTasks: The initial total tasks of the progress bar. The default value is `nil`.\n /// - totalItems: The initial total items of the progress bar. The default value is `nil`.\n /// - totalSize: The initial total size of the progress bar. The default value is `nil`.\n /// - width: The width of the progress bar in characters. The default value is `120`.\n /// - theme: The theme of the progress bar. The default value is `nil`.\n /// - clearOnFinish: The flag indicating whether to clear the progress bar before resetting the cursor. The default is `true`.\n /// - disableProgressUpdates: The flag indicating whether to update the progress bar. The default is `false`.\n public init(\n terminal: FileHandle = .standardError,\n description: String = \"\",\n subDescription: String = \"\",\n itemsName: String = \"it\",\n showSpinner: Bool = true,\n showTasks: Bool = false,\n showDescription: Bool = true,\n showPercent: Bool = true,\n showProgressBar: Bool = false,\n showItems: Bool = false,\n showSize: Bool = true,\n showSpeed: Bool = true,\n showTime: Bool = true,\n ignoreSmallSize: Bool = false,\n totalTasks: Int? = nil,\n totalItems: Int? = nil,\n totalSize: Int64? = nil,\n width: Int = 120,\n theme: ProgressTheme? = nil,\n clearOnFinish: Bool = true,\n disableProgressUpdates: Bool = false\n ) throws {\n if let totalTasks {\n guard totalTasks > 0 else {\n throw Error.invalid(\"totalTasks must be greater than zero\")\n }\n }\n if let totalItems {\n guard totalItems > 0 else {\n throw Error.invalid(\"totalItems must be greater than zero\")\n }\n }\n if let totalSize {\n guard totalSize > 0 else {\n throw Error.invalid(\"totalSize must be greater than zero\")\n }\n }\n\n self.terminal = terminal\n self.initialDescription = description\n self.initialSubDescription = subDescription\n self.initialItemsName = itemsName\n\n self.showSpinner = showSpinner\n self.showTasks = showTasks\n self.showDescription = showDescription\n self.showPercent = showPercent\n self.showProgressBar = showProgressBar\n self.showItems = showItems\n self.showSize = showSize\n self.showSpeed = showSpeed\n self.showTime = showTime\n\n self.ignoreSmallSize = ignoreSmallSize\n self.initialTotalTasks = totalTasks\n self.initialTotalItems = totalItems\n self.initialTotalSize = totalSize\n\n self.width = width\n self.theme = theme ?? DefaultProgressTheme()\n self.clearOnFinish = clearOnFinish\n self.disableProgressUpdates = disableProgressUpdates\n }\n}\n\nextension ProgressConfig {\n /// An enumeration of errors that can occur when creating a `ProgressConfig`.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalid(String)\n\n /// The description of the error.\n public var description: String {\n switch self {\n case .invalid(let reason):\n return \"Failed to validate config (\\(reason))\"\n }\n }\n }\n}\n"], ["/container/Sources/APIServer/Kernel/KernelHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nstruct KernelHarness {\n private let log: Logging.Logger\n private let service: KernelService\n\n init(service: KernelService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n public func install(_ message: XPCMessage) async throws -> XPCMessage {\n let kernelFilePath = try message.kernelFilePath()\n let platform = try message.platform()\n\n guard let kernelTarUrl = try message.kernelTarURL() else {\n // We have been given a path to a kernel binary on disk\n guard let kernelFile = URL(string: kernelFilePath) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid kernel file path: \\(kernelFilePath)\")\n }\n try await self.service.installKernel(kernelFile: kernelFile, platform: platform)\n return message.reply()\n }\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await self.service.installKernelFrom(tar: kernelTarUrl, kernelFilePath: kernelFilePath, platform: platform, progressUpdate: progressUpdateService?.handler)\n return message.reply()\n }\n\n public func getDefaultKernel(_ message: XPCMessage) async throws -> XPCMessage {\n guard let platformData = message.dataNoCopy(key: .systemPlatform) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing SystemPlatform\")\n }\n let platform = try JSONDecoder().decode(SystemPlatform.self, from: platformData)\n let kernel = try await self.service.getDefaultKernel(platform: platform)\n let reply = message.reply()\n let data = try JSONEncoder().encode(kernel)\n reply.set(key: .kernel, value: data)\n return reply\n }\n}\n\nextension XPCMessage {\n fileprivate func platform() throws -> SystemPlatform {\n guard let platformData = self.dataNoCopy(key: .systemPlatform) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing SystemPlatform in XPC Message\")\n }\n let platform = try JSONDecoder().decode(SystemPlatform.self, from: platformData)\n return platform\n }\n\n fileprivate func kernelFilePath() throws -> String {\n guard let kernelFilePath = self.string(key: .kernelFilePath) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing kernel file path in XPC Message\")\n }\n return kernelFilePath\n }\n\n fileprivate func kernelTarURL() throws -> URL? {\n guard let kernelTarURLString = self.string(key: .kernelTarURL) else {\n return nil\n }\n guard let k = URL(string: kernelTarURLString) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse URL from \\(kernelTarURLString)\")\n }\n return k\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+State.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension ProgressBar {\n /// A configuration struct for the progress bar.\n public struct State {\n /// A flag indicating whether the progress bar is finished.\n public var finished = false\n var iteration = 0\n private let speedInterval: DispatchTimeInterval = .seconds(1)\n\n var description: String\n var subDescription: String\n var itemsName: String\n\n var tasks: Int\n var totalTasks: Int?\n\n var items: Int\n var totalItems: Int?\n\n private var sizeUpdateTime: DispatchTime?\n private var sizeUpdateValue: Int64 = 0\n var size: Int64 {\n didSet {\n calculateSizeSpeed()\n }\n }\n var totalSize: Int64?\n private var sizeUpdateSpeed: String?\n var sizeSpeed: String? {\n guard sizeUpdateTime == nil || sizeUpdateTime! > .now() - speedInterval - speedInterval else {\n return Int64(0).formattedSizeSpeed(from: startTime)\n }\n return sizeUpdateSpeed\n }\n var averageSizeSpeed: String {\n size.formattedSizeSpeed(from: startTime)\n }\n\n var percent: String {\n var value = 0\n if let totalSize, totalSize > 0 {\n value = Int(size * 100 / totalSize)\n } else if let totalItems, totalItems > 0 {\n value = Int(items * 100 / totalItems)\n }\n value = min(value, 100)\n return \"\\(value)%\"\n }\n\n var startTime: DispatchTime\n var output = \"\"\n\n init(\n description: String = \"\", subDescription: String = \"\", itemsName: String = \"\", tasks: Int = 0, totalTasks: Int? = nil, items: Int = 0, totalItems: Int? = nil,\n size: Int64 = 0, totalSize: Int64? = nil, startTime: DispatchTime = .now()\n ) {\n self.description = description\n self.subDescription = subDescription\n self.itemsName = itemsName\n self.tasks = tasks\n self.totalTasks = totalTasks\n self.items = items\n self.totalItems = totalItems\n self.size = size\n self.totalSize = totalSize\n self.startTime = startTime\n }\n\n private mutating func calculateSizeSpeed() {\n if sizeUpdateTime == nil || sizeUpdateTime! < .now() - speedInterval {\n let partSize = size - sizeUpdateValue\n let partStartTime = sizeUpdateTime ?? startTime\n let partSizeSpeed = partSize.formattedSizeSpeed(from: partStartTime)\n self.sizeUpdateSpeed = partSizeSpeed\n\n sizeUpdateTime = .now()\n sizeUpdateValue = size\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\npublic struct ClientNetwork {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n\n public static let defaultNetworkName = \"default\"\n}\n\nextension ClientNetwork {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n private static func xpcSend(\n client: XPCClient,\n message: XPCMessage,\n timeout: Duration? = .seconds(15)\n ) async throws -> XPCMessage {\n try await client.send(message, responseTimeout: timeout)\n }\n\n public static func create(configuration: NetworkConfiguration) async throws -> NetworkState {\n let client = Self.newClient()\n let request = XPCMessage(route: .networkCreate)\n request.set(key: .networkId, value: configuration.id)\n\n let data = try JSONEncoder().encode(configuration)\n request.set(key: .networkConfig, value: data)\n\n let response = try await xpcSend(client: client, message: request)\n let responseData = response.dataNoCopy(key: .networkState)\n guard let responseData else {\n throw ContainerizationError(.invalidArgument, message: \"network configuration not received\")\n }\n let state = try JSONDecoder().decode(NetworkState.self, from: responseData)\n return state\n }\n\n public static func list() async throws -> [NetworkState] {\n let client = Self.newClient()\n let request = XPCMessage(route: .networkList)\n\n let response = try await xpcSend(client: client, message: request, timeout: .seconds(1))\n let responseData = response.dataNoCopy(key: .networkStates)\n guard let responseData else {\n return []\n }\n let states = try JSONDecoder().decode([NetworkState].self, from: responseData)\n return states\n }\n\n /// Get the network for the provided id.\n public static func get(id: String) async throws -> NetworkState {\n let networks = try await list()\n guard let network = networks.first(where: { $0.id == id }) else {\n throw ContainerizationError(.notFound, message: \"network \\(id) not found\")\n }\n return network\n }\n\n /// Delete the network with the given id.\n public static func delete(id: String) async throws {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .networkDelete)\n request.set(key: .networkId, value: id)\n try await client.send(request)\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ContentServiceHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\n\npublic struct ContentServiceHarness: Sendable {\n private let log: Logging.Logger\n private let service: ContentStoreService\n\n public init(service: ContentStoreService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n public func get(_ message: XPCMessage) async throws -> XPCMessage {\n let d = message.string(key: .digest)\n guard let d else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n guard let path = try await service.get(digest: d) else {\n let err = ContainerizationError(.notFound, message: \"digest \\(d) not found\")\n let reply = message.reply()\n reply.set(error: err)\n return reply\n }\n let reply = message.reply()\n reply.set(key: .contentPath, value: path.path(percentEncoded: false))\n return reply\n }\n\n @Sendable\n public func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .digests)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n let digests = try JSONDecoder().decode([String].self, from: data)\n let (deleted, size) = try await self.service.delete(digests: digests)\n let d = try JSONEncoder().encode(deleted)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n reply.set(key: .size, value: size)\n return reply\n }\n\n @Sendable\n public func clean(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .digests)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n let digests = try JSONDecoder().decode([String].self, from: data)\n let (deleted, size) = try await self.service.delete(keeping: digests)\n let d = try JSONEncoder().encode(deleted)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n reply.set(key: .size, value: size)\n return reply\n }\n\n @Sendable\n public func newIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let session = try await self.service.newIngestSession()\n let id = session.id\n let dir = session.ingestDir\n let reply = message.reply()\n reply.set(key: .directory, value: dir.path(percentEncoded: false))\n reply.set(key: .ingestSessionId, value: id)\n return reply\n }\n\n @Sendable\n public func cancelIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .ingestSessionId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"missing ingest session id\")\n }\n try await self.service.cancelIngestSession(id)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func completeIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .ingestSessionId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"missing ingest session id\")\n }\n let ingested = try await self.service.completeIngestSession(id)\n let d = try JSONEncoder().encode(ingested)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n return reply\n }\n}\n"], ["/container/Sources/ContainerClient/Measurement+Parse.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nprivate let units: [Character: UnitInformationStorage] = [\n \"b\": .bytes,\n \"k\": .kibibytes,\n \"m\": .mebibytes,\n \"g\": .gibibytes,\n \"t\": .tebibytes,\n \"p\": .pebibytes,\n]\n\nextension Measurement {\n public enum ParseError: Swift.Error, CustomStringConvertible {\n case invalidSize\n case invalidSymbol(String)\n\n public var description: String {\n switch self {\n case .invalidSize:\n return \"invalid size\"\n case .invalidSymbol(let symbol):\n return \"invalid symbol: \\(symbol)\"\n }\n }\n }\n\n /// parse the provided string into a measurement that is able to be converted to various byte sizes\n public static func parse(parsing: String) throws -> Measurement {\n let check = \"01234567890. \"\n let i = parsing.lastIndex {\n check.contains($0)\n }\n guard let i else {\n throw ParseError.invalidSize\n }\n let after = parsing.index(after: i)\n let rawValue = parsing[..(value: value, unit: unit)\n }\n\n static func parseUnit(_ unit: String) throws -> Character {\n let s = unit.dropFirst()\n switch s {\n case \"\", \"b\", \"ib\":\n return unit.first ?? \"b\"\n default:\n throw ParseError.invalidSymbol(unit)\n }\n }\n}\n"], ["/container/Sources/APIServer/Plugin/PluginsService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerPlugin\nimport Foundation\nimport Logging\n\nactor PluginsService {\n private let log: Logger\n private var loaded: [String: Plugin]\n private let pluginLoader: PluginLoader\n\n public init(pluginLoader: PluginLoader, log: Logger) {\n self.log = log\n self.loaded = [:]\n self.pluginLoader = pluginLoader\n }\n\n /// Load the specified plugins, or all plugins with services defined\n /// if none are explicitly specified.\n public func loadAll(\n _ plugins: [Plugin]? = nil,\n ) throws {\n let registerPlugins = plugins ?? pluginLoader.findPlugins()\n for plugin in registerPlugins {\n try pluginLoader.registerWithLaunchd(plugin: plugin)\n loaded[plugin.name] = plugin\n }\n }\n\n /// Stop the specified plugins, or all plugins with services defined\n /// if none are explicitly specified.\n public func stopAll(_ plugins: [Plugin]? = nil) throws {\n let deregisterPlugins = plugins ?? pluginLoader.findPlugins()\n for plugin in deregisterPlugins {\n try pluginLoader.deregisterWithLaunchd(plugin: plugin)\n self.loaded.removeValue(forKey: plugin.name)\n }\n }\n\n // MARK: XPC API surface.\n\n /// Load a single plugin, doing nothing if the plugin is already loaded.\n public func load(name: String) throws {\n guard self.loaded[name] == nil else {\n return\n }\n guard let plugin = pluginLoader.findPlugin(name: name) else {\n throw Error.pluginNotFound(name)\n }\n try pluginLoader.registerWithLaunchd(plugin: plugin)\n self.loaded[plugin.name] = plugin\n }\n\n /// Get information for a loaded plugin.\n public func get(name: String) throws -> Plugin {\n guard let plugin = loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n return plugin\n }\n\n /// Restart a loaded plugin.\n public func restart(name: String) throws {\n guard let plugin = self.loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n try ServiceManager.kickstart(fullServiceLabel: plugin.getLaunchdLabel())\n }\n\n /// Unload a loaded plugin.\n public func unload(name: String) throws {\n guard let plugin = self.loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n try pluginLoader.deregisterWithLaunchd(plugin: plugin)\n self.loaded.removeValue(forKey: plugin.name)\n }\n\n /// List all loaded plugins.\n public func list() throws -> [Plugin] {\n self.loaded.map { $0.value }\n }\n\n public enum Error: Swift.Error, CustomStringConvertible {\n case pluginNotFound(String)\n case pluginNotLoaded(String)\n\n public var description: String {\n switch self {\n case .pluginNotFound(let name):\n return \"plugin not found: \\(name)\"\n case .pluginNotLoaded(let name):\n return \"plugin not loaded: \\(name)\"\n }\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/Plugin.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\n/// Value type that contains the plugin configuration, the parsed name of the\n/// plugin and whether a CLI surface for the plugin was found.\npublic struct Plugin: Sendable, Codable {\n private static let machServicePrefix = \"com.apple.container.\"\n\n /// Pathname to installation directory for plugins.\n public let binaryURL: URL\n\n /// Configuration for the plugin.\n public let config: PluginConfig\n\n public init(binaryURL: URL, config: PluginConfig) {\n self.binaryURL = binaryURL\n self.config = config\n }\n}\n\nextension Plugin {\n public var name: String { binaryURL.lastPathComponent }\n\n public var shouldBoot: Bool {\n guard let config = self.config.servicesConfig else {\n return false\n }\n\n return config.loadAtBoot\n }\n\n public func getLaunchdLabel(instanceId: String? = nil) -> String {\n // Use the plugin name for the launchd label.\n guard let instanceId else {\n return \"\\(Self.machServicePrefix)\\(self.name)\"\n }\n return \"\\(Self.machServicePrefix)\\(self.name).\\(instanceId)\"\n }\n\n public func getMachServices(instanceId: String? = nil) -> [String] {\n // Use the service type for the mach service.\n guard let config = self.config.servicesConfig else {\n return []\n }\n var services = [String]()\n for service in config.services {\n let serviceName: String\n if let instanceId {\n serviceName = \"\\(Self.machServicePrefix)\\(service.type.rawValue).\\(name).\\(instanceId)\"\n } else {\n serviceName = \"\\(Self.machServicePrefix)\\(service.type.rawValue).\\(name)\"\n }\n services.append(serviceName)\n }\n return services\n }\n\n public func getMachService(instanceId: String? = nil, type: PluginConfig.DaemonPluginType) -> String? {\n guard hasType(type) else {\n return nil\n }\n\n guard let instanceId else {\n return \"\\(Self.machServicePrefix)\\(type.rawValue).\\(name)\"\n }\n return \"\\(Self.machServicePrefix)\\(type.rawValue).\\(name).\\(instanceId)\"\n }\n\n public func hasType(_ type: PluginConfig.DaemonPluginType) -> Bool {\n guard let config = self.config.servicesConfig else {\n return false\n }\n\n guard !(config.services.filter { $0.type == type }.isEmpty) else {\n return false\n }\n\n return true\n }\n}\n\nextension Plugin {\n public func exec(args: [String]) throws {\n var args = args\n let executable = self.binaryURL.path\n args[0] = executable\n let argv = args.map { strdup($0) } + [nil]\n guard execvp(executable, argv) != -1 else {\n throw POSIXError.fromErrno()\n }\n fatalError(\"unreachable\")\n }\n\n func helpText(padding: Int) -> String {\n guard !self.name.isEmpty else {\n return \"\"\n }\n let namePadded = name.padding(toLength: padding, withPad: \" \", startingAt: 0)\n return \" \" + namePadded + self.config.abstract\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport Foundation\n\n/// A client for interacting with a single network.\npublic struct NetworkClient: Sendable {\n // FIXME: need more flexibility than a hard-coded constant?\n static let label = \"com.apple.container.network.container-network-vmnet\"\n\n private var machServiceLabel: String {\n \"\\(Self.label).\\(id)\"\n }\n\n let id: String\n\n /// Create a client for a network.\n public init(id: String) {\n self.id = id\n }\n}\n\n// Runtime Methods\nextension NetworkClient {\n public func state() async throws -> NetworkState {\n let request = XPCMessage(route: NetworkRoutes.state.rawValue)\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n let state = try response.state()\n return state\n }\n\n public func allocate(hostname: String) async throws -> (attachment: Attachment, additionalData: XPCMessage?) {\n let request = XPCMessage(route: NetworkRoutes.allocate.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n let attachment = try response.attachment()\n let additionalData = response.additionalData()\n return (attachment, additionalData)\n }\n\n public func deallocate(hostname: String) async throws {\n let request = XPCMessage(route: NetworkRoutes.deallocate.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func lookup(hostname: String) async throws -> Attachment? {\n let request = XPCMessage(route: NetworkRoutes.lookup.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.dataNoCopy(key: NetworkKeys.attachment.rawValue).map {\n try JSONDecoder().decode(Attachment.self, from: $0)\n }\n }\n\n public func disableAllocator() async throws -> Bool {\n let request = XPCMessage(route: NetworkRoutes.disableAllocator.rawValue)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.allocatorDisabled()\n }\n\n private func createClient() -> XPCClient {\n XPCClient(service: machServiceLabel)\n }\n}\n\nextension XPCMessage {\n func additionalData() -> XPCMessage? {\n guard let additionalData = xpc_dictionary_get_dictionary(self.underlying, NetworkKeys.additionalData.rawValue) else {\n return nil\n }\n return XPCMessage(object: additionalData)\n }\n\n func allocatorDisabled() throws -> Bool {\n self.bool(key: NetworkKeys.allocatorDisabled.rawValue)\n }\n\n func attachment() throws -> Attachment {\n let data = self.dataNoCopy(key: NetworkKeys.attachment.rawValue)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No network attachment snapshot data in message\")\n }\n return try JSONDecoder().decode(Attachment.self, from: data)\n }\n\n func hostname() throws -> String {\n let hostname = self.string(key: NetworkKeys.hostname.rawValue)\n guard let hostname else {\n throw ContainerizationError(.invalidArgument, message: \"No hostname data in message\")\n }\n return hostname\n }\n\n func state() throws -> NetworkState {\n let data = self.dataNoCopy(key: NetworkKeys.state.rawValue)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No network snapshot data in message\")\n }\n return try JSONDecoder().decode(NetworkState.self, from: data)\n }\n}\n"], ["/container/Sources/APIServer/Plugin/PluginsHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nstruct PluginsHarness {\n private let log: Logging.Logger\n private let service: PluginsService\n\n init(service: PluginsService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func load(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.load(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func get(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n let plugin = try await service.get(name: name)\n let data = try JSONEncoder().encode(plugin)\n\n let reply = message.reply()\n reply.set(key: .plugin, value: data)\n return reply\n }\n\n @Sendable\n func restart(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.restart(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func unload(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.unload(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let plugins = try await service.list()\n\n let data = try JSONEncoder().encode(plugins)\n\n let reply = message.reply()\n reply.set(key: .plugins, value: data)\n return reply\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ContainerInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more containers\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Containers to inspect\")\n var containers: [String]\n\n func run() async throws {\n let objects: [any Codable] = try await ClientContainer.list().filter {\n containers.contains($0.id)\n }.map {\n PrintableContainer($0)\n }\n print(try objects.jsonArray())\n }\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSDefault.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\n\nextension Application {\n struct DNSDefault: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"default\",\n abstract: \"Set or unset the default local DNS domain\",\n subcommands: [\n DefaultSetCommand.self,\n DefaultUnsetCommand.self,\n DefaultInspectCommand.self,\n ]\n )\n\n struct DefaultSetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default local DNS domain\"\n\n )\n\n @Argument(help: \"the default `--domain-name` to use for the `create` or `run` command\")\n var domainName: String\n\n func run() async throws {\n ClientDefaults.set(value: domainName, key: .defaultDNSDomain)\n print(domainName)\n }\n }\n\n struct DefaultUnsetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"unset\",\n abstract: \"Unset the default local DNS domain\",\n aliases: [\"clear\"]\n )\n\n func run() async throws {\n ClientDefaults.unset(key: .defaultDNSDomain)\n print(\"Unset the default local DNS domain\")\n }\n }\n\n struct DefaultInspectCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display the default local DNS domain\"\n )\n\n func run() async throws {\n print(ClientDefaults.getOptional(key: .defaultDNSDomain) ?? \"\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/Filesystem.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Options to pass to a mount call.\npublic typealias MountOptions = [String]\n\nextension MountOptions {\n /// Returns true if the Filesystem should be consumed as read-only.\n public var readonly: Bool {\n self.contains(\"ro\")\n }\n}\n\n/// A host filesystem that will be attached to the sandbox for use.\n///\n/// A filesystem will be mounted automatically when starting the sandbox\n/// or container.\npublic struct Filesystem: Sendable, Codable {\n /// Type of caching to perform at the host level.\n public enum CacheMode: Sendable, Codable {\n case on\n case off\n case auto\n }\n\n /// Sync mode to perform at the host level.\n public enum SyncMode: Sendable, Codable {\n case full\n case fsync\n case nosync\n }\n\n /// The type of filesystem attachment for the sandbox.\n public enum FSType: Sendable, Codable, Equatable {\n package enum VirtiofsType: String, Sendable, Codable, Equatable {\n // This is a virtiofs share for the rootfs of a sandbox.\n case rootfs\n // Data share. This is what all virtiofs shares for anything besides\n // the rootfs for a sandbox will be.\n case data\n }\n\n case block(format: String, cache: CacheMode, sync: SyncMode)\n case virtiofs\n case tmpfs\n }\n\n /// Type of the filesystem.\n public var type: FSType\n /// Source of the filesystem.\n public var source: String\n /// Destination where the filesystem should be mounted.\n public var destination: String\n /// Mount options applied when mounting the filesystem.\n public var options: MountOptions\n\n public init() {\n self.type = .tmpfs\n self.source = \"\"\n self.destination = \"\"\n self.options = []\n }\n\n public init(type: FSType, source: String, destination: String, options: MountOptions) {\n self.type = type\n self.source = source\n self.destination = destination\n self.options = options\n }\n\n /// A block based filesystem.\n public static func block(\n format: String, source: String, destination: String, options: MountOptions, cache: CacheMode = .auto,\n sync: SyncMode = .full\n ) -> Filesystem {\n .init(\n type: .block(format: format, cache: cache, sync: sync),\n source: URL(fileURLWithPath: source).absolutePath(),\n destination: destination,\n options: options\n )\n }\n\n /// A vritiofs backed filesystem providing a directory.\n public static func virtiofs(source: String, destination: String, options: MountOptions) -> Filesystem {\n .init(\n type: .virtiofs,\n source: URL(fileURLWithPath: source).absolutePath(),\n destination: destination,\n options: options\n )\n }\n\n public static func tmpfs(destination: String, options: MountOptions) -> Filesystem {\n .init(\n type: .tmpfs,\n source: \"tmpfs\",\n destination: destination,\n options: options\n )\n }\n\n /// Returns true if the Filesystem is backed by a block device.\n public var isBlock: Bool {\n switch type {\n case .block(_, _, _): true\n default: false\n }\n }\n\n /// Returns true if the Filesystem is backed by a in-memory mount type.\n public var isTmpfs: Bool {\n switch type {\n case .tmpfs: true\n default: false\n }\n }\n\n /// Returns true if the Filesystem is backed by virtioFS.\n public var isVirtiofs: Bool {\n switch type {\n case .virtiofs: true\n default: false\n }\n }\n\n /// Clone the Filesystem to the provided path.\n ///\n /// This uses `clonefile` to provide a copy-on-write copy of the Filesystem.\n public func clone(to: String) throws -> Self {\n let fm = FileManager.default\n let src = self.source\n try fm.copyItem(atPath: src, toPath: to)\n return .init(type: self.type, source: to, destination: self.destination, options: self.options)\n }\n}\n"], ["/container/Sources/SocketForwarder/GlueHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIOCore\n\nfinal class GlueHandler {\n\n private var partner: GlueHandler?\n\n private var context: ChannelHandlerContext?\n\n private var pendingRead: Bool = false\n\n private init() {}\n}\n\nextension GlueHandler {\n static func matchedPair() -> (GlueHandler, GlueHandler) {\n let first = GlueHandler()\n let second = GlueHandler()\n\n first.partner = second\n second.partner = first\n\n return (first, second)\n }\n}\n\nextension GlueHandler {\n private func partnerWrite(_ data: NIOAny) {\n self.context?.write(data, promise: nil)\n }\n\n private func partnerFlush() {\n self.context?.flush()\n }\n\n private func partnerWriteEOF() {\n self.context?.close(mode: .output, promise: nil)\n }\n\n private func partnerCloseFull() {\n self.context?.close(promise: nil)\n }\n\n private func partnerBecameWritable() {\n if self.pendingRead {\n self.pendingRead = false\n self.context?.read()\n }\n }\n\n private var partnerWritable: Bool {\n self.context?.channel.isWritable ?? false\n }\n}\n\nextension GlueHandler: ChannelDuplexHandler {\n typealias InboundIn = NIOAny\n typealias OutboundIn = NIOAny\n typealias OutboundOut = NIOAny\n\n func handlerAdded(context: ChannelHandlerContext) {\n self.context = context\n }\n\n func handlerRemoved(context: ChannelHandlerContext) {\n self.context = nil\n self.partner = nil\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n self.partner?.partnerWrite(data)\n }\n\n func channelReadComplete(context: ChannelHandlerContext) {\n self.partner?.partnerFlush()\n }\n\n func channelInactive(context: ChannelHandlerContext) {\n self.partner?.partnerCloseFull()\n }\n\n func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {\n if let event = event as? ChannelEvent, case .inputClosed = event {\n // We have read EOF.\n self.partner?.partnerWriteEOF()\n }\n }\n\n func errorCaught(context: ChannelHandlerContext, error: Error) {\n self.partner?.partnerCloseFull()\n }\n\n func channelWritabilityChanged(context: ChannelHandlerContext) {\n if context.channel.isWritable {\n self.partner?.partnerBecameWritable()\n }\n }\n\n func read(context: ChannelHandlerContext) {\n if let partner = self.partner, partner.partnerWritable {\n context.read()\n } else {\n self.pendingRead = true\n }\n }\n}\n"], ["/container/Sources/ContainerClient/String+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension String {\n public func fromISO8601DateString(to: String) -> String? {\n if let date = fromISO8601Date() {\n let dateformatTo = DateFormatter()\n dateformatTo.dateFormat = to\n return dateformatTo.string(from: date)\n }\n return nil\n }\n\n public func fromISO8601Date() -> Date? {\n let iso8601DateFormatter = ISO8601DateFormatter()\n iso8601DateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]\n return iso8601DateFormatter.date(from: self)\n }\n\n public func isAbsolutePath() -> Bool {\n self.starts(with: \"/\")\n }\n\n /// Trim all `char` characters from the left side of the string. Stops when encountering a character that\n /// doesn't match `char`.\n mutating public func trimLeft(char: Character) {\n if self.isEmpty {\n return\n }\n var trimTo = 0\n for c in self {\n if char != c {\n break\n }\n trimTo += 1\n }\n if trimTo != 0 {\n let index = self.index(self.startIndex, offsetBy: trimTo)\n self = String(self[index...])\n }\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct NetworkInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more networks\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Networks to inspect\")\n var networks: [String]\n\n func run() async throws {\n let objects: [any Codable] = try await ClientNetwork.list().filter {\n networks.contains($0.id)\n }.map {\n PrintableNetwork($0)\n }\n print(try objects.jsonArray())\n }\n }\n}\n"], ["/container/Sources/APIServer/Networks/NetworksHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nstruct NetworksHarness: Sendable {\n let log: Logging.Logger\n let service: NetworksService\n\n init(service: NetworksService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let containers = try await service.list()\n let data = try JSONEncoder().encode(containers)\n\n let reply = message.reply()\n reply.set(key: .networkStates, value: data)\n return reply\n }\n\n @Sendable\n func create(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .networkConfig)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"network configuration cannot be empty\")\n }\n\n let config = try JSONDecoder().decode(NetworkConfiguration.self, from: data)\n let networkState = try await service.create(configuration: config)\n\n let networkData = try JSONEncoder().encode(networkState)\n\n let reply = message.reply()\n reply.set(key: .networkState, value: networkData)\n return reply\n }\n\n @Sendable\n func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .networkId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"id cannot be empty\")\n }\n try await service.delete(id: id)\n\n return message.reply()\n }\n}\n"], ["/container/Sources/APIServer/ContainerDNSHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\nimport DNSServer\n\n/// Handler that uses table lookup to resolve hostnames.\nstruct ContainerDNSHandler: DNSHandler {\n private let networkService: NetworksService\n private let ttl: UInt32\n\n public init(networkService: NetworksService, ttl: UInt32 = 5) {\n self.networkService = networkService\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n let record: ResourceRecord?\n switch question.type {\n case ResourceRecordType.host:\n record = try await answerHost(question: question)\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n\n guard let record else {\n return nil\n }\n\n return Message(\n id: query.id,\n type: .response,\n returnCode: .noError,\n questions: query.questions,\n answers: [record]\n )\n }\n\n private func answerHost(question: Question) async throws -> ResourceRecord? {\n guard let ipAllocation = try await networkService.lookup(hostname: question.name) else {\n return nil\n }\n\n let components = ipAllocation.address.split(separator: \"/\")\n guard !components.isEmpty else {\n throw DNSResolverError.serverError(\"Invalid IP format: empty address\")\n }\n\n let ipString = String(components[0])\n guard let ip = IPv4(ipString) else {\n throw DNSResolverError.serverError(\"Failed to parse IP address: \\(ipString)\")\n }\n\n return HostRecord(name: question.name, ttl: ttl, ip: ip)\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+Add.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension ProgressBar {\n /// A handler function to update the progress bar.\n /// - Parameter events: The events to handle.\n public func handler(_ events: [ProgressUpdateEvent]) {\n for event in events {\n switch event {\n case .setDescription(let description):\n set(description: description)\n case .setSubDescription(let subDescription):\n set(subDescription: subDescription)\n case .setItemsName(let itemsName):\n set(itemsName: itemsName)\n case .addTasks(let tasks):\n add(tasks: tasks)\n case .setTasks(let tasks):\n set(tasks: tasks)\n case .addTotalTasks(let totalTasks):\n add(totalTasks: totalTasks)\n case .setTotalTasks(let totalTasks):\n set(totalTasks: totalTasks)\n case .addSize(let size):\n add(size: size)\n case .setSize(let size):\n set(size: size)\n case .addTotalSize(let totalSize):\n add(totalSize: totalSize)\n case .setTotalSize(let totalSize):\n set(totalSize: totalSize)\n case .addItems(let items):\n add(items: items)\n case .setItems(let items):\n set(items: items)\n case .addTotalItems(let totalItems):\n add(totalItems: totalItems)\n case .setTotalItems(let totalItems):\n set(totalItems: totalItems)\n case .custom:\n // Custom events are handled by the client.\n break\n }\n }\n }\n\n /// Performs a check to see if the progress bar should be finished.\n public func checkIfFinished() {\n let state = self.state.withLock { $0 }\n\n var finished = true\n var defined = false\n if let totalTasks = state.totalTasks, totalTasks > 0 {\n // For tasks, we're showing the current task rather than the number of completed tasks.\n finished = finished && state.tasks == totalTasks\n defined = true\n }\n if let totalItems = state.totalItems, totalItems > 0 {\n finished = finished && state.items == totalItems\n defined = true\n }\n if let totalSize = state.totalSize, totalSize > 0 {\n finished = finished && state.size == totalSize\n defined = true\n }\n if defined && finished {\n finish()\n }\n }\n\n /// Sets the current tasks.\n /// - Parameter newTasks: The current tasks to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(tasks newTasks: Int, render: Bool = true) {\n state.withLock { $0.tasks = newTasks }\n if render {\n self.render()\n }\n checkIfFinished()\n }\n\n /// Performs an addition to the current tasks.\n /// - Parameter delta: The tasks to add to the current tasks.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(tasks delta: Int, render: Bool = true) {\n state.withLock {\n let newTasks = $0.tasks + delta\n $0.tasks = newTasks\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total tasks.\n /// - Parameter newTotalTasks: The total tasks to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalTasks newTotalTasks: Int, render: Bool = true) {\n state.withLock { $0.totalTasks = newTotalTasks }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total tasks.\n /// - Parameter delta: The tasks to add to the total tasks.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalTasks delta: Int, render: Bool = true) {\n state.withLock {\n let totalTasks = $0.totalTasks ?? 0\n let newTotalTasks = totalTasks + delta\n $0.totalTasks = newTotalTasks\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the items name.\n /// - Parameter newItemsName: The current items to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(itemsName newItemsName: String, render: Bool = true) {\n state.withLock { $0.itemsName = newItemsName }\n if render {\n self.render()\n }\n }\n\n /// Sets the current items.\n /// - Parameter newItems: The current items to set.\n public func set(items newItems: Int, render: Bool = true) {\n state.withLock { $0.items = newItems }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the current items.\n /// - Parameter delta: The items to add to the current items.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(items delta: Int, render: Bool = true) {\n state.withLock {\n let newItems = $0.items + delta\n $0.items = newItems\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total items.\n /// - Parameter newTotalItems: The total items to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalItems newTotalItems: Int, render: Bool = true) {\n state.withLock { $0.totalItems = newTotalItems }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total items.\n /// - Parameter delta: The items to add to the total items.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalItems delta: Int, render: Bool = true) {\n state.withLock {\n let totalItems = $0.totalItems ?? 0\n let newTotalItems = totalItems + delta\n $0.totalItems = newTotalItems\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the current size.\n /// - Parameter newSize: The current size to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(size newSize: Int64, render: Bool = true) {\n state.withLock { $0.size = newSize }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the current size.\n /// - Parameter delta: The size to add to the current size.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(size delta: Int64, render: Bool = true) {\n state.withLock {\n let newSize = $0.size + delta\n $0.size = newSize\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total size.\n /// - Parameter newTotalSize: The total size to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalSize newTotalSize: Int64, render: Bool = true) {\n state.withLock { $0.totalSize = newTotalSize }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total size.\n /// - Parameter delta: The size to add to the total size.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalSize delta: Int64, render: Bool = true) {\n state.withLock {\n let totalSize = $0.totalSize ?? 0\n let newTotalSize = totalSize + delta\n $0.totalSize = newTotalSize\n }\n if render {\n self.render()\n }\n }\n}\n"], ["/container/Sources/ContainerClient/RequestScheme.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\n\n/// The URL scheme to be used for a HTTP request.\npublic enum RequestScheme: String, Sendable {\n case http = \"http\"\n case https = \"https\"\n\n case auto = \"auto\"\n\n public init(_ rawValue: String) throws {\n switch rawValue {\n case RequestScheme.http.rawValue:\n self = .http\n case RequestScheme.https.rawValue:\n self = .https\n case RequestScheme.auto.rawValue:\n self = .auto\n default:\n throw ContainerizationError(.invalidArgument, message: \"Unsupported scheme \\(rawValue)\")\n }\n }\n\n /// Returns the prescribed protocol to use while making a HTTP request to a webserver\n /// - Parameter host: The domain or IP address of the webserver\n /// - Returns: RequestScheme\n package func schemeFor(host: String) throws -> Self {\n guard host.count > 0 else {\n throw ContainerizationError(.invalidArgument, message: \"Host cannot be empty\")\n }\n switch self {\n case .http, .https:\n return self\n case .auto:\n return Self.isInternalHost(host: host) ? .http : .https\n }\n }\n\n /// Checks if the given `host` string is a private IP address\n /// or a domain typically reachable only on the local system.\n private static func isInternalHost(host: String) -> Bool {\n if host.hasPrefix(\"localhost\") || host.hasPrefix(\"127.\") {\n return true\n }\n if host.hasPrefix(\"192.168.\") || host.hasPrefix(\"10.\") {\n return true\n }\n let regex = \"(^172\\\\.1[6-9]\\\\.)|(^172\\\\.2[0-9]\\\\.)|(^172\\\\.3[0-1]\\\\.)\"\n if host.range(of: regex, options: .regularExpression) != nil {\n return true\n }\n let dnsDomain = ClientDefaults.get(key: .defaultDNSDomain)\n if host.hasSuffix(\".\\(dnsDomain)\") {\n return true\n }\n return false\n }\n}\n"], ["/container/Sources/CLI/Image/ImageTag.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\n\nextension Application {\n struct ImageTag: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"tag\",\n abstract: \"Tag an image\")\n\n @Argument(help: \"SOURCE_IMAGE[:TAG]\")\n var source: String\n\n @Argument(help: \"TARGET_IMAGE[:TAG]\")\n var target: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let existing = try await ClientImage.get(reference: source)\n let targetReference = try ClientImage.normalizeReference(target)\n try await existing.tag(new: targetReference)\n print(\"Image \\(source) tagged as \\(target)\")\n }\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct NetworkCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a new network\")\n\n @Argument(help: \"Network name\")\n var name: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let config = NetworkConfiguration(id: self.name, mode: .nat)\n let state = try await ClientNetwork.create(configuration: config)\n print(state.id)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ImageDetail.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationOCI\n\npublic struct ImageDetail: Codable {\n public let name: String\n public let index: Descriptor\n public let variants: [Variants]\n\n public struct Variants: Codable {\n public let platform: Platform\n public let config: ContainerizationOCI.Image\n public let size: Int64\n\n init(platform: Platform, size: Int64, config: ContainerizationOCI.Image) {\n self.platform = platform\n self.config = config\n self.size = size\n }\n }\n\n init(name: String, index: Descriptor, variants: [Variants]) {\n self.name = name\n self.index = index\n self.variants = variants\n }\n}\n\nextension ClientImage {\n public func details() async throws -> ImageDetail {\n let indexDescriptor = self.descriptor\n let reference = self.reference\n var variants: [ImageDetail.Variants] = []\n for desc in try await self.index().manifests {\n guard let platform = desc.platform else {\n continue\n }\n let config: ContainerizationOCI.Image\n let manifest: ContainerizationOCI.Manifest\n do {\n config = try await self.config(for: platform)\n manifest = try await self.manifest(for: platform)\n } catch {\n continue\n }\n let size = desc.size + manifest.config.size + manifest.layers.reduce(0, { (l, r) in l + r.size })\n variants.append(.init(platform: platform, size: size, config: config))\n }\n return ImageDetail(name: reference, index: indexDescriptor, variants: variants)\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePrune.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\n\nextension Application {\n struct ImagePrune: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"prune\",\n abstract: \"Remove unreferenced and dangling images\")\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let (_, size) = try await ClientImage.pruneImages()\n let formatter = ByteCountFormatter()\n let freed = formatter.string(fromByteCount: Int64(size))\n print(\"Cleaned unreferenced images and snapshots\")\n print(\"Reclaimed \\(freed) in disk space\")\n }\n }\n}\n"], ["/container/Sources/ContainerClient/XPC+.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\n/// Keys for XPC fields.\npublic enum XPCKeys: String {\n /// Route key.\n case route\n /// Container array key.\n case containers\n /// ID key.\n case id\n // ID for a process.\n case processIdentifier\n /// Container configuration key.\n case containerConfig\n /// Container options key.\n case containerOptions\n /// Vsock port number key.\n case port\n /// Exit code for a process\n case exitCode\n /// An event that occurred in a container\n case containerEvent\n /// Error key.\n case error\n /// FD to a container resource key.\n case fd\n /// FDs pointing to container logs key.\n case logs\n /// Options for stopping a container key.\n case stopOptions\n /// Plugins\n case pluginName\n case plugins\n case plugin\n\n /// Health check request.\n case ping\n\n /// Process request keys.\n case signal\n case snapshot\n case stdin\n case stdout\n case stderr\n case status\n case width\n case height\n case processConfig\n\n /// Update progress\n case progressUpdateEndpoint\n case progressUpdateSetDescription\n case progressUpdateSetSubDescription\n case progressUpdateSetItemsName\n case progressUpdateAddTasks\n case progressUpdateSetTasks\n case progressUpdateAddTotalTasks\n case progressUpdateSetTotalTasks\n case progressUpdateAddItems\n case progressUpdateSetItems\n case progressUpdateAddTotalItems\n case progressUpdateSetTotalItems\n case progressUpdateAddSize\n case progressUpdateSetSize\n case progressUpdateAddTotalSize\n case progressUpdateSetTotalSize\n\n /// Network\n case networkId\n case networkConfig\n case networkState\n case networkStates\n\n /// Kernel\n case kernel\n case kernelTarURL\n case kernelFilePath\n case systemPlatform\n}\n\npublic enum XPCRoute: String {\n case listContainer\n case createContainer\n case deleteContainer\n case containerLogs\n case containerEvent\n\n case pluginLoad\n case pluginGet\n case pluginRestart\n case pluginUnload\n case pluginList\n\n case networkCreate\n case networkDelete\n case networkList\n\n case ping\n\n case installKernel\n case getDefaultKernel\n}\n\nextension XPCMessage {\n public init(route: XPCRoute) {\n self.init(route: route.rawValue)\n }\n\n public func data(key: XPCKeys) -> Data? {\n data(key: key.rawValue)\n }\n\n public func dataNoCopy(key: XPCKeys) -> Data? {\n dataNoCopy(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Data) {\n set(key: key.rawValue, value: value)\n }\n\n public func string(key: XPCKeys) -> String? {\n string(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: String) {\n set(key: key.rawValue, value: value)\n }\n\n public func bool(key: XPCKeys) -> Bool {\n bool(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Bool) {\n set(key: key.rawValue, value: value)\n }\n\n public func uint64(key: XPCKeys) -> UInt64 {\n uint64(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: UInt64) {\n set(key: key.rawValue, value: value)\n }\n\n public func int64(key: XPCKeys) -> Int64 {\n int64(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Int64) {\n set(key: key.rawValue, value: value)\n }\n\n public func int(key: XPCKeys) -> Int {\n Int(int64(key: key.rawValue))\n }\n\n public func set(key: XPCKeys, value: Int) {\n set(key: key.rawValue, value: Int64(value))\n }\n\n public func fileHandle(key: XPCKeys) -> FileHandle? {\n fileHandle(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: FileHandle) {\n set(key: key.rawValue, value: value)\n }\n\n public func fileHandles(key: XPCKeys) -> [FileHandle]? {\n fileHandles(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: [FileHandle]) throws {\n try set(key: key.rawValue, value: value)\n }\n\n public func endpoint(key: XPCKeys) -> xpc_endpoint_t? {\n endpoint(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: xpc_endpoint_t) {\n set(key: key.rawValue, value: value)\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerClient/TableOutput.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct TableOutput {\n private let rows: [[String]]\n private let spacing: Int\n\n public init(\n rows: [[String]],\n spacing: Int = 2\n ) {\n self.rows = rows\n self.spacing = spacing\n }\n\n public func format() -> String {\n var output = \"\"\n let maxLengths = self.maxLength()\n\n for rowIndex in 0.. [Int: Int] {\n var output: [Int: Int] = [:]\n for row in self.rows {\n for (i, column) in row.enumerated() {\n let currentMax = output[i] ?? 0\n output[i] = (column.count > currentMax) ? column.count : currentMax\n }\n }\n return output\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\n\npublic struct ContainerConfiguration: Sendable, Codable {\n /// Identifier for the container.\n public var id: String\n /// Image used to create the container.\n public var image: ImageDescription\n /// External mounts to add to the container.\n public var mounts: [Filesystem] = []\n /// Ports to publish from container to host.\n public var publishedPorts: [PublishPort] = []\n /// Sockets to publish from container to host.\n public var publishedSockets: [PublishSocket] = []\n /// Key/Value labels for the container.\n public var labels: [String: String] = [:]\n /// System controls for the container.\n public var sysctls: [String: String] = [:]\n /// The networks the container will be added to.\n public var networks: [String] = []\n /// The DNS configuration for the container.\n public var dns: DNSConfiguration? = nil\n /// Whether to enable rosetta x86-64 translation for the container.\n public var rosetta: Bool = false\n /// The hostname for the container.\n public var hostname: String? = nil\n /// Initial or main process of the container.\n public var initProcess: ProcessConfiguration\n /// Platform for the container\n public var platform: ContainerizationOCI.Platform = .current\n /// Resource values for the container.\n public var resources: Resources = .init()\n /// Name of the runtime that supports the container\n public var runtimeHandler: String = \"container-runtime-linux\"\n\n enum CodingKeys: String, CodingKey {\n case id\n case image\n case mounts\n case publishedPorts\n case publishedSockets\n case labels\n case sysctls\n case networks\n case dns\n case rosetta\n case hostname\n case initProcess\n case platform\n case resources\n case runtimeHandler\n }\n\n /// Create a configuration from the supplied Decoder, initializing missing\n /// values where possible to reasonable defaults.\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n id = try container.decode(String.self, forKey: .id)\n image = try container.decode(ImageDescription.self, forKey: .image)\n mounts = try container.decodeIfPresent([Filesystem].self, forKey: .mounts) ?? []\n publishedPorts = try container.decodeIfPresent([PublishPort].self, forKey: .publishedPorts) ?? []\n publishedSockets = try container.decodeIfPresent([PublishSocket].self, forKey: .publishedSockets) ?? []\n labels = try container.decodeIfPresent([String: String].self, forKey: .labels) ?? [:]\n sysctls = try container.decodeIfPresent([String: String].self, forKey: .sysctls) ?? [:]\n networks = try container.decodeIfPresent([String].self, forKey: .networks) ?? []\n dns = try container.decodeIfPresent(DNSConfiguration.self, forKey: .dns)\n rosetta = try container.decodeIfPresent(Bool.self, forKey: .rosetta) ?? false\n hostname = try container.decodeIfPresent(String.self, forKey: .hostname)\n initProcess = try container.decode(ProcessConfiguration.self, forKey: .initProcess)\n platform = try container.decodeIfPresent(ContainerizationOCI.Platform.self, forKey: .platform) ?? .current\n resources = try container.decodeIfPresent(Resources.self, forKey: .resources) ?? .init()\n runtimeHandler = try container.decodeIfPresent(String.self, forKey: .runtimeHandler) ?? \"container-runtime-linux\"\n }\n\n public struct DNSConfiguration: Sendable, Codable {\n public static let defaultNameservers = [\"1.1.1.1\"]\n\n public let nameservers: [String]\n public let domain: String?\n public let searchDomains: [String]\n public let options: [String]\n\n public init(\n nameservers: [String] = defaultNameservers,\n domain: String? = nil,\n searchDomains: [String] = [],\n options: [String] = []\n ) {\n self.nameservers = nameservers\n self.domain = domain\n self.searchDomains = searchDomains\n self.options = options\n }\n }\n\n /// Resources like cpu, memory, and storage quota.\n public struct Resources: Sendable, Codable {\n /// Number of CPU cores allocated.\n public var cpus: Int = 4\n /// Memory in bytes allocated.\n public var memoryInBytes: UInt64 = 1024.mib()\n /// Storage quota/size in bytes.\n public var storage: UInt64?\n\n public init() {}\n }\n\n public init(\n id: String,\n image: ImageDescription,\n process: ProcessConfiguration\n ) {\n self.id = id\n self.image = image\n self.initProcess = process\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/StandardQueryValidator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Pass standard queries to a delegate handler.\npublic struct StandardQueryValidator: DNSHandler {\n private let handler: DNSHandler\n\n /// Create the handler.\n /// - Parameter delegate: the handler that receives valid queries\n public init(handler: DNSHandler) {\n self.handler = handler\n }\n\n /// Ensures the query is valid before forwarding it to the delegate.\n /// - Parameter msg: the query message\n /// - Returns: the delegate response if the query is valid, and an\n /// error response otherwise\n public func answer(query: Message) async throws -> Message? {\n // Reject response messages.\n guard query.type == .query else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions\n )\n }\n\n // Standard DNS servers handle only query operations.\n guard query.operationCode == .query else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions\n )\n }\n\n // Standard DNS servers only handle messages with exactly one question.\n guard query.questions.count == 1 else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions\n )\n }\n\n return try await handler.answer(query: query)\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientDefaults.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CVersion\nimport ContainerizationError\nimport Foundation\n\npublic enum ClientDefaults {\n private static let userDefaultDomain = \"com.apple.container.defaults\"\n\n public enum Keys: String {\n case defaultBuilderImage = \"image.builder\"\n case defaultDNSDomain = \"dns.domain\"\n case defaultRegistryDomain = \"registry.domain\"\n case defaultInitImage = \"image.init\"\n case defaultKernelURL = \"kernel.url\"\n case defaultKernelBinaryPath = \"kernel.binaryPath\"\n case buildRosetta = \"build.rosetta\"\n }\n\n public static func set(value: String, key: ClientDefaults.Keys) {\n udSuite.set(value, forKey: key.rawValue)\n }\n\n public static func unset(key: ClientDefaults.Keys) {\n udSuite.removeObject(forKey: key.rawValue)\n }\n\n public static func get(key: ClientDefaults.Keys) -> String {\n let current = udSuite.string(forKey: key.rawValue)\n return current ?? key.defaultValue\n }\n\n public static func getOptional(key: ClientDefaults.Keys) -> String? {\n udSuite.string(forKey: key.rawValue)\n }\n\n public static func setBool(value: Bool, key: ClientDefaults.Keys) {\n udSuite.set(value, forKey: key.rawValue)\n }\n\n public static func getBool(key: ClientDefaults.Keys) -> Bool? {\n guard udSuite.object(forKey: key.rawValue) != nil else { return nil }\n return udSuite.bool(forKey: key.rawValue)\n }\n\n private static var udSuite: UserDefaults {\n guard let ud = UserDefaults.init(suiteName: self.userDefaultDomain) else {\n fatalError(\"Failed to initialize UserDefaults for domain \\(self.userDefaultDomain)\")\n }\n return ud\n }\n}\n\nextension ClientDefaults.Keys {\n fileprivate var defaultValue: String {\n switch self {\n case .defaultKernelURL:\n return \"https://github.com/kata-containers/kata-containers/releases/download/3.17.0/kata-static-3.17.0-arm64.tar.xz\"\n case .defaultKernelBinaryPath:\n return \"opt/kata/share/kata-containers/vmlinux-6.12.28-153\"\n case .defaultBuilderImage:\n let tag = String(cString: get_container_builder_shim_version())\n return \"ghcr.io/apple/container-builder-shim/builder:\\(tag)\"\n case .defaultDNSDomain:\n return \"test\"\n case .defaultRegistryDomain:\n return \"docker.io\"\n case .defaultInitImage:\n let tag = String(cString: get_swift_containerization_version())\n guard tag != \"latest\" else {\n return \"vminit:latest\"\n }\n return \"ghcr.io/apple/containerization/vminit:\\(tag)\"\n case .buildRosetta:\n // This is a boolean key, not used with the string get() method\n return \"true\"\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/AttachmentAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\n\nactor AttachmentAllocator {\n private let allocator: any AddressAllocator\n private var hostnames: [String: UInt32] = [:]\n\n init(lower: UInt32, size: Int) throws {\n allocator = try UInt32.rotatingAllocator(\n lower: lower,\n size: UInt32(size)\n )\n }\n\n /// Allocate a network address for a host.\n func allocate(hostname: String) async throws -> UInt32 {\n guard hostnames[hostname] == nil else {\n throw ContainerizationError(.exists, message: \"Hostname \\(hostname) already exists on the network\")\n }\n let index = try allocator.allocate()\n hostnames[hostname] = index\n\n return index\n }\n\n /// Free an allocated network address by hostname.\n func deallocate(hostname: String) async throws {\n if let index = hostnames.removeValue(forKey: hostname) {\n try allocator.release(index)\n }\n }\n\n /// If no addresses are allocated, prevent future allocations and return true.\n func disableAllocator() async -> Bool {\n allocator.disableAllocator()\n }\n\n /// Retrieve the allocator index for a hostname.\n func lookup(hostname: String) async throws -> UInt32? {\n hostnames[hostname]\n }\n}\n"], ["/container/Sources/ContainerClient/ProgressUpdateService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\n/// A service that sends progress updates to the client.\npublic actor ProgressUpdateService {\n private let endpointConnection: xpc_connection_t\n\n /// Creates a new instance for sending progress updates to the client.\n /// - Parameter message: The XPC message that contains the endpoint to connect to.\n public init?(message: XPCMessage) {\n guard let progressUpdateEndpoint = message.endpoint(key: .progressUpdateEndpoint) else {\n return nil\n }\n endpointConnection = xpc_connection_create_from_endpoint(progressUpdateEndpoint)\n xpc_connection_set_event_handler(endpointConnection) { _ in }\n // This connection will be closed by the client.\n xpc_connection_activate(endpointConnection)\n }\n\n /// Performs a progress update.\n /// - Parameter events: The events that represent the update.\n public func handler(_ events: [ProgressUpdateEvent]) async {\n let object = xpc_dictionary_create(nil, nil, 0)\n let replyMessage = XPCMessage(object: object)\n for event in events {\n switch event {\n case .setDescription(let description):\n replyMessage.set(key: .progressUpdateSetDescription, value: description)\n case .setSubDescription(let subDescription):\n replyMessage.set(key: .progressUpdateSetSubDescription, value: subDescription)\n case .setItemsName(let itemsName):\n replyMessage.set(key: .progressUpdateSetItemsName, value: itemsName)\n case .addTasks(let tasks):\n replyMessage.set(key: .progressUpdateAddTasks, value: tasks)\n case .setTasks(let tasks):\n replyMessage.set(key: .progressUpdateSetTasks, value: tasks)\n case .addTotalTasks(let totalTasks):\n replyMessage.set(key: .progressUpdateAddTotalTasks, value: totalTasks)\n case .setTotalTasks(let totalTasks):\n replyMessage.set(key: .progressUpdateSetTotalTasks, value: totalTasks)\n case .addSize(let size):\n replyMessage.set(key: .progressUpdateAddSize, value: size)\n case .setSize(let size):\n replyMessage.set(key: .progressUpdateSetSize, value: size)\n case .addTotalSize(let totalSize):\n replyMessage.set(key: .progressUpdateAddTotalSize, value: totalSize)\n case .setTotalSize(let totalSize):\n replyMessage.set(key: .progressUpdateSetTotalSize, value: totalSize)\n case .addItems(let items):\n replyMessage.set(key: .progressUpdateAddItems, value: items)\n case .setItems(let items):\n replyMessage.set(key: .progressUpdateSetItems, value: items)\n case .addTotalItems(let totalItems):\n replyMessage.set(key: .progressUpdateAddTotalItems, value: totalItems)\n case .setTotalItems(let totalItems):\n replyMessage.set(key: .progressUpdateSetTotalItems, value: totalItems)\n case .custom(_):\n // Unsupported progress update event in XPC communication.\n break\n }\n }\n xpc_connection_send_message(endpointConnection, replyMessage.underlying)\n }\n}\n"], ["/container/Sources/SocketForwarder/LRUCache.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nstruct KeyExistsError: Error {}\n\nclass LRUCache {\n private class Node {\n fileprivate var prev: Node?\n fileprivate var next: Node?\n fileprivate let key: K\n fileprivate let value: V\n\n init(key: K, value: V) {\n self.prev = nil\n self.next = nil\n self.key = key\n self.value = value\n }\n }\n\n private let size: UInt\n private var head: Node?\n private var tail: Node?\n private var members: [K: Node]\n\n init(size: UInt) {\n self.size = size\n self.head = nil\n self.tail = nil\n self.members = [:]\n }\n\n var count: Int { members.count }\n\n func get(_ key: K) -> V? {\n guard let node = members[key] else {\n return nil\n }\n listRemove(node: node)\n listInsert(node: node, after: tail)\n return node.value\n }\n\n func put(key: K, value: V) -> (K, V)? {\n let node = Node(key: key, value: value)\n var evicted: (K, V)? = nil\n\n if let existingNode = members[key] {\n // evict the replaced node\n listRemove(node: existingNode)\n evicted = (existingNode.key, existingNode.value)\n } else if self.count >= self.size {\n // evict the least recently used node\n evicted = evict()\n }\n\n // insert the new node and return any evicted node\n members[key] = node\n listInsert(node: node, after: tail)\n return evicted\n }\n\n private func evict() -> (K, V)? {\n guard let head else {\n return nil\n }\n let ret = (head.key, head.value)\n listRemove(node: head)\n members.removeValue(forKey: head.key)\n return ret\n }\n\n private func listRemove(node: Node) {\n if let prev = node.prev {\n prev.next = node.next\n } else {\n head = node.next\n }\n if let next = node.next {\n next.prev = node.prev\n } else {\n tail = node.prev\n }\n }\n\n private func listInsert(node: Node, after: Node?) {\n let before: Node?\n if let after {\n before = after.next\n after.next = node\n } else {\n before = head\n head = node\n }\n\n if let before {\n before.prev = node\n } else {\n tail = node\n }\n\n node.prev = after\n node.next = before\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ProcessConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Configuration data for an executable Process.\npublic struct ProcessConfiguration: Sendable, Codable {\n /// The on disk path to the executable binary.\n public var executable: String\n /// Arguments passed to the Process.\n public var arguments: [String]\n /// Environment variables for the Process.\n public var environment: [String]\n /// The current working directory (cwd) for the Process.\n public var workingDirectory: String\n /// A boolean value indicating if a Terminal or PTY device should\n /// be attached to the Process's Standard I/O.\n public var terminal: Bool\n /// The User a Process should execute under.\n public var user: User\n /// Supplemental groups for the Process.\n public var supplementalGroups: [UInt32]\n /// Rlimits for the Process.\n public var rlimits: [Rlimit]\n\n /// Rlimits for Processes.\n public struct Rlimit: Sendable, Codable {\n /// The Rlimit type of the Process.\n ///\n /// Values include standard Rlimit resource types, i.e. RLIMIT_NPROC, RLIMIT_NOFILE, ...\n public let limit: String\n /// The soft limit of the Process\n public let soft: UInt64\n /// The hard or max limit of the Process.\n public let hard: UInt64\n\n public init(limit: String, soft: UInt64, hard: UInt64) {\n self.limit = limit\n self.soft = soft\n self.hard = hard\n }\n }\n\n /// The User information for a Process.\n public enum User: Sendable, Codable, CustomStringConvertible {\n /// Given the raw user string of the form or or lookup the uid/gid within\n /// the container before setting it for the Process.\n case raw(userString: String)\n /// Set the provided uid/gid for the Process.\n case id(uid: UInt32, gid: UInt32)\n\n public var description: String {\n switch self {\n case .id(let uid, let gid):\n return \"\\(uid):\\(gid)\"\n case .raw(let name):\n return name\n }\n }\n }\n\n public init(\n executable: String,\n arguments: [String],\n environment: [String],\n workingDirectory: String = \"/\",\n terminal: Bool = false,\n user: User = .id(uid: 0, gid: 0),\n supplementalGroups: [UInt32] = [],\n rlimits: [Rlimit] = []\n ) {\n self.executable = executable\n self.arguments = arguments\n self.environment = environment\n self.workingDirectory = workingDirectory\n self.terminal = terminal\n self.user = user\n self.supplementalGroups = supplementalGroups\n self.rlimits = rlimits\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\nimport Foundation\n\n/// PluginConfig details all of the fields to describe and register a plugin.\n/// A plugin is registered by creating a subdirectory `/user-plugins`,\n/// where the name of the subdirectory is the name of the plugin, and then placing a\n/// file named `config.json` inside with the schema below.\n/// If `services` is filled in then there MUST be a binary named matching the plugin name\n/// in a `bin` subdirectory inside the same directory as the `config.json`.\n/// An example of a valid plugin directory structure would be\n/// $ tree foobar\n/// foobar\n/// ├── bin\n/// │ └── foobar\n/// └── config.json\npublic struct PluginConfig: Sendable, Codable {\n /// Categories of services that can be offered through plugins.\n public enum DaemonPluginType: String, Sendable, Codable {\n /// A runtime plugin provides an XPC API through which the lifecycle\n /// of a **single** container can be managed.\n /// A runtime daemon plugin would typically also have a counterpart\n /// CLI plugin which knows how to talk to the API exposed by the runtime plugin.\n /// The API server ensures that a single instance of the plugin is configured\n /// for a given container such that the client can communicate with it given an instance id.\n case runtime\n /// A network plugin provides an XPC API through which IP address allocations on a given\n /// network can be managed. The API server ensures that a single instance\n /// of this plugin is configured for a given network. Similar to the runtime plugin, it typically\n /// would be accompanied by a CLI plugin that knows how to communicate with the XPC API\n /// given an instance id.\n case network\n /// A core plugin provides an XPC API to manage a given type of resource.\n /// The API server ensures that there exist only a single running instance\n /// of this plugin type. A core plugin can be thought of a singleton whose lifecycle\n /// is tied to that of the API server. Core plugins can be used to expand the base functionality\n /// provided by the API server. As with the other plugin types, it maybe associated with a client\n /// side plugin that communicates with the XPC service exposed by the daemon plugin.\n case core\n /// Reserved for future use. Currently there is no difference between a core and auxiliary daemon plugin.\n case auxiliary\n }\n\n // An XPC service that the plugin publishes.\n public struct Service: Sendable, Codable {\n /// The type of the service the daemon is exposing.\n /// One plugin can expose multiple services of different types.\n ///\n /// The plugin MUST expose a MachService at\n /// `com.apple.container.{type}.{name}.[{id}]` for\n /// each service that it exposes.\n public let type: DaemonPluginType\n /// Optional description of this service.\n public let description: String?\n }\n\n /// Descriptor for the services that the plugin offers.\n public struct ServicesConfig: Sendable, Codable {\n /// Load the plugin into launchd when the API server starts.\n public let loadAtBoot: Bool\n /// Launch the plugin binary as soon as it loads into launchd.\n public let runAtLoad: Bool\n /// The service types that the plugin provides.\n public let services: [Service]\n /// An optional parameter that include any command line arguments\n /// that must be passed to the plugin binary when it is loaded.\n /// This parameter is used only when `servicesConfig.loadAtBoot` is `true`\n public let defaultArguments: [String]\n }\n\n /// Short description of the plugin surface. This will be displayed as the\n /// help-text for CLI plugins, and will be returned in API calls to view loaded\n /// plugins from the daemon.\n public let abstract: String\n\n /// Author of the plugin. This is solely metadata.\n public let author: String?\n\n /// Services configuration. Specify nil for a CLI plugin, and an empty array for\n /// that does not publish any XPC services.\n public let servicesConfig: ServicesConfig?\n}\n\nextension PluginConfig {\n public var isCLI: Bool { self.servicesConfig == nil }\n}\n\nextension PluginConfig {\n public init?(configURL: URL) throws {\n let fm = FileManager.default\n if !fm.fileExists(atPath: configURL.path) {\n return nil\n }\n\n guard let data = fm.contents(atPath: configURL.path) else {\n return nil\n }\n\n let decoder: JSONDecoder = JSONDecoder()\n self = try decoder.decode(PluginConfig.self, from: data)\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressTaskCoordinator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that represents a task whose progress is being monitored.\npublic struct ProgressTask: Sendable, Equatable {\n private var id = UUID()\n private var coordinator: ProgressTaskCoordinator\n\n init(manager: ProgressTaskCoordinator) {\n self.coordinator = manager\n }\n\n static public func == (lhs: ProgressTask, rhs: ProgressTask) -> Bool {\n lhs.id == rhs.id\n }\n\n /// Returns `true` if this task is the currently active task, `false` otherwise.\n public func isCurrent() async -> Bool {\n guard let currentTask = await coordinator.currentTask else {\n return false\n }\n return currentTask == self\n }\n}\n\n/// A type that coordinates progress tasks to ignore updates from completed tasks.\npublic actor ProgressTaskCoordinator {\n var currentTask: ProgressTask?\n\n /// Creates an instance of `ProgressTaskCoordinator`.\n public init() {}\n\n /// Returns a new task that should be monitored for progress updates.\n public func startTask() -> ProgressTask {\n let newTask = ProgressTask(manager: self)\n currentTask = newTask\n return newTask\n }\n\n /// Performs cleanup when the monitored tasks complete.\n public func finish() {\n currentTask = nil\n }\n\n /// Returns a handler that updates the progress of a given task.\n /// - Parameters:\n /// - task: The task whose progress is being updated.\n /// - progressUpdate: The handler to invoke when progress updates are received.\n public static func handler(for task: ProgressTask, from progressUpdate: @escaping ProgressUpdateHandler) -> ProgressUpdateHandler {\n { events in\n // Ignore updates from completed tasks.\n if await task.isCurrent() {\n await progressUpdate(events)\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Registry/Logout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\n\nextension Application {\n struct Logout: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: \"Log out from a registry\")\n\n @Argument(help: \"Registry server name\")\n var registry: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let keychain = KeychainHelper(id: Constants.keychainID)\n let r = Reference.resolveDomain(domain: registry)\n try keychain.delete(domain: r)\n }\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/HostTableResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\n\n/// Handler that uses table lookup to resolve hostnames.\npublic struct HostTableResolver: DNSHandler {\n public let hosts4: [String: IPv4]\n private let ttl: UInt32\n\n public init(hosts4: [String: IPv4], ttl: UInt32 = 300) {\n self.hosts4 = hosts4\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n let record: ResourceRecord?\n switch question.type {\n case ResourceRecordType.host:\n record = answerHost(question: question)\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n\n guard let record else {\n return nil\n }\n\n return Message(\n id: query.id,\n type: .response,\n returnCode: .noError,\n questions: query.questions,\n answers: [record]\n )\n }\n\n private func answerHost(question: Question) -> ResourceRecord? {\n guard let ip = hosts4[question.name] else {\n return nil\n }\n\n return HostRecord(name: question.name, ttl: ttl, ip: ip)\n }\n}\n"], ["/container/Sources/ContainerPlugin/LaunchPlist.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\n\npublic struct LaunchPlist: Encodable {\n public enum Domain: String, Codable {\n case Aqua\n case Background\n case System\n }\n\n public let label: String\n public let arguments: [String]\n\n public let environment: [String: String]?\n public let cwd: String?\n public let username: String?\n public let groupname: String?\n public let limitLoadToSessionType: [Domain]?\n public let runAtLoad: Bool?\n public let stdin: String?\n public let stdout: String?\n public let stderr: String?\n public let disabled: Bool?\n public let program: String?\n public let keepAlive: Bool?\n public let machServices: [String: Bool]?\n public let waitForDebugger: Bool?\n\n enum CodingKeys: String, CodingKey {\n case label = \"Label\"\n case arguments = \"ProgramArguments\"\n case environment = \"EnvironmentVariables\"\n case cwd = \"WorkingDirectory\"\n case username = \"UserName\"\n case groupname = \"GroupName\"\n case limitLoadToSessionType = \"LimitLoadToSessionType\"\n case runAtLoad = \"RunAtLoad\"\n case stdin = \"StandardInPath\"\n case stdout = \"StandardOutPath\"\n case stderr = \"StandardErrorPath\"\n case disabled = \"Disabled\"\n case program = \"Program\"\n case keepAlive = \"KeepAlive\"\n case machServices = \"MachServices\"\n case waitForDebugger = \"WaitForDebugger\"\n }\n\n public init(\n label: String,\n arguments: [String],\n environment: [String: String]? = nil,\n cwd: String? = nil,\n username: String? = nil,\n groupname: String? = nil,\n limitLoadToSessionType: [Domain]? = nil,\n runAtLoad: Bool? = nil,\n stdin: String? = nil,\n stdout: String? = nil,\n stderr: String? = nil,\n disabled: Bool? = nil,\n program: String? = nil,\n keepAlive: Bool? = nil,\n machServices: [String]? = nil,\n waitForDebugger: Bool? = nil\n ) {\n self.label = label\n self.arguments = arguments\n self.environment = environment\n self.cwd = cwd\n self.username = username\n self.groupname = groupname\n self.limitLoadToSessionType = limitLoadToSessionType\n self.runAtLoad = runAtLoad\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n self.disabled = disabled\n self.program = program\n self.keepAlive = keepAlive\n self.waitForDebugger = waitForDebugger\n if let services = machServices {\n var machServices: [String: Bool] = [:]\n for service in services {\n machServices[service] = true\n }\n self.machServices = machServices\n } else {\n self.machServices = nil\n }\n }\n}\n\nextension LaunchPlist {\n public func encode() throws -> Data {\n let enc = PropertyListEncoder()\n enc.outputFormat = .xml\n return try enc.encode(self)\n }\n}\n#endif\n"], ["/container/Sources/ContainerPlugin/CommandLine+Executable.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension CommandLine {\n public static var executablePathUrl: URL {\n /// _NSGetExecutablePath with a zero-length buffer returns the needed buffer length\n var bufferSize: Int32 = 0\n var buffer = [CChar](repeating: 0, count: Int(bufferSize))\n _ = _NSGetExecutablePath(&buffer, &bufferSize)\n\n /// Create the buffer and get the path\n buffer = [CChar](repeating: 0, count: Int(bufferSize))\n guard _NSGetExecutablePath(&buffer, &bufferSize) == 0 else {\n fatalError(\"UNEXPECTED: failed to get executable path\")\n }\n\n /// Return the path with the executable file component removed the last component and\n let executablePath = String(cString: &buffer)\n return URL(filePath: executablePath)\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/NonisolatedInterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Logging\nimport Virtualization\nimport vmnet\n\n/// Interface strategy for containers that use macOS's custom network feature.\n@available(macOS 26, *)\nstruct NonisolatedInterfaceStrategy: InterfaceStrategy {\n private let log: Logger\n\n public init(log: Logger) {\n self.log = log\n }\n\n public func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) throws -> Interface {\n guard let additionalData else {\n throw ContainerizationError(.invalidState, message: \"network state does not contain custom network reference\")\n }\n\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let networkRef = vmnet_network_create_with_serialization(additionalData.underlying, &status) else {\n throw ContainerizationError(.invalidState, message: \"cannot deserialize custom network reference, status \\(status)\")\n }\n\n log.info(\"creating NATNetworkInterface with network reference\")\n let gateway = interfaceIndex == 0 ? attachment.gateway : nil\n return NATNetworkInterface(address: attachment.address, gateway: gateway, reference: networkRef)\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ContentStoreService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\npublic actor ContentStoreService {\n private let log: Logger\n private let contentStore: LocalContentStore\n private let root: URL\n\n public init(root: URL, log: Logger) throws {\n try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)\n self.root = root.appendingPathComponent(\"content\")\n self.contentStore = try LocalContentStore(path: self.root)\n self.log = log\n }\n\n public func get(digest: String) async throws -> URL? {\n self.log.trace(\"ContentStoreService: \\(#function) digest \\(digest)\")\n return try await self.contentStore.get(digest: digest)?.path\n }\n\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n self.log.debug(\"ContentStoreService: \\(#function) digests \\(digests)\")\n return try await self.contentStore.delete(digests: digests)\n }\n\n @discardableResult\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n self.log.debug(\"ContentStoreService: \\(#function) digests \\(keeping)\")\n return try await self.contentStore.delete(keeping: keeping)\n }\n\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n self.log.debug(\"ContentStoreService: \\(#function)\")\n return try await self.contentStore.newIngestSession()\n }\n\n public func completeIngestSession(_ id: String) async throws -> [String] {\n self.log.debug(\"ContentStoreService: \\(#function) id \\(id)\")\n return try await self.contentStore.completeIngestSession(id)\n }\n\n public func cancelIngestSession(_ id: String) async throws {\n self.log.debug(\"ContentStoreService: \\(#function) id \\(id)\")\n return try await self.contentStore.cancelIngestSession(id)\n }\n}\n"], ["/container/Sources/TerminalProgress/StandardError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct StandardError {\n func write(_ string: String) {\n if let data = string.data(using: .utf8) {\n FileHandle.standardError.write(data)\n }\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/NxDomainResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\n\n/// Handler that returns NXDOMAIN for all hostnames.\npublic struct NxDomainResolver: DNSHandler {\n private let ttl: UInt32\n\n public init(ttl: UInt32 = 300) {\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n switch question.type {\n case ResourceRecordType.host:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .nonExistentDomain,\n questions: query.questions,\n answers: []\n )\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginFactory.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\nprivate let configFilename: String = \"config.json\"\n\n/// Describes the configuration and binary file locations for a plugin.\npublic protocol PluginFactory: Sendable {\n /// Create a plugin conforming to the layout, if possible.\n func create(installURL: URL) throws -> Plugin?\n}\n\n/// Default layout which uses a Unix-like structure.\npublic struct DefaultPluginFactory: PluginFactory {\n public init() {}\n\n public func create(installURL: URL) throws -> Plugin? {\n let fm = FileManager.default\n\n let configURL = installURL.appending(path: configFilename)\n guard fm.fileExists(atPath: configURL.path) else {\n return nil\n }\n\n guard let config = try PluginConfig(configURL: configURL) else {\n return nil\n }\n\n let name = installURL.lastPathComponent\n let binaryURL = installURL.appending(path: \"bin\").appending(path: name)\n guard fm.fileExists(atPath: binaryURL.path) else {\n return nil\n }\n\n return Plugin(binaryURL: binaryURL, config: config)\n }\n}\n\n/// Layout which uses a macOS application bundle structure.\npublic struct AppBundlePluginFactory: PluginFactory {\n private static let appSuffix = \".app\"\n\n public init() {}\n\n public func create(installURL: URL) throws -> Plugin? {\n let fm = FileManager.default\n\n let configURL =\n installURL\n .appending(path: \"Contents\")\n .appending(path: \"Resources\")\n .appending(path: configFilename)\n guard fm.fileExists(atPath: configURL.path) else {\n return nil\n }\n\n guard let config = try PluginConfig(configURL: configURL) else {\n return nil\n }\n\n let appName = installURL.lastPathComponent\n guard appName.hasSuffix(Self.appSuffix) else {\n return nil\n }\n let name = String(appName.dropLast(Self.appSuffix.count))\n let binaryURL =\n installURL\n .appending(path: \"Contents\")\n .appending(path: \"MacOS\")\n .appending(path: name)\n guard fm.fileExists(atPath: binaryURL.path) else {\n return nil\n }\n\n return Plugin(binaryURL: binaryURL, config: config)\n }\n}\n"], ["/container/Sources/CLI/Container/ContainersCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct ContainersCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"containers\",\n abstract: \"Manage containers\",\n subcommands: [\n ContainerCreate.self,\n ContainerDelete.self,\n ContainerExec.self,\n ContainerInspect.self,\n ContainerKill.self,\n ContainerList.self,\n ContainerLogs.self,\n ContainerStart.self,\n ContainerStop.self,\n ],\n aliases: [\"container\", \"c\"]\n )\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/ImageServiceXPCKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\n/// Keys for XPC fields.\npublic enum ImagesServiceXPCKeys: String {\n case fd\n /// FDs pointing to container logs key.\n case logs\n /// Path to a file on disk key.\n case filePath\n\n /// Images\n case imageReference\n case imageNewReference\n case imageDescription\n case imageDescriptions\n case filesystem\n case ociPlatform\n case insecureFlag\n case garbageCollect\n\n /// ContentStore\n case digest\n case digests\n case directory\n case contentPath\n case size\n case ingestSessionId\n}\n\nextension XPCMessage {\n public func set(key: ImagesServiceXPCKeys, value: String) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: UInt64) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: Data) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: Bool) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func string(key: ImagesServiceXPCKeys) -> String? {\n self.string(key: key.rawValue)\n }\n\n public func data(key: ImagesServiceXPCKeys) -> Data? {\n self.data(key: key.rawValue)\n }\n\n public func dataNoCopy(key: ImagesServiceXPCKeys) -> Data? {\n self.dataNoCopy(key: key.rawValue)\n }\n\n public func uint64(key: ImagesServiceXPCKeys) -> UInt64 {\n self.uint64(key: key.rawValue)\n }\n\n public func bool(key: ImagesServiceXPCKeys) -> Bool {\n self.bool(key: key.rawValue)\n }\n}\n\n#endif\n"], ["/container/Sources/CLI/System/SystemDNS.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct SystemDNS: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"dns\",\n abstract: \"Manage local DNS domains\",\n subcommands: [\n DNSCreate.self,\n DNSDelete.self,\n DNSList.self,\n DNSDefault.self,\n ]\n )\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\n\nextension Application {\n struct DNSList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List local DNS domains\",\n aliases: [\"ls\"]\n )\n\n func run() async throws {\n let resolver: HostDNSResolver = HostDNSResolver()\n let domains = resolver.listDomains()\n print(domains.joined(separator: \"\\n\"))\n }\n\n }\n}\n"], ["/container/Sources/ContainerBuild/TerminalCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct TerminalCommand: Codable {\n let commandType: String\n let code: String\n let rows: UInt16\n let cols: UInt16\n\n enum CodingKeys: String, CodingKey {\n case commandType = \"command_type\"\n case code\n case rows\n case cols\n }\n\n init(rows: UInt16, cols: UInt16) {\n self.commandType = \"terminal\"\n self.code = \"winch\"\n self.rows = rows\n self.cols = cols\n }\n\n init() {\n self.commandType = \"terminal\"\n self.code = \"ack\"\n self.rows = 0\n self.cols = 0\n }\n\n func json() throws -> String? {\n let encoder = JSONEncoder()\n let data = try encoder.encode(self)\n return data.base64EncodedString().trimmingCharacters(in: CharacterSet(charactersIn: \"=\"))\n }\n}\n"], ["/container/Sources/TerminalProgress/Int64+Formatted.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Int64 {\n func formattedSize() -> String {\n let formattedSize = ByteCountFormatter.string(fromByteCount: self, countStyle: .binary)\n return formattedSize\n }\n\n func formattedSizeSpeed(from startTime: DispatchTime) -> String {\n let elapsedTimeNanoseconds = DispatchTime.now().uptimeNanoseconds - startTime.uptimeNanoseconds\n let elapsedTimeSeconds = Double(elapsedTimeNanoseconds) / 1_000_000_000\n guard elapsedTimeSeconds > 0 else {\n return \"0 B/s\"\n }\n\n let speed = Double(self) / elapsedTimeSeconds\n let formattedSpeed = ByteCountFormatter.string(fromByteCount: Int64(speed), countStyle: .binary)\n return \"\\(formattedSpeed)/s\"\n }\n}\n"], ["/container/Sources/CLI/Codable+JSON.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\nextension [any Codable] {\n func jsonArray() throws -> String {\n \"[\\(try self.map { String(data: try JSONEncoder().encode($0), encoding: .utf8)! }.joined(separator: \",\"))]\"\n }\n}\n"], ["/container/Sources/CLI/System/SystemCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct SystemCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"system\",\n abstract: \"Manage system components\",\n subcommands: [\n SystemDNS.self,\n SystemLogs.self,\n SystemStart.self,\n SystemStop.self,\n SystemStatus.self,\n SystemKernel.self,\n ],\n aliases: [\"s\"]\n )\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct NetworkCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"network\",\n abstract: \"Manage container networks\",\n subcommands: [\n NetworkCreate.self,\n NetworkDelete.self,\n NetworkList.self,\n NetworkInspect.self,\n ],\n aliases: [\"n\"]\n )\n }\n}\n"], ["/container/Sources/TerminalProgress/Int+Formatted.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Int {\n func formattedTime() -> String {\n let secondsInMinute = 60\n let secondsInHour = secondsInMinute * 60\n let secondsInDay = secondsInHour * 24\n\n let days = self / secondsInDay\n let hours = (self % secondsInDay) / secondsInHour\n let minutes = (self % secondsInHour) / secondsInMinute\n let seconds = self % secondsInMinute\n\n var components = [String]()\n if days > 0 {\n components.append(\"\\(days)d\")\n }\n if hours > 0 || days > 0 {\n components.append(\"\\(hours)h\")\n }\n if minutes > 0 || hours > 0 || days > 0 {\n components.append(\"\\(minutes)m\")\n }\n components.append(\"\\(seconds)s\")\n return components.joined(separator: \" \")\n }\n\n func formattedNumber() -> String {\n let formatter = NumberFormatter()\n formatter.numberStyle = .decimal\n guard let formattedNumber = formatter.string(from: NSNumber(value: self)) else {\n return \"\"\n }\n return formattedNumber\n }\n}\n"], ["/container/Sources/CLI/Image/ImagesCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct ImagesCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"images\",\n abstract: \"Manage images\",\n subcommands: [\n ImageInspect.self,\n ImageList.self,\n ImageLoad.self,\n ImagePrune.self,\n ImagePull.self,\n ImagePush.self,\n ImageRemove.self,\n ImageSave.self,\n ImageTag.self,\n ],\n aliases: [\"image\", \"i\"]\n )\n }\n}\n"], ["/container/Sources/CLI/Registry/RegistryCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct RegistryCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"registry\",\n abstract: \"Manage registry configurations\",\n subcommands: [\n Login.self,\n Logout.self,\n RegistryDefault.self,\n ],\n aliases: [\"r\"]\n )\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkState.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct NetworkStatus: Codable, Sendable {\n /// The address allocated for the network if no subnet was specified at\n /// creation time; otherwise, the subnet from the configuration.\n public let address: String\n /// The gateway IPv4 address.\n public let gateway: String\n\n public init(\n address: String,\n gateway: String\n ) {\n self.address = address\n self.gateway = gateway\n }\n\n}\n\n/// The configuration and runtime attributes for a network.\npublic enum NetworkState: Codable, Sendable {\n // The network has been configured.\n case created(NetworkConfiguration)\n // The network is running.\n case running(NetworkConfiguration, NetworkStatus)\n\n public var state: String {\n switch self {\n case .created: \"created\"\n case .running: \"running\"\n }\n }\n\n public var id: String {\n switch self {\n case .created(let configuration): configuration.id\n case .running(let configuration, _): configuration.id\n }\n }\n}\n"], ["/container/Sources/DNSServer/Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport DNS\nimport Foundation\n\npublic typealias Message = DNS.Message\npublic typealias ResourceRecord = DNS.ResourceRecord\npublic typealias HostRecord = DNS.HostRecord\npublic typealias IPv4 = DNS.IPv4\npublic typealias IPv6 = DNS.IPv6\npublic typealias ReturnCode = DNS.ReturnCode\n\npublic enum DNSResolverError: Swift.Error, CustomStringConvertible {\n case serverError(_ msg: String)\n case invalidHandlerSpec(_ spec: String)\n case unsupportedHandlerType(_ t: String)\n case invalidIP(_ v: String)\n case invalidHandlerOption(_ v: String)\n case handlerConfigError(_ msg: String)\n\n public var description: String {\n switch self {\n case .serverError(let msg):\n return \"server error: \\(msg)\"\n case .invalidHandlerSpec(let msg):\n return \"invalid handler spec: \\(msg)\"\n case .unsupportedHandlerType(let t):\n return \"unsupported handler type specified: \\(t)\"\n case .invalidIP(let ip):\n return \"invalid IP specified: \\(ip)\"\n case .invalidHandlerOption(let v):\n return \"invalid handler option specified: \\(v)\"\n case .handlerConfigError(let msg):\n return \"error configuring handler: \\(msg)\"\n }\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/CompositeResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Delegates a query sequentially to handlers until one provides a response.\npublic struct CompositeResolver: DNSHandler {\n private let handlers: [DNSHandler]\n\n public init(handlers: [DNSHandler]) {\n self.handlers = handlers\n }\n\n public func answer(query: Message) async throws -> Message? {\n for handler in self.handlers {\n if let response = try await handler.answer(query: query) {\n return response\n }\n }\n\n return nil\n }\n}\n"], ["/container/Sources/CLI/Builder/Builder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct BuilderCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"builder\",\n abstract: \"Manage an image builder instance\",\n subcommands: [\n BuilderStart.self,\n BuilderStatus.self,\n BuilderStop.self,\n BuilderDelete.self,\n ])\n }\n}\n"], ["/container/Sources/CLI/System/SystemKernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct SystemKernel: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kernel\",\n abstract: \"Manage the default kernel configuration\",\n subcommands: [\n KernelSet.self\n ]\n )\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientHealthCheck.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Foundation\n\npublic enum ClientHealthCheck {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n}\n\nextension ClientHealthCheck {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public static func ping(timeout: Duration? = .seconds(5)) async throws {\n let client = Self.newClient()\n let request = XPCMessage(route: .ping)\n try await client.send(request, responseTimeout: timeout)\n }\n}\n"], ["/container/Sources/CLI/Container/ProcessUtils.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n static func ensureRunning(container: ClientContainer) throws {\n if container.status != .running {\n throw ContainerizationError(.invalidState, message: \"container \\(container.id) is not running\")\n }\n }\n}\n"], ["/container/Sources/SocketForwarder/SocketForwarderResult.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIO\n\npublic struct SocketForwarderResult: Sendable {\n private let channel: any Channel\n\n public init(channel: Channel) {\n self.channel = channel\n }\n\n public var proxyAddress: SocketAddress? { self.channel.localAddress }\n\n public func close() {\n self.channel.eventLoop.execute {\n _ = channel.close()\n }\n }\n\n public func wait() async throws {\n try await self.channel.closeFuture.get()\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressTheme.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A theme for progress bar.\npublic protocol ProgressTheme: Sendable {\n /// The icons used to represent a spinner.\n var spinner: [String] { get }\n /// The icon used to represent a progress bar.\n var bar: String { get }\n /// The icon used to indicate that a progress bar finished.\n var done: String { get }\n}\n\npublic struct DefaultProgressTheme: ProgressTheme {\n public let spinner = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"]\n public let bar = \"█\"\n public let done = \"✔\"\n}\n\nextension ProgressTheme {\n func getSpinnerIcon(_ iteration: Int) -> String {\n spinner[iteration % spinner.count]\n }\n}\n"], ["/container/Sources/ContainerClient/Core/PublishPort.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The network protocols available for port forwarding.\npublic enum PublishProtocol: String, Sendable, Codable {\n case tcp = \"tcp\"\n case udp = \"udp\"\n\n /// Initialize a protocol with to default value, `.tcp`.\n public init() {\n self = .tcp\n }\n\n /// Initialize a protocol value from the provided string.\n public init?(_ value: String) {\n switch value.lowercased() {\n case \"tcp\": self = .tcp\n case \"udp\": self = .udp\n default: return nil\n }\n }\n}\n\n/// Specifies internet port forwarding from host to container.\npublic struct PublishPort: Sendable, Codable {\n /// The IP address of the proxy listener on the host\n public let hostAddress: String\n\n /// The port number of the proxy listener on the host\n public let hostPort: Int\n\n /// The port number of the container listener\n public let containerPort: Int\n\n /// The network protocol for the proxy\n public let proto: PublishProtocol\n\n /// Creates a new port forwarding specification.\n public init(hostAddress: String, hostPort: Int, containerPort: Int, proto: PublishProtocol) {\n self.hostAddress = hostAddress\n self.hostPort = hostPort\n self.containerPort = containerPort\n self.proto = proto\n }\n}\n"], ["/container/Sources/APIServer/HealthCheck/HealthCheckHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport Logging\n\nactor HealthCheckHarness {\n private let log: Logger\n\n public init(log: Logger) {\n self.log = log\n }\n\n @Sendable\n func ping(_ message: XPCMessage) async -> XPCMessage {\n message.reply()\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/IsolatedInterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\n\n/// Isolated container network interface strategy. This strategy prohibits\n/// container to container networking, but it is the only approach that\n/// works for macOS Sequoia.\nstruct IsolatedInterfaceStrategy: InterfaceStrategy {\n public func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) -> Interface {\n let gateway = interfaceIndex == 0 ? attachment.gateway : nil\n return NATInterface(address: attachment.address, gateway: gateway)\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/Network.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\n\n/// Defines common characteristics and operations for a network.\npublic protocol Network: Sendable {\n // Contains network attributes while the network is running\n var state: NetworkState { get async }\n\n // Use implementation-dependent network attributes\n nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws\n\n // Start the network\n func start() async throws\n}\n"], ["/container/Sources/ContainerClient/Core/ImageDescription.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\n\n/// A type that represents an OCI image that can be used with sandboxes or containers.\npublic struct ImageDescription: Sendable, Codable {\n /// The public reference/name of the image.\n public let reference: String\n /// The descriptor of the image.\n public let descriptor: Descriptor\n\n public var digest: String { descriptor.digest }\n public var mediaType: String { descriptor.mediaType }\n\n public init(reference: String, descriptor: Descriptor) {\n self.reference = reference\n self.descriptor = descriptor\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/InterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\n\n/// A strategy for mapping network attachment information to a network interface.\npublic protocol InterfaceStrategy: Sendable {\n /// Map a client network attachment request to a network interface specification.\n ///\n /// - Parameters:\n /// - attachment: General attachment information that is common\n /// for all networks.\n /// - interfaceIndex: The zero-based index of the interface.\n /// - additionalData: If present, attachment information that is\n /// specific for the network to which the container will attach.\n ///\n /// - Returns: An XPC message with no parameters.\n func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) throws -> Interface\n}\n"], ["/container/Sources/TerminalProgress/ProgressUpdate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum ProgressUpdateEvent: Sendable {\n case setDescription(String)\n case setSubDescription(String)\n case setItemsName(String)\n case addTasks(Int)\n case setTasks(Int)\n case addTotalTasks(Int)\n case setTotalTasks(Int)\n case addItems(Int)\n case setItems(Int)\n case addTotalItems(Int)\n case setTotalItems(Int)\n case addSize(Int64)\n case setSize(Int64)\n case addTotalSize(Int64)\n case setTotalSize(Int64)\n case custom(String)\n}\n\npublic typealias ProgressUpdateHandler = @Sendable (_ events: [ProgressUpdateEvent]) async -> Void\n\npublic protocol ProgressAdapter {\n associatedtype T\n static func handler(from progressUpdate: ProgressUpdateHandler?) -> (@Sendable ([T]) async -> Void)?\n}\n"], ["/container/Sources/ContainerClient/Core/PublishSocket.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\n/// Represents a socket that should be published from container to host.\npublic struct PublishSocket: Sendable, Codable {\n /// The path to the socket in the container.\n public var containerPath: URL\n\n /// The path where the socket should appear on the host.\n public var hostPath: URL\n\n /// File permissions for the socket on the host.\n public var permissions: FilePermissions?\n\n public init(\n containerPath: URL,\n hostPath: URL,\n permissions: FilePermissions? = nil\n ) {\n self.containerPath = containerPath\n self.hostPath = hostPath\n self.permissions = permissions\n }\n}\n"], ["/container/Sources/ContainerClient/Arch.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum Arch: String {\n case arm64, amd64\n\n public static func hostArchitecture() -> Arch {\n #if arch(arm64)\n return .arm64\n #elseif arch(x86_64)\n return .amd64\n #endif\n }\n}\n"], ["/container/Sources/ContainerClient/Array+Dedupe.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension Array where Element: Hashable {\n func dedupe() -> [Element] {\n var elems = Set()\n return filter { elems.insert($0).inserted }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkMode.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Networking mode that applies to client containers.\npublic enum NetworkMode: String, Codable, Sendable {\n /// NAT networking mode.\n /// Containers do not have routable IPs, and the host performs network\n /// address translation to allow containers to reach external services.\n case nat = \"nat\"\n}\n\nextension NetworkMode {\n public init() {\n self = .nat\n }\n\n public init?(_ value: String) {\n switch value.lowercased() {\n case \"nat\": self = .nat\n default: return nil\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Configuration parameters for network creation.\npublic struct NetworkConfiguration: Codable, Sendable, Identifiable {\n /// A unique identifier for the network\n public let id: String\n\n /// The network type\n public let mode: NetworkMode\n\n /// The preferred CIDR address for the subnet, if specified\n public let subnet: String?\n\n /// Creates a network configuration\n public init(\n id: String,\n mode: NetworkMode,\n subnet: String? = nil\n ) {\n self.id = id\n self.mode = mode\n self.subnet = subnet\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerStopOptions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct ContainerStopOptions: Sendable, Codable {\n public let timeoutInSeconds: Int32\n public let signal: Int32\n\n public static let `default` = ContainerStopOptions(\n timeoutInSeconds: 5,\n signal: SIGTERM\n )\n\n public init(timeoutInSeconds: Int32, signal: Int32) {\n self.timeoutInSeconds = timeoutInSeconds\n self.signal = signal\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerSnapshot.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\n\n/// A snapshot of a container along with its configuration\n/// and any runtime state information.\npublic struct ContainerSnapshot: Codable, Sendable {\n /// The configuration of the container.\n public let configuration: ContainerConfiguration\n /// The runtime status of the container.\n public let status: RuntimeStatus\n /// Network interfaces attached to the sandbox that are provided to the container.\n public let networks: [Attachment]\n\n public init(\n configuration: ContainerConfiguration,\n status: RuntimeStatus,\n networks: [Attachment]\n ) {\n self.configuration = configuration\n self.status = status\n self.networks = networks\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerCreateOptions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct ContainerCreateOptions: Codable, Sendable {\n public let autoRemove: Bool\n\n public init(autoRemove: Bool) {\n self.autoRemove = autoRemove\n }\n\n public static let `default` = ContainerCreateOptions(autoRemove: false)\n\n}\n"], ["/container/Sources/ContainerClient/SandboxSnapshot.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\n\n/// A snapshot of a sandbox and its resources.\npublic struct SandboxSnapshot: Codable, Sendable {\n /// The runtime status of the sandbox.\n public let status: RuntimeStatus\n /// Network attachments for the sandbox.\n public let networks: [Attachment]\n /// Containers placed in the sandbox.\n public let containers: [ContainerSnapshot]\n\n public init(\n status: RuntimeStatus,\n networks: [Attachment],\n containers: [ContainerSnapshot]\n ) {\n self.status = status\n self.networks = networks\n self.containers = containers\n }\n}\n"], ["/container/Sources/ContainerClient/ContainerEvents.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\npublic enum ContainerEvent: Sendable, Codable {\n case containerStart(id: String)\n case containerExit(id: String, exitCode: Int64)\n}\n"], ["/container/Sources/DNSServer/DNSHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Protocol for implementing custom DNS handlers.\npublic protocol DNSHandler {\n /// Attempt to answer a DNS query\n /// - Parameter query: the query message\n /// - Throws: a server failure occurred during the query\n /// - Returns: The response message for the query, or nil if the request\n /// is not within the scope of the handler.\n func answer(query: Message) async throws -> Message?\n}\n"], ["/container/Sources/Services/ContainerNetworkService/Attachment.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A snapshot of a network interface allocated to a sandbox.\npublic struct Attachment: Codable, Sendable {\n /// The network ID associated with the attachment.\n public let network: String\n /// The hostname associated with the attachment.\n public let hostname: String\n /// The subnet CIDR, where the address is the container interface IPv4 address.\n public let address: String\n /// The IPv4 gateway address.\n public let gateway: String\n\n public init(network: String, hostname: String, address: String, gateway: String) {\n self.network = network\n self.hostname = hostname\n self.address = address\n self.gateway = gateway\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/ImageServiceXPCRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\npublic enum ImagesServiceXPCRoute: String {\n case imageList\n case imagePull\n case imagePush\n case imageTag\n case imageBuild\n case imageDelete\n case imageSave\n case imageLoad\n case imagePrune\n\n case contentGet\n case contentDelete\n case contentClean\n case contentIngestStart\n case contentIngestComplete\n case contentIngestCancel\n\n case imageUnpack\n case snapshotDelete\n case snapshotGet\n}\n\nextension XPCMessage {\n public init(route: ImagesServiceXPCRoute) {\n self.init(route: route.rawValue)\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerClient/SandboxRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum SandboxRoutes: String {\n /// Bootstrap the sandbox instance and create the init process.\n case bootstrap = \"com.apple.container.sandbox/bootstrap\"\n /// Create a process in the sandbox.\n case createProcess = \"com.apple.container.sandbox/createProcess\"\n /// Start a process in the sandbox.\n case start = \"com.apple.container.sandbox/start\"\n /// Stop the sandbox.\n case stop = \"com.apple.container.sandbox/stop\"\n /// Return the current state of the sandbox.\n case state = \"com.apple.container.sandbox/state\"\n /// Kill a process in the sandbox.\n case kill = \"com.apple.container.sandbox/kill\"\n /// Resize the pty of a process in the sandbox.\n case resize = \"com.apple.container.sandbox/resize\"\n /// Wait on a process in the sandbox.\n case wait = \"com.apple.container.sandbox/wait\"\n /// Execute a new process in the sandbox.\n case exec = \"com.apple.container.sandbox/exec\"\n /// Dial a vsock port in the sandbox.\n case dial = \"com.apple.container.sandbox/dial\"\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum NetworkRoutes: String {\n /// Return the current state of the network.\n case state = \"com.apple.container.network/state\"\n /// Allocates parameters for attaching a sandbox to the network.\n case allocate = \"com.apple.container.network/allocate\"\n /// Deallocates parameters for attaching a sandbox to the network.\n case deallocate = \"com.apple.container.network/deallocate\"\n /// Disables the allocator if no sandboxes are attached.\n case disableAllocator = \"com.apple.container.network/disableAllocator\"\n /// Retrieves the allocation for a hostname.\n case lookup = \"com.apple.container.network/lookup\"\n}\n"], ["/container/Sources/Services/ContainerNetworkService/UserDefaults+Container.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension UserDefaults {\n public static let appSuiteName = \"com.apple.container.defaults\"\n}\n"], ["/container/Sources/ContainerClient/Core/Constants.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum Constants {\n public static let keychainID = \"com.apple.container\"\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum NetworkKeys: String {\n case additionalData\n case allocatorDisabled\n case attachment\n case hostname\n case network\n case state\n}\n"], ["/container/Sources/SocketForwarder/SocketForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIO\n\npublic protocol SocketForwarder: Sendable {\n func run() throws -> EventLoopFuture\n}\n"], ["/container/Sources/ContainerClient/Core/RuntimeStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Runtime status for a sandbox or container.\npublic enum RuntimeStatus: String, CaseIterable, Sendable, Codable {\n /// The object is in an unknown status.\n case unknown\n /// The object is currently stopped.\n case stopped\n /// The object is currently running.\n case running\n /// The object is currently stopping.\n case stopping\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:21:52", "created_task_model": "DeepSeek-R1", "function_skeleton": "func run ( ) async throws { }", "code_description": "This code segment functions to: Retrieve and manage log output streams by selecting the appropriate source based on configuration flags, apply line limit constraints when specified, and implement continuous monitoring of updates while handling potential data conversion errors during processing."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\n func run() async throws {\n let client = try ContainerClient(global: global)\n let fh = try await client.getLogs(\n container: container,\n boot: boot\n )\n try await Self.tail(\n fh: fh,\n n: numLines,\n follow: follow\n )\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 03-22-21"}, "editdistance_info": {"edit_distance": 30.3571, "calculate_time": "2025-08-21 03:22:21", "true_code_clean": "func run() async throws {\n do {\n let container = try await ClientContainer.get(id: container)\n let fhs = try await container.logs()\n let fileHandle = boot ? fhs[1] : fhs[0]\n try await Self.tail(\n fh: fileHandle,\n n: numLines,\n follow: follow\n )\n } catch {\n throw ContainerizationError(\n .invalidArgument,\n message: \"failed to fetch container logs for \\(container): \\(error)\"\n )\n }\n }", "predict_code_clean": "func run() async throws {\n let client = try ContainerClient(global: global)\n let fh = try await client.getLogs(\n container: container,\n boot: boot\n )\n try await Self.tail(\n fh: fh,\n n: numLines,\n follow: follow\n )\n }"}} {"repo_name": "container", "file_name": "/container/Sources/ContainerPlugin/Plugin.swift", "inference_info": {"prefix_code": "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\n/// Value type that contains the plugin configuration, the parsed name of the\n/// plugin and whether a CLI surface for the plugin was found.\npublic struct Plugin: Sendable, Codable {\n private static let machServicePrefix = \"com.apple.container.\"\n\n /// Pathname to installation directory for plugins.\n public let binaryURL: URL\n\n /// Configuration for the plugin.\n public let config: PluginConfig\n\n public init(binaryURL: URL, config: PluginConfig) {\n self.binaryURL = binaryURL\n self.config = config\n }\n}\n\nextension Plugin {\n public var name: String { binaryURL.lastPathComponent }\n\n public var shouldBoot: Bool {\n guard let config = self.config.servicesConfig else {\n return false\n }\n\n return config.loadAtBoot\n }\n\n public func getLaunchdLabel(instanceId: String? = nil) -> String {\n // Use the plugin name for the launchd label.\n guard let instanceId else {\n return \"\\(Self.machServicePrefix)\\(self.name)\"\n }\n return \"\\(Self.machServicePrefix)\\(self.name).\\(instanceId)\"\n }\n\n ", "suffix_code": "\n\n public func getMachService(instanceId: String? = nil, type: PluginConfig.DaemonPluginType) -> String? {\n guard hasType(type) else {\n return nil\n }\n\n guard let instanceId else {\n return \"\\(Self.machServicePrefix)\\(type.rawValue).\\(name)\"\n }\n return \"\\(Self.machServicePrefix)\\(type.rawValue).\\(name).\\(instanceId)\"\n }\n\n public func hasType(_ type: PluginConfig.DaemonPluginType) -> Bool {\n guard let config = self.config.servicesConfig else {\n return false\n }\n\n guard !(config.services.filter { $0.type == type }.isEmpty) else {\n return false\n }\n\n return true\n }\n}\n\nextension Plugin {\n public func exec(args: [String]) throws {\n var args = args\n let executable = self.binaryURL.path\n args[0] = executable\n let argv = args.map { strdup($0) } + [nil]\n guard execvp(executable, argv) != -1 else {\n throw POSIXError.fromErrno()\n }\n fatalError(\"unreachable\")\n }\n\n func helpText(padding: Int) -> String {\n guard !self.name.isEmpty else {\n return \"\"\n }\n let namePadded = name.padding(toLength: padding, withPad: \" \", startingAt: 0)\n return \" \" + namePadded + self.config.abstract\n }\n}\n", "middle_code": "public func getMachServices(instanceId: String? = nil) -> [String] {\n guard let config = self.config.servicesConfig else {\n return []\n }\n var services = [String]()\n for service in config.services {\n let serviceName: String\n if let instanceId {\n serviceName = \"\\(Self.machServicePrefix)\\(service.type.rawValue).\\(name).\\(instanceId)\"\n } else {\n serviceName = \"\\(Self.machServicePrefix)\\(service.type.rawValue).\\(name)\"\n }\n services.append(serviceName)\n }\n return services\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/container/Sources/ContainerPlugin/PluginLoader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\npublic struct PluginLoader: Sendable {\n // A path on disk managed by the PluginLoader, where it stores\n // runtime data for loaded plugins. This includes the launchd plists\n // and logs files.\n private let defaultPluginResourcePath: URL\n\n private let pluginDirectories: [URL]\n\n private let pluginFactories: [PluginFactory]\n\n private let log: Logger?\n\n public typealias PluginQualifier = ((Plugin) -> Bool)\n\n public init(pluginDirectories: [URL], pluginFactories: [PluginFactory], defaultResourcePath: URL, log: Logger? = nil) {\n self.pluginDirectories = pluginDirectories\n self.pluginFactories = pluginFactories\n self.log = log\n self.defaultPluginResourcePath = defaultResourcePath\n }\n\n static public func defaultPluginResourcePath(root: URL) -> URL {\n root.appending(path: \"plugin-state\")\n }\n\n static public func userPluginsDir(root: URL) -> URL {\n root\n .appending(path: \"libexec\")\n .appending(path: \"container-plugins\")\n .resolvingSymlinksInPath()\n }\n}\n\nextension PluginLoader {\n public func alterCLIHelpText(original: String) -> String {\n var plugins = findPlugins()\n plugins = plugins.filter { $0.config.isCLI }\n guard !plugins.isEmpty else {\n return original\n }\n\n var lines = original.split(separator: \"\\n\").map { String($0) }\n\n let sectionHeader = \"PLUGINS:\"\n lines.append(sectionHeader)\n\n for plugin in plugins {\n let helpText = plugin.helpText(padding: 24)\n lines.append(helpText)\n }\n\n return lines.joined(separator: \"\\n\")\n }\n\n public func findPlugins() -> [Plugin] {\n let fm = FileManager.default\n\n var pluginNames = Set()\n var plugins: [Plugin] = []\n\n for pluginDir in pluginDirectories {\n if !fm.fileExists(atPath: pluginDir.path) {\n continue\n }\n\n guard\n var dirs = try? fm.contentsOfDirectory(\n at: pluginDir,\n includingPropertiesForKeys: [.isDirectoryKey],\n options: .skipsHiddenFiles\n )\n else {\n continue\n }\n dirs = dirs.filter {\n $0.isDirectory\n }\n\n for installURL in dirs {\n do {\n guard\n let plugin = try\n (pluginFactories.compactMap {\n try $0.create(installURL: installURL)\n }.first)\n else {\n log?.warning(\n \"Not installing plugin with missing configuration\",\n metadata: [\n \"path\": \"\\(installURL.path)\"\n ]\n )\n continue\n }\n\n guard !pluginNames.contains(plugin.name) else {\n log?.warning(\n \"Not installing shadowed plugin\",\n metadata: [\n \"path\": \"\\(installURL.path)\",\n \"name\": \"\\(plugin.name)\",\n ])\n continue\n }\n\n plugins.append(plugin)\n pluginNames.insert(plugin.name)\n } catch {\n log?.warning(\n \"Not installing plugin with invalid configuration\",\n metadata: [\n \"path\": \"\\(installURL.path)\",\n \"error\": \"\\(error)\",\n ]\n )\n }\n }\n }\n\n return plugins\n }\n\n public func findPlugin(name: String, log: Logger? = nil) -> Plugin? {\n do {\n return\n try pluginDirectories\n .compactMap { installURL in\n try pluginFactories.compactMap { try $0.create(installURL: installURL.appending(path: name)) }.first\n }\n .first\n } catch {\n log?.warning(\n \"Not installing plugin with invalid configuration\",\n metadata: [\n \"name\": \"\\(name)\",\n \"error\": \"\\(error)\",\n ]\n )\n return nil\n }\n }\n}\n\nextension PluginLoader {\n public func registerWithLaunchd(\n plugin: Plugin,\n rootURL: URL? = nil,\n args: [String]? = nil,\n instanceId: String? = nil\n ) throws {\n // We only care about loading plugins that have a service\n // to expose; otherwise, they may just be CLI commands.\n guard let serviceConfig = plugin.config.servicesConfig else {\n return\n }\n\n let id = plugin.getLaunchdLabel(instanceId: instanceId)\n log?.info(\"Registering plugin\", metadata: [\"id\": \"\\(id)\"])\n let rootURL = rootURL ?? self.defaultPluginResourcePath.appending(path: plugin.name)\n try FileManager.default.createDirectory(at: rootURL, withIntermediateDirectories: true)\n let env = ProcessInfo.processInfo.environment.filter { key, _ in\n key.hasPrefix(\"CONTAINER_\")\n }\n let logUrl = rootURL.appendingPathComponent(\"service.log\")\n let plist = LaunchPlist(\n label: id,\n arguments: [plugin.binaryURL.path] + (args ?? serviceConfig.defaultArguments),\n environment: env,\n limitLoadToSessionType: [.Aqua, .Background, .System],\n runAtLoad: serviceConfig.runAtLoad,\n stdout: logUrl.path,\n stderr: logUrl.path,\n machServices: plugin.getMachServices(instanceId: instanceId)\n )\n\n let plistUrl = rootURL.appendingPathComponent(\"service.plist\")\n let data = try plist.encode()\n try data.write(to: plistUrl)\n try ServiceManager.register(plistPath: plistUrl.path)\n }\n\n public func deregisterWithLaunchd(plugin: Plugin, instanceId: String? = nil) throws {\n // We only care about loading plugins that have a service\n // to expose; otherwise, they may just be CLI commands.\n guard plugin.config.servicesConfig != nil else {\n return\n }\n let domain = try ServiceManager.getDomainString()\n let label = \"\\(domain)/\\(plugin.getLaunchdLabel(instanceId: instanceId))\"\n log?.info(\"Deregistering plugin\", metadata: [\"id\": \"\\(plugin.getLaunchdLabel())\"])\n try ServiceManager.deregister(fullServiceLabel: label)\n }\n}\n"], ["/container/Sources/APIServer/Containers/ContainersService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CVersion\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerSandboxService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ContainersService {\n private static let machServicePrefix = \"com.apple.container\"\n private static let launchdDomainString = try! ServiceManager.getDomainString()\n\n private let log: Logger\n private let containerRoot: URL\n private let pluginLoader: PluginLoader\n private let runtimePlugins: [Plugin]\n\n private let lock = AsyncLock()\n private var containers: [String: Item]\n\n struct Item: Sendable {\n let bundle: ContainerClient.Bundle\n var state: State\n\n enum State: Sendable {\n case dead\n case alive(SandboxClient)\n case exited(Int32)\n\n func isDead() -> Bool {\n switch self {\n case .dead: return true\n default: return false\n }\n }\n }\n }\n\n public init(root: URL, pluginLoader: PluginLoader, log: Logger) throws {\n let containerRoot = root.appendingPathComponent(\"containers\")\n try FileManager.default.createDirectory(at: containerRoot, withIntermediateDirectories: true)\n self.containerRoot = containerRoot\n self.pluginLoader = pluginLoader\n self.log = log\n self.runtimePlugins = pluginLoader.findPlugins().filter { $0.hasType(.runtime) }\n self.containers = try Self.loadAtBoot(root: containerRoot, loader: pluginLoader, log: log)\n }\n\n static func loadAtBoot(root: URL, loader: PluginLoader, log: Logger) throws -> [String: Item] {\n var directories = try FileManager.default.contentsOfDirectory(\n at: root,\n includingPropertiesForKeys: [.isDirectoryKey]\n )\n directories = directories.filter {\n $0.isDirectory\n }\n\n let runtimePlugins = loader.findPlugins().filter { $0.hasType(.runtime) }\n var results = [String: Item]()\n for dir in directories {\n do {\n let bundle = ContainerClient.Bundle(path: dir)\n let config = try bundle.configuration\n results[config.id] = .init(bundle: bundle, state: .dead)\n let plugin = runtimePlugins.first { $0.name == config.runtimeHandler }\n guard let plugin else {\n throw ContainerizationError(.internalError, message: \"Failed to find runtime plugin \\(config.runtimeHandler)\")\n }\n try Self.registerService(plugin: plugin, loader: loader, configuration: config, path: dir)\n } catch {\n try? FileManager.default.removeItem(at: dir)\n log.warning(\"failed to load container bundle at \\(dir.path)\")\n }\n }\n return results\n }\n\n private func setContainer(_ id: String, _ item: Item, context: AsyncLock.Context) async {\n self.containers[id] = item\n }\n\n /// List all containers registered with the service.\n public func list() async throws -> [ContainerSnapshot] {\n self.log.debug(\"\\(#function)\")\n return await lock.withLock { context in\n var snapshots = [ContainerSnapshot]()\n\n for (id, item) in await self.containers {\n do {\n let result = try await item.asSnapshot()\n snapshots.append(result.0)\n } catch {\n self.log.error(\"unable to load bundle for \\(id) \\(error)\")\n }\n }\n return snapshots\n }\n }\n\n /// Create a new container from the provided id and configuration.\n public func create(configuration: ContainerConfiguration, kernel: Kernel, options: ContainerCreateOptions) async throws {\n self.log.debug(\"\\(#function)\")\n\n let runtimePlugin = self.runtimePlugins.filter {\n $0.name == configuration.runtimeHandler\n }.first\n guard let runtimePlugin else {\n throw ContainerizationError(.notFound, message: \"unable to locate runtime plugin \\(configuration.runtimeHandler)\")\n }\n\n let path = self.containerRoot.appendingPathComponent(configuration.id)\n let systemPlatform = kernel.platform\n let initFs = try await getInitBlock(for: systemPlatform.ociPlatform())\n\n let bundle = try ContainerClient.Bundle.create(\n path: path,\n initialFilesystem: initFs,\n kernel: kernel,\n containerConfiguration: configuration\n )\n do {\n let containerImage = ClientImage(description: configuration.image)\n let imageFs = try await containerImage.getCreateSnapshot(platform: configuration.platform)\n try bundle.setContainerRootFs(cloning: imageFs)\n try bundle.write(filename: \"options.json\", value: options)\n\n try Self.registerService(\n plugin: runtimePlugin,\n loader: self.pluginLoader,\n configuration: configuration,\n path: path\n )\n } catch {\n do {\n try bundle.delete()\n } catch {\n self.log.error(\"failed to delete bundle for container \\(configuration.id): \\(error)\")\n }\n throw error\n }\n self.containers[configuration.id] = Item(bundle: bundle, state: .dead)\n }\n\n private func getInitBlock(for platform: Platform) async throws -> Filesystem {\n let initImage = try await ClientImage.fetch(reference: ClientImage.initImageRef, platform: platform)\n var fs = try await initImage.getCreateSnapshot(platform: platform)\n fs.options = [\"ro\"]\n return fs\n }\n\n private static func registerService(\n plugin: Plugin,\n loader: PluginLoader,\n configuration: ContainerConfiguration,\n path: URL\n ) throws {\n let args = [\n \"--root\", path.path,\n \"--uuid\", configuration.id,\n \"--debug\",\n ]\n try loader.registerWithLaunchd(\n plugin: plugin,\n rootURL: path,\n args: args,\n instanceId: configuration.id\n )\n }\n\n private func get(id: String, context: AsyncLock.Context) throws -> Item {\n try self._get(id: id)\n }\n\n private func _get(id: String) throws -> Item {\n let item = self.containers[id]\n guard let item else {\n throw ContainerizationError(\n .notFound,\n message: \"container with ID \\(id) not found\"\n )\n }\n return item\n }\n\n /// Delete a container and its resources.\n public func delete(id: String) async throws {\n self.log.debug(\"\\(#function)\")\n let item = try self._get(id: id)\n switch item.state {\n case .alive(let client):\n let state = try await client.state()\n if state.status == .running || state.status == .stopping {\n throw ContainerizationError(\n .invalidState,\n message: \"container \\(id) is not yet stopped and can not be deleted\"\n )\n }\n try self._cleanup(id: id, item: item)\n case .dead, .exited(_):\n try self._cleanup(id: id, item: item)\n }\n }\n\n private static func fullLaunchdServiceLabel(runtimeName: String, instanceId: String) -> String {\n \"\\(Self.launchdDomainString)/\\(Self.machServicePrefix).\\(runtimeName).\\(instanceId)\"\n }\n\n private func _cleanup(id: String, item: Item) throws {\n self.log.debug(\"\\(#function)\")\n let config = try item.bundle.configuration\n let label = Self.fullLaunchdServiceLabel(runtimeName: config.runtimeHandler, instanceId: id)\n try ServiceManager.deregister(fullServiceLabel: label)\n try item.bundle.delete()\n self.containers.removeValue(forKey: id)\n }\n\n private func _shutdown(id: String, item: Item) throws {\n let config = try item.bundle.configuration\n let label = Self.fullLaunchdServiceLabel(runtimeName: config.runtimeHandler, instanceId: id)\n try ServiceManager.kill(fullServiceLabel: label)\n }\n\n private func cleanup(id: String, item: Item, context: AsyncLock.Context) async throws {\n try self._cleanup(id: id, item: item)\n }\n\n private func containerProcessExitHandler(_ id: String, _ exitCode: Int32, context: AsyncLock.Context) async {\n self.log.info(\"Handling container \\(id) exit. Code \\(exitCode)\")\n do {\n var item = try self.get(id: id, context: context)\n switch item.state {\n case .dead, .exited(_):\n break\n case .alive(_):\n item.state = .exited(exitCode)\n await self.setContainer(id, item, context: context)\n }\n let options: ContainerCreateOptions = try item.bundle.load(filename: \"options.json\")\n if options.autoRemove {\n try await self.cleanup(id: id, item: item, context: context)\n }\n } catch {\n self.log.error(\n \"Failed to handle container exit\",\n metadata: [\n \"id\": .string(id),\n \"error\": .string(String(describing: error)),\n ])\n }\n }\n\n private func containerStartHandler(_ id: String, context: AsyncLock.Context) async throws {\n self.log.debug(\"\\(#function)\")\n self.log.info(\"Handling container \\(id) Start.\")\n do {\n var item = try self.get(id: id, context: context)\n let configuration = try item.bundle.configuration\n let client = SandboxClient(id: configuration.id, runtime: configuration.runtimeHandler)\n item.state = .alive(client)\n await self.setContainer(id, item, context: context)\n } catch {\n self.log.error(\n \"Failed to handle container start\",\n metadata: [\n \"id\": .string(id),\n \"error\": .string(String(describing: error)),\n ])\n }\n }\n}\n\nextension ContainersService {\n public func handleContainerEvents(event: ContainerEvent) async throws {\n self.log.debug(\"\\(#function)\")\n try await self.lock.withLock { context in\n switch event {\n case .containerExit(let id, let code):\n await self.containerProcessExitHandler(id, Int32(code), context: context)\n case .containerStart(let id):\n try await self.containerStartHandler(id, context: context)\n }\n }\n }\n\n /// Stop all containers inside the sandbox, aborting any processes currently\n /// executing inside the container, before stopping the underlying sandbox.\n public func stop(id: String, options: ContainerStopOptions) async throws {\n self.log.debug(\"\\(#function)\")\n try await lock.withLock { context in\n let item = try await self.get(id: id, context: context)\n switch item.state {\n case .dead, .exited(_):\n return\n case .alive(let client):\n try await client.stop(options: options)\n }\n }\n }\n\n public func logs(id: String) async throws -> [FileHandle] {\n self.log.debug(\"\\(#function)\")\n // Logs doesn't care if the container is running or not, just that\n // the bundle is there, and that the files actually exist.\n do {\n let item = try self._get(id: id)\n return [\n try FileHandle(forReadingFrom: item.bundle.containerLog),\n try FileHandle(forReadingFrom: item.bundle.bootlog),\n ]\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to open container logs: \\(error)\"\n )\n }\n }\n}\n\nextension ContainersService.Item {\n func asSnapshot() async throws -> (ContainerSnapshot, RuntimeStatus) {\n let config = try self.bundle.configuration\n\n switch self.state {\n case .dead, .exited(_):\n return (\n .init(\n configuration: config,\n status: RuntimeStatus.stopped,\n networks: []\n ), .stopped\n )\n case .alive(let client):\n let state = try await client.state()\n return (\n .init(\n configuration: config,\n status: state.status,\n networks: state.networks\n ), state.status\n )\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\nimport Foundation\n\n/// PluginConfig details all of the fields to describe and register a plugin.\n/// A plugin is registered by creating a subdirectory `/user-plugins`,\n/// where the name of the subdirectory is the name of the plugin, and then placing a\n/// file named `config.json` inside with the schema below.\n/// If `services` is filled in then there MUST be a binary named matching the plugin name\n/// in a `bin` subdirectory inside the same directory as the `config.json`.\n/// An example of a valid plugin directory structure would be\n/// $ tree foobar\n/// foobar\n/// ├── bin\n/// │ └── foobar\n/// └── config.json\npublic struct PluginConfig: Sendable, Codable {\n /// Categories of services that can be offered through plugins.\n public enum DaemonPluginType: String, Sendable, Codable {\n /// A runtime plugin provides an XPC API through which the lifecycle\n /// of a **single** container can be managed.\n /// A runtime daemon plugin would typically also have a counterpart\n /// CLI plugin which knows how to talk to the API exposed by the runtime plugin.\n /// The API server ensures that a single instance of the plugin is configured\n /// for a given container such that the client can communicate with it given an instance id.\n case runtime\n /// A network plugin provides an XPC API through which IP address allocations on a given\n /// network can be managed. The API server ensures that a single instance\n /// of this plugin is configured for a given network. Similar to the runtime plugin, it typically\n /// would be accompanied by a CLI plugin that knows how to communicate with the XPC API\n /// given an instance id.\n case network\n /// A core plugin provides an XPC API to manage a given type of resource.\n /// The API server ensures that there exist only a single running instance\n /// of this plugin type. A core plugin can be thought of a singleton whose lifecycle\n /// is tied to that of the API server. Core plugins can be used to expand the base functionality\n /// provided by the API server. As with the other plugin types, it maybe associated with a client\n /// side plugin that communicates with the XPC service exposed by the daemon plugin.\n case core\n /// Reserved for future use. Currently there is no difference between a core and auxiliary daemon plugin.\n case auxiliary\n }\n\n // An XPC service that the plugin publishes.\n public struct Service: Sendable, Codable {\n /// The type of the service the daemon is exposing.\n /// One plugin can expose multiple services of different types.\n ///\n /// The plugin MUST expose a MachService at\n /// `com.apple.container.{type}.{name}.[{id}]` for\n /// each service that it exposes.\n public let type: DaemonPluginType\n /// Optional description of this service.\n public let description: String?\n }\n\n /// Descriptor for the services that the plugin offers.\n public struct ServicesConfig: Sendable, Codable {\n /// Load the plugin into launchd when the API server starts.\n public let loadAtBoot: Bool\n /// Launch the plugin binary as soon as it loads into launchd.\n public let runAtLoad: Bool\n /// The service types that the plugin provides.\n public let services: [Service]\n /// An optional parameter that include any command line arguments\n /// that must be passed to the plugin binary when it is loaded.\n /// This parameter is used only when `servicesConfig.loadAtBoot` is `true`\n public let defaultArguments: [String]\n }\n\n /// Short description of the plugin surface. This will be displayed as the\n /// help-text for CLI plugins, and will be returned in API calls to view loaded\n /// plugins from the daemon.\n public let abstract: String\n\n /// Author of the plugin. This is solely metadata.\n public let author: String?\n\n /// Services configuration. Specify nil for a CLI plugin, and an empty array for\n /// that does not publish any XPC services.\n public let servicesConfig: ServicesConfig?\n}\n\nextension PluginConfig {\n public var isCLI: Bool { self.servicesConfig == nil }\n}\n\nextension PluginConfig {\n public init?(configURL: URL) throws {\n let fm = FileManager.default\n if !fm.fileExists(atPath: configURL.path) {\n return nil\n }\n\n guard let data = fm.contents(atPath: configURL.path) else {\n return nil\n }\n\n let decoder: JSONDecoder = JSONDecoder()\n self = try decoder.decode(PluginConfig.self, from: data)\n }\n}\n"], ["/container/Sources/APIServer/Networks/NetworksService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerPersistence\nimport ContainerPlugin\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor NetworksService {\n private let resourceRoot: URL\n // FIXME: remove qualifier once we can update Containerization dependency.\n private let store: ContainerPersistence.FilesystemEntityStore\n private let pluginLoader: PluginLoader\n private let log: Logger\n private let networkPlugin: Plugin\n\n private var networkStates = [String: NetworkState]()\n private var busyNetworks = Set()\n\n public init(pluginLoader: PluginLoader, resourceRoot: URL, log: Logger) async throws {\n try FileManager.default.createDirectory(at: resourceRoot, withIntermediateDirectories: true)\n self.resourceRoot = resourceRoot\n self.store = try FilesystemEntityStore(path: resourceRoot, type: \"network\", log: log)\n self.pluginLoader = pluginLoader\n self.log = log\n\n let networkPlugin =\n pluginLoader\n .findPlugins()\n .filter { $0.hasType(.network) }\n .first\n guard let networkPlugin else {\n throw ContainerizationError(.internalError, message: \"cannot find network plugin\")\n }\n self.networkPlugin = networkPlugin\n\n let configurations = try await store.list()\n for configuration in configurations {\n do {\n try await registerService(configuration: configuration)\n } catch {\n log.error(\n \"failed to start network\",\n metadata: [\n \"id\": \"\\(configuration.id)\"\n ])\n }\n\n let client = NetworkClient(id: configuration.id)\n let networkState = try await client.state()\n networkStates[configuration.id] = networkState\n guard case .running = networkState else {\n log.error(\n \"network failed to start\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"state\": \"\\(networkState.state)\",\n ])\n return\n }\n }\n }\n\n /// List all networks registered with the service.\n public func list() async throws -> [NetworkState] {\n log.info(\"network service: list\")\n return networkStates.reduce(into: [NetworkState]()) {\n $0.append($1.value)\n }\n }\n\n /// Create a new network from the provided configuration.\n public func create(configuration: NetworkConfiguration) async throws -> NetworkState {\n guard !busyNetworks.contains(configuration.id) else {\n throw ContainerizationError(.exists, message: \"network \\(configuration.id) has a pending operation\")\n }\n\n busyNetworks.insert(configuration.id)\n defer { busyNetworks.remove(configuration.id) }\n\n log.info(\n \"network service: create\",\n metadata: [\n \"id\": \"\\(configuration.id)\"\n ])\n\n // Ensure the network doesn't already exist.\n guard networkStates[configuration.id] == nil else {\n throw ContainerizationError(.exists, message: \"network \\(configuration.id) already exists\")\n }\n\n // Create and start the network.\n try await registerService(configuration: configuration)\n let client = NetworkClient(id: configuration.id)\n let networkState = try await client.state()\n networkStates[configuration.id] = networkState\n\n // Persist the configuration data.\n do {\n try await store.create(configuration)\n return networkState\n } catch {\n networkStates.removeValue(forKey: configuration.id)\n do {\n try pluginLoader.deregisterWithLaunchd(plugin: networkPlugin, instanceId: configuration.id)\n } catch {\n log.error(\n \"failed to deregister network service after failed creation\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"error\": \"\\(error.localizedDescription)\",\n ])\n }\n\n throw error\n }\n }\n\n /// Delete a network.\n public func delete(id: String) async throws {\n guard !busyNetworks.contains(id) else {\n throw ContainerizationError(.exists, message: \"network \\(id) has a pending operation\")\n }\n\n busyNetworks.insert(id)\n defer { busyNetworks.remove(id) }\n\n log.info(\n \"network service: delete\",\n metadata: [\n \"id\": \"\\(id)\"\n ])\n if id == ClientNetwork.defaultNetworkName {\n throw ContainerizationError(.invalidArgument, message: \"cannot delete system subnet \\(ClientNetwork.defaultNetworkName)\")\n }\n\n guard let networkState = networkStates[id] else {\n throw ContainerizationError(.notFound, message: \"no network for id \\(id)\")\n }\n\n guard case .running = networkState else {\n throw ContainerizationError(.invalidState, message: \"cannot delete subnet \\(id) in state \\(networkState.state)\")\n }\n\n let client = NetworkClient(id: id)\n guard try await client.disableAllocator() else {\n throw ContainerizationError(.invalidState, message: \"cannot delete subnet \\(id) with containers attached\")\n }\n\n defer { networkStates.removeValue(forKey: id) }\n do {\n try pluginLoader.deregisterWithLaunchd(plugin: networkPlugin, instanceId: id)\n } catch {\n log.error(\n \"failed to deregister network service after failed creation\",\n metadata: [\n \"id\": \"\\(id)\",\n \"error\": \"\\(error.localizedDescription)\",\n ])\n }\n\n do {\n try await store.delete(id)\n } catch {\n throw ContainerizationError(.notFound, message: error.localizedDescription)\n }\n }\n\n /// Perform a hostname lookup on all networks.\n public func lookup(hostname: String) async throws -> Attachment? {\n for id in networkStates.keys {\n let client = NetworkClient(id: id)\n guard let allocation = try await client.lookup(hostname: hostname) else {\n continue\n }\n return allocation\n }\n return nil\n }\n\n private func registerService(configuration: NetworkConfiguration) async throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported network mode \\(configuration.mode.rawValue)\")\n }\n\n guard let serviceIdentifier = networkPlugin.getMachService(instanceId: configuration.id, type: .network) else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported network mode \\(configuration.mode.rawValue)\")\n }\n var args = [\n \"start\",\n \"--id\",\n configuration.id,\n \"--service-identifier\",\n serviceIdentifier,\n ]\n\n if let subnet = (try configuration.subnet.map { try CIDRAddress($0) }) {\n var existingCidrs: [CIDRAddress] = []\n for networkState in networkStates.values {\n if case .running(_, let status) = networkState {\n existingCidrs.append(try CIDRAddress(status.address))\n }\n }\n let overlap = existingCidrs.first { $0.overlaps(cidr: subnet) }\n if let overlap {\n throw ContainerizationError(.exists, message: \"subnet \\(subnet) overlaps an existing network with subnet \\(overlap)\")\n }\n\n args += [\"--subnet\", subnet.description]\n }\n\n try await pluginLoader.registerWithLaunchd(\n plugin: networkPlugin,\n rootURL: store.entityUrl(configuration.id),\n args: args,\n instanceId: configuration.id\n )\n }\n}\n"], ["/container/Sources/ContainerClient/HostDNSResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n/// Functions for managing local DNS domains for containers.\npublic struct HostDNSResolver {\n public static let defaultConfigPath = URL(filePath: \"/etc/resolver\")\n\n // prefix used to mark our files as /etc/resolver/{prefix}{domainName}\n private static let containerizationPrefix = \"containerization.\"\n\n private let configURL: URL\n\n public init(configURL: URL = Self.defaultConfigPath) {\n self.configURL = configURL\n }\n\n /// Creates a DNS resolver configuration file for domain resolved by the application.\n public func createDomain(name: String) throws {\n let path = self.configURL.appending(path: \"\\(Self.containerizationPrefix)\\(name)\").path\n let fm: FileManager = FileManager.default\n\n if fm.fileExists(atPath: self.configURL.path) {\n guard let isDir = try self.configURL.resourceValues(forKeys: [.isDirectoryKey]).isDirectory, isDir else {\n throw ContainerizationError(.invalidState, message: \"expected \\(self.configURL.path) to be a directory, but found a file\")\n }\n } else {\n try fm.createDirectory(at: self.configURL, withIntermediateDirectories: true)\n }\n\n guard !fm.fileExists(atPath: path) else {\n throw ContainerizationError(.exists, message: \"domain \\(name) already exists\")\n }\n\n let resolverText = \"\"\"\n domain \\(name)\n search \\(name)\n nameserver 127.0.0.1\n port 2053\n \"\"\"\n\n do {\n try resolverText.write(toFile: path, atomically: true, encoding: .utf8)\n } catch {\n throw ContainerizationError(.invalidState, message: \"failed to write resolver configuration for \\(name)\")\n }\n }\n\n /// Removes a DNS resolver configuration file for domain resolved by the application.\n public func deleteDomain(name: String) throws {\n let path = self.configURL.appending(path: \"\\(Self.containerizationPrefix)\\(name)\").path\n let fm = FileManager.default\n guard fm.fileExists(atPath: path) else {\n throw ContainerizationError(.notFound, message: \"domain \\(name) at \\(path) not found\")\n }\n\n do {\n try fm.removeItem(atPath: path)\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot delete domain (try sudo?)\")\n }\n }\n\n /// Lists application-created local DNS domains.\n public func listDomains() -> [String] {\n let fm: FileManager = FileManager.default\n guard\n let resolverPaths = try? fm.contentsOfDirectory(\n at: self.configURL,\n includingPropertiesForKeys: [.isDirectoryKey]\n )\n else {\n return []\n }\n\n return\n resolverPaths\n .filter { $0.lastPathComponent.starts(with: Self.containerizationPrefix) }\n .compactMap { try? getDomainFromResolver(url: $0) }\n .sorted()\n }\n\n /// Reinitializes the macOS DNS daemon.\n public static func reinitialize() throws {\n do {\n let kill = Foundation.Process()\n kill.executableURL = URL(fileURLWithPath: \"/usr/bin/killall\")\n kill.arguments = [\"-HUP\", \"mDNSResponder\"]\n\n let null = FileHandle.nullDevice\n kill.standardOutput = null\n kill.standardError = null\n\n try kill.run()\n kill.waitUntilExit()\n let status = kill.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(.internalError, message: \"mDNSResponder restart failed with status \\(status)\")\n }\n }\n }\n\n private func getDomainFromResolver(url: URL) throws -> String? {\n let text = try String(contentsOf: url, encoding: .utf8)\n for line in text.components(separatedBy: .newlines) {\n let trimmed = line.trimmingCharacters(in: .whitespaces)\n let components = trimmed.split(whereSeparator: { $0.isWhitespace })\n guard components.count == 2 else {\n continue\n }\n guard components[0] == \"domain\" else {\n continue\n }\n\n return String(components[1])\n }\n\n return nil\n }\n}\n"], ["/container/Sources/CLI/Application.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerPlugin\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport TerminalProgress\n\n// `log` is updated only once in the `validate()` method.\nnonisolated(unsafe) var log = {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"CLI\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n log.logLevel = .debug\n return log\n}()\n\n@main\nstruct Application: AsyncParsableCommand {\n @OptionGroup\n var global: Flags.Global\n\n static let configuration = CommandConfiguration(\n commandName: \"container\",\n abstract: \"A container platform for macOS\",\n version: releaseVersion(),\n subcommands: [\n DefaultCommand.self\n ],\n groupedSubcommands: [\n CommandGroup(\n name: \"Container\",\n subcommands: [\n ContainerCreate.self,\n ContainerDelete.self,\n ContainerExec.self,\n ContainerInspect.self,\n ContainerKill.self,\n ContainerList.self,\n ContainerLogs.self,\n ContainerRunCommand.self,\n ContainerStart.self,\n ContainerStop.self,\n ]\n ),\n CommandGroup(\n name: \"Image\",\n subcommands: [\n BuildCommand.self,\n ImagesCommand.self,\n RegistryCommand.self,\n ]\n ),\n CommandGroup(\n name: \"Other\",\n subcommands: Self.otherCommands()\n ),\n ],\n // Hidden command to handle plugins on unrecognized input.\n defaultSubcommand: DefaultCommand.self\n )\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n static let pluginLoader: PluginLoader = {\n let installRoot = CommandLine.executablePathUrl\n .deletingLastPathComponent()\n .appendingPathComponent(\"..\")\n .standardized\n let pluginsURL = PluginLoader.userPluginsDir(root: installRoot)\n var directoryExists: ObjCBool = false\n _ = FileManager.default.fileExists(atPath: pluginsURL.path, isDirectory: &directoryExists)\n let userPluginsURL = directoryExists.boolValue ? pluginsURL : nil\n\n // plugins built into the application installed as a macOS app bundle\n let appBundlePluginsURL = Bundle.main.resourceURL?.appending(path: \"plugins\")\n\n // plugins built into the application installed as a Unix-like application\n let installRootPluginsURL =\n installRoot\n .appendingPathComponent(\"libexec\")\n .appendingPathComponent(\"container\")\n .appendingPathComponent(\"plugins\")\n .standardized\n\n let pluginDirectories = [\n userPluginsURL,\n appBundlePluginsURL,\n installRootPluginsURL,\n ].compactMap { $0 }\n\n let pluginFactories = [\n DefaultPluginFactory()\n ]\n\n let statePath = PluginLoader.defaultPluginResourcePath(root: Self.appRoot)\n try! FileManager.default.createDirectory(at: statePath, withIntermediateDirectories: true)\n return PluginLoader(pluginDirectories: pluginDirectories, pluginFactories: pluginFactories, defaultResourcePath: statePath, log: log)\n }()\n\n public static func main() async throws {\n restoreCursorAtExit()\n\n #if DEBUG\n let warning = \"Running debug build. Performance may be degraded.\"\n let formattedWarning = \"\\u{001B}[33mWarning!\\u{001B}[0m \\(warning)\\n\"\n let warningData = Data(formattedWarning.utf8)\n FileHandle.standardError.write(warningData)\n #endif\n\n let fullArgs = CommandLine.arguments\n let args = Array(fullArgs.dropFirst())\n\n do {\n // container -> defaultHelpCommand\n var command = try Application.parseAsRoot(args)\n if var asyncCommand = command as? AsyncParsableCommand {\n try await asyncCommand.run()\n } else {\n try command.run()\n }\n } catch {\n // Regular ol `command` with no args will get caught by DefaultCommand. --help\n // on the root command will land here.\n let containsHelp = fullArgs.contains(\"-h\") || fullArgs.contains(\"--help\")\n if fullArgs.count <= 2 && containsHelp {\n Self.printModifiedHelpText()\n return\n }\n let errorAsString: String = String(describing: error)\n if errorAsString.contains(\"XPC connection error\") {\n let modifiedError = ContainerizationError(.interrupted, message: \"\\(error)\\nEnsure container system service has been started with `container system start`.\")\n Application.exit(withError: modifiedError)\n } else {\n Application.exit(withError: error)\n }\n }\n }\n\n static func handleProcess(io: ProcessIO, process: ClientProcess) async throws -> Int32 {\n let signals = AsyncSignalHandler.create(notify: Application.signalSet)\n return try await withThrowingTaskGroup(of: Int32?.self, returning: Int32.self) { group in\n let waitAdded = group.addTaskUnlessCancelled {\n let code = try await process.wait()\n try await io.wait()\n return code\n }\n\n guard waitAdded else {\n group.cancelAll()\n return -1\n }\n\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n\n if let current = io.console {\n let size = try current.size\n // It's supremely possible the process could've exited already. We shouldn't treat\n // this as fatal.\n try? await process.resize(size)\n _ = group.addTaskUnlessCancelled {\n let winchHandler = AsyncSignalHandler.create(notify: [SIGWINCH])\n for await _ in winchHandler.signals {\n do {\n try await process.resize(try current.size)\n } catch {\n log.error(\n \"failed to send terminal resize event\",\n metadata: [\n \"error\": \"\\(error)\"\n ]\n )\n }\n }\n return nil\n }\n } else {\n _ = group.addTaskUnlessCancelled {\n for await sig in signals.signals {\n do {\n try await process.kill(sig)\n } catch {\n log.error(\n \"failed to send signal\",\n metadata: [\n \"signal\": \"\\(sig)\",\n \"error\": \"\\(error)\",\n ]\n )\n }\n }\n return nil\n }\n }\n\n while true {\n let result = try await group.next()\n if result == nil {\n return -1\n }\n let status = result!\n if let status {\n group.cancelAll()\n return status\n }\n }\n return -1\n }\n }\n\n func validate() throws {\n // Not really a \"validation\", but a cheat to run this before\n // any of the commands do their business.\n let debugEnvVar = ProcessInfo.processInfo.environment[\"CONTAINER_DEBUG\"]\n if self.global.debug || debugEnvVar != nil {\n log.logLevel = .debug\n }\n // Ensure we're not running under Rosetta.\n if try isTranslated() {\n throw ValidationError(\n \"\"\"\n `container` is currently running under Rosetta Translation, which could be\n caused by your terminal application. Please ensure this is turned off.\n \"\"\"\n )\n }\n }\n\n private static func otherCommands() -> [any ParsableCommand.Type] {\n guard #available(macOS 26, *) else {\n return [\n BuilderCommand.self,\n SystemCommand.self,\n ]\n }\n\n return [\n BuilderCommand.self,\n NetworkCommand.self,\n SystemCommand.self,\n ]\n }\n\n private static func restoreCursorAtExit() {\n let signalHandler: @convention(c) (Int32) -> Void = { signal in\n let exitCode = ExitCode(signal + 128)\n Application.exit(withError: exitCode)\n }\n // Termination by Ctrl+C.\n signal(SIGINT, signalHandler)\n // Termination using `kill`.\n signal(SIGTERM, signalHandler)\n // Normal and explicit exit.\n atexit {\n if let progressConfig = try? ProgressConfig() {\n let progressBar = ProgressBar(config: progressConfig)\n progressBar.resetCursor()\n }\n }\n }\n}\n\nextension Application {\n // Because we support plugins, we need to modify the help text to display\n // any if we found some.\n static func printModifiedHelpText() {\n let altered = Self.pluginLoader.alterCLIHelpText(\n original: Application.helpMessage(for: Application.self)\n )\n print(altered)\n }\n\n enum ListFormat: String, CaseIterable, ExpressibleByArgument {\n case json\n case table\n }\n\n static let signalSet: [Int32] = [\n SIGTERM,\n SIGINT,\n SIGUSR1,\n SIGUSR2,\n SIGWINCH,\n ]\n\n func isTranslated() throws -> Bool {\n do {\n return try Sysctl.byName(\"sysctl.proc_translated\") == 1\n } catch let posixErr as POSIXError {\n if posixErr.code == .ENOENT {\n return false\n }\n throw posixErr\n }\n }\n\n private static func releaseVersion() -> String {\n var versionDetails: [String: String] = [\"build\": \"release\"]\n #if DEBUG\n versionDetails[\"build\"] = \"debug\"\n #endif\n let gitCommit = {\n let sha = get_git_commit().map { String(cString: $0) }\n guard let sha else {\n return \"unspecified\"\n }\n return String(sha.prefix(7))\n }()\n versionDetails[\"commit\"] = gitCommit\n let extras: String = versionDetails.map { \"\\($0): \\($1)\" }.sorted().joined(separator: \", \")\n\n let bundleVersion = (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String)\n let releaseVersion = bundleVersion ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n\n return \"container CLI version \\(releaseVersion) (\\(extras))\"\n }\n}\n"], ["/container/Sources/APIServer/Plugin/PluginsService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerPlugin\nimport Foundation\nimport Logging\n\nactor PluginsService {\n private let log: Logger\n private var loaded: [String: Plugin]\n private let pluginLoader: PluginLoader\n\n public init(pluginLoader: PluginLoader, log: Logger) {\n self.log = log\n self.loaded = [:]\n self.pluginLoader = pluginLoader\n }\n\n /// Load the specified plugins, or all plugins with services defined\n /// if none are explicitly specified.\n public func loadAll(\n _ plugins: [Plugin]? = nil,\n ) throws {\n let registerPlugins = plugins ?? pluginLoader.findPlugins()\n for plugin in registerPlugins {\n try pluginLoader.registerWithLaunchd(plugin: plugin)\n loaded[plugin.name] = plugin\n }\n }\n\n /// Stop the specified plugins, or all plugins with services defined\n /// if none are explicitly specified.\n public func stopAll(_ plugins: [Plugin]? = nil) throws {\n let deregisterPlugins = plugins ?? pluginLoader.findPlugins()\n for plugin in deregisterPlugins {\n try pluginLoader.deregisterWithLaunchd(plugin: plugin)\n self.loaded.removeValue(forKey: plugin.name)\n }\n }\n\n // MARK: XPC API surface.\n\n /// Load a single plugin, doing nothing if the plugin is already loaded.\n public func load(name: String) throws {\n guard self.loaded[name] == nil else {\n return\n }\n guard let plugin = pluginLoader.findPlugin(name: name) else {\n throw Error.pluginNotFound(name)\n }\n try pluginLoader.registerWithLaunchd(plugin: plugin)\n self.loaded[plugin.name] = plugin\n }\n\n /// Get information for a loaded plugin.\n public func get(name: String) throws -> Plugin {\n guard let plugin = loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n return plugin\n }\n\n /// Restart a loaded plugin.\n public func restart(name: String) throws {\n guard let plugin = self.loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n try ServiceManager.kickstart(fullServiceLabel: plugin.getLaunchdLabel())\n }\n\n /// Unload a loaded plugin.\n public func unload(name: String) throws {\n guard let plugin = self.loaded[name] else {\n throw Error.pluginNotLoaded(name)\n }\n try pluginLoader.deregisterWithLaunchd(plugin: plugin)\n self.loaded.removeValue(forKey: plugin.name)\n }\n\n /// List all loaded plugins.\n public func list() throws -> [Plugin] {\n self.loaded.map { $0.value }\n }\n\n public enum Error: Swift.Error, CustomStringConvertible {\n case pluginNotFound(String)\n case pluginNotLoaded(String)\n\n public var description: String {\n switch self {\n case .pluginNotFound(let name):\n return \"plugin not found: \\(name)\"\n case .pluginNotLoaded(let name):\n return \"plugin not loaded: \\(name)\"\n }\n }\n }\n}\n"], ["/container/Sources/APIServer/Kernel/KernelService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\nimport TerminalProgress\n\nactor KernelService {\n private static let defaultKernelNamePrefix: String = \"default.kernel-\"\n\n private let log: Logger\n private let kernelDirectory: URL\n\n public init(log: Logger, appRoot: URL) throws {\n self.log = log\n self.kernelDirectory = appRoot.appending(path: \"kernels\")\n try FileManager.default.createDirectory(at: self.kernelDirectory, withIntermediateDirectories: true)\n }\n\n /// Copies a kernel binary from a local path on disk into the managed kernels directory\n /// as the default kernel for the provided platform.\n public func installKernel(kernelFile url: URL, platform: SystemPlatform = .linuxArm) throws {\n self.log.info(\"KernelService: \\(#function) - kernelFile: \\(url), platform: \\(String(describing: platform))\")\n let kFile = url.resolvingSymlinksInPath()\n let destPath = self.kernelDirectory.appendingPathComponent(kFile.lastPathComponent)\n try FileManager.default.copyItem(at: kFile, to: destPath)\n try Task.checkCancellation()\n do {\n try self.setDefaultKernel(name: kFile.lastPathComponent, platform: platform)\n } catch {\n try? FileManager.default.removeItem(at: destPath)\n throw error\n }\n }\n\n /// Copies a kernel binary from inside of tar file into the managed kernels directory\n /// as the default kernel for the provided platform.\n /// The parameter `tar` maybe a location to a local file on disk, or a remote URL.\n public func installKernelFrom(tar: URL, kernelFilePath: String, platform: SystemPlatform, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"KernelService: \\(#function) - tar: \\(tar), kernelFilePath: \\(kernelFilePath), platform: \\(String(describing: platform))\")\n\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n\n await progressUpdate?([\n .setDescription(\"Downloading kernel\")\n ])\n let taskManager = ProgressTaskCoordinator()\n let downloadTask = await taskManager.startTask()\n var tarFile = tar\n if !FileManager.default.fileExists(atPath: tar.absoluteString) {\n self.log.debug(\"KernelService: Downloading \\(tar)\")\n tarFile = tempDir.appendingPathComponent(tar.lastPathComponent)\n var downloadProgressUpdate: ProgressUpdateHandler?\n if let progressUpdate {\n downloadProgressUpdate = ProgressTaskCoordinator.handler(for: downloadTask, from: progressUpdate)\n }\n try await FileDownloader.downloadFile(url: tar, to: tarFile, progressUpdate: downloadProgressUpdate)\n }\n await taskManager.finish()\n\n await progressUpdate?([\n .setDescription(\"Unpacking kernel\")\n ])\n let archiveReader = try ArchiveReader(file: tarFile)\n let kernelFile = try archiveReader.extractFile(from: kernelFilePath, to: tempDir)\n try self.installKernel(kernelFile: kernelFile, platform: platform)\n\n if !FileManager.default.fileExists(atPath: tar.absoluteString) {\n try FileManager.default.removeItem(at: tarFile)\n }\n }\n\n private func setDefaultKernel(name: String, platform: SystemPlatform) throws {\n self.log.info(\"KernelService: \\(#function) - name: \\(name), platform: \\(String(describing: platform))\")\n let kernelPath = self.kernelDirectory.appendingPathComponent(name)\n guard FileManager.default.fileExists(atPath: kernelPath.path) else {\n throw ContainerizationError(.notFound, message: \"Kernel not found at \\(kernelPath)\")\n }\n let name = \"\\(Self.defaultKernelNamePrefix)\\(platform.architecture)\"\n let defaultKernelPath = self.kernelDirectory.appendingPathComponent(name)\n try? FileManager.default.removeItem(at: defaultKernelPath)\n try FileManager.default.createSymbolicLink(at: defaultKernelPath, withDestinationURL: kernelPath)\n }\n\n public func getDefaultKernel(platform: SystemPlatform = .linuxArm) async throws -> Kernel {\n self.log.info(\"KernelService: \\(#function) - platform: \\(String(describing: platform))\")\n let name = \"\\(Self.defaultKernelNamePrefix)\\(platform.architecture)\"\n let defaultKernelPath = self.kernelDirectory.appendingPathComponent(name).resolvingSymlinksInPath()\n guard FileManager.default.fileExists(atPath: defaultKernelPath.path) else {\n throw ContainerizationError(.notFound, message: \"Default kernel not found at \\(defaultKernelPath)\")\n }\n return Kernel(path: defaultKernelPath, platform: platform)\n }\n}\n\nextension ArchiveReader {\n fileprivate func extractFile(from: String, to directory: URL) throws -> URL {\n let (_, data) = try self.extractFile(path: from)\n try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)\n let fileName = URL(filePath: from).lastPathComponent\n let fileURL = directory.appendingPathComponent(fileName)\n try data.write(to: fileURL, options: .atomic)\n return fileURL\n }\n}\n"], ["/container/Sources/ContainerPlugin/ServiceManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\npublic struct ServiceManager {\n private static func runLaunchctlCommand(args: [String]) throws -> Int32 {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = args\n\n let null = FileHandle.nullDevice\n launchctl.standardOutput = null\n launchctl.standardError = null\n\n try launchctl.run()\n launchctl.waitUntilExit()\n\n return launchctl.terminationStatus\n }\n\n /// Register a service by providing the path to a plist.\n public static func register(plistPath: String) throws {\n let domain = try Self.getDomainString()\n _ = try runLaunchctlCommand(args: [\"bootstrap\", domain, plistPath])\n }\n\n /// Deregister a service by a launchd label.\n public static func deregister(fullServiceLabel label: String) throws {\n _ = try runLaunchctlCommand(args: [\"bootout\", label])\n }\n\n /// Restart a service by a launchd label.\n public static func kickstart(fullServiceLabel label: String) throws {\n _ = try runLaunchctlCommand(args: [\"kickstart\", \"-k\", label])\n }\n\n /// Send a signal to a service by a launchd label.\n public static func kill(fullServiceLabel label: String, signal: Int32 = 15) throws {\n _ = try runLaunchctlCommand(args: [\"kill\", \"\\(signal)\", label])\n }\n\n /// Retrieve labels for all loaded launch units.\n public static func enumerate() throws -> [String] {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = [\"list\"]\n\n let stdoutPipe = Pipe()\n let stderrPipe = Pipe()\n launchctl.standardOutput = stdoutPipe\n launchctl.standardError = stderrPipe\n\n try launchctl.run()\n let outputData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()\n let stderrData = stderrPipe.fileHandleForReading.readDataToEndOfFile()\n launchctl.waitUntilExit()\n let status = launchctl.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(\n .internalError, message: \"Command `launchctl list` failed with status \\(status). Message: \\(String(data: stderrData, encoding: .utf8) ?? \"No error message\")\")\n }\n\n guard let outputText = String(data: outputData, encoding: .utf8) else {\n throw ContainerizationError(\n .internalError, message: \"Could not decode output of command `launchctl list`. Message: \\(String(data: stderrData, encoding: .utf8) ?? \"No error message\")\")\n }\n\n // The third field of each line of launchctl list output is the label\n return outputText.split { $0.isNewline }\n .map { String($0).split { $0.isWhitespace } }\n .filter { $0.count >= 3 }\n .map { String($0[2]) }\n }\n\n /// Check if a service has been registered or not.\n public static func isRegistered(fullServiceLabel label: String) throws -> Bool {\n let exitStatus = try runLaunchctlCommand(args: [\"list\", label])\n return exitStatus == 0\n }\n\n private static func getLaunchdSessionType() throws -> String {\n let launchctl = Foundation.Process()\n launchctl.executableURL = URL(fileURLWithPath: \"/bin/launchctl\")\n launchctl.arguments = [\"managername\"]\n\n let null = FileHandle.nullDevice\n let stdoutPipe = Pipe()\n launchctl.standardOutput = stdoutPipe\n launchctl.standardError = null\n\n try launchctl.run()\n let outputData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()\n launchctl.waitUntilExit()\n let status = launchctl.terminationStatus\n guard status == 0 else {\n throw ContainerizationError(.internalError, message: \"Command `launchctl managername` failed with status \\(status)\")\n }\n guard let outputText = String(data: outputData, encoding: .utf8) else {\n throw ContainerizationError(.internalError, message: \"Could not decode output of command `launchctl managername`\")\n }\n return outputText.trimmingCharacters(in: .whitespacesAndNewlines)\n }\n\n public static func getDomainString() throws -> String {\n let currentSessionType = try getLaunchdSessionType()\n switch currentSessionType {\n case LaunchPlist.Domain.System.rawValue:\n return LaunchPlist.Domain.System.rawValue.lowercased()\n case LaunchPlist.Domain.Background.rawValue:\n return \"user/\\(getuid())\"\n case LaunchPlist.Domain.Aqua.rawValue:\n return \"gui/\\(getuid())\"\n default:\n throw ContainerizationError(.internalError, message: \"Unsupported session type \\(currentSessionType)\")\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/PluginFactory.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\nprivate let configFilename: String = \"config.json\"\n\n/// Describes the configuration and binary file locations for a plugin.\npublic protocol PluginFactory: Sendable {\n /// Create a plugin conforming to the layout, if possible.\n func create(installURL: URL) throws -> Plugin?\n}\n\n/// Default layout which uses a Unix-like structure.\npublic struct DefaultPluginFactory: PluginFactory {\n public init() {}\n\n public func create(installURL: URL) throws -> Plugin? {\n let fm = FileManager.default\n\n let configURL = installURL.appending(path: configFilename)\n guard fm.fileExists(atPath: configURL.path) else {\n return nil\n }\n\n guard let config = try PluginConfig(configURL: configURL) else {\n return nil\n }\n\n let name = installURL.lastPathComponent\n let binaryURL = installURL.appending(path: \"bin\").appending(path: name)\n guard fm.fileExists(atPath: binaryURL.path) else {\n return nil\n }\n\n return Plugin(binaryURL: binaryURL, config: config)\n }\n}\n\n/// Layout which uses a macOS application bundle structure.\npublic struct AppBundlePluginFactory: PluginFactory {\n private static let appSuffix = \".app\"\n\n public init() {}\n\n public func create(installURL: URL) throws -> Plugin? {\n let fm = FileManager.default\n\n let configURL =\n installURL\n .appending(path: \"Contents\")\n .appending(path: \"Resources\")\n .appending(path: configFilename)\n guard fm.fileExists(atPath: configURL.path) else {\n return nil\n }\n\n guard let config = try PluginConfig(configURL: configURL) else {\n return nil\n }\n\n let appName = installURL.lastPathComponent\n guard appName.hasSuffix(Self.appSuffix) else {\n return nil\n }\n let name = String(appName.dropLast(Self.appSuffix.count))\n let binaryURL =\n installURL\n .appending(path: \"Contents\")\n .appending(path: \"MacOS\")\n .appending(path: name)\n guard fm.fileExists(atPath: binaryURL.path) else {\n return nil\n }\n\n return Plugin(binaryURL: binaryURL, config: config)\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/SandboxService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\nimport SocketForwarder\n\nimport struct ContainerizationOCI.Mount\nimport struct ContainerizationOCI.Process\n\n/// An XPC service that manages the lifecycle of a single VM-backed container.\npublic actor SandboxService {\n private let root: URL\n private let interfaceStrategy: InterfaceStrategy\n private var container: ContainerInfo?\n private let monitor: ExitMonitor\n private let eventLoopGroup: any EventLoopGroup\n private var waiters: [String: [CheckedContinuation]] = [:]\n private let lock: AsyncLock = AsyncLock()\n private let log: Logging.Logger\n private var state: State = .created\n private var processes: [String: ProcessInfo] = [:]\n private var socketForwarders: [SocketForwarderResult] = []\n\n /// Create an instance with a bundle that describes the container.\n ///\n /// - Parameters:\n /// - root: The file URL for the bundle root.\n /// - interfaceStrategy: The strategy for producing network interface\n /// objects for each network to which the container attaches.\n /// - log: The destination for log messages.\n public init(root: URL, interfaceStrategy: InterfaceStrategy, eventLoopGroup: any EventLoopGroup, log: Logger) {\n self.root = root\n self.interfaceStrategy = interfaceStrategy\n self.log = log\n self.monitor = ExitMonitor(log: log)\n self.eventLoopGroup = eventLoopGroup\n }\n\n /// Start the VM and the guest agent process for a container.\n ///\n /// - Parameters:\n /// - message: An XPC message with no parameters.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func bootstrap(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`bootstrap` xpc handler\")\n return try await self.lock.withLock { _ in\n guard await self.state == .created else {\n throw ContainerizationError(\n .invalidState,\n message: \"container expected to be in created state, got: \\(await self.state)\"\n )\n }\n\n let bundle = ContainerClient.Bundle(path: self.root)\n try bundle.createLogFile()\n\n let vmm = VZVirtualMachineManager(\n kernel: try bundle.kernel,\n initialFilesystem: bundle.initialFilesystem.asMount,\n bootlog: bundle.bootlog.path,\n logger: self.log\n )\n var config = try bundle.configuration\n let container = LinuxContainer(\n config.id,\n rootfs: try bundle.containerRootfs.asMount,\n vmm: vmm,\n logger: self.log\n )\n\n // dynamically configure the DNS nameserver from a network if no explicit configuration\n if let dns = config.dns, dns.nameservers.isEmpty {\n if let nameserver = try await self.getDefaultNameserver(networks: config.networks) {\n config.dns = ContainerConfiguration.DNSConfiguration(\n nameservers: [nameserver],\n domain: dns.domain,\n searchDomains: dns.searchDomains,\n options: dns.options\n )\n }\n }\n\n try await self.configureContainer(container: container, config: config)\n\n let fqdn: String\n if let hostname = config.hostname {\n if let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName),\n let dnsDomain = suite.string(forKey: \"dns.domain\"),\n !hostname.contains(\".\")\n {\n // TODO: Make the suiteName a constant defined in ClientDefaults and use that.\n // This will need some re-working of dependencies between SandboxService and Client\n fqdn = \"\\(hostname).\\(dnsDomain).\"\n } else {\n fqdn = \"\\(hostname).\"\n }\n } else {\n fqdn = config.id\n }\n\n var attachments: [Attachment] = []\n for index in 0.. XPCMessage {\n self.log.info(\"`start` xpc handler\")\n return try await self.lock.withLock { lock in\n let id = try message.id()\n let stdio = message.stdio()\n let containerInfo = try await self.getContainer()\n let containerId = containerInfo.container.id\n if id == containerId {\n try await self.startInitProcess(stdio: stdio, lock: lock)\n await self.setState(.running)\n try await self.sendContainerEvent(.containerStart(id: id))\n } else {\n try await self.startExecProcess(processId: id, stdio: stdio, lock: lock)\n }\n return message.reply()\n }\n }\n\n private func startInitProcess(stdio: [FileHandle?], lock: AsyncLock.Context) async throws {\n let info = try self.getContainer()\n let container = info.container\n let bundle = info.bundle\n let id = container.id\n guard self.state == .booted else {\n throw ContainerizationError(\n .invalidState,\n message: \"container expected to be in booted state, got: \\(self.state)\"\n )\n }\n let containerLog = try FileHandle(forWritingTo: bundle.containerLog)\n let config = info.config\n let stdout = {\n if let h = stdio[1] {\n return MultiWriter(handles: [h, containerLog])\n }\n return MultiWriter(handles: [containerLog])\n }()\n let stderr: MultiWriter? = {\n if !config.initProcess.terminal {\n if let h = stdio[2] {\n return MultiWriter(handles: [h, containerLog])\n }\n return MultiWriter(handles: [containerLog])\n }\n return nil\n }()\n if let h = stdio[0] {\n container.stdin = h\n }\n container.stdout = stdout\n if let stderr {\n container.stderr = stderr\n }\n self.setState(.starting)\n do {\n try await container.start()\n let waitFunc: ExitMonitor.WaitHandler = {\n let code = try await container.wait()\n if let out = stdio[1] {\n try self.closeHandle(out.fileDescriptor)\n }\n if let err = stdio[2] {\n try self.closeHandle(err.fileDescriptor)\n }\n return code\n }\n try await self.monitor.track(id: id, waitingOn: waitFunc)\n } catch {\n try? await self.cleanupContainer()\n self.setState(.created)\n try await self.sendContainerEvent(.containerExit(id: id, exitCode: -1))\n throw error\n }\n }\n\n private func startExecProcess(processId id: String, stdio: [FileHandle?], lock: AsyncLock.Context) async throws {\n let container = try self.getContainer().container\n guard let processInfo = self.processes[id] else {\n throw ContainerizationError(.notFound, message: \"Process with id \\(id)\")\n }\n let ociConfig = self.configureProcessConfig(config: processInfo.config)\n let stdin: ReaderStream? = {\n if let h = stdio[0] {\n return h\n }\n return nil\n }()\n let process = try await container.exec(\n id,\n configuration: ociConfig,\n stdin: stdin,\n stdout: stdio[1],\n stderr: stdio[2]\n )\n try self.setUnderlyingProcess(id, process)\n try await process.start()\n let waitFunc: ExitMonitor.WaitHandler = {\n let code = try await process.wait()\n if let out = stdio[1] {\n try self.closeHandle(out.fileDescriptor)\n }\n if let err = stdio[2] {\n try self.closeHandle(err.fileDescriptor)\n }\n return code\n }\n try await self.monitor.track(id: id, waitingOn: waitFunc)\n }\n\n private func startSocketForwarders(containerIpAddress: String, publishedPorts: [PublishPort]) async throws {\n var forwarders: [SocketForwarderResult] = []\n try await withThrowingTaskGroup(of: SocketForwarderResult.self) { group in\n for publishedPort in publishedPorts {\n let proxyAddress = try SocketAddress(ipAddress: publishedPort.hostAddress, port: Int(publishedPort.hostPort))\n let serverAddress = try SocketAddress(ipAddress: containerIpAddress, port: Int(publishedPort.containerPort))\n log.info(\n \"creating forwarder for\",\n metadata: [\n \"proxy\": \"\\(proxyAddress)\",\n \"server\": \"\\(serverAddress)\",\n \"protocol\": \"\\(publishedPort.proto)\",\n ])\n group.addTask {\n let forwarder: SocketForwarder\n switch publishedPort.proto {\n case .tcp:\n forwarder = try TCPForwarder(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: self.log\n )\n case .udp:\n forwarder = try UDPForwarder(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: self.log\n )\n }\n return try await forwarder.run().get()\n }\n }\n for try await result in group {\n forwarders.append(result)\n }\n }\n\n self.socketForwarders = forwarders\n }\n\n private func stopSocketForwarders() async {\n log.info(\"closing forwarders\")\n for forwarder in self.socketForwarders {\n forwarder.close()\n try? await forwarder.wait()\n }\n log.info(\"closed forwarders\")\n }\n\n /// Create a process inside the virtual machine for the container.\n ///\n /// Use this procedure to run ad hoc processes in the virtual\n /// machine (`container exec`).\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: A client identifier for the process.\n /// - processConfig: JSON serialization of the `ProcessConfiguration`\n /// containing the process attributes.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func createProcess(_ message: XPCMessage) async throws -> XPCMessage {\n log.info(\"`createProcess` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped(_), .starting, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot exec: container is not running\"\n )\n case .running, .booted:\n let id = try message.id()\n let config = try message.processConfig()\n await self.addNewProcess(id, config)\n try await self.monitor.registerProcess(\n id: id,\n onExit: { id, code in\n guard let process = await self.processes[id]?.process else {\n throw ContainerizationError(.invalidState, message: \"ProcessInfo missing for process \\(id)\")\n }\n for cc in await self.waiters[id] ?? [] {\n cc.resume(returning: code)\n }\n await self.removeWaiters(for: id)\n try await process.delete()\n try await self.setProcessState(id: id, state: .stopped(code))\n })\n return message.reply()\n }\n }\n }\n\n /// Return the state for the sandbox and its containers.\n ///\n /// - Parameters:\n /// - message: An XPC message with no parameters.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - snapshot: The JSON serialization of the `SandboxSnapshot`\n /// that contains the state information.\n @Sendable\n public func state(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`state` xpc handler\")\n var status: RuntimeStatus = .unknown\n var networks: [Attachment] = []\n var cs: ContainerSnapshot?\n\n switch state {\n case .created, .stopped(_), .starting, .booted:\n status = .stopped\n case .stopping:\n status = .stopping\n case .running:\n let ctr = try getContainer()\n\n status = .running\n networks = ctr.attachments\n cs = ContainerSnapshot(\n configuration: ctr.config,\n status: RuntimeStatus.running,\n networks: networks\n )\n }\n\n let reply = message.reply()\n try reply.setState(\n .init(\n status: status,\n networks: networks,\n containers: cs != nil ? [cs!] : []\n )\n )\n return reply\n }\n\n /// Stop the container workload, any ad hoc processes, and the underlying\n /// virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - stopOptions: JSON serialization of `ContainerStopOptions`\n /// that modify stop behavior.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func stop(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`stop` xpc handler\")\n let reply = try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .stopped(_), .created, .stopping:\n return message.reply()\n case .starting:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot stop: container is not running\"\n )\n case .running, .booted:\n let ctr = try await getContainer()\n let stopOptions = try message.stopOptions()\n do {\n try await gracefulStopContainer(\n ctr.container,\n stopOpts: stopOptions\n )\n } catch {\n log.notice(\"failed to stop sandbox gracefully: \\(error)\")\n }\n await setState(.stopping)\n return message.reply()\n }\n }\n do {\n try await cleanupContainer()\n } catch {\n self.log.error(\"failed to cleanup container: \\(error)\")\n }\n return reply\n }\n\n /// Signal a process running in the virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n /// - signal: The signal value.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func kill(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`kill` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped, .starting, .booted, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot kill: container is not running\"\n )\n case .running:\n let ctr = try await getContainer()\n let id = try message.id()\n if id != ctr.container.id {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) does not exist\")\n }\n\n guard let proc = processInfo.process else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not started\")\n }\n try await proc.kill(Int32(try message.signal()))\n return message.reply()\n }\n\n // TODO: fix underlying signal value to int64\n try await ctr.container.kill(Int32(try message.signal()))\n return message.reply()\n }\n }\n }\n\n /// Resize the terminal for a process.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n /// - width: The terminal width.\n /// - height: The terminal height.\n ///\n /// - Returns: An XPC message with no parameters.\n @Sendable\n public func resize(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`resize` xpc handler\")\n return try await self.lock.withLock { [self] _ in\n switch await self.state {\n case .created, .stopped, .starting, .booted, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot resize: container is not running\"\n )\n case .running:\n let id = try message.id()\n let ctr = try await getContainer()\n let width = message.uint64(key: .width)\n let height = message.uint64(key: .height)\n if id != ctr.container.id {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) does not exist\")\n }\n\n guard let proc = processInfo.process else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not started\")\n }\n\n try await proc.resize(to: .init(width: UInt16(width), height: UInt16(height)))\n return message.reply()\n }\n\n try await ctr.container.resize(to: .init(width: UInt16(width), height: UInt16(height)))\n return message.reply()\n }\n }\n }\n\n /// Wait for a process.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - id: The process identifier.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - exitCode: The exit code for the process.\n @Sendable\n public func wait(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`wait` xpc handler\")\n guard let id = message.string(key: .id) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing id in wait xpc message\")\n }\n\n let cachedCode: Int32? = try await self.lock.withLock { _ in\n let ctrInfo = try await self.getContainer()\n let ctr = ctrInfo.container\n if id == ctr.id {\n switch await self.state {\n case .stopped(let code):\n return code\n default:\n break\n }\n } else {\n guard let processInfo = await self.processes[id] else {\n throw ContainerizationError(.notFound, message: \"Process with id \\(id)\")\n }\n switch processInfo.state {\n case .stopped(let code):\n return code\n default:\n break\n }\n }\n return nil\n }\n if let cachedCode {\n let reply = message.reply()\n reply.set(key: .exitCode, value: Int64(cachedCode))\n return reply\n }\n\n let exitCode = await withCheckedContinuation { cc in\n // Is this safe since we are in an actor? :(\n self.addWaiter(id: id, cont: cc)\n }\n let reply = message.reply()\n reply.set(key: .exitCode, value: Int64(exitCode))\n return reply\n }\n\n /// Dial a vsock port on the virtual machine.\n ///\n /// - Parameters:\n /// - message: An XPC message with the following parameters:\n /// - port: The port number.\n ///\n /// - Returns: An XPC message with the following parameters:\n /// - fd: The file descriptor for the vsock.\n @Sendable\n public func dial(_ message: XPCMessage) async throws -> XPCMessage {\n self.log.info(\"`dial` xpc handler\")\n switch self.state {\n case .starting, .created, .stopped, .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"cannot dial: container is not running\"\n )\n case .running, .booted:\n let port = message.uint64(key: .port)\n guard port > 0 else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"no vsock port supplied for dial\"\n )\n }\n\n let ctr = try getContainer()\n let fh = try await ctr.container.dialVsock(port: UInt32(port))\n\n let reply = message.reply()\n reply.set(key: .fd, value: fh)\n return reply\n }\n }\n\n private func onContainerExit(id: String, code: Int32) async throws {\n self.log.info(\"init process exited with: \\(code)\")\n\n try await self.lock.withLock { [self] _ in\n let ctrInfo = try await getContainer()\n let ctr = ctrInfo.container\n // Did someone explicitly call stop and we're already\n // cleaning up?\n switch await self.state {\n case .stopped(_):\n return\n default:\n break\n }\n\n do {\n try await ctr.stop()\n } catch {\n log.notice(\"failed to stop sandbox gracefully: \\(error)\")\n }\n\n do {\n try await cleanupContainer()\n } catch {\n self.log.error(\"failed to cleanup container: \\(error)\")\n }\n await setState(.stopped(code))\n let waiters = await self.waiters[id] ?? []\n for cc in waiters {\n cc.resume(returning: code)\n }\n await self.removeWaiters(for: id)\n try await self.sendContainerEvent(.containerExit(id: id, exitCode: Int64(code)))\n exit(code)\n }\n }\n\n private func configureContainer(container: LinuxContainer, config: ContainerConfiguration) throws {\n container.cpus = config.resources.cpus\n container.memoryInBytes = config.resources.memoryInBytes\n container.rosetta = config.rosetta\n container.sysctl = config.sysctls.reduce(into: [String: String]()) {\n $0[$1.key] = $1.value\n }\n\n for mount in config.mounts {\n if try mount.isSocket() {\n let socket = UnixSocketConfiguration(\n source: URL(filePath: mount.source),\n destination: URL(filePath: mount.destination)\n )\n container.sockets.append(socket)\n } else {\n container.mounts.append(mount.asMount)\n }\n }\n\n for publishedSocket in config.publishedSockets {\n let socketConfig = UnixSocketConfiguration(\n source: publishedSocket.containerPath,\n destination: publishedSocket.hostPath,\n permissions: publishedSocket.permissions,\n direction: .outOf\n )\n container.sockets.append(socketConfig)\n }\n\n container.hostname = config.hostname ?? config.id\n\n if let dns = config.dns {\n container.dns = DNS(\n nameservers: dns.nameservers, domain: dns.domain,\n searchDomains: dns.searchDomains, options: dns.options)\n }\n\n configureInitialProcess(container: container, process: config.initProcess)\n }\n\n private func getDefaultNameserver(networks: [String]) async throws -> String? {\n for network in networks {\n let client = NetworkClient(id: network)\n let state = try await client.state()\n guard case .running(_, let status) = state else {\n continue\n }\n return status.gateway\n }\n\n return nil\n }\n\n private func configureInitialProcess(container: LinuxContainer, process: ProcessConfiguration) {\n container.arguments = [process.executable] + process.arguments\n container.environment = modifyingEnvironment(process)\n container.terminal = process.terminal\n container.workingDirectory = process.workingDirectory\n container.rlimits = process.rlimits.map {\n .init(type: $0.limit, hard: $0.hard, soft: $0.soft)\n }\n switch process.user {\n case .raw(let name):\n container.user = .init(\n uid: 0,\n gid: 0,\n umask: nil,\n additionalGids: process.supplementalGroups,\n username: name\n )\n case .id(let uid, let gid):\n container.user = .init(\n uid: uid,\n gid: gid,\n umask: nil,\n additionalGids: process.supplementalGroups,\n username: \"\"\n )\n }\n }\n\n private nonisolated func configureProcessConfig(config: ProcessConfiguration) -> ContainerizationOCI.Process {\n var proc = ContainerizationOCI.Process()\n proc.args = [config.executable] + config.arguments\n proc.env = modifyingEnvironment(config)\n proc.terminal = config.terminal\n proc.cwd = config.workingDirectory\n proc.rlimits = config.rlimits.map {\n .init(type: $0.limit, hard: $0.hard, soft: $0.soft)\n }\n switch config.user {\n case .raw(let name):\n proc.user = .init(\n uid: 0,\n gid: 0,\n umask: nil,\n additionalGids: config.supplementalGroups,\n username: name\n )\n case .id(let uid, let gid):\n proc.user = .init(\n uid: uid,\n gid: gid,\n umask: nil,\n additionalGids: config.supplementalGroups,\n username: \"\"\n )\n }\n\n return proc\n }\n\n private nonisolated func closeHandle(_ handle: Int32) throws {\n guard close(handle) == 0 else {\n guard let errCode = POSIXErrorCode(rawValue: errno) else {\n fatalError(\"failed to convert errno to POSIXErrorCode\")\n }\n throw POSIXError(errCode)\n }\n }\n\n private nonisolated func modifyingEnvironment(_ config: ProcessConfiguration) -> [String] {\n guard config.terminal else {\n return config.environment\n }\n // Prepend the TERM env var. If the user has it specified our value will be overridden.\n return [\"TERM=xterm\"] + config.environment\n }\n\n private func getContainer() throws -> ContainerInfo {\n guard let container else {\n throw ContainerizationError(\n .invalidState,\n message: \"no container found\"\n )\n }\n return container\n }\n\n private func gracefulStopContainer(_ lc: LinuxContainer, stopOpts: ContainerStopOptions) async throws {\n // Try and gracefully shut down the process. Even if this succeeds we need to power off\n // the vm, but we should try this first always.\n do {\n try await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n try await lc.wait()\n }\n group.addTask {\n try await lc.kill(stopOpts.signal)\n try await Task.sleep(for: .seconds(stopOpts.timeoutInSeconds))\n try await lc.kill(SIGKILL)\n }\n try await group.next()\n group.cancelAll()\n }\n } catch {}\n // Now actually bring down the vm.\n try await lc.stop()\n }\n\n private func cleanupContainer() async throws {\n // Give back our lovely IP(s)\n await self.stopSocketForwarders()\n let containerInfo = try self.getContainer()\n for attachment in containerInfo.attachments {\n let client = NetworkClient(id: attachment.network)\n do {\n try await client.deallocate(hostname: attachment.hostname)\n } catch {\n self.log.error(\"failed to deallocate hostname \\(attachment.hostname) on network \\(attachment.network): \\(error)\")\n }\n }\n }\n\n private func sendContainerEvent(_ event: ContainerEvent) async throws {\n let serviceIdentifier = \"com.apple.container.apiserver\"\n let client = XPCClient(service: serviceIdentifier)\n let message = XPCMessage(route: .containerEvent)\n\n let data = try JSONEncoder().encode(event)\n message.set(key: .containerEvent, value: data)\n try await client.send(message)\n }\n\n}\n\nextension XPCMessage {\n fileprivate func signal() throws -> Int64 {\n self.int64(key: .signal)\n }\n\n fileprivate func stopOptions() throws -> ContainerStopOptions {\n guard let data = self.dataNoCopy(key: .stopOptions) else {\n throw ContainerizationError(.invalidArgument, message: \"empty StopOptions\")\n }\n return try JSONDecoder().decode(ContainerStopOptions.self, from: data)\n }\n\n fileprivate func setState(_ state: SandboxSnapshot) throws {\n let data = try JSONEncoder().encode(state)\n self.set(key: .snapshot, value: data)\n }\n\n fileprivate func stdio() -> [FileHandle?] {\n var handles = [FileHandle?](repeating: nil, count: 3)\n if let stdin = self.fileHandle(key: .stdin) {\n handles[0] = stdin\n }\n if let stdout = self.fileHandle(key: .stdout) {\n handles[1] = stdout\n }\n if let stderr = self.fileHandle(key: .stderr) {\n handles[2] = stderr\n }\n return handles\n }\n\n fileprivate func setFileHandle(_ handle: FileHandle) {\n self.set(key: .fd, value: handle)\n }\n\n fileprivate func processConfig() throws -> ProcessConfiguration {\n guard let data = self.dataNoCopy(key: .processConfig) else {\n throw ContainerizationError(.invalidArgument, message: \"empty process configuration\")\n }\n return try JSONDecoder().decode(ProcessConfiguration.self, from: data)\n }\n}\n\nextension ContainerClient.Bundle {\n /// The pathname for the workload log file.\n public var containerLog: URL {\n path.appendingPathComponent(\"stdio.log\")\n }\n\n func createLogFile() throws {\n // Create the log file we'll write stdio to.\n // O_TRUNC resolves a log delay issue on restarted containers by force-updating internal state\n let fd = Darwin.open(self.containerLog.path, O_CREAT | O_RDONLY | O_TRUNC, 0o644)\n guard fd > 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n close(fd)\n }\n}\n\nextension Filesystem {\n var asMount: Containerization.Mount {\n switch self.type {\n case .tmpfs:\n return .any(\n type: \"tmpfs\",\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n case .virtiofs:\n return .share(\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n case .block(let format, _, _):\n return .block(\n format: format,\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n }\n }\n\n func isSocket() throws -> Bool {\n if !self.isVirtiofs {\n return false\n }\n let info = try File.info(self.source)\n return info.isSocket\n }\n}\n\nstruct MultiWriter: Writer {\n let handles: [FileHandle]\n\n func write(_ data: Data) throws {\n for handle in self.handles {\n try handle.write(contentsOf: data)\n }\n }\n}\n\nextension FileHandle: @retroactive ReaderStream, @retroactive Writer {\n public func write(_ data: Data) throws {\n try self.write(contentsOf: data)\n }\n\n public func stream() -> AsyncStream {\n .init { cont in\n self.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n self.readabilityHandler = nil\n cont.finish()\n return\n }\n cont.yield(data)\n }\n }\n }\n}\n\n// MARK: State handler helpers\n\nextension SandboxService {\n private func addWaiter(id: String, cont: CheckedContinuation) {\n var current = self.waiters[id] ?? []\n current.append(cont)\n self.waiters[id] = current\n }\n\n private func removeWaiters(for id: String) {\n self.waiters[id] = []\n }\n\n private func setUnderlyingProcess(_ id: String, _ process: LinuxProcess) throws {\n guard var info = self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not found\")\n }\n info.process = process\n self.processes[id] = info\n }\n\n private func setProcessState(id: String, state: State) throws {\n guard var info = self.processes[id] else {\n throw ContainerizationError(.invalidState, message: \"Process \\(id) not found\")\n }\n info.state = state\n self.processes[id] = info\n }\n\n private func setContainer(_ info: ContainerInfo) {\n self.container = info\n }\n\n private func addNewProcess(_ id: String, _ config: ProcessConfiguration) {\n self.processes[id] = ProcessInfo(config: config, process: nil, state: .created)\n }\n\n private struct ProcessInfo {\n let config: ProcessConfiguration\n var process: LinuxProcess?\n var state: State\n }\n\n private struct ContainerInfo {\n let container: LinuxContainer\n let config: ContainerConfiguration\n let attachments: [Attachment]\n let bundle: ContainerClient.Bundle\n }\n\n public enum State: Sendable, Equatable {\n case created\n case booted\n case starting\n case running\n case stopping\n case stopped(Int32)\n }\n\n func setState(_ new: State) {\n self.state = new\n }\n}\n"], ["/container/Sources/APIServer/APIServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerPlugin\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport DNSServer\nimport Foundation\nimport Logging\n\n@main\nstruct APIServer: AsyncParsableCommand {\n static let listenAddress = \"127.0.0.1\"\n static let dnsPort = 2053\n\n static let configuration = CommandConfiguration(\n commandName: \"container-apiserver\",\n abstract: \"Container management API server\",\n version: releaseVersion()\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .shortAndLong, help: \"Daemon root directory\")\n var root = Self.appRoot.path\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n func run() async throws {\n let commandName = Self.configuration.commandName ?? \"container-apiserver\"\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n do {\n log.info(\"configuring XPC server\")\n let root = URL(filePath: root)\n var routes = [XPCRoute: XPCServer.RouteHandler]()\n let pluginLoader = try initializePluginLoader(log: log)\n try await initializePlugins(pluginLoader: pluginLoader, log: log, routes: &routes)\n try initializeContainerService(root: root, pluginLoader: pluginLoader, log: log, routes: &routes)\n let networkService = try await initializeNetworkService(\n root: root,\n pluginLoader: pluginLoader,\n log: log,\n routes: &routes\n )\n initializeHealthCheckService(log: log, routes: &routes)\n try initializeKernelService(log: log, routes: &routes)\n\n let server = XPCServer(\n identifier: \"com.apple.container.apiserver\",\n routes: routes.reduce(\n into: [String: XPCServer.RouteHandler](),\n {\n $0[$1.key.rawValue] = $1.value\n }), log: log)\n\n await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n log.info(\"starting XPC server\")\n try await server.listen()\n }\n // start up host table DNS\n group.addTask {\n let hostsResolver = ContainerDNSHandler(networkService: networkService)\n let nxDomainResolver = NxDomainResolver()\n let compositeResolver = CompositeResolver(handlers: [hostsResolver, nxDomainResolver])\n let hostsQueryValidator = StandardQueryValidator(handler: compositeResolver)\n let dnsServer: DNSServer = DNSServer(handler: hostsQueryValidator, log: log)\n log.info(\n \"starting DNS host query resolver\",\n metadata: [\n \"host\": \"\\(Self.listenAddress)\",\n \"port\": \"\\(Self.dnsPort)\",\n ]\n )\n try await dnsServer.run(host: Self.listenAddress, port: Self.dnsPort)\n }\n }\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n APIServer.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"APIServer\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n return log\n }\n\n private func initializePluginLoader(log: Logger) throws -> PluginLoader {\n let installRoot = CommandLine.executablePathUrl\n .deletingLastPathComponent()\n .appendingPathComponent(\"..\")\n .standardized\n let pluginsURL = PluginLoader.userPluginsDir(root: installRoot)\n var directoryExists: ObjCBool = false\n _ = FileManager.default.fileExists(atPath: pluginsURL.path, isDirectory: &directoryExists)\n let userPluginsURL = directoryExists.boolValue ? pluginsURL : nil\n\n // plugins built into the application installed as a macOS app bundle\n let appBundlePluginsURL = Bundle.main.resourceURL?.appending(path: \"plugins\")\n\n // plugins built into the application installed as a Unix-like application\n let installRootPluginsURL =\n installRoot\n .appendingPathComponent(\"libexec\")\n .appendingPathComponent(\"container\")\n .appendingPathComponent(\"plugins\")\n .standardized\n\n let pluginDirectories = [\n userPluginsURL,\n appBundlePluginsURL,\n installRootPluginsURL,\n ].compactMap { $0 }\n\n let pluginFactories: [PluginFactory] = [\n DefaultPluginFactory(),\n AppBundlePluginFactory(),\n ]\n\n log.info(\"PLUGINS: \\(pluginDirectories)\")\n let statePath = PluginLoader.defaultPluginResourcePath(root: Self.appRoot)\n try FileManager.default.createDirectory(at: statePath, withIntermediateDirectories: true)\n return PluginLoader(pluginDirectories: pluginDirectories, pluginFactories: pluginFactories, defaultResourcePath: statePath, log: log)\n }\n\n // First load all of the plugins we can find. Then just expose\n // the handlers for clients to do whatever they want.\n private func initializePlugins(\n pluginLoader: PluginLoader,\n log: Logger,\n routes: inout [XPCRoute: XPCServer.RouteHandler]\n ) async throws {\n let bootPlugins = pluginLoader.findPlugins().filter { $0.shouldBoot }\n\n let service = PluginsService(pluginLoader: pluginLoader, log: log)\n try await service.loadAll(bootPlugins)\n\n let harness = PluginsHarness(service: service, log: log)\n routes[XPCRoute.pluginGet] = harness.get\n routes[XPCRoute.pluginList] = harness.list\n routes[XPCRoute.pluginLoad] = harness.load\n routes[XPCRoute.pluginUnload] = harness.unload\n routes[XPCRoute.pluginRestart] = harness.restart\n }\n\n private func initializeHealthCheckService(log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) {\n let svc = HealthCheckHarness(log: log)\n routes[XPCRoute.ping] = svc.ping\n }\n\n private func initializeKernelService(log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) throws {\n let svc = try KernelService(log: log, appRoot: Self.appRoot)\n let harness = KernelHarness(service: svc, log: log)\n routes[XPCRoute.installKernel] = harness.install\n routes[XPCRoute.getDefaultKernel] = harness.getDefaultKernel\n }\n\n private func initializeContainerService(root: URL, pluginLoader: PluginLoader, log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) throws {\n let service = try ContainersService(\n root: root,\n pluginLoader: pluginLoader,\n log: log\n )\n let harness = ContainersHarness(service: service, log: log)\n\n routes[XPCRoute.listContainer] = harness.list\n routes[XPCRoute.createContainer] = harness.create\n routes[XPCRoute.deleteContainer] = harness.delete\n routes[XPCRoute.containerLogs] = harness.logs\n routes[XPCRoute.containerEvent] = harness.eventHandler\n }\n\n private func initializeNetworkService(\n root: URL,\n pluginLoader: PluginLoader,\n log: Logger,\n routes: inout [XPCRoute: XPCServer.RouteHandler]\n ) async throws -> NetworksService {\n let resourceRoot = root.appendingPathComponent(\"networks\")\n let service = try await NetworksService(\n pluginLoader: pluginLoader,\n resourceRoot: resourceRoot,\n log: log\n )\n\n let defaultNetwork = try await service.list()\n .filter { $0.id == ClientNetwork.defaultNetworkName }\n .first\n if defaultNetwork == nil {\n let config = NetworkConfiguration(id: ClientNetwork.defaultNetworkName, mode: .nat)\n _ = try await service.create(configuration: config)\n }\n\n let harness = NetworksHarness(service: service, log: log)\n\n routes[XPCRoute.networkCreate] = harness.create\n routes[XPCRoute.networkDelete] = harness.delete\n routes[XPCRoute.networkList] = harness.list\n return service\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/CLI/BuildCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerBuild\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport NIO\nimport TerminalProgress\n\nextension Application {\n struct BuildCommand: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"build\"\n config.abstract = \"Build an image from a Dockerfile\"\n config._superCommandName = \"container\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64 = 2\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n var memory: String = \"2048MB\"\n\n @Option(name: .long, help: ArgumentHelp(\"Set build-time variables\", valueName: \"key=val\"))\n var buildArg: [String] = []\n\n @Argument(help: \"Build directory\")\n var contextDir: String = \".\"\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Path to Dockerfile\", valueName: \"path\"))\n var file: String = \"Dockerfile\"\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Set a label\", valueName: \"key=val\"))\n var label: [String] = []\n\n @Flag(name: .long, help: \"Do not use cache\")\n var noCache: Bool = false\n\n @Option(name: .shortAndLong, help: ArgumentHelp(\"Output configuration for the build\", valueName: \"value\"))\n var output: [String] = {\n [\"type=oci\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Cache imports for the build\", valueName: \"value\", visibility: .hidden))\n var cacheIn: [String] = {\n []\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Cache exports for the build\", valueName: \"value\", visibility: .hidden))\n var cacheOut: [String] = {\n []\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"set the build architecture\", valueName: \"value\"))\n var arch: [String] = {\n [\"arm64\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"set the build os\", valueName: \"value\"))\n var os: [String] = {\n [\"linux\"]\n }()\n\n @Option(name: .long, help: ArgumentHelp(\"Progress type - one of [auto|plain|tty]\", valueName: \"type\"))\n var progress: String = \"auto\"\n\n @Option(name: .long, help: ArgumentHelp(\"Builder-shim vsock port\", valueName: \"port\"))\n var vsockPort: UInt32 = 8088\n\n @Option(name: [.customShort(\"t\"), .customLong(\"tag\")], help: ArgumentHelp(\"Name for the built image\", valueName: \"name\"))\n var targetImageName: String = UUID().uuidString.lowercased()\n\n @Option(name: .long, help: ArgumentHelp(\"Set the target build stage\", valueName: \"stage\"))\n var target: String = \"\"\n\n @Flag(name: .shortAndLong, help: \"Suppress build output\")\n var quiet: Bool = false\n\n func run() async throws {\n do {\n let timeout: Duration = .seconds(300)\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Dialing builder\")\n\n let builder: Builder? = try await withThrowingTaskGroup(of: Builder.self) { group in\n defer {\n group.cancelAll()\n }\n\n group.addTask {\n while true {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n let fh = try await container.dial(self.vsockPort)\n\n let threadGroup: MultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n let b = try Builder(socket: fh, group: threadGroup)\n\n // If this call succeeds, then BuildKit is running.\n let _ = try await b.info()\n return b\n } catch {\n // If we get here, \"Dialing builder\" is shown for such a short period\n // of time that it's invisible to the user.\n progress.set(tasks: 0)\n progress.set(totalTasks: 3)\n\n try await BuilderStart.start(\n cpus: self.cpus,\n memory: self.memory,\n progressUpdate: progress.handler\n )\n\n // wait (seconds) for builder to start listening on vsock\n try await Task.sleep(for: .seconds(5))\n continue\n }\n }\n }\n\n group.addTask {\n try await Task.sleep(for: timeout)\n throw ValidationError(\n \"\"\"\n Timeout waiting for connection to builder\n \"\"\"\n )\n }\n\n return try await group.next()\n }\n\n guard let builder else {\n throw ValidationError(\"builder is not running\")\n }\n\n let dockerfile = try Data(contentsOf: URL(filePath: file))\n let exportPath = Application.appRoot.appendingPathComponent(\".build\")\n\n let buildID = UUID().uuidString\n let tempURL = exportPath.appendingPathComponent(buildID)\n try FileManager.default.createDirectory(at: tempURL, withIntermediateDirectories: true, attributes: nil)\n defer {\n try? FileManager.default.removeItem(at: tempURL)\n }\n\n let imageName: String = try {\n let parsedReference = try Reference.parse(targetImageName)\n parsedReference.normalize()\n return parsedReference.description\n }()\n\n var terminal: Terminal?\n switch self.progress {\n case \"tty\":\n terminal = try Terminal(descriptor: STDERR_FILENO)\n case \"auto\":\n terminal = try? Terminal(descriptor: STDERR_FILENO)\n case \"plain\":\n terminal = nil\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid progress mode \\(self.progress)\")\n }\n\n defer { terminal?.tryReset() }\n\n let exports: [Builder.BuildExport] = try output.map { output in\n var exp = try Builder.BuildExport(from: output)\n if exp.destination == nil {\n exp.destination = tempURL.appendingPathComponent(\"out.tar\")\n }\n return exp\n }\n\n try await withThrowingTaskGroup(of: Void.self) { [terminal] group in\n defer {\n group.cancelAll()\n }\n group.addTask {\n let handler = AsyncSignalHandler.create(notify: [SIGTERM, SIGINT, SIGUSR1, SIGUSR2])\n for await sig in handler.signals {\n throw ContainerizationError(.interrupted, message: \"exiting on signal \\(sig)\")\n }\n }\n let platforms: [Platform] = try {\n var results: [Platform] = []\n for o in self.os {\n for a in self.arch {\n guard let platform = try? Platform(from: \"\\(o)/\\(a)\") else {\n throw ValidationError(\"invalid os/architecture combination \\(o)/\\(a)\")\n }\n results.append(platform)\n }\n }\n return results\n }()\n group.addTask { [terminal] in\n let config = ContainerBuild.Builder.BuildConfig(\n buildID: buildID,\n contentStore: RemoteContentStoreClient(),\n buildArgs: buildArg,\n contextDir: contextDir,\n dockerfile: dockerfile,\n labels: label,\n noCache: noCache,\n platforms: platforms,\n terminal: terminal,\n tag: imageName,\n target: target,\n quiet: quiet,\n exports: exports,\n cacheIn: cacheIn,\n cacheOut: cacheOut\n )\n progress.finish()\n\n try await builder.build(config)\n }\n\n try await group.next()\n }\n\n let unpackProgressConfig = try ProgressConfig(\n description: \"Unpacking built image\",\n itemsName: \"entries\",\n showTasks: exports.count > 1,\n totalTasks: exports.count\n )\n let unpackProgress = ProgressBar(config: unpackProgressConfig)\n defer {\n unpackProgress.finish()\n }\n unpackProgress.start()\n\n var finalMessage = \"Successfully built \\(imageName)\"\n let taskManager = ProgressTaskCoordinator()\n // Currently, only a single export can be specified.\n for exp in exports {\n unpackProgress.add(tasks: 1)\n let unpackTask = await taskManager.startTask()\n switch exp.type {\n case \"oci\":\n try Task.checkCancellation()\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let loaded = try await ClientImage.load(from: dest.absolutePath())\n\n for image in loaded {\n try Task.checkCancellation()\n try await image.unpack(platform: nil, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: unpackProgress.handler))\n }\n case \"tar\":\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let tarURL = tempURL.appendingPathComponent(\"out.tar\")\n try FileManager.default.moveItem(at: tarURL, to: dest)\n finalMessage = \"Successfully exported to \\(dest.absolutePath())\"\n case \"local\":\n guard let dest = exp.destination else {\n throw ContainerizationError(.invalidArgument, message: \"dest is required \\(exp.rawValue)\")\n }\n let localDir = tempURL.appendingPathComponent(\"local\")\n\n guard FileManager.default.fileExists(atPath: localDir.path) else {\n throw ContainerizationError(.invalidArgument, message: \"expected local output not found\")\n }\n try FileManager.default.copyItem(at: localDir, to: dest)\n finalMessage = \"Successfully exported to \\(dest.absolutePath())\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid exporter \\(exp.rawValue)\")\n }\n }\n await taskManager.finish()\n unpackProgress.finish()\n print(finalMessage)\n } catch {\n throw NSError(domain: \"Build\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"\\(error)\"])\n }\n }\n\n func validate() throws {\n guard FileManager.default.fileExists(atPath: file) else {\n throw ValidationError(\"Dockerfile does not exist at path: \\(file)\")\n }\n guard FileManager.default.fileExists(atPath: contextDir) else {\n throw ValidationError(\"context dir does not exist \\(contextDir)\")\n }\n guard let _ = try? Reference.parse(targetImageName) else {\n throw ValidationError(\"invalid reference \\(targetImageName)\")\n }\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SendableProperty\nimport Synchronization\n\n/// A progress bar that updates itself as tasks are completed.\npublic final class ProgressBar: Sendable {\n let config: ProgressConfig\n let state: Mutex\n @SendableProperty\n var printedWidth = 0\n let term: FileHandle?\n let termQueue = DispatchQueue(label: \"com.apple.container.ProgressBar\")\n private let standardError = StandardError()\n\n /// Returns `true` if the progress bar has finished.\n public var isFinished: Bool {\n state.withLock { $0.finished }\n }\n\n /// Creates a new progress bar.\n /// - Parameter config: The configuration for the progress bar.\n public init(config: ProgressConfig) {\n self.config = config\n term = isatty(config.terminal.fileDescriptor) == 1 ? config.terminal : nil\n let state = State(\n description: config.initialDescription, itemsName: config.initialItemsName, totalTasks: config.initialTotalTasks,\n totalItems: config.initialTotalItems,\n totalSize: config.initialTotalSize)\n self.state = Mutex(state)\n display(EscapeSequence.hideCursor)\n }\n\n deinit {\n clear()\n }\n\n /// Allows resetting the progress state.\n public func reset() {\n state.withLock {\n $0 = State(description: config.initialDescription)\n }\n }\n\n /// Allows resetting the progress state of the current task.\n public func resetCurrentTask() {\n state.withLock {\n $0 = State(description: $0.description, itemsName: $0.itemsName, tasks: $0.tasks, totalTasks: $0.totalTasks, startTime: $0.startTime)\n }\n }\n\n private func printFullDescription() {\n let (description, subDescription) = state.withLock { ($0.description, $0.subDescription) }\n\n if subDescription != \"\" {\n standardError.write(\"\\(description) \\(subDescription)\")\n } else {\n standardError.write(description)\n }\n }\n\n /// Updates the description of the progress bar and increments the tasks by one.\n /// - Parameter description: The description of the action being performed.\n public func set(description: String) {\n resetCurrentTask()\n\n state.withLock {\n $0.description = description\n $0.subDescription = \"\"\n $0.tasks += 1\n }\n if config.disableProgressUpdates {\n printFullDescription()\n }\n }\n\n /// Updates the additional description of the progress bar.\n /// - Parameter subDescription: The additional description of the action being performed.\n public func set(subDescription: String) {\n resetCurrentTask()\n\n state.withLock { $0.subDescription = subDescription }\n if config.disableProgressUpdates {\n printFullDescription()\n }\n }\n\n private func start(intervalSeconds: TimeInterval) async {\n if config.disableProgressUpdates && !state.withLock({ $0.description.isEmpty }) {\n printFullDescription()\n }\n\n while !state.withLock({ $0.finished }) {\n let intervalNanoseconds = UInt64(intervalSeconds * 1_000_000_000)\n render()\n state.withLock { $0.iteration += 1 }\n if (try? await Task.sleep(nanoseconds: intervalNanoseconds)) == nil {\n return\n }\n }\n }\n\n /// Starts an animation of the progress bar.\n /// - Parameter intervalSeconds: The time interval between updates in seconds.\n public func start(intervalSeconds: TimeInterval = 0.04) {\n Task(priority: .utility) {\n await start(intervalSeconds: intervalSeconds)\n }\n }\n\n /// Finishes the progress bar.\n public func finish() {\n guard !state.withLock({ $0.finished }) else {\n return\n }\n\n state.withLock { $0.finished = true }\n\n // The last render.\n render(force: true)\n\n if !config.disableProgressUpdates && !config.clearOnFinish {\n displayText(state.withLock { $0.output }, terminating: \"\\n\")\n }\n\n if config.clearOnFinish {\n clearAndResetCursor()\n } else {\n resetCursor()\n }\n // Allow printed output to flush.\n usleep(100_000)\n }\n}\n\nextension ProgressBar {\n private func secondsSinceStart() -> Int {\n let timeDifferenceNanoseconds = DispatchTime.now().uptimeNanoseconds - state.withLock { $0.startTime.uptimeNanoseconds }\n let timeDifferenceSeconds = Int(floor(Double(timeDifferenceNanoseconds) / 1_000_000_000))\n return timeDifferenceSeconds\n }\n\n func render(force: Bool = false) {\n guard term != nil && !config.disableProgressUpdates && (force || !state.withLock { $0.finished }) else {\n return\n }\n let output = draw()\n displayText(output)\n }\n\n func draw() -> String {\n let state = self.state.withLock { $0 }\n\n var components = [String]()\n if config.showSpinner && !config.showProgressBar {\n if !state.finished {\n let spinnerIcon = config.theme.getSpinnerIcon(state.iteration)\n components.append(\"\\(spinnerIcon)\")\n } else {\n components.append(\"\\(config.theme.done)\")\n }\n }\n\n if config.showTasks, let totalTasks = state.totalTasks {\n let tasks = min(state.tasks, totalTasks)\n components.append(\"[\\(tasks)/\\(totalTasks)]\")\n }\n\n if config.showDescription && !state.description.isEmpty {\n components.append(\"\\(state.description)\")\n if !state.subDescription.isEmpty {\n components.append(\"\\(state.subDescription)\")\n }\n }\n\n let allowProgress = !config.ignoreSmallSize || state.totalSize == nil || state.totalSize! > Int64(1024 * 1024)\n\n let value = state.totalSize != nil ? state.size : Int64(state.items)\n let total = state.totalSize ?? Int64(state.totalItems ?? 0)\n\n if config.showPercent && total > 0 && allowProgress {\n components.append(\"\\(state.finished ? \"100%\" : state.percent)\")\n }\n\n if config.showProgressBar, total > 0, allowProgress {\n let usedWidth = components.joined(separator: \" \").count + 45 /* the maximum number of characters we may need */\n let remainingWidth = max(config.width - usedWidth, 1 /* the minimum width of a progress bar */)\n let barLength = state.finished ? remainingWidth : Int(Int64(remainingWidth) * value / total)\n let barPaddingLength = remainingWidth - barLength\n let bar = \"\\(String(repeating: config.theme.bar, count: barLength))\\(String(repeating: \" \", count: barPaddingLength))\"\n components.append(\"|\\(bar)|\")\n }\n\n var additionalComponents = [String]()\n\n if config.showItems, state.items > 0 {\n var itemsName = \"\"\n if !state.itemsName.isEmpty {\n itemsName = \" \\(state.itemsName)\"\n }\n if state.finished {\n if let totalItems = state.totalItems {\n additionalComponents.append(\"\\(totalItems.formattedNumber())\\(itemsName)\")\n }\n } else {\n if let totalItems = state.totalItems {\n additionalComponents.append(\"\\(state.items.formattedNumber()) of \\(totalItems.formattedNumber())\\(itemsName)\")\n } else {\n additionalComponents.append(\"\\(state.items.formattedNumber())\\(itemsName)\")\n }\n }\n }\n\n if state.size > 0 && allowProgress {\n if state.finished {\n if config.showSize {\n if let totalSize = state.totalSize {\n var formattedTotalSize = totalSize.formattedSize()\n formattedTotalSize = adjustFormattedSize(formattedTotalSize)\n additionalComponents.append(formattedTotalSize)\n }\n }\n } else {\n var formattedCombinedSize = \"\"\n if config.showSize {\n var formattedSize = state.size.formattedSize()\n formattedSize = adjustFormattedSize(formattedSize)\n if let totalSize = state.totalSize {\n var formattedTotalSize = totalSize.formattedSize()\n formattedTotalSize = adjustFormattedSize(formattedTotalSize)\n formattedCombinedSize = combineSize(size: formattedSize, totalSize: formattedTotalSize)\n } else {\n formattedCombinedSize = formattedSize\n }\n }\n\n var formattedSpeed = \"\"\n if config.showSpeed {\n formattedSpeed = \"\\(state.sizeSpeed ?? state.averageSizeSpeed)\"\n formattedSpeed = adjustFormattedSize(formattedSpeed)\n }\n\n if config.showSize && config.showSpeed {\n additionalComponents.append(formattedCombinedSize)\n additionalComponents.append(formattedSpeed)\n } else if config.showSize {\n additionalComponents.append(formattedCombinedSize)\n } else if config.showSpeed {\n additionalComponents.append(formattedSpeed)\n }\n }\n }\n\n if additionalComponents.count > 0 {\n let joinedAdditionalComponents = additionalComponents.joined(separator: \", \")\n components.append(\"(\\(joinedAdditionalComponents))\")\n }\n\n if config.showTime {\n let timeDifferenceSeconds = secondsSinceStart()\n let formattedTime = timeDifferenceSeconds.formattedTime()\n components.append(\"[\\(formattedTime)]\")\n }\n\n return components.joined(separator: \" \")\n }\n\n private func adjustFormattedSize(_ size: String) -> String {\n // Ensure we always have one digit after the decimal point to prevent flickering.\n let zero = Int64(0).formattedSize()\n guard !size.contains(\".\"), let first = size.first, first.isNumber || !size.contains(zero) else {\n return size\n }\n var size = size\n for unit in [\"MB\", \"GB\", \"TB\"] {\n size = size.replacingOccurrences(of: \" \\(unit)\", with: \".0 \\(unit)\")\n }\n return size\n }\n\n private func combineSize(size: String, totalSize: String) -> String {\n let sizeComponents = size.split(separator: \" \", maxSplits: 1)\n let totalSizeComponents = totalSize.split(separator: \" \", maxSplits: 1)\n guard sizeComponents.count == 2, totalSizeComponents.count == 2 else {\n return \"\\(size)/\\(totalSize)\"\n }\n let sizeNumber = sizeComponents[0]\n let sizeUnit = sizeComponents[1]\n let totalSizeNumber = totalSizeComponents[0]\n let totalSizeUnit = totalSizeComponents[1]\n guard sizeUnit == totalSizeUnit else {\n return \"\\(size)/\\(totalSize)\"\n }\n return \"\\(sizeNumber)/\\(totalSizeNumber) \\(totalSizeUnit)\"\n }\n}\n"], ["/container/Sources/ContainerClient/SandboxClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport TerminalProgress\n\n/// A client for interacting with a single sandbox.\npublic struct SandboxClient: Sendable, Codable {\n static let label = \"com.apple.container.runtime\"\n\n public static func machServiceLabel(runtime: String, id: String) -> String {\n \"\\(Self.label).\\(runtime).\\(id)\"\n }\n\n private var machServiceLabel: String {\n Self.machServiceLabel(runtime: runtime, id: id)\n }\n\n let id: String\n let runtime: String\n\n /// Create a container.\n public init(id: String, runtime: String) {\n self.id = id\n self.runtime = runtime\n }\n}\n\n// Runtime Methods\nextension SandboxClient {\n public func bootstrap() async throws {\n let request = XPCMessage(route: SandboxRoutes.bootstrap.rawValue)\n let client = createClient()\n defer { client.close() }\n\n try await client.send(request)\n }\n\n public func state() async throws -> SandboxSnapshot {\n let request = XPCMessage(route: SandboxRoutes.state.rawValue)\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.sandboxSnapshot()\n }\n\n public func createProcess(_ id: String, config: ProcessConfiguration) async throws {\n let request = XPCMessage(route: SandboxRoutes.createProcess.rawValue)\n request.set(key: .id, value: id)\n let data = try JSONEncoder().encode(config)\n request.set(key: .processConfig, value: data)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func startProcess(_ id: String, stdio: [FileHandle?]) async throws {\n let request = XPCMessage(route: SandboxRoutes.start.rawValue)\n for (i, h) in stdio.enumerated() {\n let key: XPCKeys = {\n switch i {\n case 0: .stdin\n case 1: .stdout\n case 2: .stderr\n default:\n fatalError(\"invalid fd \\(i)\")\n }\n }()\n\n if let h {\n request.set(key: key, value: h)\n }\n }\n request.set(key: .id, value: id)\n\n let client = createClient()\n defer { client.close() }\n\n try await client.send(request)\n }\n\n public func stop(options: ContainerStopOptions) async throws {\n let request = XPCMessage(route: SandboxRoutes.stop.rawValue)\n\n let data = try JSONEncoder().encode(options)\n request.set(key: .stopOptions, value: data)\n\n let client = createClient()\n defer { client.close() }\n let responseTimeout = Duration(.seconds(Int64(options.timeoutInSeconds + 1)))\n try await client.send(request, responseTimeout: responseTimeout)\n }\n\n public func kill(_ id: String, signal: Int64) async throws {\n let request = XPCMessage(route: SandboxRoutes.kill.rawValue)\n request.set(key: .id, value: id)\n request.set(key: .signal, value: signal)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func resize(_ id: String, size: Terminal.Size) async throws {\n let request = XPCMessage(route: SandboxRoutes.resize.rawValue)\n request.set(key: .id, value: id)\n request.set(key: .width, value: UInt64(size.width))\n request.set(key: .height, value: UInt64(size.height))\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func wait(_ id: String) async throws -> Int32 {\n let request = XPCMessage(route: SandboxRoutes.wait.rawValue)\n request.set(key: .id, value: id)\n\n let client = createClient()\n defer { client.close() }\n let response = try await client.send(request)\n let code = response.int64(key: .exitCode)\n return Int32(code)\n }\n\n public func dial(_ port: UInt32) async throws -> FileHandle {\n let request = XPCMessage(route: SandboxRoutes.dial.rawValue)\n request.set(key: .port, value: UInt64(port))\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n guard let fh = response.fileHandle(key: .fd) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get fd for vsock port \\(port)\"\n )\n }\n return fh\n }\n\n private func createClient() -> XPCClient {\n XPCClient(service: machServiceLabel)\n }\n}\n\nextension XPCMessage {\n public func id() throws -> String {\n let id = self.string(key: .id)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"No id\")\n }\n return id\n }\n\n func sandboxSnapshot() throws -> SandboxSnapshot {\n let data = self.dataNoCopy(key: .snapshot)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No state data returned\")\n }\n return try JSONDecoder().decode(SandboxSnapshot.self, from: data)\n }\n}\n"], ["/container/Sources/ContainerClient/Parser.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\npublic struct Parser {\n public static func memoryString(_ memory: String) throws -> Int64 {\n let ram = try Measurement.parse(parsing: memory)\n let mb = ram.converted(to: .mebibytes)\n return Int64(mb.value)\n }\n\n public static func user(\n user: String?, uid: UInt32?, gid: UInt32?,\n defaultUser: ProcessConfiguration.User = .id(uid: 0, gid: 0)\n ) -> (user: ProcessConfiguration.User, groups: [UInt32]) {\n\n var supplementalGroups: [UInt32] = []\n let user: ProcessConfiguration.User = {\n if let user = user, !user.isEmpty {\n return .raw(userString: user)\n }\n if let uid, let gid {\n return .id(uid: uid, gid: gid)\n }\n if uid == nil, gid == nil {\n // Neither uid nor gid is set. return the default user\n return defaultUser\n }\n // One of uid / gid is left unspecified. Set the user accordingly\n if let uid {\n return .raw(userString: \"\\(uid)\")\n }\n if let gid {\n supplementalGroups.append(gid)\n }\n return defaultUser\n }()\n return (user, supplementalGroups)\n }\n\n public static func platform(os: String, arch: String) -> ContainerizationOCI.Platform {\n .init(arch: arch, os: os)\n }\n\n public static func resources(cpus: Int64?, memory: String?) throws -> ContainerConfiguration.Resources {\n var resource = ContainerConfiguration.Resources()\n if let cpus {\n resource.cpus = Int(cpus)\n }\n if let memory {\n resource.memoryInBytes = try Parser.memoryString(memory).mib()\n }\n return resource\n }\n\n public static func allEnv(imageEnvs: [String], envFiles: [String], envs: [String]) throws -> [String] {\n var output: [String] = []\n output.append(contentsOf: Parser.env(envList: imageEnvs))\n for envFile in envFiles {\n let content = try Parser.envFile(path: envFile)\n output.append(contentsOf: content)\n }\n output.append(contentsOf: Parser.env(envList: envs))\n return output\n }\n\n static func envFile(path: String) throws -> [String] {\n guard FileManager.default.fileExists(atPath: path) else {\n throw ContainerizationError(.notFound, message: \"envfile at \\(path) not found\")\n }\n\n let data = try String(contentsOfFile: path, encoding: .utf8)\n let lines = data.components(separatedBy: .newlines)\n var envVars: [String] = []\n for line in lines {\n let line = line.trimmingCharacters(in: .whitespaces)\n if line.isEmpty {\n continue\n }\n if !line.hasPrefix(\"#\") {\n let keyVals = line.split(separator: \"=\")\n if keyVals.count != 2 {\n continue\n }\n let key = keyVals[0].trimmingCharacters(in: .whitespaces)\n let val = keyVals[1].trimmingCharacters(in: .whitespaces)\n if key.isEmpty || val.isEmpty {\n continue\n }\n envVars.append(\"\\(key)=\\(val)\")\n }\n }\n return envVars\n }\n\n static func env(envList: [String]) -> [String] {\n var envVar: [String] = []\n for env in envList {\n var env = env\n let parts = env.split(separator: \"=\", maxSplits: 2)\n if parts.count == 1 {\n guard let val = ProcessInfo.processInfo.environment[env] else {\n continue\n }\n env = \"\\(env)=\\(val)\"\n }\n envVar.append(env)\n }\n return envVar\n }\n\n static func labels(_ rawLabels: [String]) throws -> [String: String] {\n var result: [String: String] = [:]\n for label in rawLabels {\n if label.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"label cannot be an empty string\")\n }\n let parts = label.split(separator: \"=\", maxSplits: 2)\n switch parts.count {\n case 1:\n result[String(parts[0])] = \"\"\n case 2:\n result[String(parts[0])] = String(parts[1])\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid label format \\(label)\")\n }\n }\n return result\n }\n\n static func process(\n arguments: [String],\n processFlags: Flags.Process,\n managementFlags: Flags.Management,\n config: ContainerizationOCI.ImageConfig?\n ) throws -> ProcessConfiguration {\n\n let imageEnvVars = config?.env ?? []\n let envvars = try Parser.allEnv(imageEnvs: imageEnvVars, envFiles: processFlags.envFile, envs: processFlags.env)\n\n let workingDir: String = {\n if let cwd = processFlags.cwd {\n return cwd\n }\n if let cwd = config?.workingDir {\n return cwd\n }\n return \"/\"\n }()\n\n let processArguments: [String]? = {\n var result: [String] = []\n var hasEntrypointOverride: Bool = false\n // ensure the entrypoint is honored if it has been explicitly set by the user\n if let entrypoint = managementFlags.entryPoint, !entrypoint.isEmpty {\n result = [entrypoint]\n hasEntrypointOverride = true\n } else if let entrypoint = config?.entrypoint, !entrypoint.isEmpty {\n result = entrypoint\n }\n if !arguments.isEmpty {\n result.append(contentsOf: arguments)\n } else {\n if let cmd = config?.cmd, !hasEntrypointOverride, !cmd.isEmpty {\n result.append(contentsOf: cmd)\n }\n }\n return result.count > 0 ? result : nil\n }()\n\n guard let commandToRun = processArguments, commandToRun.count > 0 else {\n throw ContainerizationError(.invalidArgument, message: \"Command/Entrypoint not specified for container process\")\n }\n\n let defaultUser: ProcessConfiguration.User = {\n if let u = config?.user {\n return .raw(userString: u)\n }\n return .id(uid: 0, gid: 0)\n }()\n\n let (user, additionalGroups) = Parser.user(\n user: processFlags.user, uid: processFlags.uid,\n gid: processFlags.gid, defaultUser: defaultUser)\n\n return .init(\n executable: commandToRun.first!,\n arguments: [String](commandToRun.dropFirst()),\n environment: envvars,\n workingDirectory: workingDir,\n terminal: processFlags.tty,\n user: user,\n supplementalGroups: additionalGroups\n )\n }\n\n // MARK: Mounts\n\n static let mountTypes = [\n \"virtiofs\",\n \"bind\",\n \"tmpfs\",\n ]\n\n static let defaultDirectives = [\"type\": \"virtiofs\"]\n\n static func tmpfsMounts(_ mounts: [String]) throws -> [Filesystem] {\n var result: [Filesystem] = []\n let mounts = mounts.dedupe()\n for tmpfs in mounts {\n let fs = Filesystem.tmpfs(destination: tmpfs, options: [])\n try validateMount(fs)\n result.append(fs)\n }\n return result\n }\n\n static func mounts(_ rawMounts: [String]) throws -> [Filesystem] {\n var mounts: [Filesystem] = []\n let rawMounts = rawMounts.dedupe()\n for mount in rawMounts {\n let m = try Parser.mount(mount)\n try validateMount(m)\n mounts.append(m)\n }\n return mounts\n }\n\n static func mount(_ mount: String) throws -> Filesystem {\n let parts = mount.split(separator: \",\")\n if parts.count == 0 {\n throw ContainerizationError(.invalidArgument, message: \"invalid mount format: \\(mount)\")\n }\n var directives = defaultDirectives\n for part in parts {\n let keyVal = part.split(separator: \"=\", maxSplits: 2)\n var key = String(keyVal[0])\n var skipValue = false\n switch key {\n case \"type\", \"size\", \"mode\":\n break\n case \"source\", \"src\":\n key = \"source\"\n case \"destination\", \"dst\", \"target\":\n key = \"destination\"\n case \"readonly\", \"ro\":\n key = \"ro\"\n skipValue = true\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown directive \\(key) when parsing mount \\(mount)\")\n }\n var value = \"\"\n if !skipValue {\n if keyVal.count != 2 {\n throw ContainerizationError(.invalidArgument, message: \"invalid directive format missing value \\(part) in \\(mount)\")\n }\n value = String(keyVal[1])\n }\n directives[key] = value\n }\n\n var fs = Filesystem()\n for (key, val) in directives {\n var val = val\n let type = directives[\"type\"] ?? \"\"\n\n switch key {\n case \"type\":\n if val == \"bind\" {\n val = \"virtiofs\"\n }\n switch val {\n case \"virtiofs\":\n fs.type = Filesystem.FSType.virtiofs\n case \"tmpfs\":\n fs.type = Filesystem.FSType.tmpfs\n default:\n throw ContainerizationError(.invalidArgument, message: \"unsupported mount type \\(val)\")\n }\n\n case \"ro\":\n fs.options.append(\"ro\")\n case \"size\":\n if type != \"tmpfs\" {\n throw ContainerizationError(.invalidArgument, message: \"unsupported option size for \\(type) mount\")\n }\n var overflow: Bool\n var memory = try Parser.memoryString(val)\n (memory, overflow) = memory.multipliedReportingOverflow(by: 1024 * 1024)\n if overflow {\n throw ContainerizationError(.invalidArgument, message: \"overflow encountered when parsing memory string: \\(val)\")\n }\n let s = \"size=\\(memory)\"\n fs.options.append(s)\n case \"mode\":\n if type != \"tmpfs\" {\n throw ContainerizationError(.invalidArgument, message: \"unsupported option mode for \\(type) mount\")\n }\n let s = \"mode=\\(val)\"\n fs.options.append(s)\n case \"source\":\n let absPath = URL(filePath: val).absoluteURL.path\n switch type {\n case \"virtiofs\", \"bind\":\n fs.source = absPath\n case \"tmpfs\":\n throw ContainerizationError(.invalidArgument, message: \"cannot specify source for tmpfs mount\")\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown mount type \\(type)\")\n }\n case \"destination\":\n fs.destination = val\n default:\n throw ContainerizationError(.invalidArgument, message: \"unknown mount directive \\(key)\")\n }\n }\n return fs\n }\n\n static func volumes(_ rawVolumes: [String]) throws -> [Filesystem] {\n var mounts: [Filesystem] = []\n for volume in rawVolumes {\n let m = try Parser.volume(volume)\n try Parser.validateMount(m)\n mounts.append(m)\n }\n return mounts\n }\n\n private static func volume(_ volume: String) throws -> Filesystem {\n var vol = volume\n vol.trimLeft(char: \":\")\n\n let parts = vol.split(separator: \":\")\n switch parts.count {\n case 1:\n throw ContainerizationError(.invalidArgument, message: \"anonymous volumes are not supported\")\n case 2, 3:\n // Bind / volume mounts.\n let src = String(parts[0])\n let dst = String(parts[1])\n\n let abs = URL(filePath: src).absoluteURL.path\n if !FileManager.default.fileExists(atPath: abs) {\n throw ContainerizationError(.invalidArgument, message: \"named volumes are not supported\")\n }\n\n var fs = Filesystem.virtiofs(\n source: URL(fileURLWithPath: src).absolutePath(),\n destination: dst,\n options: []\n )\n if parts.count == 3 {\n fs.options = parts[2].split(separator: \",\").map { String($0) }\n }\n return fs\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid volume format \\(volume)\")\n }\n }\n\n static func validMountType(_ type: String) -> Bool {\n mountTypes.contains(type)\n }\n\n static func validateMount(_ mount: Filesystem) throws {\n if !mount.isTmpfs {\n if !mount.source.isAbsolutePath() {\n throw ContainerizationError(\n .invalidArgument, message: \"\\(mount.source) is not an absolute path on the host\")\n }\n if !FileManager.default.fileExists(atPath: mount.source) {\n throw ContainerizationError(.invalidArgument, message: \"file path '\\(mount.source)' does not exist\")\n }\n }\n\n if mount.destination.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"mount destination cannot be empty\")\n }\n }\n\n /// Parse --publish-port arguments into PublishPort objects\n /// The format of each argument is `[host-ip:]host-port:container-port[/protocol]`\n /// (e.g., \"127.0.0.1:8080:80/tcp\")\n ///\n /// - Parameter rawPublishPorts: Array of port arguments\n /// - Returns: Array of PublishPort objects\n /// - Throws: ContainerizationError if parsing fails\n static func publishPorts(_ rawPublishPorts: [String]) throws -> [PublishPort] {\n var sockets: [PublishPort] = []\n\n // Process each raw port string\n for socket in rawPublishPorts {\n let parsedSocket = try Parser.publishPort(socket)\n sockets.append(parsedSocket)\n }\n return sockets\n }\n\n // Parse a single `--publish-port` argument into a `PublishPort`.\n private static func publishPort(_ portText: String) throws -> PublishPort {\n let protoSplit = portText.split(separator: \"/\")\n let proto: PublishProtocol\n let addressAndPortText: String\n switch protoSplit.count {\n case 1:\n addressAndPortText = String(protoSplit[0])\n proto = .tcp\n case 2:\n addressAndPortText = String(protoSplit[0])\n let protoText = String(protoSplit[1])\n guard let parsedProto = PublishProtocol(protoText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish protocol: \\(protoText)\")\n }\n proto = parsedProto\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid publish value: \\(portText)\")\n }\n\n let hostAddress: String\n let hostPortText: String\n let containerPortText: String\n let parts = addressAndPortText.split(separator: \":\")\n switch parts.count {\n case 2:\n hostAddress = \"0.0.0.0\"\n hostPortText = String(parts[0])\n containerPortText = String(parts[1])\n case 3:\n hostAddress = String(parts[0])\n hostPortText = String(parts[1])\n containerPortText = String(parts[2])\n default:\n throw ContainerizationError(.invalidArgument, message: \"invalid publish address: \\(portText)\")\n }\n\n guard let hostPort = Int(hostPortText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish host port: \\(hostPortText)\")\n }\n\n guard let containerPort = Int(containerPortText) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid publish container port: \\(containerPortText)\")\n }\n\n return PublishPort(\n hostAddress: hostAddress,\n hostPort: hostPort,\n containerPort: containerPort,\n proto: proto\n )\n }\n\n /// Parse --publish-socket arguments into PublishSocket objects\n /// The format of each argument is `host_path:container_path`\n /// (e.g., \"/tmp/docker.sock:/var/run/docker.sock\")\n ///\n /// - Parameter rawPublishSockets: Array of socket arguments\n /// - Returns: Array of PublishSocket objects\n /// - Throws: ContainerizationError if parsing fails or a path is invalid\n static func publishSockets(_ rawPublishSockets: [String]) throws -> [PublishSocket] {\n var sockets: [PublishSocket] = []\n\n // Process each raw socket string\n for socket in rawPublishSockets {\n let parsedSocket = try Parser.publishSocket(socket)\n sockets.append(parsedSocket)\n }\n return sockets\n }\n\n // Parse a single `--publish-socket`` argument into a `PublishSocket`.\n private static func publishSocket(_ socketText: String) throws -> PublishSocket {\n // Split by colon to two parts: [host_path, container_path]\n let parts = socketText.split(separator: \":\")\n\n switch parts.count {\n case 2:\n // Extract host and container paths\n let hostPath = String(parts[0])\n let containerPath = String(parts[1])\n\n // Validate paths are not empty\n if hostPath.isEmpty {\n throw ContainerizationError(\n .invalidArgument, message: \"host socket path cannot be empty\")\n }\n if containerPath.isEmpty {\n throw ContainerizationError(\n .invalidArgument, message: \"container socket path cannot be empty\")\n }\n\n // Ensure container path must start with /\n if !containerPath.hasPrefix(\"/\") {\n throw ContainerizationError(\n .invalidArgument,\n message: \"container socket path must be absolute: \\(containerPath)\")\n }\n\n // Convert host path to absolute path for consistency\n let hostURL = URL(fileURLWithPath: hostPath)\n let absoluteHostPath = hostURL.absoluteURL.path\n\n // Check if host socket already exists and might be in use\n if FileManager.default.fileExists(atPath: absoluteHostPath) {\n do {\n let attrs = try FileManager.default.attributesOfItem(atPath: absoluteHostPath)\n if let fileType = attrs[.type] as? FileAttributeType, fileType == .typeSocket {\n throw ContainerizationError(\n .invalidArgument,\n message: \"host socket \\(absoluteHostPath) already exists and may be in use\")\n }\n // If it exists but is not a socket, we can remove it and create socket\n try FileManager.default.removeItem(atPath: absoluteHostPath)\n } catch let error as ContainerizationError {\n throw error\n } catch {\n // For other file system errors, continue with creation\n }\n }\n\n // Create host directory if it doesn't exist\n let hostDir = hostURL.deletingLastPathComponent()\n if !FileManager.default.fileExists(atPath: hostDir.path) {\n try FileManager.default.createDirectory(\n at: hostDir, withIntermediateDirectories: true)\n }\n\n // Create and return PublishSocket object with validated paths\n return PublishSocket(\n containerPath: URL(fileURLWithPath: containerPath),\n hostPath: URL(fileURLWithPath: absoluteHostPath),\n permissions: nil\n )\n\n default:\n throw ContainerizationError(\n .invalidArgument,\n message:\n \"invalid publish-socket format \\(socketText). Expected: host_path:container_path\")\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIO\nimport NIOHPACK\nimport NIOHTTP2\n\npublic struct Builder: Sendable {\n let client: BuilderClientProtocol\n let clientAsync: BuilderClientAsyncProtocol\n let group: EventLoopGroup\n let builderShimSocket: FileHandle\n let channel: GRPCChannel\n\n public init(socket: FileHandle, group: EventLoopGroup) throws {\n try socket.setSendBufSize(4 << 20)\n try socket.setRecvBufSize(2 << 20)\n var config = ClientConnection.Configuration.default(\n target: .connectedSocket(socket.fileDescriptor),\n eventLoopGroup: group\n )\n config.connectionIdleTimeout = TimeAmount(.seconds(600))\n config.connectionKeepalive = .init(\n interval: TimeAmount(.seconds(600)),\n timeout: TimeAmount(.seconds(500)),\n permitWithoutCalls: true\n )\n config.connectionBackoff = .init(\n initialBackoff: TimeInterval(1),\n maximumBackoff: TimeInterval(10)\n )\n config.callStartBehavior = .fastFailure\n config.httpMaxFrameSize = 8 << 10\n config.maximumReceiveMessageLength = 512 << 20\n config.httpTargetWindowSize = 16 << 10\n\n let channel = ClientConnection(configuration: config)\n self.channel = channel\n self.clientAsync = BuilderClientAsync(channel: channel)\n self.client = BuilderClient(channel: channel)\n self.group = group\n self.builderShimSocket = socket\n }\n\n public func info() throws -> InfoResponse {\n let resp = self.client.info(InfoRequest(), callOptions: CallOptions())\n return try resp.response.wait()\n }\n\n public func info() async throws -> InfoResponse {\n let opts = CallOptions(timeLimit: .timeout(.seconds(30)))\n return try await self.clientAsync.info(InfoRequest(), callOptions: opts)\n }\n\n // TODO\n // - Symlinks in build context dir\n // - cache-to, cache-from\n // - output (other than the default OCI image output, e.g., local, tar, Docker)\n public func build(_ config: BuildConfig) async throws {\n var continuation: AsyncStream.Continuation?\n let reqStream = AsyncStream { (cont: AsyncStream.Continuation) in\n continuation = cont\n }\n guard let continuation else {\n throw Error.invalidContinuation\n }\n\n defer {\n continuation.finish()\n }\n\n if let terminal = config.terminal {\n Task {\n let winchHandler = AsyncSignalHandler.create(notify: [SIGWINCH])\n let setWinch = { (rows: UInt16, cols: UInt16) in\n var winch = ClientStream()\n winch.command = .init()\n if let cmdString = try TerminalCommand(rows: rows, cols: cols).json() {\n winch.command.command = cmdString\n continuation.yield(winch)\n }\n }\n let size = try terminal.size\n var width = size.width\n var height = size.height\n try setWinch(height, width)\n\n for await _ in winchHandler.signals {\n let size = try terminal.size\n let cols = size.width\n let rows = size.height\n if cols != width || rows != height {\n width = cols\n height = rows\n try setWinch(height, width)\n }\n }\n }\n }\n\n let respStream = self.clientAsync.performBuild(reqStream, callOptions: try CallOptions(config))\n let pipeline = try await BuildPipeline(config)\n do {\n try await pipeline.run(sender: continuation, receiver: respStream)\n } catch Error.buildComplete {\n _ = channel.close()\n try await group.shutdownGracefully()\n return\n }\n }\n\n public struct BuildExport: Sendable {\n public let type: String\n public var destination: URL?\n public let additionalFields: [String: String]\n public let rawValue: String\n\n public init(type: String, destination: URL?, additionalFields: [String: String], rawValue: String) {\n self.type = type\n self.destination = destination\n self.additionalFields = additionalFields\n self.rawValue = rawValue\n }\n\n public init(from input: String) throws {\n var typeValue: String?\n var destinationValue: URL?\n var additionalFields: [String: String] = [:]\n\n let pairs = input.components(separatedBy: \",\")\n for pair in pairs {\n let parts = pair.components(separatedBy: \"=\")\n guard parts.count == 2 else { continue }\n\n let key = parts[0].trimmingCharacters(in: .whitespaces)\n let value = parts[1].trimmingCharacters(in: .whitespaces)\n\n switch key {\n case \"type\":\n typeValue = value\n case \"dest\":\n destinationValue = try Self.resolveDestination(dest: value)\n default:\n additionalFields[key] = value\n }\n }\n\n guard let type = typeValue else {\n throw Builder.Error.invalidExport(input, \"type field is required\")\n }\n\n switch type {\n case \"oci\":\n break\n case \"tar\":\n if destinationValue == nil {\n throw Builder.Error.invalidExport(input, \"dest field is required\")\n }\n case \"local\":\n if destinationValue == nil {\n throw Builder.Error.invalidExport(input, \"dest field is required\")\n }\n default:\n throw Builder.Error.invalidExport(input, \"unsupported output type\")\n }\n\n self.init(type: type, destination: destinationValue, additionalFields: additionalFields, rawValue: input)\n }\n\n public var stringValue: String {\n get throws {\n var components = [\"type=\\(type)\"]\n\n switch type {\n case \"oci\", \"tar\", \"local\":\n break // ignore destination\n default:\n throw Builder.Error.invalidExport(rawValue, \"unsupported output type\")\n }\n\n for (key, value) in additionalFields {\n components.append(\"\\(key)=\\(value)\")\n }\n\n return components.joined(separator: \",\")\n }\n }\n\n static func resolveDestination(dest: String) throws -> URL {\n let destination = URL(fileURLWithPath: dest)\n let fileManager = FileManager.default\n\n if fileManager.fileExists(atPath: destination.path) {\n let resourceValues = try destination.resourceValues(forKeys: [.isDirectoryKey])\n let isDir = resourceValues.isDirectory\n if isDir != nil && isDir == false {\n throw Builder.Error.invalidExport(dest, \"dest path already exists\")\n }\n\n var finalDestination = destination.appendingPathComponent(\"out.tar\")\n var index = 1\n while fileManager.fileExists(atPath: finalDestination.path) {\n let path = \"out.tar.\\(index)\"\n finalDestination = destination.appendingPathComponent(path)\n index += 1\n }\n return finalDestination\n } else {\n let parentDirectory = destination.deletingLastPathComponent()\n try? fileManager.createDirectory(at: parentDirectory, withIntermediateDirectories: true, attributes: nil)\n }\n\n return destination\n }\n }\n\n public struct BuildConfig: Sendable {\n public let buildID: String\n public let contentStore: ContentStore\n public let buildArgs: [String]\n public let contextDir: String\n public let dockerfile: Data\n public let labels: [String]\n public let noCache: Bool\n public let platforms: [Platform]\n public let terminal: Terminal?\n public let tag: String\n public let target: String\n public let quiet: Bool\n public let exports: [BuildExport]\n public let cacheIn: [String]\n public let cacheOut: [String]\n\n public init(\n buildID: String,\n contentStore: ContentStore,\n buildArgs: [String],\n contextDir: String,\n dockerfile: Data,\n labels: [String],\n noCache: Bool,\n platforms: [Platform],\n terminal: Terminal?,\n tag: String,\n target: String,\n quiet: Bool,\n exports: [BuildExport],\n cacheIn: [String],\n cacheOut: [String],\n ) {\n self.buildID = buildID\n self.contentStore = contentStore\n self.buildArgs = buildArgs\n self.contextDir = contextDir\n self.dockerfile = dockerfile\n self.labels = labels\n self.noCache = noCache\n self.platforms = platforms\n self.terminal = terminal\n self.tag = tag\n self.target = target\n self.quiet = quiet\n self.exports = exports\n self.cacheIn = cacheIn\n self.cacheOut = cacheOut\n }\n }\n}\n\nextension Builder {\n enum Error: Swift.Error, CustomStringConvertible {\n case invalidContinuation\n case buildComplete\n case invalidExport(String, String)\n\n var description: String {\n switch self {\n case .invalidContinuation:\n return \"continuation could not created\"\n case .buildComplete:\n return \"build completed\"\n case .invalidExport(let exp, let reason):\n return \"export entry \\(exp) is invalid: \\(reason)\"\n }\n }\n }\n}\n\nextension CallOptions {\n public init(_ config: Builder.BuildConfig) throws {\n var headers: [(String, String)] = [\n (\"build-id\", config.buildID),\n (\"context\", URL(filePath: config.contextDir).path(percentEncoded: false)),\n (\"dockerfile\", config.dockerfile.base64EncodedString()),\n (\"progress\", config.terminal != nil ? \"tty\" : \"plain\"),\n (\"tag\", config.tag),\n (\"target\", config.target),\n ]\n for platform in config.platforms {\n headers.append((\"platforms\", platform.description))\n }\n if config.noCache {\n headers.append((\"no-cache\", \"\"))\n }\n for label in config.labels {\n headers.append((\"labels\", label))\n }\n for buildArg in config.buildArgs {\n headers.append((\"build-args\", buildArg))\n }\n for output in config.exports {\n headers.append((\"outputs\", try output.stringValue))\n }\n for cacheIn in config.cacheIn {\n headers.append((\"cache-in\", cacheIn))\n }\n for cacheOut in config.cacheOut {\n headers.append((\"cache-out\", cacheOut))\n }\n\n self.init(\n customMetadata: HPACKHeaders(headers)\n )\n }\n}\n\nextension FileHandle {\n @discardableResult\n func setSendBufSize(_ bytes: Int) throws -> Int {\n try setSockOpt(\n level: SOL_SOCKET,\n name: SO_SNDBUF,\n value: bytes)\n return bytes\n }\n\n @discardableResult\n func setRecvBufSize(_ bytes: Int) throws -> Int {\n try setSockOpt(\n level: SOL_SOCKET,\n name: SO_RCVBUF,\n value: bytes)\n return bytes\n }\n\n private func setSockOpt(level: Int32, name: Int32, value: Int) throws {\n var v = Int32(value)\n let res = withUnsafePointer(to: &v) { ptr -> Int32 in\n ptr.withMemoryRebound(\n to: UInt8.self,\n capacity: MemoryLayout.size\n ) { raw in\n #if canImport(Darwin)\n return setsockopt(\n self.fileDescriptor,\n level, name,\n raw,\n socklen_t(MemoryLayout.size))\n #else\n fatalError(\"unsupported platform\")\n #endif\n }\n }\n if res == -1 {\n throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EPERM)\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct SystemStart: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Start `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Path to the `container-apiserver` binary\")\n var path: String = Bundle.main.executablePath ?? \"\"\n\n @Flag(name: .long, help: \"Enable debug logging for the runtime daemon.\")\n var debug = false\n\n @Flag(\n name: .long, inversion: .prefixedEnableDisable,\n help: \"Specify whether the default kernel should be installed or not. The default behavior is to prompt the user for a response.\")\n var kernelInstall: Bool?\n\n func run() async throws {\n // Without the true path to the binary in the plist, `container-apiserver` won't launch properly.\n let executableUrl = URL(filePath: path)\n .resolvingSymlinksInPath()\n .deletingLastPathComponent()\n .appendingPathComponent(\"container-apiserver\")\n\n var args = [executableUrl.absolutePath()]\n if debug {\n args.append(\"--debug\")\n }\n\n let apiServerDataUrl = appRoot.appending(path: \"apiserver\")\n try! FileManager.default.createDirectory(at: apiServerDataUrl, withIntermediateDirectories: true)\n let env = ProcessInfo.processInfo.environment.filter { key, _ in\n key.hasPrefix(\"CONTAINER_\")\n }\n\n let logURL = apiServerDataUrl.appending(path: \"apiserver.log\")\n let plist = LaunchPlist(\n label: \"com.apple.container.apiserver\",\n arguments: args,\n environment: env,\n limitLoadToSessionType: [.Aqua, .Background, .System],\n runAtLoad: true,\n stdout: logURL.path,\n stderr: logURL.path,\n machServices: [\"com.apple.container.apiserver\"]\n )\n\n let plistURL = apiServerDataUrl.appending(path: \"apiserver.plist\")\n let data = try plist.encode()\n try data.write(to: plistURL)\n\n try ServiceManager.register(plistPath: plistURL.path)\n\n // Now ping our friendly daemon. Fail if we don't get a response.\n do {\n print(\"Verifying apiserver is running...\")\n try await ClientHealthCheck.ping(timeout: .seconds(10))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get a response from apiserver: \\(error)\"\n )\n }\n\n if await !initImageExists() {\n try? await installInitialFilesystem()\n }\n\n guard await !kernelExists() else {\n return\n }\n try await installDefaultKernel()\n }\n\n private func installInitialFilesystem() async throws {\n let dep = Dependencies.initFs\n let pullCommand = ImagePull(reference: dep.source)\n print(\"Installing base container filesystem...\")\n do {\n try await pullCommand.run()\n } catch {\n log.error(\"Failed to install base container filesystem: \\(error)\")\n }\n }\n\n private func installDefaultKernel() async throws {\n let kernelDependency = Dependencies.kernel\n let defaultKernelURL = kernelDependency.source\n let defaultKernelBinaryPath = ClientDefaults.get(key: .defaultKernelBinaryPath)\n\n var shouldInstallKernel = false\n if kernelInstall == nil {\n print(\"No default kernel configured.\")\n print(\"Install the recommended default kernel from [\\(kernelDependency.source)]? [Y/n]: \", terminator: \"\")\n guard let read = readLine(strippingNewline: true) else {\n throw ContainerizationError(.internalError, message: \"Failed to read user input\")\n }\n guard read.lowercased() == \"y\" || read.count == 0 else {\n print(\"Please use the `container system kernel set --recommended` command to configure the default kernel\")\n return\n }\n shouldInstallKernel = true\n } else {\n shouldInstallKernel = kernelInstall ?? false\n }\n guard shouldInstallKernel else {\n return\n }\n print(\"Installing kernel...\")\n try await KernelSet.downloadAndInstallWithProgressBar(tarRemoteURL: defaultKernelURL, kernelFilePath: defaultKernelBinaryPath)\n }\n\n private func initImageExists() async -> Bool {\n do {\n let img = try await ClientImage.get(reference: Dependencies.initFs.source)\n let _ = try await img.getSnapshot(platform: .current)\n return true\n } catch {\n return false\n }\n }\n\n private func kernelExists() async -> Bool {\n do {\n try await ClientKernel.getDefaultKernel(for: .current)\n return true\n } catch {\n return false\n }\n }\n }\n\n private enum Dependencies: String {\n case kernel\n case initFs\n\n var source: String {\n switch self {\n case .initFs:\n return ClientDefaults.get(key: .defaultInitImage)\n case .kernel:\n return ClientDefaults.get(key: .defaultKernelURL)\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientImage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\n// MARK: ClientImage structure\n\npublic struct ClientImage: Sendable {\n private let contentStore: ContentStore = RemoteContentStoreClient()\n public let description: ImageDescription\n\n public var digest: String { description.digest }\n public var descriptor: Descriptor { description.descriptor }\n public var reference: String { description.reference }\n\n public init(description: ImageDescription) {\n self.description = description\n }\n\n /// Returns the underlying OCI index for the image.\n public func index() async throws -> Index {\n guard let content: Content = try await contentStore.get(digest: description.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(description.digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the manifest for the specified platform.\n public func manifest(for platform: Platform) async throws -> Manifest {\n let index = try await self.index()\n let desc = index.manifests.first { desc in\n desc.platform == platform\n }\n guard let desc else {\n throw ContainerizationError(.unsupported, message: \"Platform \\(platform.description)\")\n }\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the OCI config for the specified platform.\n public func config(for platform: Platform) async throws -> ContainerizationOCI.Image {\n let manifest = try await self.manifest(for: platform)\n let desc = manifest.config\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n return try content.decode()\n }\n}\n\n// MARK: ClientImage constants\n\nextension ClientImage {\n private static let serviceIdentifier = \"com.apple.container.core.container-core-images\"\n public static let initImageRef = ClientDefaults.get(key: .defaultInitImage)\n\n private static func newXPCClient() -> XPCClient {\n XPCClient(service: Self.serviceIdentifier)\n }\n\n private static func newRequest(_ route: ImagesServiceXPCRoute) -> XPCMessage {\n XPCMessage(route: route)\n }\n\n private static var defaultRegistryDomain: String {\n ClientDefaults.get(key: .defaultRegistryDomain)\n }\n}\n\n// MARK: Static methods\n\nextension ClientImage {\n private static let legacyDockerRegistryHost = \"docker.io\"\n private static let dockerRegistryHost = \"registry-1.docker.io\"\n private static let defaultDockerRegistryRepo = \"library\"\n\n public static func normalizeReference(_ ref: String) throws -> String {\n guard ref != Self.initImageRef else {\n // Don't modify the default init image reference.\n // This is to allow for easier local development against\n // an updated containerization.\n return ref\n }\n // Check if the input reference has a domain specified\n var updatedRawReference: String = ref\n let r = try Reference.parse(ref)\n if r.domain == nil {\n updatedRawReference = \"\\(Self.defaultRegistryDomain)/\\(ref)\"\n }\n\n let updatedReference = try Reference.parse(updatedRawReference)\n\n // Handle adding the :latest tag if it isn't specified,\n // as well as adding the \"library/\" repository if it isn't set only if the host is docker.io\n updatedReference.normalize()\n return updatedReference.description\n }\n\n public static func denormalizeReference(_ ref: String) throws -> String {\n var updatedRawReference: String = ref\n let r = try Reference.parse(ref)\n let defaultRegistry = Self.defaultRegistryDomain\n if r.domain == defaultRegistry {\n updatedRawReference = \"\\(r.path)\"\n if let tag = r.tag {\n updatedRawReference += \":\\(tag)\"\n } else if let digest = r.digest {\n updatedRawReference += \"@\\(digest)\"\n }\n if defaultRegistry == dockerRegistryHost || defaultRegistry == legacyDockerRegistryHost {\n updatedRawReference.trimPrefix(\"\\(defaultDockerRegistryRepo)/\")\n }\n }\n return updatedRawReference\n }\n\n public static func list() async throws -> [ClientImage] {\n let client = newXPCClient()\n let request = newRequest(.imageList)\n let response = try await client.send(request)\n\n let imageDescriptions = try response.imageDescriptions()\n return imageDescriptions.map { desc in\n ClientImage(description: desc)\n }\n }\n\n public static func get(names: [String]) async throws -> (images: [ClientImage], error: [String]) {\n let all = try await self.list()\n var errors: [String] = []\n var found: [ClientImage] = []\n for name in names {\n do {\n guard let img = try Self._search(reference: name, in: all) else {\n errors.append(name)\n continue\n }\n found.append(img)\n } catch {\n errors.append(name)\n }\n }\n return (found, errors)\n }\n\n public static func get(reference: String) async throws -> ClientImage {\n let all = try await self.list()\n guard let found = try self._search(reference: reference, in: all) else {\n throw ContainerizationError(.notFound, message: \"Image with reference \\(reference)\")\n }\n return found\n }\n\n private static func _search(reference: String, in all: [ClientImage]) throws -> ClientImage? {\n let locallyBuiltImage = try {\n // Check if we have an image whose index descriptor contains the image name\n // as an annotation. Prefer this in all cases, since these are locally built images.\n let r = try Reference.parse(reference)\n r.normalize()\n let withDefaultTag = r.description\n\n let localImageMatches = all.filter { $0.description.nameFromAnnotation() == withDefaultTag }\n guard localImageMatches.count > 1 else {\n return localImageMatches.first\n }\n // More than one image matched. Check against the tagged reference\n return localImageMatches.first { $0.reference == withDefaultTag }\n }()\n if let locallyBuiltImage {\n return locallyBuiltImage\n }\n // If we don't find a match, try matching `ImageDescription.name` against the given\n // input string, while also checking against its normalized form.\n // Return the first match.\n let normalizedReference = try Self.normalizeReference(reference)\n return all.first(where: { image in\n image.reference == reference || image.reference == normalizedReference\n })\n }\n\n public static func pull(reference: String, platform: Platform? = nil, scheme: RequestScheme = .auto, progressUpdate: ProgressUpdateHandler? = nil) async throws -> ClientImage {\n let client = newXPCClient()\n let request = newRequest(.imagePull)\n\n let reference = try self.normalizeReference(reference)\n guard let host = try Reference.parse(reference).domain else {\n throw ContainerizationError(.invalidArgument, message: \"Could not extract host from reference \\(reference)\")\n }\n\n request.set(key: .imageReference, value: reference)\n try request.set(platform: platform)\n\n let insecure = try scheme.schemeFor(host: host) == .http\n request.set(key: .insecureFlag, value: insecure)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n\n let response = try await client.send(request)\n let description = try response.imageDescription()\n let image = ClientImage(description: description)\n\n await progressUpdateClient?.finish()\n return image\n }\n\n public static func delete(reference: String, garbageCollect: Bool = false) async throws {\n let client = newXPCClient()\n let request = newRequest(.imageDelete)\n request.set(key: .imageReference, value: reference)\n request.set(key: .garbageCollect, value: garbageCollect)\n let _ = try await client.send(request)\n }\n\n public static func load(from tarFile: String) async throws -> [ClientImage] {\n let client = newXPCClient()\n let request = newRequest(.imageLoad)\n request.set(key: .filePath, value: tarFile)\n let reply = try await client.send(request)\n\n let loaded = try reply.imageDescriptions()\n return loaded.map { desc in\n ClientImage(description: desc)\n }\n }\n\n public static func pruneImages() async throws -> ([String], UInt64) {\n let client = newXPCClient()\n let request = newRequest(.imagePrune)\n let response = try await client.send(request)\n let digests = try response.digests()\n let size = response.uint64(key: .size)\n return (digests, size)\n }\n\n public static func fetch(reference: String, platform: Platform? = nil, scheme: RequestScheme = .auto, progressUpdate: ProgressUpdateHandler? = nil) async throws -> ClientImage\n {\n do {\n let match = try await self.get(reference: reference)\n if let platform {\n // The image exists, but we dont know if we have the right platform pulled\n // Check if we do, if not pull the requested platform\n _ = try await match.config(for: platform)\n }\n return match\n } catch let err as ContainerizationError {\n guard err.isCode(.notFound) else {\n throw err\n }\n return try await Self.pull(reference: reference, platform: platform, scheme: scheme, progressUpdate: progressUpdate)\n }\n }\n}\n\n// MARK: Instance methods\n\nextension ClientImage {\n public func push(platform: Platform? = nil, scheme: RequestScheme, progressUpdate: ProgressUpdateHandler?) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imagePush)\n\n guard let host = try Reference.parse(reference).domain else {\n throw ContainerizationError(.invalidArgument, message: \"Could not extract host from reference \\(reference)\")\n }\n request.set(key: .imageReference, value: reference)\n\n let insecure = try scheme.schemeFor(host: host) == .http\n request.set(key: .insecureFlag, value: insecure)\n\n try request.set(platform: platform)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n _ = try await client.send(request)\n await progressUpdateClient?.finish()\n }\n\n @discardableResult\n public func tag(new: String) async throws -> ClientImage {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageTag)\n request.set(key: .imageReference, value: self.description.reference)\n request.set(key: .imageNewReference, value: new)\n let reply = try await client.send(request)\n let description = try reply.imageDescription()\n return ClientImage(description: description)\n }\n\n // MARK: Snapshot Methods\n\n public func save(out: String, platform: Platform? = nil) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageSave)\n try request.set(description: self.description)\n request.set(key: .filePath, value: out)\n try request.set(platform: platform)\n let _ = try await client.send(request)\n }\n\n public func unpack(platform: Platform?, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.imageUnpack)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: request)\n }\n\n try await client.send(request)\n\n await progressUpdateClient?.finish()\n }\n\n public func deleteSnapshot(platform: Platform?) async throws {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.snapshotDelete)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n try await client.send(request)\n }\n\n public func getSnapshot(platform: Platform) async throws -> Filesystem {\n let client = Self.newXPCClient()\n let request = Self.newRequest(.snapshotGet)\n\n try request.set(description: description)\n try request.set(platform: platform)\n\n let response = try await client.send(request)\n let fs = try response.filesystem()\n return fs\n }\n\n @discardableResult\n public func getCreateSnapshot(platform: Platform, progressUpdate: ProgressUpdateHandler? = nil) async throws -> Filesystem {\n do {\n return try await self.getSnapshot(platform: platform)\n } catch let err as ContainerizationError {\n guard err.code == .notFound else {\n throw err\n }\n try await self.unpack(platform: platform, progressUpdate: progressUpdate)\n return try await self.getSnapshot(platform: platform)\n }\n }\n}\n\nextension XPCMessage {\n fileprivate func set(description: ImageDescription) throws {\n let descData = try JSONEncoder().encode(description)\n self.set(key: .imageDescription, value: descData)\n }\n\n fileprivate func set(descriptions: [ImageDescription]) throws {\n let descData = try JSONEncoder().encode(descriptions)\n self.set(key: .imageDescriptions, value: descData)\n }\n\n fileprivate func set(platform: Platform?) throws {\n guard let platform else {\n return\n }\n let platformData = try JSONEncoder().encode(platform)\n self.set(key: .ociPlatform, value: platformData)\n }\n\n fileprivate func imageDescription() throws -> ImageDescription {\n let responseData = self.dataNoCopy(key: .imageDescription)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"imageDescription not received\")\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: responseData)\n return description\n }\n\n fileprivate func imageDescriptions() throws -> [ImageDescription] {\n let responseData = self.dataNoCopy(key: .imageDescriptions)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"imageDescriptions not received\")\n }\n let descriptions = try JSONDecoder().decode([ImageDescription].self, from: responseData)\n return descriptions\n }\n\n fileprivate func filesystem() throws -> Filesystem {\n let responseData = self.dataNoCopy(key: .filesystem)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"filesystem not received\")\n }\n let fs = try JSONDecoder().decode(Filesystem.self, from: responseData)\n return fs\n }\n\n fileprivate func digests() throws -> [String] {\n let responseData = self.dataNoCopy(key: .digests)\n guard let responseData else {\n throw ContainerizationError(.empty, message: \"digests not received\")\n }\n let digests = try JSONDecoder().decode([String].self, from: responseData)\n return digests\n }\n}\n\nextension ImageDescription {\n fileprivate func nameFromAnnotation() -> String? {\n guard let annotations = self.descriptor.annotations else {\n return nil\n }\n guard let name = annotations[AnnotationKeys.containerizationImageName] else {\n return nil\n }\n return name\n }\n}\n"], ["/container/Sources/ContainerPlugin/LaunchPlist.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\n\npublic struct LaunchPlist: Encodable {\n public enum Domain: String, Codable {\n case Aqua\n case Background\n case System\n }\n\n public let label: String\n public let arguments: [String]\n\n public let environment: [String: String]?\n public let cwd: String?\n public let username: String?\n public let groupname: String?\n public let limitLoadToSessionType: [Domain]?\n public let runAtLoad: Bool?\n public let stdin: String?\n public let stdout: String?\n public let stderr: String?\n public let disabled: Bool?\n public let program: String?\n public let keepAlive: Bool?\n public let machServices: [String: Bool]?\n public let waitForDebugger: Bool?\n\n enum CodingKeys: String, CodingKey {\n case label = \"Label\"\n case arguments = \"ProgramArguments\"\n case environment = \"EnvironmentVariables\"\n case cwd = \"WorkingDirectory\"\n case username = \"UserName\"\n case groupname = \"GroupName\"\n case limitLoadToSessionType = \"LimitLoadToSessionType\"\n case runAtLoad = \"RunAtLoad\"\n case stdin = \"StandardInPath\"\n case stdout = \"StandardOutPath\"\n case stderr = \"StandardErrorPath\"\n case disabled = \"Disabled\"\n case program = \"Program\"\n case keepAlive = \"KeepAlive\"\n case machServices = \"MachServices\"\n case waitForDebugger = \"WaitForDebugger\"\n }\n\n public init(\n label: String,\n arguments: [String],\n environment: [String: String]? = nil,\n cwd: String? = nil,\n username: String? = nil,\n groupname: String? = nil,\n limitLoadToSessionType: [Domain]? = nil,\n runAtLoad: Bool? = nil,\n stdin: String? = nil,\n stdout: String? = nil,\n stderr: String? = nil,\n disabled: Bool? = nil,\n program: String? = nil,\n keepAlive: Bool? = nil,\n machServices: [String]? = nil,\n waitForDebugger: Bool? = nil\n ) {\n self.label = label\n self.arguments = arguments\n self.environment = environment\n self.cwd = cwd\n self.username = username\n self.groupname = groupname\n self.limitLoadToSessionType = limitLoadToSessionType\n self.runAtLoad = runAtLoad\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n self.disabled = disabled\n self.program = program\n self.keepAlive = keepAlive\n self.waitForDebugger = waitForDebugger\n if let services = machServices {\n var machServices: [String: Bool] = [:]\n for service in services {\n machServices[service] = true\n }\n self.machServices = machServices\n } else {\n self.machServices = nil\n }\n }\n}\n\nextension LaunchPlist {\n public func encode() throws -> Data {\n let enc = PropertyListEncoder()\n enc.outputFormat = .xml\n return try enc.encode(self)\n }\n}\n#endif\n"], ["/container/Sources/Services/ContainerImagesService/Server/SnapshotStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport TerminalProgress\n\npublic actor SnapshotStore {\n private static let snapshotFileName = \"snapshot\"\n private static let snapshotInfoFileName = \"snapshot-info\"\n private static let ingestDirName = \"ingest\"\n\n /// Return the Unpacker to use for a given image.\n /// If the given platform for the image cannot be unpacked return `nil`.\n public typealias UnpackStrategy = @Sendable (Containerization.Image, Platform) async throws -> Unpacker?\n\n public static let defaultUnpackStrategy: UnpackStrategy = { image, platform in\n guard platform.os == \"linux\" else {\n return nil\n }\n var minBlockSize = 512.gib()\n if image.reference == ClientDefaults.get(key: .defaultInitImage) {\n minBlockSize = 512.mib()\n }\n return EXT4Unpacker(blockSizeInBytes: minBlockSize)\n }\n\n let path: URL\n let fm = FileManager.default\n let ingestDir: URL\n let unpackStrategy: UnpackStrategy\n let log: Logger?\n\n public init(path: URL, unpackStrategy: @escaping UnpackStrategy, log: Logger?) throws {\n let root = path.appendingPathComponent(\"snapshots\")\n self.path = root\n self.ingestDir = self.path.appendingPathComponent(Self.ingestDirName)\n self.unpackStrategy = unpackStrategy\n self.log = log\n try self.fm.createDirectory(at: root, withIntermediateDirectories: true)\n try self.fm.createDirectory(at: self.ingestDir, withIntermediateDirectories: true)\n }\n\n public func unpack(image: Containerization.Image, platform: Platform? = nil, progressUpdate: ProgressUpdateHandler?) async throws {\n var toUnpack: [Descriptor] = []\n if let platform {\n let desc = try await image.descriptor(for: platform)\n toUnpack = [desc]\n } else {\n toUnpack = try await image.unpackableDescriptors()\n }\n\n let taskManager = ProgressTaskCoordinator()\n var taskUpdateProgress: ProgressUpdateHandler?\n\n for desc in toUnpack {\n try Task.checkCancellation()\n let snapshotDir = self.snapshotDir(desc)\n guard !self.fm.fileExists(atPath: snapshotDir.absolutePath()) else {\n // We have already unpacked this image + platform. Skip\n continue\n }\n guard let platform = desc.platform else {\n throw ContainerizationError(.internalError, message: \"Missing platform for descriptor \\(desc.digest)\")\n }\n guard let unpacker = try await self.unpackStrategy(image, platform) else {\n self.log?.warning(\"Skipping unpack for \\(image.reference) for platform \\(platform.description). No unpacker configured.\")\n continue\n }\n let currentSubTask = await taskManager.startTask()\n if let progressUpdate {\n let _taskUpdateProgress = ProgressTaskCoordinator.handler(for: currentSubTask, from: progressUpdate)\n await _taskUpdateProgress([\n .setSubDescription(\"for platform \\(platform.description)\")\n ])\n taskUpdateProgress = _taskUpdateProgress\n }\n\n let tempDir = try self.tempUnpackDir()\n\n let tempSnapshotPath = tempDir.appendingPathComponent(Self.snapshotFileName, isDirectory: false)\n let infoPath = tempDir.appendingPathComponent(Self.snapshotInfoFileName, isDirectory: false)\n do {\n let progress = ContainerizationProgressAdapter.handler(from: taskUpdateProgress)\n let mount = try await unpacker.unpack(image, for: platform, at: tempSnapshotPath, progress: progress)\n let fs = Filesystem.block(\n format: mount.type,\n source: self.snapshotPath(desc).absolutePath(),\n destination: mount.destination,\n options: mount.options\n )\n let snapshotInfo = try JSONEncoder().encode(fs)\n self.fm.createFile(atPath: infoPath.absolutePath(), contents: snapshotInfo)\n } catch {\n try? self.fm.removeItem(at: tempDir)\n throw error\n }\n do {\n try fm.moveItem(at: tempDir, to: snapshotDir)\n } catch let err as NSError {\n guard err.code == NSFileWriteFileExistsError else {\n throw err\n }\n try? self.fm.removeItem(at: tempDir)\n }\n }\n await taskManager.finish()\n }\n\n public func delete(for image: Containerization.Image, platform: Platform? = nil) async throws {\n var toDelete: [Descriptor] = []\n if let platform {\n let desc = try await image.descriptor(for: platform)\n toDelete.append(desc)\n } else {\n toDelete = try await image.unpackableDescriptors()\n }\n for desc in toDelete {\n let p = self.snapshotDir(desc)\n guard self.fm.fileExists(atPath: p.absolutePath()) else {\n continue\n }\n try self.fm.removeItem(at: p)\n }\n }\n\n public func get(for image: Containerization.Image, platform: Platform) async throws -> Filesystem {\n let desc = try await image.descriptor(for: platform)\n let infoPath = snapshotInfoPath(desc)\n let fsPath = snapshotPath(desc)\n\n guard self.fm.fileExists(atPath: infoPath.absolutePath()),\n self.fm.fileExists(atPath: fsPath.absolutePath())\n else {\n throw ContainerizationError(.notFound, message: \"image snapshot for \\(image.reference) with platform \\(platform.description)\")\n }\n let decoder = JSONDecoder()\n let data = try Data(contentsOf: infoPath)\n let fs = try decoder.decode(Filesystem.self, from: data)\n return fs\n }\n\n public func clean(keepingSnapshotsFor images: [Containerization.Image] = []) async throws -> UInt64 {\n var toKeep: [String] = [Self.ingestDirName]\n for image in images {\n for manifest in try await image.index().manifests {\n guard let platform = manifest.platform else {\n continue\n }\n let desc = try await image.descriptor(for: platform)\n toKeep.append(desc.digest.trimmingDigestPrefix)\n }\n }\n let all = try self.fm.contentsOfDirectory(at: self.path, includingPropertiesForKeys: [.totalFileAllocatedSizeKey]).map {\n $0.lastPathComponent\n }\n let delete = Set(all).subtracting(Set(toKeep))\n var deletedBytes: UInt64 = 0\n for dir in delete {\n let unpackedPath = self.path.appending(path: dir, directoryHint: .isDirectory)\n guard self.fm.fileExists(atPath: unpackedPath.absolutePath()) else {\n continue\n }\n deletedBytes += (try? self.fm.directorySize(dir: unpackedPath)) ?? 0\n try self.fm.removeItem(at: unpackedPath)\n }\n return deletedBytes\n }\n\n private func snapshotDir(_ desc: Descriptor) -> URL {\n let p = self.path.appendingPathComponent(desc.digest.trimmingDigestPrefix, isDirectory: true)\n return p\n }\n\n private func snapshotPath(_ desc: Descriptor) -> URL {\n let p = self.snapshotDir(desc)\n .appendingPathComponent(Self.snapshotFileName, isDirectory: false)\n return p\n }\n\n private func snapshotInfoPath(_ desc: Descriptor) -> URL {\n let p = self.snapshotDir(desc)\n .appendingPathComponent(Self.snapshotInfoFileName, isDirectory: false)\n return p\n }\n\n private func tempUnpackDir() throws -> URL {\n let uniqueDirectoryURL = ingestDir.appendingPathComponent(UUID().uuidString, isDirectory: true)\n try self.fm.createDirectory(at: uniqueDirectoryURL, withIntermediateDirectories: true, attributes: nil)\n return uniqueDirectoryURL\n }\n}\n\nextension FileManager {\n fileprivate func directorySize(dir: URL) throws -> UInt64 {\n var size = 0\n let resourceKeys: [URLResourceKey] = [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey]\n let contents = try self.contentsOfDirectory(\n at: dir,\n includingPropertiesForKeys: resourceKeys)\n\n for p in contents {\n let val = try p.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey])\n size += val.totalFileAllocatedSize ?? val.fileAllocatedSize ?? 0\n }\n return UInt64(size)\n }\n}\n\nextension Containerization.Image {\n fileprivate func unpackableDescriptors() async throws -> [Descriptor] {\n let index = try await self.index()\n return index.manifests.filter { desc in\n guard desc.platform != nil else {\n return false\n }\n if let referenceType = desc.annotations?[\"vnd.docker.reference.type\"], referenceType == \"attestation-manifest\" {\n return false\n }\n return true\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Utility.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct Utility {\n private static let infraImages = [\n ClientDefaults.get(key: .defaultBuilderImage),\n ClientDefaults.get(key: .defaultInitImage),\n ]\n\n public static func createContainerID(name: String?) -> String {\n guard let name else {\n return UUID().uuidString.lowercased()\n }\n return name\n }\n\n public static func isInfraImage(name: String) -> Bool {\n for infraImage in infraImages {\n if name == infraImage {\n return true\n }\n }\n return false\n }\n\n public static func trimDigest(digest: String) -> String {\n var digest = digest\n digest.trimPrefix(\"sha256:\")\n if digest.count > 24 {\n digest = String(digest.prefix(24)) + \"...\"\n }\n return digest\n }\n\n public static func validEntityName(_ name: String) throws {\n let pattern = #\"^[a-zA-Z0-9][a-zA-Z0-9_.-]+$\"#\n let regex = try Regex(pattern)\n if try regex.firstMatch(in: name) == nil {\n throw ContainerizationError(.invalidArgument, message: \"invalid entity name \\(name)\")\n }\n }\n\n public static func containerConfigFromFlags(\n id: String,\n image: String,\n arguments: [String],\n process: Flags.Process,\n management: Flags.Management,\n resource: Flags.Resource,\n registry: Flags.Registry,\n progressUpdate: @escaping ProgressUpdateHandler\n ) async throws -> (ContainerConfiguration, Kernel) {\n let requestedPlatform = Parser.platform(os: management.os, arch: management.arch)\n let scheme = try RequestScheme(registry.scheme)\n\n await progressUpdate([\n .setDescription(\"Fetching image\"),\n .setItemsName(\"blobs\"),\n ])\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n let img = try await ClientImage.fetch(\n reference: image,\n platform: requestedPlatform,\n scheme: scheme,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progressUpdate)\n )\n\n // Unpack a fetched image before use\n await progressUpdate([\n .setDescription(\"Unpacking image\"),\n .setItemsName(\"entries\"),\n ])\n let unpackTask = await taskManager.startTask()\n try await img.getCreateSnapshot(\n platform: requestedPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progressUpdate))\n\n await progressUpdate([\n .setDescription(\"Fetching kernel\"),\n .setItemsName(\"binary\"),\n ])\n\n let kernel = try await self.getKernel(management: management)\n\n // Pull and unpack the initial filesystem\n await progressUpdate([\n .setDescription(\"Fetching init image\"),\n .setItemsName(\"blobs\"),\n ])\n let fetchInitTask = await taskManager.startTask()\n let initImage = try await ClientImage.fetch(\n reference: ClientImage.initImageRef, platform: .current, scheme: scheme,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchInitTask, from: progressUpdate))\n\n await progressUpdate([\n .setDescription(\"Unpacking init image\"),\n .setItemsName(\"entries\"),\n ])\n let unpackInitTask = await taskManager.startTask()\n _ = try await initImage.getCreateSnapshot(\n platform: .current,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackInitTask, from: progressUpdate))\n\n await taskManager.finish()\n\n let imageConfig = try await img.config(for: requestedPlatform).config\n let description = img.description\n let pc = try Parser.process(\n arguments: arguments,\n processFlags: process,\n managementFlags: management,\n config: imageConfig\n )\n\n var config = ContainerConfiguration(id: id, image: description, process: pc)\n config.platform = requestedPlatform\n config.hostname = id\n\n config.resources = try Parser.resources(\n cpus: resource.cpus,\n memory: resource.memory\n )\n\n let tmpfs = try Parser.tmpfsMounts(management.tmpFs)\n let volumes = try Parser.volumes(management.volumes)\n var mounts = try Parser.mounts(management.mounts)\n mounts.append(contentsOf: tmpfs)\n mounts.append(contentsOf: volumes)\n config.mounts = mounts\n\n if management.networks.isEmpty {\n config.networks = [ClientNetwork.defaultNetworkName]\n } else {\n // networks may only be specified for macOS 26+\n guard #available(macOS 26, *) else {\n throw ContainerizationError(.invalidArgument, message: \"non-default network configuration requires macOS 26 or newer\")\n }\n config.networks = management.networks\n }\n\n var networkStatuses: [NetworkStatus] = []\n for networkName in config.networks {\n let network: NetworkState = try await ClientNetwork.get(id: networkName)\n guard case .running(_, let networkStatus) = network else {\n throw ContainerizationError(.invalidState, message: \"network \\(networkName) is not running\")\n }\n networkStatuses.append(networkStatus)\n }\n\n if management.dnsDisabled {\n config.dns = nil\n } else {\n let domain = management.dnsDomain ?? ClientDefaults.getOptional(key: .defaultDNSDomain)\n config.dns = .init(\n nameservers: management.dnsNameservers,\n domain: domain,\n searchDomains: management.dnsSearchDomains,\n options: management.dnsOptions\n )\n }\n\n if Platform.current.architecture == \"arm64\" && requestedPlatform.architecture == \"amd64\" {\n config.rosetta = true\n }\n\n config.labels = try Parser.labels(management.labels)\n\n config.publishedPorts = try Parser.publishPorts(management.publishPorts)\n\n // Parse --publish-socket arguments and add to container configuration\n // to enable socket forwarding from container to host.\n config.publishedSockets = try Parser.publishSockets(management.publishSockets)\n\n return (config, kernel)\n }\n\n private static func getKernel(management: Flags.Management) async throws -> Kernel {\n // For the image itself we'll take the user input and try with it as we can do userspace\n // emulation for x86, but for the kernel we need it to match the hosts architecture.\n let s: SystemPlatform = .current\n if let userKernel = management.kernel {\n guard FileManager.default.fileExists(atPath: userKernel) else {\n throw ContainerizationError(.notFound, message: \"Kernel file not found at path \\(userKernel)\")\n }\n let p = URL(filePath: userKernel)\n return .init(path: p, platform: s)\n }\n return try await ClientKernel.getDefaultKernel(for: s)\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildFSSync.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport ContainerClient\nimport ContainerizationArchive\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\n\nactor BuildFSSync: BuildPipelineHandler {\n let contextDir: URL\n\n init(_ contextDir: URL) throws {\n guard FileManager.default.fileExists(atPath: contextDir.cleanPath) else {\n throw Error.contextNotFound(contextDir.cleanPath)\n }\n guard try contextDir.isDir() else {\n throw Error.contextIsNotDirectory(contextDir.cleanPath)\n }\n\n self.contextDir = contextDir\n }\n\n nonisolated func accept(_ packet: ServerStream) throws -> Bool {\n guard let buildTransfer = packet.getBuildTransfer() else {\n return false\n }\n guard buildTransfer.stage() == \"fssync\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let buildTransfer = packet.getBuildTransfer() else {\n throw Error.buildTransferMissing\n }\n guard let method = buildTransfer.method() else {\n throw Error.methodMissing\n }\n switch try FSSyncMethod(method) {\n case .read:\n try await self.read(sender, buildTransfer, packet.buildID)\n case .info:\n try await self.info(sender, buildTransfer, packet.buildID)\n case .walk:\n try await self.walk(sender, buildTransfer, packet.buildID)\n }\n }\n\n func read(_ sender: AsyncStream.Continuation, _ packet: BuildTransfer, _ buildID: String) async throws {\n let offset: UInt64 = packet.offset() ?? 0\n let size: Int = packet.len() ?? 0\n var path: URL\n if packet.source.hasPrefix(\"/\") {\n path = URL(fileURLWithPath: packet.source).standardizedFileURL\n } else {\n path =\n contextDir\n .appendingPathComponent(packet.source)\n .standardizedFileURL\n }\n if !FileManager.default.fileExists(atPath: path.cleanPath) {\n path = URL(filePath: self.contextDir.cleanPath)\n path.append(components: packet.source.cleanPathComponent)\n }\n let data = try {\n if try path.isDir() {\n return Data()\n }\n let file = try LocalContent(path: path.standardizedFileURL)\n return try file.data(offset: offset, length: size) ?? Data()\n }()\n\n let transfer = try path.buildTransfer(id: packet.id, contextDir: self.contextDir, complete: true, data: data)\n var response = ClientStream()\n response.buildID = buildID\n response.buildTransfer = transfer\n response.packetType = .buildTransfer(transfer)\n sender.yield(response)\n }\n\n func info(_ sender: AsyncStream.Continuation, _ packet: BuildTransfer, _ buildID: String) async throws {\n let path: URL\n if packet.source.hasPrefix(\"/\") {\n path = URL(fileURLWithPath: packet.source).standardizedFileURL\n } else {\n path =\n contextDir\n .appendingPathComponent(packet.source)\n .standardizedFileURL\n }\n let transfer = try path.buildTransfer(id: packet.id, contextDir: self.contextDir, complete: true)\n var response = ClientStream()\n response.buildID = buildID\n response.buildTransfer = transfer\n response.packetType = .buildTransfer(transfer)\n sender.yield(response)\n }\n\n private struct DirEntry: Hashable {\n let url: URL\n let isDirectory: Bool\n let relativePath: String\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(relativePath)\n }\n\n static func == (lhs: DirEntry, rhs: DirEntry) -> Bool {\n lhs.relativePath == rhs.relativePath\n }\n }\n\n func walk(\n _ sender: AsyncStream.Continuation,\n _ packet: BuildTransfer,\n _ buildID: String\n ) async throws {\n let wantsTar = packet.mode() == \"tar\"\n\n var entries: [String: Set] = [:]\n let followPaths: [String] = packet.followPaths() ?? []\n\n let followPathsWalked = try walk(root: self.contextDir, includePatterns: followPaths)\n for url in followPathsWalked {\n guard self.contextDir.absoluteURL.cleanPath != url.absoluteURL.cleanPath else {\n continue\n }\n guard self.contextDir.parentOf(url) else {\n continue\n }\n\n let relPath = try url.relativeChildPath(to: contextDir)\n let parentPath = try url.deletingLastPathComponent().relativeChildPath(to: contextDir)\n let entry = DirEntry(url: url, isDirectory: url.hasDirectoryPath, relativePath: relPath)\n entries[parentPath, default: []].insert(entry)\n\n if url.isSymlink {\n let target: URL = url.resolvingSymlinksInPath()\n if self.contextDir.parentOf(target) {\n let relPath = try target.relativeChildPath(to: self.contextDir)\n let entry = DirEntry(url: target, isDirectory: target.hasDirectoryPath, relativePath: relPath)\n let parentPath: String = try target.deletingLastPathComponent().relativeChildPath(to: self.contextDir)\n entries[parentPath, default: []].insert(entry)\n }\n }\n }\n\n var fileOrder = [String]()\n try processDirectory(\"\", inputEntries: entries, processedPaths: &fileOrder)\n\n if !wantsTar {\n let fileInfos = try fileOrder.map { rel -> FileInfo in\n try FileInfo(path: contextDir.appendingPathComponent(rel), contextDir: contextDir)\n }\n\n let data = try JSONEncoder().encode(fileInfos)\n let transfer = BuildTransfer(\n id: packet.id,\n source: packet.source,\n complete: true,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"json\",\n ],\n data: data\n )\n var resp = ClientStream()\n resp.buildID = buildID\n resp.buildTransfer = transfer\n resp.packetType = .buildTransfer(transfer)\n sender.yield(resp)\n return\n }\n\n let tarURL = URL.temporaryDirectory\n .appendingPathComponent(UUID().uuidString + \".tar\")\n\n defer { try? FileManager.default.removeItem(at: tarURL) }\n\n let writerCfg = ArchiveWriterConfiguration(\n format: .paxRestricted,\n filter: .none)\n\n try Archiver.compress(\n source: contextDir,\n destination: tarURL,\n writerConfiguration: writerCfg\n ) { url in\n guard let rel = try? url.relativeChildPath(to: contextDir) else {\n return nil\n }\n\n guard let parent = try? url.deletingLastPathComponent().relativeChildPath(to: self.contextDir) else {\n return nil\n }\n\n guard let items = entries[parent] else {\n return nil\n }\n\n let include = items.contains { item in\n item.relativePath == rel\n }\n\n guard include else {\n return nil\n }\n\n return Archiver.ArchiveEntryInfo(\n pathOnHost: url,\n pathInArchive: URL(fileURLWithPath: rel))\n }\n\n for try await chunk in try tarURL.bufferedCopyReader() {\n let part = BuildTransfer(\n id: packet.id,\n source: tarURL.path,\n complete: false,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"tar\",\n ],\n data: chunk\n )\n var resp = ClientStream()\n resp.buildID = buildID\n resp.buildTransfer = part\n resp.packetType = .buildTransfer(part)\n sender.yield(resp)\n }\n\n let done = BuildTransfer(\n id: packet.id,\n source: tarURL.path,\n complete: true,\n isDir: false,\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": \"tar\",\n ],\n data: Data()\n )\n\n var finalResp = ClientStream()\n finalResp.buildID = buildID\n finalResp.buildTransfer = done\n finalResp.packetType = .buildTransfer(done)\n sender.yield(finalResp)\n }\n\n func walk(root: URL, includePatterns: [String]) throws -> [URL] {\n let globber = Globber(root)\n\n for p in includePatterns {\n try globber.match(p)\n }\n return Array(globber.results)\n }\n\n private func processDirectory(\n _ currentDir: String,\n inputEntries: [String: Set],\n processedPaths: inout [String]\n ) throws {\n guard let entries = inputEntries[currentDir] else {\n return\n }\n\n // Sort purely by lexicographical order of relativePath\n let sortedEntries = entries.sorted { $0.relativePath < $1.relativePath }\n\n for entry in sortedEntries {\n processedPaths.append(entry.relativePath)\n\n if entry.isDirectory {\n try processDirectory(\n entry.relativePath,\n inputEntries: inputEntries,\n processedPaths: &processedPaths\n )\n }\n }\n }\n\n struct FileInfo: Codable {\n let name: String\n let modTime: String\n let mode: UInt32\n let size: UInt64\n let isDir: Bool\n let uid: UInt32\n let gid: UInt32\n let target: String\n\n init(path: URL, contextDir: URL) throws {\n if path.isSymlink {\n let target: URL = path.resolvingSymlinksInPath()\n if contextDir.parentOf(target) {\n self.target = target.relativePathFrom(from: path)\n } else {\n self.target = target.cleanPath\n }\n } else {\n self.target = \"\"\n }\n\n self.name = try path.relativeChildPath(to: contextDir)\n self.modTime = try path.modTime()\n self.mode = try path.mode()\n self.size = try path.size()\n self.isDir = path.hasDirectoryPath\n self.uid = 0\n self.gid = 0\n }\n }\n\n enum FSSyncMethod: String {\n case read = \"Read\"\n case info = \"Info\"\n case walk = \"Walk\"\n\n init(_ method: String) throws {\n switch method {\n case \"Read\":\n self = .read\n case \"Info\":\n self = .info\n case \"Walk\":\n self = .walk\n default:\n throw Error.unknownMethod(method)\n }\n }\n }\n}\n\nextension BuildFSSync {\n enum Error: Swift.Error, CustomStringConvertible, Equatable {\n case buildTransferMissing\n case methodMissing\n case unknownMethod(String)\n case contextNotFound(String)\n case contextIsNotDirectory(String)\n case couldNotDetermineFileSize(String)\n case couldNotDetermineModTime(String)\n case couldNotDetermineFileMode(String)\n case invalidOffsetSizeForFile(String, UInt64, Int)\n case couldNotDetermineUID(String)\n case couldNotDetermineGID(String)\n case pathIsNotChild(String, String)\n\n var description: String {\n switch self {\n case .buildTransferMissing:\n return \"buildTransfer field missing in packet\"\n case .methodMissing:\n return \"method is missing in request\"\n case .unknownMethod(let m):\n return \"unknown content-store method \\(m)\"\n case .contextNotFound(let path):\n return \"context dir \\(path) not found\"\n case .contextIsNotDirectory(let path):\n return \"context \\(path) not a directory\"\n case .couldNotDetermineFileSize(let path):\n return \"could not determine size of file \\(path)\"\n case .couldNotDetermineModTime(let path):\n return \"could not determine last modified time of \\(path)\"\n case .couldNotDetermineFileMode(let path):\n return \"could not determine posix permissions (FileMode) of \\(path)\"\n case .invalidOffsetSizeForFile(let digest, let offset, let size):\n return \"invalid request for file: \\(digest) with offset: \\(offset) size: \\(size)\"\n case .couldNotDetermineUID(let path):\n return \"could not determine UID of file at path: \\(path)\"\n case .couldNotDetermineGID(let path):\n return \"could not determine GID of file at path: \\(path)\"\n case .pathIsNotChild(let path, let parent):\n return \"\\(path) is not a child of \\(parent)\"\n }\n }\n }\n}\n\nextension BuildTransfer {\n fileprivate init(id: String, source: String, complete: Bool, isDir: Bool, metadata: [String: String], data: Data? = nil) {\n self.init()\n self.id = id\n self.source = source\n self.direction = .outof\n self.complete = complete\n self.metadata = metadata\n self.isDirectory = isDir\n if let data {\n self.data = data\n }\n }\n}\n\nextension URL {\n fileprivate func size() throws -> UInt64 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let size = attrs[FileAttributeKey.size] as? UInt64 {\n return size\n }\n throw BuildFSSync.Error.couldNotDetermineFileSize(self.cleanPath)\n }\n\n fileprivate func modTime() throws -> String {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let date = attrs[FileAttributeKey.modificationDate] as? Date {\n return date.rfc3339()\n }\n throw BuildFSSync.Error.couldNotDetermineModTime(self.cleanPath)\n }\n\n fileprivate func isDir() throws -> Bool {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n guard let t = attrs[.type] as? FileAttributeType, t == .typeDirectory else {\n return false\n }\n return true\n }\n\n fileprivate func mode() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let mode = attrs[FileAttributeKey.posixPermissions] as? NSNumber {\n return mode.uint32Value\n }\n throw BuildFSSync.Error.couldNotDetermineFileMode(self.cleanPath)\n }\n\n fileprivate func uid() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let uid = attrs[.ownerAccountID] as? UInt32 {\n return uid\n }\n throw BuildFSSync.Error.couldNotDetermineUID(self.cleanPath)\n }\n\n fileprivate func gid() throws -> UInt32 {\n let attrs = try FileManager.default.attributesOfItem(atPath: self.cleanPath)\n if let gid = attrs[.groupOwnerAccountID] as? UInt32 {\n return gid\n }\n throw BuildFSSync.Error.couldNotDetermineGID(self.cleanPath)\n }\n\n fileprivate func buildTransfer(\n id: String,\n contextDir: URL? = nil,\n complete: Bool = false,\n data: Data = Data()\n ) throws -> BuildTransfer {\n let p = try {\n if let contextDir { return try self.relativeChildPath(to: contextDir) }\n return self.cleanPath\n }()\n return BuildTransfer(\n id: id,\n source: String(p),\n complete: complete,\n isDir: try self.isDir(),\n metadata: [\n \"os\": \"linux\",\n \"stage\": \"fssync\",\n \"mode\": String(try self.mode()),\n \"size\": String(try self.size()),\n \"modified_at\": try self.modTime(),\n \"uid\": String(try self.uid()),\n \"gid\": String(try self.gid()),\n ],\n data: data\n )\n }\n}\n\nextension Date {\n fileprivate func rfc3339() -> String {\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"yyyy-MM-dd'T'HH:mm:ssZZZZZ\"\n dateFormatter.locale = Locale(identifier: \"en_US_POSIX\")\n dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // Adjust if necessary\n\n return dateFormatter.string(from: self)\n }\n}\n\nextension String {\n var cleanPathComponent: String {\n let trimmed = self.trimmingCharacters(in: CharacterSet(charactersIn: \"/\"))\n if let clean = trimmed.removingPercentEncoding {\n return clean\n }\n return trimmed\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/RuntimeLinuxHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerClient\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\nimport NIO\n\n@main\nstruct RuntimeLinuxHelper: AsyncParsableCommand {\n static let label = \"com.apple.container.runtime.container-runtime-linux\"\n\n static let configuration = CommandConfiguration(\n commandName: \"container-runtime-linux\",\n abstract: \"XPC Service for managing a Linux sandbox\",\n version: releaseVersion()\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .shortAndLong, help: \"Sandbox UUID\")\n var uuid: String\n\n @Option(name: .shortAndLong, help: \"Root directory for the sandbox\")\n var root: String\n\n var machServiceLabel: String {\n \"\\(Self.label).\\(uuid)\"\n }\n\n func run() async throws {\n let commandName = Self._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n do {\n try adjustLimits()\n signal(SIGPIPE, SIG_IGN)\n\n log.info(\"configuring XPC server\")\n let interfaceStrategy: any InterfaceStrategy\n if #available(macOS 26, *) {\n interfaceStrategy = NonisolatedInterfaceStrategy(log: log)\n } else {\n interfaceStrategy = IsolatedInterfaceStrategy()\n }\n let server = SandboxService(root: .init(fileURLWithPath: root), interfaceStrategy: interfaceStrategy, eventLoopGroup: eventLoopGroup, log: log)\n let xpc = XPCServer(\n identifier: machServiceLabel,\n routes: [\n SandboxRoutes.bootstrap.rawValue: server.bootstrap,\n SandboxRoutes.createProcess.rawValue: server.createProcess,\n SandboxRoutes.state.rawValue: server.state,\n SandboxRoutes.stop.rawValue: server.stop,\n SandboxRoutes.kill.rawValue: server.kill,\n SandboxRoutes.resize.rawValue: server.resize,\n SandboxRoutes.wait.rawValue: server.wait,\n SandboxRoutes.start.rawValue: server.startProcess,\n SandboxRoutes.dial.rawValue: server.dial,\n ],\n log: log\n )\n\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n try? await eventLoopGroup.shutdownGracefully()\n RuntimeLinuxHelper.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"RuntimeLinuxHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n log[metadataKey: \"uuid\"] = \"\\(uuid)\"\n return log\n }\n\n private func adjustLimits() throws {\n var limits = rlimit()\n guard getrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n limits.rlim_cur = 65536\n limits.rlim_max = 65536\n guard setrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/CLI/System/SystemStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nextension Application {\n struct SystemStop: AsyncParsableCommand {\n private static let stopTimeoutSeconds: Int32 = 5\n private static let shutdownTimeoutSeconds: Int32 = 20\n\n static let configuration = CommandConfiguration(\n commandName: \"stop\",\n abstract: \"Stop all `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Launchd prefix for `container` services\")\n var prefix: String = \"com.apple.container.\"\n\n func run() async throws {\n let log = Logger(\n label: \"com.apple.container.cli\",\n factory: { label in\n StreamLogHandler.standardOutput(label: label)\n }\n )\n\n let launchdDomainString = try ServiceManager.getDomainString()\n let fullLabel = \"\\(launchdDomainString)/\\(prefix)apiserver\"\n\n log.info(\"stopping containers\", metadata: [\"stopTimeoutSeconds\": \"\\(Self.stopTimeoutSeconds)\"])\n do {\n let containers = try await ClientContainer.list()\n let signal = try Signals.parseSignal(\"SIGTERM\")\n let opts = ContainerStopOptions(timeoutInSeconds: Self.stopTimeoutSeconds, signal: signal)\n let failed = try await ContainerStop.stopContainers(containers: containers, stopOptions: opts)\n if !failed.isEmpty {\n log.warning(\"some containers could not be stopped gracefully\", metadata: [\"ids\": \"\\(failed)\"])\n }\n\n } catch {\n log.warning(\"failed to stop all containers\", metadata: [\"error\": \"\\(error)\"])\n }\n\n log.info(\"waiting for containers to exit\")\n do {\n for _ in 0.. ArchiveEntryInfo?\n ) throws {\n let source = source.standardizedFileURL\n let destination = destination.standardizedFileURL\n\n let fileManager = FileManager.default\n try? fileManager.removeItem(at: destination)\n\n do {\n let directory = destination.deletingLastPathComponent()\n try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)\n\n guard\n let enumerator = FileManager.default.enumerator(\n at: source,\n includingPropertiesForKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]\n )\n else {\n throw Error.fileDoesNotExist(source)\n }\n\n var entryInfo = [ArchiveEntryInfo]()\n if !source.isDirectory {\n if let info = closure(source) {\n entryInfo.append(info)\n }\n } else {\n while let url = enumerator.nextObject() as? URL {\n guard let info = closure(url) else {\n continue\n }\n entryInfo.append(info)\n }\n }\n\n let archiver = try ArchiveWriter(\n configuration: writerConfiguration\n )\n try archiver.open(file: destination)\n\n for info in entryInfo {\n guard let entry = try Self._createEntry(entryInfo: info) else {\n throw Error.failedToCreateEntry\n }\n try Self._compressFile(item: info.pathOnHost, entry: entry, archiver: archiver)\n }\n try archiver.finishEncoding()\n } catch {\n try? fileManager.removeItem(at: destination)\n throw error\n }\n }\n\n public static func uncompress(source: URL, destination: URL) throws {\n let source = source.standardizedFileURL\n let destination = destination.standardizedFileURL\n\n // TODO: ArchiveReader needs some enhancement to support buffered uncompression\n let reader = try ArchiveReader(\n format: .paxRestricted,\n filter: .gzip,\n file: source\n )\n\n for (entry, data) in reader {\n guard let path = entry.path else {\n continue\n }\n let uncompressPath = destination.appendingPathComponent(path)\n\n let fileManager = FileManager.default\n switch entry.fileType {\n case .blockSpecial, .characterSpecial, .socket:\n continue\n case .directory:\n try fileManager.createDirectory(\n at: uncompressPath,\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: entry.permissions\n ]\n )\n case .regular:\n try fileManager.createDirectory(\n at: uncompressPath.deletingLastPathComponent(),\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: 0o755\n ]\n )\n let success = fileManager.createFile(\n atPath: uncompressPath.path,\n contents: data,\n attributes: [\n FileAttributeKey.posixPermissions: entry.permissions\n ]\n )\n if !success {\n throw POSIXError.fromErrno()\n }\n try data.write(to: uncompressPath)\n case .symbolicLink:\n guard let target = entry.symlinkTarget else {\n continue\n }\n try fileManager.createDirectory(\n at: uncompressPath.deletingLastPathComponent(),\n withIntermediateDirectories: true,\n attributes: [\n FileAttributeKey.posixPermissions: 0o755\n ]\n )\n try fileManager.createSymbolicLink(atPath: uncompressPath.path, withDestinationPath: target)\n continue\n default:\n continue\n }\n\n // FIXME: uid/gid for compress.\n try fileManager.setAttributes(\n [.posixPermissions: NSNumber(value: entry.permissions)],\n ofItemAtPath: uncompressPath.path\n )\n\n if let creationDate = entry.creationDate {\n try fileManager.setAttributes(\n [.creationDate: creationDate],\n ofItemAtPath: uncompressPath.path\n )\n }\n\n if let modificationDate = entry.modificationDate {\n try fileManager.setAttributes(\n [.modificationDate: modificationDate],\n ofItemAtPath: uncompressPath.path\n )\n }\n }\n }\n\n // MARK: private functions\n private static func _compressFile(item: URL, entry: WriteEntry, archiver: ArchiveWriter) throws {\n guard let stream = InputStream(url: item) else {\n return\n }\n\n let writer = archiver.makeTransactionWriter()\n\n let bufferSize = Int(1.mib())\n let readBuffer = UnsafeMutablePointer.allocate(capacity: bufferSize)\n\n stream.open()\n try writer.writeHeader(entry: entry)\n while true {\n let byteRead = stream.read(readBuffer, maxLength: bufferSize)\n if byteRead <= 0 {\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n try data.withUnsafeBytes { pointer in\n try writer.writeChunk(data: pointer)\n }\n }\n }\n stream.close()\n try writer.finish()\n }\n\n private static func _createEntry(entryInfo: ArchiveEntryInfo, pathPrefix: String = \"\") throws -> WriteEntry? {\n let entry = WriteEntry()\n let fileManager = FileManager.default\n let attributes = try fileManager.attributesOfItem(atPath: entryInfo.pathOnHost.path)\n\n if let fileType = attributes[.type] as? FileAttributeType {\n switch fileType {\n case .typeBlockSpecial, .typeCharacterSpecial, .typeSocket:\n return nil\n case .typeDirectory:\n entry.fileType = .directory\n case .typeRegular:\n entry.fileType = .regular\n case .typeSymbolicLink:\n entry.fileType = .symbolicLink\n let symlinkTarget = try fileManager.destinationOfSymbolicLink(atPath: entryInfo.pathOnHost.path)\n entry.symlinkTarget = symlinkTarget\n default:\n return nil\n }\n }\n if let posixPermissions = attributes[.posixPermissions] as? NSNumber {\n #if os(macOS)\n entry.permissions = posixPermissions.uint16Value\n #else\n entry.permissions = posixPermissions.uint32Value\n #endif\n }\n if let fileSize = attributes[.size] as? UInt64 {\n entry.size = Int64(fileSize)\n }\n if let uid = attributes[.ownerAccountID] as? NSNumber {\n entry.owner = uid.uint32Value\n }\n if let gid = attributes[.groupOwnerAccountID] as? NSNumber {\n entry.group = gid.uint32Value\n }\n if let creationDate = attributes[.creationDate] as? Date {\n entry.creationDate = creationDate\n }\n if let modificationDate = attributes[.modificationDate] as? Date {\n entry.modificationDate = modificationDate\n }\n\n let pathTrimmed = Self._trimPathPrefix(entryInfo.pathInArchive.relativePath, pathPrefix: pathPrefix)\n entry.path = pathTrimmed\n return entry\n }\n\n private static func _trimPathPrefix(_ path: String, pathPrefix: String) -> String {\n guard !path.isEmpty && !pathPrefix.isEmpty else {\n return path\n }\n\n let decodedPath = path.removingPercentEncoding ?? path\n\n guard decodedPath.hasPrefix(pathPrefix) else {\n return decodedPath\n }\n let trimmedPath = String(decodedPath.suffix(from: pathPrefix.endIndex))\n return trimmedPath\n }\n\n private static func _isSymbolicLink(_ path: URL) throws -> Bool {\n let resourceValues = try path.resourceValues(forKeys: [.isSymbolicLinkKey])\n if let isSymbolicLink = resourceValues.isSymbolicLink {\n if isSymbolicLink {\n return true\n }\n }\n return false\n }\n}\n\nextension Archiver {\n public enum Error: Swift.Error, CustomStringConvertible {\n case failedToCreateEntry\n case fileDoesNotExist(_ url: URL)\n\n public var description: String {\n switch self {\n case .failedToCreateEntry:\n return \"failed to create entry\"\n case .fileDoesNotExist(let url):\n return \"file \\(url.path) does not exist\"\n }\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport Foundation\n\n/// A client for interacting with a single network.\npublic struct NetworkClient: Sendable {\n // FIXME: need more flexibility than a hard-coded constant?\n static let label = \"com.apple.container.network.container-network-vmnet\"\n\n private var machServiceLabel: String {\n \"\\(Self.label).\\(id)\"\n }\n\n let id: String\n\n /// Create a client for a network.\n public init(id: String) {\n self.id = id\n }\n}\n\n// Runtime Methods\nextension NetworkClient {\n public func state() async throws -> NetworkState {\n let request = XPCMessage(route: NetworkRoutes.state.rawValue)\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n let state = try response.state()\n return state\n }\n\n public func allocate(hostname: String) async throws -> (attachment: Attachment, additionalData: XPCMessage?) {\n let request = XPCMessage(route: NetworkRoutes.allocate.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n let attachment = try response.attachment()\n let additionalData = response.additionalData()\n return (attachment, additionalData)\n }\n\n public func deallocate(hostname: String) async throws {\n let request = XPCMessage(route: NetworkRoutes.deallocate.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n try await client.send(request)\n }\n\n public func lookup(hostname: String) async throws -> Attachment? {\n let request = XPCMessage(route: NetworkRoutes.lookup.rawValue)\n request.set(key: NetworkKeys.hostname.rawValue, value: hostname)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.dataNoCopy(key: NetworkKeys.attachment.rawValue).map {\n try JSONDecoder().decode(Attachment.self, from: $0)\n }\n }\n\n public func disableAllocator() async throws -> Bool {\n let request = XPCMessage(route: NetworkRoutes.disableAllocator.rawValue)\n\n let client = createClient()\n defer { client.close() }\n\n let response = try await client.send(request)\n return try response.allocatorDisabled()\n }\n\n private func createClient() -> XPCClient {\n XPCClient(service: machServiceLabel)\n }\n}\n\nextension XPCMessage {\n func additionalData() -> XPCMessage? {\n guard let additionalData = xpc_dictionary_get_dictionary(self.underlying, NetworkKeys.additionalData.rawValue) else {\n return nil\n }\n return XPCMessage(object: additionalData)\n }\n\n func allocatorDisabled() throws -> Bool {\n self.bool(key: NetworkKeys.allocatorDisabled.rawValue)\n }\n\n func attachment() throws -> Attachment {\n let data = self.dataNoCopy(key: NetworkKeys.attachment.rawValue)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No network attachment snapshot data in message\")\n }\n return try JSONDecoder().decode(Attachment.self, from: data)\n }\n\n func hostname() throws -> String {\n let hostname = self.string(key: NetworkKeys.hostname.rawValue)\n guard let hostname else {\n throw ContainerizationError(.invalidArgument, message: \"No hostname data in message\")\n }\n return hostname\n }\n\n func state() throws -> NetworkState {\n let data = self.dataNoCopy(key: NetworkKeys.state.rawValue)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"No network snapshot data in message\")\n }\n return try JSONDecoder().decode(NetworkState.self, from: data)\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerBuild\nimport ContainerClient\nimport ContainerNetworkService\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct BuilderStart: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"start\"\n config._superCommandName = \"builder\"\n config.abstract = \"Start builder\"\n config.usage = \"\\nbuilder start [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64 = 2\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n public var memory: String = \"2048MB\"\n\n func run() async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n totalTasks: 4\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n try await Self.start(cpus: self.cpus, memory: self.memory, progressUpdate: progress.handler)\n progress.finish()\n }\n\n static func start(cpus: Int64?, memory: String?, progressUpdate: @escaping ProgressUpdateHandler) async throws {\n await progressUpdate([\n .setDescription(\"Fetching BuildKit image\"),\n .setItemsName(\"blobs\"),\n ])\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n\n let builderImage: String = ClientDefaults.get(key: .defaultBuilderImage)\n let exportsMount: String = Application.appRoot.appendingPathComponent(\".build\").absolutePath()\n\n if !FileManager.default.fileExists(atPath: exportsMount) {\n try FileManager.default.createDirectory(\n atPath: exportsMount,\n withIntermediateDirectories: true,\n attributes: nil\n )\n }\n\n let builderPlatform = ContainerizationOCI.Platform(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n\n let existingContainer = try? await ClientContainer.get(id: \"buildkit\")\n if let existingContainer {\n let existingImage = existingContainer.configuration.image.reference\n let existingResources = existingContainer.configuration.resources\n\n // Check if we need to recreate the builder due to different image\n let imageChanged = existingImage != builderImage\n let cpuChanged = {\n if let cpus {\n if existingResources.cpus != cpus {\n return true\n }\n }\n return false\n }()\n let memChanged = try {\n if let memory {\n let memoryInBytes = try Parser.resources(cpus: nil, memory: memory).memoryInBytes\n if existingResources.memoryInBytes != memoryInBytes {\n return true\n }\n }\n return false\n }()\n\n switch existingContainer.status {\n case .running:\n guard imageChanged || cpuChanged || memChanged else {\n // If image, mem and cpu are the same, continue using the existing builder\n return\n }\n // If they changed, stop and delete the existing builder\n try await existingContainer.stop()\n try await existingContainer.delete()\n case .stopped:\n // If the builder is stopped and matches our requirements, start it\n // Otherwise, delete it and create a new one\n guard imageChanged || cpuChanged || memChanged else {\n try await existingContainer.startBuildKit(progressUpdate, nil)\n return\n }\n try await existingContainer.delete()\n case .stopping:\n throw ContainerizationError(\n .invalidState,\n message: \"builder is stopping, please wait until it is fully stopped before proceeding\"\n )\n case .unknown:\n break\n }\n }\n\n let shimArguments: [String] = [\n \"--debug\",\n \"--vsock\",\n ]\n\n let id = \"buildkit\"\n try ContainerClient.Utility.validEntityName(id)\n\n let processConfig = ProcessConfiguration(\n executable: \"/usr/local/bin/container-builder-shim\",\n arguments: shimArguments,\n environment: [],\n workingDirectory: \"/\",\n terminal: false,\n user: .id(uid: 0, gid: 0)\n )\n\n let resources = try Parser.resources(\n cpus: cpus,\n memory: memory\n )\n\n let image = try await ClientImage.fetch(\n reference: builderImage,\n platform: builderPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progressUpdate)\n )\n // Unpack fetched image before use\n await progressUpdate([\n .setDescription(\"Unpacking BuildKit image\"),\n .setItemsName(\"entries\"),\n ])\n\n let unpackTask = await taskManager.startTask()\n _ = try await image.getCreateSnapshot(\n platform: builderPlatform,\n progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progressUpdate)\n )\n let imageConfig = ImageDescription(\n reference: builderImage,\n descriptor: image.descriptor\n )\n\n var config = ContainerConfiguration(id: id, image: imageConfig, process: processConfig)\n config.resources = resources\n config.mounts = [\n .init(\n type: .tmpfs,\n source: \"\",\n destination: \"/run\",\n options: []\n ),\n .init(\n type: .virtiofs,\n source: exportsMount,\n destination: \"/var/lib/container-builder-shim/exports\",\n options: []\n ),\n ]\n // Enable Rosetta only if the user didn't ask to disable it\n config.rosetta = ClientDefaults.getBool(key: .buildRosetta) ?? true\n\n let network = try await ClientNetwork.get(id: ClientNetwork.defaultNetworkName)\n guard case .running(_, let networkStatus) = network else {\n throw ContainerizationError(.invalidState, message: \"default network is not running\")\n }\n config.networks = [network.id]\n let subnet = try CIDRAddress(networkStatus.address)\n let nameserver = IPv4Address(fromValue: subnet.lower.value + 1).description\n let nameservers = [nameserver]\n config.dns = ContainerConfiguration.DNSConfiguration(nameservers: nameservers)\n\n let kernel = try await {\n await progressUpdate([\n .setDescription(\"Fetching kernel\"),\n .setItemsName(\"binary\"),\n ])\n\n let kernel = try await ClientKernel.getDefaultKernel(for: .current)\n return kernel\n }()\n\n await progressUpdate([\n .setDescription(\"Starting BuildKit container\")\n ])\n\n let container = try await ClientContainer.create(\n configuration: config,\n options: .default,\n kernel: kernel\n )\n\n try await container.startBuildKit(progressUpdate, taskManager)\n }\n }\n}\n\n// MARK: - ClientContainer Extension for BuildKit\n\nextension ClientContainer {\n /// Starts the BuildKit process within the container\n /// This method handles bootstrapping the container and starting the BuildKit process\n fileprivate func startBuildKit(_ progress: @escaping ProgressUpdateHandler, _ taskManager: ProgressTaskCoordinator? = nil) async throws {\n do {\n let io = try ProcessIO.create(\n tty: false,\n interactive: false,\n detach: true\n )\n defer { try? io.close() }\n let process = try await bootstrap()\n _ = try await process.start(io.stdio)\n await taskManager?.finish()\n try io.closeAfterStart()\n log.debug(\"starting BuildKit and BuildKit-shim\")\n } catch {\n try? await stop()\n try? await delete()\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to start BuildKit: \\(error)\")\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension String {\n fileprivate var fs_cleaned: String {\n var value = self\n\n if value.hasPrefix(\"file://\") {\n value.removeFirst(\"file://\".count)\n }\n\n if value.count > 1 && value.last == \"/\" {\n value.removeLast()\n }\n\n return value.removingPercentEncoding ?? value\n }\n\n fileprivate var fs_components: [String] {\n var parts: [String] = []\n for segment in self.split(separator: \"/\", omittingEmptySubsequences: true) {\n switch segment {\n case \".\":\n continue\n case \"..\":\n if !parts.isEmpty { parts.removeLast() }\n default:\n parts.append(String(segment))\n }\n }\n return parts\n }\n\n fileprivate var fs_isAbsolute: Bool { first == \"/\" }\n}\n\nextension URL {\n var cleanPath: String {\n self.path.fs_cleaned\n }\n\n func parentOf(_ url: URL) -> Bool {\n let parentPath = self.absoluteURL.cleanPath\n let childPath = url.absoluteURL.cleanPath\n\n guard parentPath.fs_isAbsolute else {\n return true\n }\n\n let parentParts = parentPath.fs_components\n let childParts = childPath.fs_components\n\n guard parentParts.count <= childParts.count else { return false }\n return zip(parentParts, childParts).allSatisfy { $0 == $1 }\n }\n\n func relativeChildPath(to context: URL) throws -> String {\n guard context.parentOf(self) else {\n throw BuildFSSync.Error.pathIsNotChild(cleanPath, context.cleanPath)\n }\n\n let ctxParts = context.cleanPath.fs_components\n let selfParts = cleanPath.fs_components\n\n return selfParts.dropFirst(ctxParts.count).joined(separator: \"/\")\n }\n\n func relativePathFrom(from base: URL) -> String {\n let destParts = cleanPath.fs_components\n let baseParts = base.cleanPath.fs_components\n\n let common = zip(destParts, baseParts).prefix { $0 == $1 }.count\n guard common > 0 else { return cleanPath }\n\n let ups = Array(repeating: \"..\", count: baseParts.count - common)\n let remainder = destParts.dropFirst(common)\n return (ups + remainder).joined(separator: \"/\")\n }\n\n func zeroCopyReader(\n chunk: Int = 1024 * 1024,\n buffer: AsyncStream.Continuation.BufferingPolicy = .unbounded\n ) throws -> AsyncStream {\n\n let path = self.cleanPath\n let fd = open(path, O_RDONLY | O_NONBLOCK)\n guard fd >= 0 else { throw POSIXError.fromErrno() }\n\n let channel = DispatchIO(\n type: .stream,\n fileDescriptor: fd,\n queue: .global(qos: .userInitiated)\n ) { errno in\n close(fd)\n }\n\n channel.setLimit(highWater: chunk)\n return AsyncStream(bufferingPolicy: buffer) { continuation in\n\n channel.read(\n offset: 0, length: Int.max,\n queue: .global(qos: .userInitiated)\n ) { done, ddata, err in\n if err != 0 {\n continuation.finish()\n return\n }\n\n if let ddata, ddata.count > -1 {\n let data = Data(ddata)\n\n switch continuation.yield(data) {\n case .terminated:\n channel.close(flags: .stop)\n default: break\n }\n }\n\n if done {\n channel.close(flags: .stop)\n continuation.finish()\n }\n }\n }\n }\n\n func bufferedCopyReader(chunkSize: Int = 4 * 1024 * 1024) throws -> BufferedCopyReader {\n try BufferedCopyReader(url: self, chunkSize: chunkSize)\n }\n}\n\n/// A synchronous buffered reader that reads one chunk at a time from a file\n/// Uses a configurable buffer size (default 4MB) and only reads when nextChunk() is called\n/// Implements AsyncSequence for use with `for await` loops\npublic final class BufferedCopyReader: AsyncSequence {\n public typealias Element = Data\n public typealias AsyncIterator = BufferedCopyReaderIterator\n\n private let inputStream: InputStream\n private let chunkSize: Int\n private var isFinished: Bool = false\n private let reusableBuffer: UnsafeMutablePointer\n\n /// Initialize a buffered copy reader for the given URL\n /// - Parameters:\n /// - url: The file URL to read from\n /// - chunkSize: Size of each chunk to read (default: 4MB)\n public init(url: URL, chunkSize: Int = 4 * 1024 * 1024) throws {\n guard let stream = InputStream(url: url) else {\n throw CocoaError(.fileReadNoSuchFile)\n }\n self.inputStream = stream\n self.chunkSize = chunkSize\n self.reusableBuffer = UnsafeMutablePointer.allocate(capacity: chunkSize)\n self.inputStream.open()\n }\n\n deinit {\n inputStream.close()\n reusableBuffer.deallocate()\n }\n\n /// Create an async iterator for this sequence\n public func makeAsyncIterator() -> BufferedCopyReaderIterator {\n BufferedCopyReaderIterator(reader: self)\n }\n\n /// Read the next chunk of data from the file\n /// - Returns: Data chunk, or nil if end of file reached\n /// - Throws: Any file reading errors\n public func nextChunk() throws -> Data? {\n guard !isFinished else { return nil }\n\n // Read directly into our reusable buffer\n let bytesRead = inputStream.read(reusableBuffer, maxLength: chunkSize)\n\n // Check for errors\n if bytesRead < 0 {\n if let error = inputStream.streamError {\n throw error\n }\n throw CocoaError(.fileReadUnknown)\n }\n\n // If we read no data, we've reached the end\n if bytesRead == 0 {\n isFinished = true\n return nil\n }\n\n // If we read less than the chunk size, this is the last chunk\n if bytesRead < chunkSize {\n isFinished = true\n }\n\n // Create Data object only with the bytes actually read\n return Data(bytes: reusableBuffer, count: bytesRead)\n }\n\n /// Check if the reader has finished reading the file\n public var hasFinished: Bool {\n isFinished\n }\n\n /// Reset the reader to the beginning of the file\n /// Note: InputStream doesn't support seeking, so this recreates the stream\n /// - Throws: Any file opening errors\n public func reset() throws {\n inputStream.close()\n // Note: InputStream doesn't provide a way to get the original URL,\n // so reset functionality is limited. Consider removing this method\n // or storing the original URL if reset is needed.\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Reset not supported with InputStream-based implementation\"\n ])\n }\n\n /// Get the current file offset\n /// Note: InputStream doesn't provide offset information\n /// - Returns: Current position in the file\n /// - Throws: Unsupported operation error\n public func currentOffset() throws -> UInt64 {\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Offset tracking not supported with InputStream-based implementation\"\n ])\n }\n\n /// Seek to a specific offset in the file\n /// Note: InputStream doesn't support seeking\n /// - Parameter offset: The byte offset to seek to\n /// - Throws: Unsupported operation error\n public func seek(to offset: UInt64) throws {\n throw CocoaError(\n .fileReadUnsupportedScheme,\n userInfo: [\n NSLocalizedDescriptionKey: \"Seeking not supported with InputStream-based implementation\"\n ])\n }\n\n /// Close the input stream explicitly (called automatically in deinit)\n public func close() {\n inputStream.close()\n isFinished = true\n }\n}\n\n/// AsyncIteratorProtocol implementation for BufferedCopyReader\npublic struct BufferedCopyReaderIterator: AsyncIteratorProtocol {\n public typealias Element = Data\n\n private let reader: BufferedCopyReader\n\n init(reader: BufferedCopyReader) {\n self.reader = reader\n }\n\n /// Get the next chunk of data asynchronously\n /// - Returns: Next data chunk, or nil when finished\n /// - Throws: Any file reading errors\n public mutating func next() async throws -> Data? {\n // Yield control to allow other tasks to run, then read synchronously\n await Task.yield()\n return try reader.nextChunk()\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct ClientContainer: Sendable, Codable {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n\n private var sandboxClient: SandboxClient {\n SandboxClient(id: configuration.id, runtime: configuration.runtimeHandler)\n }\n\n /// Identifier of the container.\n public var id: String {\n configuration.id\n }\n\n public let status: RuntimeStatus\n\n /// Configured platform for the container.\n public var platform: ContainerizationOCI.Platform {\n configuration.platform\n }\n\n /// Configuration for the container.\n public let configuration: ContainerConfiguration\n\n /// Network allocated to the container.\n public let networks: [Attachment]\n\n package init(configuration: ContainerConfiguration) {\n self.configuration = configuration\n self.status = .stopped\n self.networks = []\n }\n\n init(snapshot: ContainerSnapshot) {\n self.configuration = snapshot.configuration\n self.status = snapshot.status\n self.networks = snapshot.networks\n }\n\n public var initProcess: ClientProcess {\n ClientProcessImpl(containerId: self.id, client: self.sandboxClient)\n }\n}\n\nextension ClientContainer {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n @discardableResult\n private static func xpcSend(\n client: XPCClient,\n message: XPCMessage,\n timeout: Duration? = .seconds(15)\n ) async throws -> XPCMessage {\n try await client.send(message, responseTimeout: timeout)\n }\n\n public static func create(\n configuration: ContainerConfiguration,\n options: ContainerCreateOptions = .default,\n kernel: Kernel\n ) async throws -> ClientContainer {\n do {\n let client = Self.newClient()\n let request = XPCMessage(route: .createContainer)\n\n let data = try JSONEncoder().encode(configuration)\n let kdata = try JSONEncoder().encode(kernel)\n let odata = try JSONEncoder().encode(options)\n request.set(key: .containerConfig, value: data)\n request.set(key: .kernel, value: kdata)\n request.set(key: .containerOptions, value: odata)\n\n try await xpcSend(client: client, message: request)\n return ClientContainer(configuration: configuration)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to create container\",\n cause: error\n )\n }\n }\n\n public static func list() async throws -> [ClientContainer] {\n do {\n let client = Self.newClient()\n let request = XPCMessage(route: .listContainer)\n\n let response = try await xpcSend(\n client: client,\n message: request,\n timeout: .seconds(10)\n )\n let data = response.dataNoCopy(key: .containers)\n guard let data else {\n return []\n }\n let configs = try JSONDecoder().decode([ContainerSnapshot].self, from: data)\n return configs.map { ClientContainer(snapshot: $0) }\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to list containers\",\n cause: error\n )\n }\n }\n\n /// Get the container for the provided id.\n public static func get(id: String) async throws -> ClientContainer {\n let containers = try await list()\n guard let container = containers.first(where: { $0.id == id }) else {\n throw ContainerizationError(\n .notFound,\n message: \"get failed: container \\(id) not found\"\n )\n }\n return container\n }\n}\n\nextension ClientContainer {\n public func bootstrap() async throws -> ClientProcess {\n let client = self.sandboxClient\n try await client.bootstrap()\n return ClientProcessImpl(containerId: self.id, client: self.sandboxClient)\n }\n\n /// Stop the container and all processes currently executing inside.\n public func stop(opts: ContainerStopOptions = ContainerStopOptions.default) async throws {\n do {\n let client = self.sandboxClient\n try await client.stop(options: opts)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to stop container\",\n cause: error\n )\n }\n }\n\n /// Delete the container along with any resources.\n public func delete() async throws {\n do {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .deleteContainer)\n request.set(key: .id, value: self.id)\n try await client.send(request)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to delete container\",\n cause: error\n )\n }\n }\n}\n\nextension ClientContainer {\n /// Execute a new process inside a running container.\n public func createProcess(id: String, configuration: ProcessConfiguration) async throws -> ClientProcess {\n do {\n let client = self.sandboxClient\n try await client.createProcess(id, config: configuration)\n return ClientProcessImpl(containerId: self.id, processId: id, client: client)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to exec in container\",\n cause: error\n )\n }\n }\n\n /// Send or \"kill\" a signal to the initial process of the container.\n /// Kill does not wait for the process to exit, it only delivers the signal.\n public func kill(_ signal: Int32) async throws {\n do {\n let client = self.sandboxClient\n try await client.kill(self.id, signal: Int64(signal))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill container \\(self.id)\",\n cause: error\n )\n }\n }\n\n public func logs() async throws -> [FileHandle] {\n do {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .containerLogs)\n request.set(key: .id, value: self.id)\n\n let response = try await client.send(request)\n let fds = response.fileHandles(key: .logs)\n guard let fds else {\n throw ContainerizationError(\n .internalError,\n message: \"No log fds returned\"\n )\n }\n return fds\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to get logs for container \\(self.id)\",\n cause: error\n )\n }\n }\n\n public func dial(_ port: UInt32) async throws -> FileHandle {\n do {\n let client = self.sandboxClient\n return try await client.dial(port)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to dial \\(port) in container \\(self.id)\",\n cause: error\n )\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildRemoteContentProxy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\n\nstruct BuildRemoteContentProxy: BuildPipelineHandler {\n let local: ContentStore\n\n public init(_ contentStore: ContentStore) throws {\n self.local = contentStore\n }\n\n func accept(_ packet: ServerStream) throws -> Bool {\n guard let imageTransfer = packet.getImageTransfer() else {\n return false\n }\n guard imageTransfer.stage() == \"content-store\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let imageTransfer = packet.getImageTransfer() else {\n throw Error.imageTransferMissing\n }\n\n guard let method = imageTransfer.method() else {\n throw Error.methodMissing\n }\n\n switch try ContentStoreMethod(method) {\n case .info:\n try await self.info(sender, imageTransfer, packet.buildID)\n case .readerAt:\n try await self.readerAt(sender, imageTransfer, packet.buildID)\n default:\n throw Error.unknownMethod(method)\n }\n }\n\n func info(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer, _ buildID: String) async throws {\n let descriptor = try await local.get(digest: packet.tag)\n let size = try descriptor?.size()\n let transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.info.rawValue,\n size: size\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n }\n\n func readerAt(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer, _ buildID: String) async throws {\n let digest = packet.descriptor.digest\n let offset: UInt64 = packet.offset() ?? 0\n let size: Int = packet.len() ?? 0\n guard let descriptor = try await local.get(digest: digest) else {\n throw Error.contentMissing\n }\n if offset == 0 && size == 0 { // Metadata request\n var transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.readerAt.rawValue,\n size: descriptor.size(),\n data: Data()\n )\n transfer.complete = true\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n return\n }\n guard let data = try descriptor.data(offset: offset, length: size) else {\n throw Error.invalidOffsetSizeForContent(packet.descriptor.digest, offset, size)\n }\n\n let transfer = try ImageTransfer(\n id: packet.id,\n digest: packet.tag,\n method: ContentStoreMethod.readerAt.rawValue,\n size: UInt64(data.count),\n data: data\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n }\n\n func delete(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.delete)\"])\n }\n\n func update(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.update)\"])\n }\n\n func walk(_ sender: AsyncStream.Continuation, _ packet: ImageTransfer) async throws {\n throw NSError(domain: \"RemoteContentProxy\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"unimplemented method \\(ContentStoreMethod.walk)\"])\n }\n\n enum ContentStoreMethod: String {\n case info = \"/containerd.services.content.v1.Content/Info\"\n case readerAt = \"/containerd.services.content.v1.Content/ReaderAt\"\n case delete = \"/containerd.services.content.v1.Content/Delete\"\n case update = \"/containerd.services.content.v1.Content/Update\"\n case walk = \"/containerd.services.content.v1.Content/Walk\"\n\n init(_ method: String) throws {\n guard let value = ContentStoreMethod(rawValue: method) else {\n throw Error.unknownMethod(method)\n }\n self = value\n }\n }\n}\n\nextension ImageTransfer {\n fileprivate init(id: String, digest: String, method: String, size: UInt64? = nil, data: Data = Data()) throws {\n self.init()\n self.id = id\n self.tag = digest\n self.metadata = [\n \"os\": \"linux\",\n \"stage\": \"content-store\",\n \"method\": method,\n ]\n if let size {\n self.metadata[\"size\"] = String(size)\n }\n self.complete = true\n self.direction = .into\n self.data = data\n }\n}\n\nextension BuildRemoteContentProxy {\n enum Error: Swift.Error, CustomStringConvertible {\n case imageTransferMissing\n case methodMissing\n case contentMissing\n case unknownMethod(String)\n case invalidOffsetSizeForContent(String, UInt64, Int)\n\n var description: String {\n switch self {\n case .imageTransferMissing:\n return \"imageTransfer is missing\"\n case .methodMissing:\n return \"method is missing in request\"\n case .contentMissing:\n return \"content cannot be found\"\n case .unknownMethod(let m):\n return \"unknown content-store method \\(m)\"\n case .invalidOffsetSizeForContent(let digest, let offset, let size):\n return \"invalid request for content: \\(digest) with offset: \\(offset) size: \\(size)\"\n }\n }\n }\n\n}\n"], ["/container/Sources/APIServer/ContainerDNSHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\nimport DNSServer\n\n/// Handler that uses table lookup to resolve hostnames.\nstruct ContainerDNSHandler: DNSHandler {\n private let networkService: NetworksService\n private let ttl: UInt32\n\n public init(networkService: NetworksService, ttl: UInt32 = 5) {\n self.networkService = networkService\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n let record: ResourceRecord?\n switch question.type {\n case ResourceRecordType.host:\n record = try await answerHost(question: question)\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n\n guard let record else {\n return nil\n }\n\n return Message(\n id: query.id,\n type: .response,\n returnCode: .noError,\n questions: query.questions,\n answers: [record]\n )\n }\n\n private func answerHost(question: Question) async throws -> ResourceRecord? {\n guard let ipAllocation = try await networkService.lookup(hostname: question.name) else {\n return nil\n }\n\n let components = ipAllocation.address.split(separator: \"/\")\n guard !components.isEmpty else {\n throw DNSResolverError.serverError(\"Invalid IP format: empty address\")\n }\n\n let ipString = String(components[0])\n guard let ip = IPv4(ipString) else {\n throw DNSResolverError.serverError(\"Failed to parse IP address: \\(ipString)\")\n }\n\n return HostRecord(name: question.name, ttl: ttl, ip: ip)\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/RemoteContentStoreClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Crypto\nimport ContainerizationError\nimport Foundation\nimport ContainerizationOCI\nimport ContainerXPC\n\npublic struct RemoteContentStoreClient: ContentStore {\n private static let serviceIdentifier = \"com.apple.container.core.container-core-images\"\n private static let encoder = JSONEncoder()\n\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public init() {}\n\n private func _get(digest: String) async throws -> URL? {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentGet)\n request.set(key: .digest, value: digest)\n do {\n let response = try await client.send(request)\n guard let path = response.string(key: .contentPath) else {\n return nil\n }\n return URL(filePath: path)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return nil\n }\n throw error\n }\n }\n\n public func get(digest: String) async throws -> Content? {\n guard let url = try await self._get(digest: digest) else {\n return nil\n }\n return try LocalContent(path: url)\n }\n\n public func get(digest: String) async throws -> T? {\n guard let content: Content = try await self.get(digest: digest) else {\n return nil\n }\n return try content.decode()\n }\n\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentClean)\n\n let d = try Self.encoder.encode(keeping)\n request.set(key: .digests, value: d)\n let response = try await client.send(request)\n\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let deleted = try decoder.decode([String].self, from: data)\n let size = response.uint64(key: .size)\n return (deleted, size)\n }\n\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentDelete)\n\n let d = try Self.encoder.encode(digests)\n request.set(key: .digests, value: d)\n let response = try await client.send(request)\n\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let deleted = try decoder.decode([String].self, from: data)\n let size = response.uint64(key: .size)\n return (deleted, size)\n }\n\n @discardableResult\n public func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String] {\n let (id, tempPath) = try await self.newIngestSession()\n try await body(tempPath)\n return try await self.completeIngestSession(id)\n }\n\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestStart)\n let response = try await client.send(request)\n guard let id = response.string(key: .ingestSessionId) else {\n throw ContainerizationError.init(.internalError, message: \"failed create new ingest session\")\n }\n guard let dir = response.string(key: .directory) else {\n throw ContainerizationError.init(.internalError, message: \"failed create new ingest session\")\n }\n return (id, URL(filePath: dir))\n }\n\n @discardableResult\n public func completeIngestSession(_ id: String) async throws -> [String] {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestComplete)\n\n request.set(key: .ingestSessionId, value: id)\n\n let response = try await client.send(request)\n guard let data = response.dataNoCopy(key: .digests) else {\n throw ContainerizationError.init(.internalError, message: \"failed to delete digests\")\n }\n\n let decoder = JSONDecoder()\n let ingested = try decoder.decode([String].self, from: data)\n return ingested\n }\n\n public func cancelIngestSession(_ id: String) async throws {\n let client = Self.newClient()\n let request = XPCMessage(route: .contentIngestCancel)\n request.set(key: .ingestSessionId, value: id)\n try await client.send(request)\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerBuild/Builder.pb.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// DO NOT EDIT.\n// swift-format-ignore-file\n// swiftlint:disable all\n//\n// Generated by the Swift generator plugin for the protocol buffer compiler.\n// Source: Builder.proto\n//\n// For information on using the generated types, please see the documentation:\n// https://github.com/apple/swift-protobuf/\n\nimport Foundation\nimport SwiftProtobuf\n\n// If the compiler emits an error on this type, it is because this file\n// was generated by a version of the `protoc` Swift plug-in that is\n// incompatible with the version of SwiftProtobuf to which you are linking.\n// Please ensure that you are building against the same version of the API\n// that was used to generate this file.\nfileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {\n struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}\n typealias Version = _2\n}\n\npublic enum Com_Apple_Container_Build_V1_TransferDirection: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case into // = 0\n case outof // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .into\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .into\n case 1: self = .outof\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .into: return 0\n case .outof: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_TransferDirection] = [\n .into,\n .outof,\n ]\n\n}\n\n/// Standard input/output.\npublic enum Com_Apple_Container_Build_V1_Stdio: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case stdin // = 0\n case stdout // = 1\n case stderr // = 2\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .stdin\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .stdin\n case 1: self = .stdout\n case 2: self = .stderr\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .stdin: return 0\n case .stdout: return 1\n case .stderr: return 2\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_Stdio] = [\n .stdin,\n .stdout,\n .stderr,\n ]\n\n}\n\n/// Build error type.\npublic enum Com_Apple_Container_Build_V1_BuildErrorType: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case buildFailed // = 0\n case `internal` // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .buildFailed\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .buildFailed\n case 1: self = .internal\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .buildFailed: return 0\n case .internal: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Container_Build_V1_BuildErrorType] = [\n .buildFailed,\n .internal,\n ]\n\n}\n\npublic struct Com_Apple_Container_Build_V1_InfoRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_InfoResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_CreateBuildRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The name of the build stage.\n public var stageName: String = String()\n\n /// The tag of the image to be created.\n public var tag: String = String()\n\n /// Any additional metadata to be associated with the build.\n public var metadata: Dictionary = [:]\n\n /// Additional build arguments.\n public var buildArgs: [String] = []\n\n /// Enable debug logging.\n public var debug: Bool = false\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_CreateBuildResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String = String()\n\n /// Any additional metadata to be associated with the build.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_ClientStream: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String {\n get {return _storage._buildID}\n set {_uniqueStorage()._buildID = newValue}\n }\n\n /// The packet type.\n public var packetType: OneOf_PacketType? {\n get {return _storage._packetType}\n set {_uniqueStorage()._packetType = newValue}\n }\n\n public var signal: Com_Apple_Container_Build_V1_Signal {\n get {\n if case .signal(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_Signal()\n }\n set {_uniqueStorage()._packetType = .signal(newValue)}\n }\n\n public var command: Com_Apple_Container_Build_V1_Run {\n get {\n if case .command(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_Run()\n }\n set {_uniqueStorage()._packetType = .command(newValue)}\n }\n\n public var buildTransfer: Com_Apple_Container_Build_V1_BuildTransfer {\n get {\n if case .buildTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildTransfer()\n }\n set {_uniqueStorage()._packetType = .buildTransfer(newValue)}\n }\n\n public var imageTransfer: Com_Apple_Container_Build_V1_ImageTransfer {\n get {\n if case .imageTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_ImageTransfer()\n }\n set {_uniqueStorage()._packetType = .imageTransfer(newValue)}\n }\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n /// The packet type.\n public enum OneOf_PacketType: Equatable, Sendable {\n case signal(Com_Apple_Container_Build_V1_Signal)\n case command(Com_Apple_Container_Build_V1_Run)\n case buildTransfer(Com_Apple_Container_Build_V1_BuildTransfer)\n case imageTransfer(Com_Apple_Container_Build_V1_ImageTransfer)\n\n }\n\n public init() {}\n\n fileprivate var _storage = _StorageClass.defaultInstance\n}\n\npublic struct Com_Apple_Container_Build_V1_Signal: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A POSIX signal to send to the build process.\n /// Can be used for cancelling builds.\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_Run: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the execution.\n public var id: String = String()\n\n /// The type of command to execute.\n public var command: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_RunComplete: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the execution.\n public var id: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_BuildTransfer: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the transfer.\n public var id: String = String()\n\n /// The direction for transferring data (either to the server or from the\n /// server).\n public var direction: Com_Apple_Container_Build_V1_TransferDirection = .into\n\n /// The absolute path to the source from the server perspective.\n public var source: String {\n get {return _source ?? String()}\n set {_source = newValue}\n }\n /// Returns true if `source` has been explicitly set.\n public var hasSource: Bool {return self._source != nil}\n /// Clears the value of `source`. Subsequent reads from it will return its default value.\n public mutating func clearSource() {self._source = nil}\n\n /// The absolute path for the destination from the server perspective.\n public var destination: String {\n get {return _destination ?? String()}\n set {_destination = newValue}\n }\n /// Returns true if `destination` has been explicitly set.\n public var hasDestination: Bool {return self._destination != nil}\n /// Clears the value of `destination`. Subsequent reads from it will return its default value.\n public mutating func clearDestination() {self._destination = nil}\n\n /// The actual data bytes to be transferred.\n public var data: Data = Data()\n\n /// Signal to indicate that the transfer of data for the request has finished.\n public var complete: Bool = false\n\n /// Boolean to indicate if the content is a directory.\n public var isDirectory: Bool = false\n\n /// Metadata for the transfer.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _source: String? = nil\n fileprivate var _destination: String? = nil\n}\n\npublic struct Com_Apple_Container_Build_V1_ImageTransfer: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the transfer.\n public var id: String = String()\n\n /// The direction for transferring data (either to the server or from the\n /// server).\n public var direction: Com_Apple_Container_Build_V1_TransferDirection = .into\n\n /// The tag for the image.\n public var tag: String = String()\n\n /// The descriptor for the image content.\n public var descriptor: Com_Apple_Container_Build_V1_Descriptor {\n get {return _descriptor ?? Com_Apple_Container_Build_V1_Descriptor()}\n set {_descriptor = newValue}\n }\n /// Returns true if `descriptor` has been explicitly set.\n public var hasDescriptor: Bool {return self._descriptor != nil}\n /// Clears the value of `descriptor`. Subsequent reads from it will return its default value.\n public mutating func clearDescriptor() {self._descriptor = nil}\n\n /// The actual data bytes to be transferred.\n public var data: Data = Data()\n\n /// Signal to indicate that the transfer of data for the request has finished.\n public var complete: Bool = false\n\n /// Metadata for the image.\n public var metadata: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _descriptor: Com_Apple_Container_Build_V1_Descriptor? = nil\n}\n\npublic struct Com_Apple_Container_Build_V1_ServerStream: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// A unique ID for the build.\n public var buildID: String {\n get {return _storage._buildID}\n set {_uniqueStorage()._buildID = newValue}\n }\n\n /// The packet type.\n public var packetType: OneOf_PacketType? {\n get {return _storage._packetType}\n set {_uniqueStorage()._packetType = newValue}\n }\n\n public var io: Com_Apple_Container_Build_V1_IO {\n get {\n if case .io(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_IO()\n }\n set {_uniqueStorage()._packetType = .io(newValue)}\n }\n\n public var buildError: Com_Apple_Container_Build_V1_BuildError {\n get {\n if case .buildError(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildError()\n }\n set {_uniqueStorage()._packetType = .buildError(newValue)}\n }\n\n public var commandComplete: Com_Apple_Container_Build_V1_RunComplete {\n get {\n if case .commandComplete(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_RunComplete()\n }\n set {_uniqueStorage()._packetType = .commandComplete(newValue)}\n }\n\n public var buildTransfer: Com_Apple_Container_Build_V1_BuildTransfer {\n get {\n if case .buildTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_BuildTransfer()\n }\n set {_uniqueStorage()._packetType = .buildTransfer(newValue)}\n }\n\n public var imageTransfer: Com_Apple_Container_Build_V1_ImageTransfer {\n get {\n if case .imageTransfer(let v)? = _storage._packetType {return v}\n return Com_Apple_Container_Build_V1_ImageTransfer()\n }\n set {_uniqueStorage()._packetType = .imageTransfer(newValue)}\n }\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n /// The packet type.\n public enum OneOf_PacketType: Equatable, Sendable {\n case io(Com_Apple_Container_Build_V1_IO)\n case buildError(Com_Apple_Container_Build_V1_BuildError)\n case commandComplete(Com_Apple_Container_Build_V1_RunComplete)\n case buildTransfer(Com_Apple_Container_Build_V1_BuildTransfer)\n case imageTransfer(Com_Apple_Container_Build_V1_ImageTransfer)\n\n }\n\n public init() {}\n\n fileprivate var _storage = _StorageClass.defaultInstance\n}\n\npublic struct Com_Apple_Container_Build_V1_IO: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The type of IO.\n public var type: Com_Apple_Container_Build_V1_Stdio = .stdin\n\n /// The IO data bytes.\n public var data: Data = Data()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Container_Build_V1_BuildError: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n /// The type of build error.\n public var type: Com_Apple_Container_Build_V1_BuildErrorType = .buildFailed\n\n /// Additional message for the build failure.\n public var message: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n/// OCI Platform metadata.\npublic struct Com_Apple_Container_Build_V1_Platform: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var architecture: String = String()\n\n public var os: String = String()\n\n public var osVersion: String = String()\n\n public var osFeatures: [String] = []\n\n public var variant: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n/// OCI Descriptor metadata.\npublic struct Com_Apple_Container_Build_V1_Descriptor: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var mediaType: String = String()\n\n public var digest: String = String()\n\n public var size: Int64 = 0\n\n public var urls: [String] = []\n\n public var annotations: Dictionary = [:]\n\n public var platform: Com_Apple_Container_Build_V1_Platform {\n get {return _platform ?? Com_Apple_Container_Build_V1_Platform()}\n set {_platform = newValue}\n }\n /// Returns true if `platform` has been explicitly set.\n public var hasPlatform: Bool {return self._platform != nil}\n /// Clears the value of `platform`. Subsequent reads from it will return its default value.\n public mutating func clearPlatform() {self._platform = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _platform: Com_Apple_Container_Build_V1_Platform? = nil\n}\n\n// MARK: - Code below here is support for the SwiftProtobuf runtime.\n\nfileprivate let _protobuf_package = \"com.apple.container.build.v1\"\n\nextension Com_Apple_Container_Build_V1_TransferDirection: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"INTO\"),\n 1: .same(proto: \"OUTOF\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_Stdio: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"STDIN\"),\n 1: .same(proto: \"STDOUT\"),\n 2: .same(proto: \"STDERR\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_BuildErrorType: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"BUILD_FAILED\"),\n 1: .same(proto: \"INTERNAL\"),\n ]\n}\n\nextension Com_Apple_Container_Build_V1_InfoRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".InfoRequest\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_InfoRequest, rhs: Com_Apple_Container_Build_V1_InfoRequest) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_InfoResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".InfoResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_InfoResponse, rhs: Com_Apple_Container_Build_V1_InfoResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_CreateBuildRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateBuildRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"stage_name\"),\n 2: .same(proto: \"tag\"),\n 3: .same(proto: \"metadata\"),\n 4: .standard(proto: \"build_args\"),\n 5: .same(proto: \"debug\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.stageName) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.tag) }()\n case 3: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.buildArgs) }()\n case 5: try { try decoder.decodeSingularBoolField(value: &self.debug) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.stageName.isEmpty {\n try visitor.visitSingularStringField(value: self.stageName, fieldNumber: 1)\n }\n if !self.tag.isEmpty {\n try visitor.visitSingularStringField(value: self.tag, fieldNumber: 2)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 3)\n }\n if !self.buildArgs.isEmpty {\n try visitor.visitRepeatedStringField(value: self.buildArgs, fieldNumber: 4)\n }\n if self.debug != false {\n try visitor.visitSingularBoolField(value: self.debug, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_CreateBuildRequest, rhs: Com_Apple_Container_Build_V1_CreateBuildRequest) -> Bool {\n if lhs.stageName != rhs.stageName {return false}\n if lhs.tag != rhs.tag {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.buildArgs != rhs.buildArgs {return false}\n if lhs.debug != rhs.debug {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_CreateBuildResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateBuildResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.buildID) }()\n case 2: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.buildID.isEmpty {\n try visitor.visitSingularStringField(value: self.buildID, fieldNumber: 1)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_CreateBuildResponse, rhs: Com_Apple_Container_Build_V1_CreateBuildResponse) -> Bool {\n if lhs.buildID != rhs.buildID {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ClientStream: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ClientStream\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"signal\"),\n 3: .same(proto: \"command\"),\n 4: .standard(proto: \"build_transfer\"),\n 5: .standard(proto: \"image_transfer\"),\n ]\n\n fileprivate class _StorageClass {\n var _buildID: String = String()\n var _packetType: Com_Apple_Container_Build_V1_ClientStream.OneOf_PacketType?\n\n // This property is used as the initial default value for new instances of the type.\n // The type itself is protecting the reference to its storage via CoW semantics.\n // This will force a copy to be made of this reference when the first mutation occurs;\n // hence, it is safe to mark this as `nonisolated(unsafe)`.\n static nonisolated(unsafe) let defaultInstance = _StorageClass()\n\n private init() {}\n\n init(copying source: _StorageClass) {\n _buildID = source._buildID\n _packetType = source._packetType\n }\n }\n\n fileprivate mutating func _uniqueStorage() -> _StorageClass {\n if !isKnownUniquelyReferenced(&_storage) {\n _storage = _StorageClass(copying: _storage)\n }\n return _storage\n }\n\n public mutating func decodeMessage(decoder: inout D) throws {\n _ = _uniqueStorage()\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &_storage._buildID) }()\n case 2: try {\n var v: Com_Apple_Container_Build_V1_Signal?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .signal(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .signal(v)\n }\n }()\n case 3: try {\n var v: Com_Apple_Container_Build_V1_Run?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .command(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .command(v)\n }\n }()\n case 4: try {\n var v: Com_Apple_Container_Build_V1_BuildTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildTransfer(v)\n }\n }()\n case 5: try {\n var v: Com_Apple_Container_Build_V1_ImageTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .imageTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .imageTransfer(v)\n }\n }()\n default: break\n }\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !_storage._buildID.isEmpty {\n try visitor.visitSingularStringField(value: _storage._buildID, fieldNumber: 1)\n }\n switch _storage._packetType {\n case .signal?: try {\n guard case .signal(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 2)\n }()\n case .command?: try {\n guard case .command(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 3)\n }()\n case .buildTransfer?: try {\n guard case .buildTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n }()\n case .imageTransfer?: try {\n guard case .imageTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 5)\n }()\n case nil: break\n }\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ClientStream, rhs: Com_Apple_Container_Build_V1_ClientStream) -> Bool {\n if lhs._storage !== rhs._storage {\n let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in\n let _storage = _args.0\n let rhs_storage = _args.1\n if _storage._buildID != rhs_storage._buildID {return false}\n if _storage._packetType != rhs_storage._packetType {return false}\n return true\n }\n if !storagesAreEqual {return false}\n }\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Signal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Signal\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Signal, rhs: Com_Apple_Container_Build_V1_Signal) -> Bool {\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Run: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Run\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"command\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.command) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if !self.command.isEmpty {\n try visitor.visitSingularStringField(value: self.command, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Run, rhs: Com_Apple_Container_Build_V1_Run) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.command != rhs.command {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_RunComplete: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".RunComplete\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_RunComplete, rhs: Com_Apple_Container_Build_V1_RunComplete) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_BuildTransfer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".BuildTransfer\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"direction\"),\n 3: .same(proto: \"source\"),\n 4: .same(proto: \"destination\"),\n 5: .same(proto: \"data\"),\n 6: .same(proto: \"complete\"),\n 7: .standard(proto: \"is_directory\"),\n 8: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularEnumField(value: &self.direction) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._source) }()\n case 4: try { try decoder.decodeSingularStringField(value: &self._destination) }()\n case 5: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n case 6: try { try decoder.decodeSingularBoolField(value: &self.complete) }()\n case 7: try { try decoder.decodeSingularBoolField(value: &self.isDirectory) }()\n case 8: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.direction != .into {\n try visitor.visitSingularEnumField(value: self.direction, fieldNumber: 2)\n }\n try { if let v = self._source {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try { if let v = self._destination {\n try visitor.visitSingularStringField(value: v, fieldNumber: 4)\n } }()\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 5)\n }\n if self.complete != false {\n try visitor.visitSingularBoolField(value: self.complete, fieldNumber: 6)\n }\n if self.isDirectory != false {\n try visitor.visitSingularBoolField(value: self.isDirectory, fieldNumber: 7)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 8)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_BuildTransfer, rhs: Com_Apple_Container_Build_V1_BuildTransfer) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.direction != rhs.direction {return false}\n if lhs._source != rhs._source {return false}\n if lhs._destination != rhs._destination {return false}\n if lhs.data != rhs.data {return false}\n if lhs.complete != rhs.complete {return false}\n if lhs.isDirectory != rhs.isDirectory {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ImageTransfer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ImageTransfer\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"direction\"),\n 3: .same(proto: \"tag\"),\n 4: .same(proto: \"descriptor\"),\n 5: .same(proto: \"data\"),\n 6: .same(proto: \"complete\"),\n 7: .same(proto: \"metadata\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularEnumField(value: &self.direction) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.tag) }()\n case 4: try { try decoder.decodeSingularMessageField(value: &self._descriptor) }()\n case 5: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n case 6: try { try decoder.decodeSingularBoolField(value: &self.complete) }()\n case 7: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.metadata) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.direction != .into {\n try visitor.visitSingularEnumField(value: self.direction, fieldNumber: 2)\n }\n if !self.tag.isEmpty {\n try visitor.visitSingularStringField(value: self.tag, fieldNumber: 3)\n }\n try { if let v = self._descriptor {\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n } }()\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 5)\n }\n if self.complete != false {\n try visitor.visitSingularBoolField(value: self.complete, fieldNumber: 6)\n }\n if !self.metadata.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.metadata, fieldNumber: 7)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ImageTransfer, rhs: Com_Apple_Container_Build_V1_ImageTransfer) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.direction != rhs.direction {return false}\n if lhs.tag != rhs.tag {return false}\n if lhs._descriptor != rhs._descriptor {return false}\n if lhs.data != rhs.data {return false}\n if lhs.complete != rhs.complete {return false}\n if lhs.metadata != rhs.metadata {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_ServerStream: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ServerStream\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"build_id\"),\n 2: .same(proto: \"io\"),\n 3: .standard(proto: \"build_error\"),\n 4: .standard(proto: \"command_complete\"),\n 5: .standard(proto: \"build_transfer\"),\n 6: .standard(proto: \"image_transfer\"),\n ]\n\n fileprivate class _StorageClass {\n var _buildID: String = String()\n var _packetType: Com_Apple_Container_Build_V1_ServerStream.OneOf_PacketType?\n\n // This property is used as the initial default value for new instances of the type.\n // The type itself is protecting the reference to its storage via CoW semantics.\n // This will force a copy to be made of this reference when the first mutation occurs;\n // hence, it is safe to mark this as `nonisolated(unsafe)`.\n static nonisolated(unsafe) let defaultInstance = _StorageClass()\n\n private init() {}\n\n init(copying source: _StorageClass) {\n _buildID = source._buildID\n _packetType = source._packetType\n }\n }\n\n fileprivate mutating func _uniqueStorage() -> _StorageClass {\n if !isKnownUniquelyReferenced(&_storage) {\n _storage = _StorageClass(copying: _storage)\n }\n return _storage\n }\n\n public mutating func decodeMessage(decoder: inout D) throws {\n _ = _uniqueStorage()\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &_storage._buildID) }()\n case 2: try {\n var v: Com_Apple_Container_Build_V1_IO?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .io(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .io(v)\n }\n }()\n case 3: try {\n var v: Com_Apple_Container_Build_V1_BuildError?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildError(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildError(v)\n }\n }()\n case 4: try {\n var v: Com_Apple_Container_Build_V1_RunComplete?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .commandComplete(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .commandComplete(v)\n }\n }()\n case 5: try {\n var v: Com_Apple_Container_Build_V1_BuildTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .buildTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .buildTransfer(v)\n }\n }()\n case 6: try {\n var v: Com_Apple_Container_Build_V1_ImageTransfer?\n var hadOneofValue = false\n if let current = _storage._packetType {\n hadOneofValue = true\n if case .imageTransfer(let m) = current {v = m}\n }\n try decoder.decodeSingularMessageField(value: &v)\n if let v = v {\n if hadOneofValue {try decoder.handleConflictingOneOf()}\n _storage._packetType = .imageTransfer(v)\n }\n }()\n default: break\n }\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n try withExtendedLifetime(_storage) { (_storage: _StorageClass) in\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !_storage._buildID.isEmpty {\n try visitor.visitSingularStringField(value: _storage._buildID, fieldNumber: 1)\n }\n switch _storage._packetType {\n case .io?: try {\n guard case .io(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 2)\n }()\n case .buildError?: try {\n guard case .buildError(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 3)\n }()\n case .commandComplete?: try {\n guard case .commandComplete(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 4)\n }()\n case .buildTransfer?: try {\n guard case .buildTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 5)\n }()\n case .imageTransfer?: try {\n guard case .imageTransfer(let v)? = _storage._packetType else { preconditionFailure() }\n try visitor.visitSingularMessageField(value: v, fieldNumber: 6)\n }()\n case nil: break\n }\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_ServerStream, rhs: Com_Apple_Container_Build_V1_ServerStream) -> Bool {\n if lhs._storage !== rhs._storage {\n let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in\n let _storage = _args.0\n let rhs_storage = _args.1\n if _storage._buildID != rhs_storage._buildID {return false}\n if _storage._packetType != rhs_storage._packetType {return false}\n return true\n }\n if !storagesAreEqual {return false}\n }\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_IO: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IO\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"data\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularEnumField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularBytesField(value: &self.data) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.type != .stdin {\n try visitor.visitSingularEnumField(value: self.type, fieldNumber: 1)\n }\n if !self.data.isEmpty {\n try visitor.visitSingularBytesField(value: self.data, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_IO, rhs: Com_Apple_Container_Build_V1_IO) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.data != rhs.data {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_BuildError: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".BuildError\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"message\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularEnumField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.message) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.type != .buildFailed {\n try visitor.visitSingularEnumField(value: self.type, fieldNumber: 1)\n }\n if !self.message.isEmpty {\n try visitor.visitSingularStringField(value: self.message, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_BuildError, rhs: Com_Apple_Container_Build_V1_BuildError) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.message != rhs.message {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Platform: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Platform\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"architecture\"),\n 2: .same(proto: \"os\"),\n 3: .standard(proto: \"os_version\"),\n 4: .standard(proto: \"os_features\"),\n 5: .same(proto: \"variant\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.architecture) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.os) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.osVersion) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.osFeatures) }()\n case 5: try { try decoder.decodeSingularStringField(value: &self.variant) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.architecture.isEmpty {\n try visitor.visitSingularStringField(value: self.architecture, fieldNumber: 1)\n }\n if !self.os.isEmpty {\n try visitor.visitSingularStringField(value: self.os, fieldNumber: 2)\n }\n if !self.osVersion.isEmpty {\n try visitor.visitSingularStringField(value: self.osVersion, fieldNumber: 3)\n }\n if !self.osFeatures.isEmpty {\n try visitor.visitRepeatedStringField(value: self.osFeatures, fieldNumber: 4)\n }\n if !self.variant.isEmpty {\n try visitor.visitSingularStringField(value: self.variant, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Platform, rhs: Com_Apple_Container_Build_V1_Platform) -> Bool {\n if lhs.architecture != rhs.architecture {return false}\n if lhs.os != rhs.os {return false}\n if lhs.osVersion != rhs.osVersion {return false}\n if lhs.osFeatures != rhs.osFeatures {return false}\n if lhs.variant != rhs.variant {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Container_Build_V1_Descriptor: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Descriptor\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"media_type\"),\n 2: .same(proto: \"digest\"),\n 3: .same(proto: \"size\"),\n 4: .same(proto: \"urls\"),\n 5: .same(proto: \"annotations\"),\n 6: .same(proto: \"platform\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.mediaType) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.digest) }()\n case 3: try { try decoder.decodeSingularInt64Field(value: &self.size) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.urls) }()\n case 5: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.annotations) }()\n case 6: try { try decoder.decodeSingularMessageField(value: &self._platform) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.mediaType.isEmpty {\n try visitor.visitSingularStringField(value: self.mediaType, fieldNumber: 1)\n }\n if !self.digest.isEmpty {\n try visitor.visitSingularStringField(value: self.digest, fieldNumber: 2)\n }\n if self.size != 0 {\n try visitor.visitSingularInt64Field(value: self.size, fieldNumber: 3)\n }\n if !self.urls.isEmpty {\n try visitor.visitRepeatedStringField(value: self.urls, fieldNumber: 4)\n }\n if !self.annotations.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.annotations, fieldNumber: 5)\n }\n try { if let v = self._platform {\n try visitor.visitSingularMessageField(value: v, fieldNumber: 6)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Container_Build_V1_Descriptor, rhs: Com_Apple_Container_Build_V1_Descriptor) -> Bool {\n if lhs.mediaType != rhs.mediaType {return false}\n if lhs.digest != rhs.digest {return false}\n if lhs.size != rhs.size {return false}\n if lhs.urls != rhs.urls {return false}\n if lhs.annotations != rhs.annotations {return false}\n if lhs._platform != rhs._platform {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n"], ["/container/Sources/ContainerClient/Core/Bundle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport Foundation\n\npublic struct Bundle: Sendable {\n private static let initfsFilename = \"initfs.ext4\"\n private static let kernelFilename = \"kernel.json\"\n private static let kernelBinaryFilename = \"kernel.bin\"\n private static let containerRootFsBlockFilename = \"rootfs.ext4\"\n private static let containerRootFsFilename = \"rootfs.json\"\n\n static let containerConfigFilename = \"config.json\"\n\n /// The path to the bundle.\n public let path: URL\n\n public init(path: URL) {\n self.path = path\n }\n\n public var bootlog: URL {\n self.path.appendingPathComponent(\"vminitd.log\")\n }\n\n private var containerRootfsBlock: URL {\n self.path.appendingPathComponent(Self.containerRootFsBlockFilename)\n }\n\n private var containerRootfsConfig: URL {\n self.path.appendingPathComponent(Self.containerRootFsFilename)\n }\n\n public var containerRootfs: Filesystem {\n get throws {\n let data = try Data(contentsOf: containerRootfsConfig)\n let fs = try JSONDecoder().decode(Filesystem.self, from: data)\n return fs\n }\n }\n\n /// Return the initial filesystem for a sandbox.\n public var initialFilesystem: Filesystem {\n .block(\n format: \"ext4\",\n source: self.path.appendingPathComponent(Self.initfsFilename).path,\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n\n public var kernel: Kernel {\n get throws {\n try load(path: self.path.appendingPathComponent(Self.kernelFilename))\n }\n }\n\n public var configuration: ContainerConfiguration {\n get throws {\n try load(path: self.path.appendingPathComponent(Self.containerConfigFilename))\n }\n }\n}\n\nextension Bundle {\n public static func create(\n path: URL,\n initialFilesystem: Filesystem,\n kernel: Kernel,\n containerConfiguration: ContainerConfiguration? = nil\n ) throws -> Bundle {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n let kbin = path.appendingPathComponent(Self.kernelBinaryFilename)\n try FileManager.default.copyItem(at: kernel.path, to: kbin)\n var k = kernel\n k.path = kbin\n try write(path.appendingPathComponent(Self.kernelFilename), value: k)\n\n switch initialFilesystem.type {\n case .block(let fmt, _, _):\n guard fmt == \"ext4\" else {\n fatalError(\"ext4 is the only supported format for initial filesystem\")\n }\n // when saving the Initial Filesystem to the bundle\n // discard any filesystem information and just persist\n // the block into the Bundle.\n _ = try initialFilesystem.clone(to: path.appendingPathComponent(Self.initfsFilename).path)\n default:\n fatalError(\"invalid filesystem type for initial filesystem\")\n }\n let bundle = Bundle(path: path)\n if let containerConfiguration {\n try bundle.write(filename: Self.containerConfigFilename, value: containerConfiguration)\n }\n return bundle\n }\n}\n\nextension Bundle {\n /// Set the value of the configuration for the Bundle.\n public func set(configuration: ContainerConfiguration) throws {\n try write(filename: Self.containerConfigFilename, value: configuration)\n }\n\n /// Return the full filepath for a named resource in the Bundle.\n public func filePath(for name: String) -> URL {\n path.appendingPathComponent(name)\n }\n\n public func setContainerRootFs(cloning fs: Filesystem) throws {\n let cloned = try fs.clone(to: self.containerRootfsBlock.absolutePath())\n let fsData = try JSONEncoder().encode(cloned)\n try fsData.write(to: self.containerRootfsConfig)\n }\n\n /// Delete the bundle and all of the resources contained inside.\n public func delete() throws {\n try FileManager.default.removeItem(at: self.path)\n }\n\n public func write(filename: String, value: Encodable) throws {\n try Self.write(self.path.appendingPathComponent(filename), value: value)\n }\n\n private static func write(_ path: URL, value: Encodable) throws {\n let data = try JSONEncoder().encode(value)\n try data.write(to: path)\n }\n\n public func load(filename: String) throws -> T where T: Decodable {\n try load(path: self.path.appendingPathComponent(filename))\n }\n\n private func load(path: URL) throws -> T where T: Decodable {\n let data = try Data(contentsOf: path)\n return try JSONDecoder().decode(T.self, from: data)\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientDefaults.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CVersion\nimport ContainerizationError\nimport Foundation\n\npublic enum ClientDefaults {\n private static let userDefaultDomain = \"com.apple.container.defaults\"\n\n public enum Keys: String {\n case defaultBuilderImage = \"image.builder\"\n case defaultDNSDomain = \"dns.domain\"\n case defaultRegistryDomain = \"registry.domain\"\n case defaultInitImage = \"image.init\"\n case defaultKernelURL = \"kernel.url\"\n case defaultKernelBinaryPath = \"kernel.binaryPath\"\n case buildRosetta = \"build.rosetta\"\n }\n\n public static func set(value: String, key: ClientDefaults.Keys) {\n udSuite.set(value, forKey: key.rawValue)\n }\n\n public static func unset(key: ClientDefaults.Keys) {\n udSuite.removeObject(forKey: key.rawValue)\n }\n\n public static func get(key: ClientDefaults.Keys) -> String {\n let current = udSuite.string(forKey: key.rawValue)\n return current ?? key.defaultValue\n }\n\n public static func getOptional(key: ClientDefaults.Keys) -> String? {\n udSuite.string(forKey: key.rawValue)\n }\n\n public static func setBool(value: Bool, key: ClientDefaults.Keys) {\n udSuite.set(value, forKey: key.rawValue)\n }\n\n public static func getBool(key: ClientDefaults.Keys) -> Bool? {\n guard udSuite.object(forKey: key.rawValue) != nil else { return nil }\n return udSuite.bool(forKey: key.rawValue)\n }\n\n private static var udSuite: UserDefaults {\n guard let ud = UserDefaults.init(suiteName: self.userDefaultDomain) else {\n fatalError(\"Failed to initialize UserDefaults for domain \\(self.userDefaultDomain)\")\n }\n return ud\n }\n}\n\nextension ClientDefaults.Keys {\n fileprivate var defaultValue: String {\n switch self {\n case .defaultKernelURL:\n return \"https://github.com/kata-containers/kata-containers/releases/download/3.17.0/kata-static-3.17.0-arm64.tar.xz\"\n case .defaultKernelBinaryPath:\n return \"opt/kata/share/kata-containers/vmlinux-6.12.28-153\"\n case .defaultBuilderImage:\n let tag = String(cString: get_container_builder_shim_version())\n return \"ghcr.io/apple/container-builder-shim/builder:\\(tag)\"\n case .defaultDNSDomain:\n return \"test\"\n case .defaultRegistryDomain:\n return \"docker.io\"\n case .defaultInitImage:\n let tag = String(cString: get_swift_containerization_version())\n guard tag != \"latest\" else {\n return \"vminit:latest\"\n }\n return \"ghcr.io/apple/containerization/vminit:\\(tag)\"\n case .buildRosetta:\n // This is a boolean key, not used with the string get() method\n return \"true\"\n }\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCMessage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\n\n/// A message that can be pass across application boundaries via XPC.\npublic struct XPCMessage: Sendable {\n /// Defined message key storing the route value.\n public static let routeKey = \"com.apple.container.xpc.route\"\n /// Defined message key storing the error value.\n public static let errorKey = \"com.apple.container.xpc.error\"\n\n // Access to `object` is protected by a lock\n private nonisolated(unsafe) let object: xpc_object_t\n private let lock = NSLock()\n private let isErr: Bool\n\n /// The underlying xpc object that the message wraps.\n public var underlying: xpc_object_t {\n lock.withLock {\n object\n }\n }\n public var isErrorType: Bool { isErr }\n\n public init(object: xpc_object_t) {\n self.object = object\n self.isErr = xpc_get_type(self.object) == XPC_TYPE_ERROR\n }\n\n public init(route: String) {\n self.object = xpc_dictionary_create_empty()\n self.isErr = false\n xpc_dictionary_set_string(self.object, Self.routeKey, route)\n }\n}\n\nextension XPCMessage {\n public static func == (lhs: XPCMessage, rhs: xpc_object_t) -> Bool {\n xpc_equal(lhs.underlying, rhs)\n }\n\n public func reply() -> XPCMessage {\n lock.withLock {\n XPCMessage(object: xpc_dictionary_create_reply(object)!)\n }\n }\n\n public func errorKeyDescription() -> String? {\n guard self.isErr,\n let xpcErr = lock.withLock({\n xpc_dictionary_get_string(\n self.object,\n XPC_ERROR_KEY_DESCRIPTION\n )\n })\n else {\n return nil\n }\n return String(cString: xpcErr)\n }\n\n public func error() throws {\n let data = data(key: Self.errorKey)\n if let data {\n let item = try? JSONDecoder().decode(ContainerXPCError.self, from: data)\n precondition(item != nil, \"expected to receive a ContainerXPCXPCError\")\n\n throw ContainerizationError(item!.code, message: item!.message)\n }\n }\n\n public func set(error: ContainerizationError) {\n var message = error.message\n if let cause = error.cause {\n message += \" (cause: \\\"\\(cause)\\\")\"\n }\n let serializableError = ContainerXPCError(code: error.code.description, message: message)\n let data = try? JSONEncoder().encode(serializableError)\n precondition(data != nil)\n\n set(key: Self.errorKey, value: data!)\n }\n}\n\nstruct ContainerXPCError: Codable {\n let code: String\n let message: String\n}\n\nextension XPCMessage {\n public func data(key: String) -> Data? {\n var length: Int = 0\n let bytes = lock.withLock {\n xpc_dictionary_get_data(self.object, key, &length)\n }\n\n guard let bytes else {\n return nil\n }\n\n return Data(bytes: bytes, count: length)\n }\n\n /// dataNoCopy is similar to data, except the data is not copied\n /// to a new buffer. What this means in practice is the second the\n /// underlying xpc_object_t gets released by ARC the data will be\n /// released as well. This variant should be used when you know the\n /// data will be used before the object has no more references.\n public func dataNoCopy(key: String) -> Data? {\n var length: Int = 0\n let bytes = lock.withLock {\n xpc_dictionary_get_data(self.object, key, &length)\n }\n\n guard let bytes else {\n return nil\n }\n\n return Data(\n bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes),\n count: length,\n deallocator: .none\n )\n }\n\n public func set(key: String, value: Data) {\n value.withUnsafeBytes { ptr in\n if let addr = ptr.baseAddress {\n lock.withLock {\n xpc_dictionary_set_data(self.object, key, addr, value.count)\n }\n }\n }\n }\n\n public func string(key: String) -> String? {\n let _id = lock.withLock {\n xpc_dictionary_get_string(self.object, key)\n }\n if let _id {\n return String(cString: _id)\n }\n return nil\n }\n\n public func set(key: String, value: String) {\n lock.withLock {\n xpc_dictionary_set_string(self.object, key, value)\n }\n }\n\n public func bool(key: String) -> Bool {\n lock.withLock {\n xpc_dictionary_get_bool(self.object, key)\n }\n }\n\n public func set(key: String, value: Bool) {\n lock.withLock {\n xpc_dictionary_set_bool(self.object, key, value)\n }\n }\n\n public func uint64(key: String) -> UInt64 {\n lock.withLock {\n xpc_dictionary_get_uint64(self.object, key)\n }\n }\n\n public func set(key: String, value: UInt64) {\n lock.withLock {\n xpc_dictionary_set_uint64(self.object, key, value)\n }\n }\n\n public func int64(key: String) -> Int64 {\n lock.withLock {\n xpc_dictionary_get_int64(self.object, key)\n }\n }\n\n public func set(key: String, value: Int64) {\n lock.withLock {\n xpc_dictionary_set_int64(self.object, key, value)\n }\n }\n\n public func fileHandle(key: String) -> FileHandle? {\n let fd = lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n if let fd {\n let fd2 = xpc_fd_dup(fd)\n return FileHandle(fileDescriptor: fd2, closeOnDealloc: false)\n }\n return nil\n }\n\n public func set(key: String, value: FileHandle) {\n let fd = xpc_fd_create(value.fileDescriptor)\n close(value.fileDescriptor)\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, fd)\n }\n }\n\n public func fileHandles(key: String) -> [FileHandle]? {\n let fds = lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n if let fds {\n let fd1 = xpc_array_dup_fd(fds, 0)\n let fd2 = xpc_array_dup_fd(fds, 1)\n if fd1 == -1 || fd2 == -1 {\n return nil\n }\n return [\n FileHandle(fileDescriptor: fd1, closeOnDealloc: false),\n FileHandle(fileDescriptor: fd2, closeOnDealloc: false),\n ]\n }\n return nil\n }\n\n public func set(key: String, value: [FileHandle]) throws {\n let fdArray = xpc_array_create(nil, 0)\n for fh in value {\n guard let xpcFd = xpc_fd_create(fh.fileDescriptor) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to create xpc fd for \\(fh.fileDescriptor)\"\n )\n }\n xpc_array_append_value(fdArray, xpcFd)\n close(fh.fileDescriptor)\n }\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, fdArray)\n }\n }\n\n public func endpoint(key: String) -> xpc_endpoint_t? {\n lock.withLock {\n xpc_dictionary_get_value(self.object, key)\n }\n }\n\n public func set(key: String, value: xpc_endpoint_t) {\n lock.withLock {\n xpc_dictionary_set_value(self.object, key, value)\n }\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerClient/Core/ClientNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\npublic struct ClientNetwork {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n\n public static let defaultNetworkName = \"default\"\n}\n\nextension ClientNetwork {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n private static func xpcSend(\n client: XPCClient,\n message: XPCMessage,\n timeout: Duration? = .seconds(15)\n ) async throws -> XPCMessage {\n try await client.send(message, responseTimeout: timeout)\n }\n\n public static func create(configuration: NetworkConfiguration) async throws -> NetworkState {\n let client = Self.newClient()\n let request = XPCMessage(route: .networkCreate)\n request.set(key: .networkId, value: configuration.id)\n\n let data = try JSONEncoder().encode(configuration)\n request.set(key: .networkConfig, value: data)\n\n let response = try await xpcSend(client: client, message: request)\n let responseData = response.dataNoCopy(key: .networkState)\n guard let responseData else {\n throw ContainerizationError(.invalidArgument, message: \"network configuration not received\")\n }\n let state = try JSONDecoder().decode(NetworkState.self, from: responseData)\n return state\n }\n\n public static func list() async throws -> [NetworkState] {\n let client = Self.newClient()\n let request = XPCMessage(route: .networkList)\n\n let response = try await xpcSend(client: client, message: request, timeout: .seconds(1))\n let responseData = response.dataNoCopy(key: .networkStates)\n guard let responseData else {\n return []\n }\n let states = try JSONDecoder().decode([NetworkState].self, from: responseData)\n return states\n }\n\n /// Get the network for the provided id.\n public static func get(id: String) async throws -> NetworkState {\n let networks = try await list()\n guard let network = networks.first(where: { $0.id == id }) else {\n throw ContainerizationError(.notFound, message: \"network \\(id) not found\")\n }\n return network\n }\n\n /// Delete the network with the given id.\n public static func delete(id: String) async throws {\n let client = XPCClient(service: Self.serviceIdentifier)\n let request = XPCMessage(route: .networkDelete)\n request.set(key: .networkId, value: id)\n try await client.send(request)\n }\n}\n"], ["/container/Sources/ContainerPersistence/EntityStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nlet metadataFilename: String = \"entity.json\"\n\npublic protocol EntityStore {\n associatedtype T: Codable & Identifiable & Sendable\n\n func list() async throws -> [T]\n func create(_ entity: T) async throws\n func retrieve(_ id: String) async throws -> T?\n func update(_ entity: T) async throws\n func upsert(_ entity: T) async throws\n func delete(_ id: String) async throws\n}\n\npublic actor FilesystemEntityStore: EntityStore where T: Codable & Identifiable & Sendable {\n typealias Index = [String: T]\n\n private let path: URL\n private let type: String\n private var index: Index\n private let log: Logger\n private let encoder = JSONEncoder()\n\n public init(path: URL, type: String, log: Logger) throws {\n self.path = path\n self.type = type\n self.log = log\n self.index = try Self.load(path: path, log: log)\n }\n\n public func list() async throws -> [T] {\n Array(index.values)\n }\n\n public func create(_ entity: T) async throws {\n let metadataUrl = metadataUrl(entity.id)\n guard !FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.exists, message: \"Entity \\(entity.id) already exist\")\n }\n\n try FileManager.default.createDirectory(at: entityUrl(entity.id), withIntermediateDirectories: true)\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func retrieve(_ id: String) throws -> T? {\n index[id]\n }\n\n public func update(_ entity: T) async throws {\n let metadataUrl: URL = metadataUrl(entity.id)\n guard FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.notFound, message: \"Entity \\(entity.id) not found\")\n }\n\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func upsert(_ entity: T) async throws {\n let metadataUrl: URL = metadataUrl(entity.id)\n let data = try encoder.encode(entity)\n try data.write(to: metadataUrl)\n index[entity.id] = entity\n }\n\n public func delete(_ id: String) async throws {\n let metadataUrl = entityUrl(id)\n guard FileManager.default.fileExists(atPath: metadataUrl.path) else {\n throw ContainerizationError(.notFound, message: \"entity \\(id) not found\")\n }\n try FileManager.default.removeItem(at: metadataUrl)\n index.removeValue(forKey: id)\n }\n\n public func entityUrl(_ id: String) -> URL {\n path.appendingPathComponent(id)\n }\n\n private static func load(path: URL, log: Logger) throws -> Index {\n let directories = try FileManager.default.contentsOfDirectory(at: path, includingPropertiesForKeys: nil)\n var index: FilesystemEntityStore.Index = Index()\n let decoder = JSONDecoder()\n\n for entityUrl in directories {\n do {\n let metadataUrl = entityUrl.appendingPathComponent(metadataFilename)\n let data = try Data(contentsOf: metadataUrl)\n let entity = try decoder.decode(T.self, from: data)\n index[entity.id] = entity\n } catch {\n log.warning(\n \"failed to load entity, ignoring\",\n metadata: [\n \"path\": \"\\(entityUrl)\"\n ])\n }\n }\n\n return index\n }\n\n private func metadataUrl(_ id: String) -> URL {\n entityUrl(id).appendingPathComponent(metadataFilename)\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ImageDetail.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationOCI\n\npublic struct ImageDetail: Codable {\n public let name: String\n public let index: Descriptor\n public let variants: [Variants]\n\n public struct Variants: Codable {\n public let platform: Platform\n public let config: ContainerizationOCI.Image\n public let size: Int64\n\n init(platform: Platform, size: Int64, config: ContainerizationOCI.Image) {\n self.platform = platform\n self.config = config\n self.size = size\n }\n }\n\n init(name: String, index: Descriptor, variants: [Variants]) {\n self.name = name\n self.index = index\n self.variants = variants\n }\n}\n\nextension ClientImage {\n public func details() async throws -> ImageDetail {\n let indexDescriptor = self.descriptor\n let reference = self.reference\n var variants: [ImageDetail.Variants] = []\n for desc in try await self.index().manifests {\n guard let platform = desc.platform else {\n continue\n }\n let config: ContainerizationOCI.Image\n let manifest: ContainerizationOCI.Manifest\n do {\n config = try await self.config(for: platform)\n manifest = try await self.manifest(for: platform)\n } catch {\n continue\n }\n let size = desc.size + manifest.config.size + manifest.layers.reduce(0, { (l, r) in l + r.size })\n variants.append(.init(platform: platform, size: size, config: config))\n }\n return ImageDetail(name: reference, index: indexDescriptor, variants: variants)\n }\n}\n"], ["/container/Sources/CLI/System/Kernel/KernelSet.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct KernelSet: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default kernel\"\n )\n\n @Option(name: .customLong(\"binary\"), help: \"Path to the binary to set as the default kernel. If used with --tar, this points to a location inside the tar\")\n var binaryPath: String? = nil\n\n @Option(name: .customLong(\"tar\"), help: \"Filesystem path or remote URL to a tar ball that contains the kernel to use\")\n var tarPath: String? = nil\n\n @Option(name: .customLong(\"arch\"), help: \"The architecture of the kernel binary. One of (amd64, arm64)\")\n var architecture: String = ContainerizationOCI.Platform.current.architecture.description\n\n @Flag(name: .customLong(\"recommended\"), help: \"Download and install the recommended kernel as the default. This flag ignores any other arguments\")\n var recommended: Bool = false\n\n func run() async throws {\n if recommended {\n let url = ClientDefaults.get(key: .defaultKernelURL)\n let path = ClientDefaults.get(key: .defaultKernelBinaryPath)\n print(\"Installing the recommended kernel from \\(url)...\")\n try await Self.downloadAndInstallWithProgressBar(tarRemoteURL: url, kernelFilePath: path)\n return\n }\n guard tarPath != nil else {\n return try await self.setKernelFromBinary()\n }\n try await self.setKernelFromTar()\n }\n\n private func setKernelFromBinary() async throws {\n guard let binaryPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--binary'\")\n }\n let absolutePath = URL(fileURLWithPath: binaryPath, relativeTo: .currentDirectory()).absoluteURL.absoluteString\n let platform = try getSystemPlatform()\n try await ClientKernel.installKernel(kernelFilePath: absolutePath, platform: platform)\n }\n\n private func setKernelFromTar() async throws {\n guard let binaryPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--binary'\")\n }\n guard let tarPath else {\n throw ArgumentParser.ValidationError(\"Missing argument '--tar\")\n }\n let platform = try getSystemPlatform()\n let localTarPath = URL(fileURLWithPath: tarPath, relativeTo: .currentDirectory()).absoluteString\n let fm = FileManager.default\n if fm.fileExists(atPath: localTarPath) {\n try await ClientKernel.installKernelFromTar(tarFile: localTarPath, kernelFilePath: binaryPath, platform: platform)\n return\n }\n guard let remoteURL = URL(string: tarPath) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid remote URL '\\(tarPath)' for argument '--tar'. Missing protocol?\")\n }\n try await Self.downloadAndInstallWithProgressBar(tarRemoteURL: remoteURL.absoluteString, kernelFilePath: binaryPath, platform: platform)\n }\n\n private func getSystemPlatform() throws -> SystemPlatform {\n switch architecture {\n case \"arm64\":\n return .linuxArm\n case \"amd64\":\n return .linuxAmd\n default:\n throw ContainerizationError(.unsupported, message: \"Unsupported architecture \\(architecture)\")\n }\n }\n\n public static func downloadAndInstallWithProgressBar(tarRemoteURL: String, kernelFilePath: String, platform: SystemPlatform = .current) async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n totalTasks: 2\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n try await ClientKernel.installKernelFromTar(tarFile: tarRemoteURL, kernelFilePath: kernelFilePath, platform: platform, progressUpdate: progress.handler)\n progress.finish()\n }\n\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ImageService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport Logging\nimport TerminalProgress\n\npublic actor ImagesService {\n public static let keychainID = \"com.apple.container\"\n\n private let log: Logger\n private let contentStore: ContentStore\n private let imageStore: ImageStore\n private let snapshotStore: SnapshotStore\n\n public init(contentStore: ContentStore, imageStore: ImageStore, snapshotStore: SnapshotStore, log: Logger) throws {\n self.contentStore = contentStore\n self.imageStore = imageStore\n self.snapshotStore = snapshotStore\n self.log = log\n }\n\n private func _list() async throws -> [Containerization.Image] {\n try await imageStore.list()\n }\n\n private func _get(_ reference: String) async throws -> Containerization.Image {\n try await imageStore.get(reference: reference)\n }\n\n private func _get(_ description: ImageDescription) async throws -> Containerization.Image {\n let exists = try await self._get(description.reference)\n guard exists.descriptor == description.descriptor else {\n throw ContainerizationError(.invalidState, message: \"Descriptor mismatch. Expected \\(description.descriptor), got \\(exists.descriptor)\")\n }\n return exists\n }\n\n public func list() async throws -> [ImageDescription] {\n self.log.info(\"ImagesService: \\(#function)\")\n return try await imageStore.list().map { $0.description.fromCZ }\n }\n\n public func pull(reference: String, platform: Platform?, insecure: Bool, progressUpdate: ProgressUpdateHandler?) async throws -> ImageDescription {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference), platform: \\(String(describing: platform)), insecure: \\(insecure)\")\n let img = try await Self.withAuthentication(ref: reference) { auth in\n try await self.imageStore.pull(\n reference: reference, platform: platform, insecure: insecure, auth: auth, progress: ContainerizationProgressAdapter.handler(from: progressUpdate))\n }\n guard let img else {\n throw ContainerizationError(.internalError, message: \"Failed to pull image \\(reference)\")\n }\n return img.description.fromCZ\n }\n\n public func push(reference: String, platform: Platform?, insecure: Bool, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference), platform: \\(String(describing: platform)), insecure: \\(insecure)\")\n try await Self.withAuthentication(ref: reference) { auth in\n try await self.imageStore.push(\n reference: reference, platform: platform, insecure: insecure, auth: auth, progress: ContainerizationProgressAdapter.handler(from: progressUpdate))\n }\n }\n\n public func tag(old: String, new: String) async throws -> ImageDescription {\n self.log.info(\"ImagesService: \\(#function) - old: \\(old), new: \\(new)\")\n let img = try await self.imageStore.tag(existing: old, new: new)\n return img.description.fromCZ\n }\n\n public func delete(reference: String, garbageCollect: Bool) async throws {\n self.log.info(\"ImagesService: \\(#function) - ref: \\(reference)\")\n try await self.imageStore.delete(reference: reference, performCleanup: garbageCollect)\n }\n\n public func save(reference: String, out: URL, platform: Platform?) async throws {\n self.log.info(\"ImagesService: \\(#function) - reference: \\(reference) , platform: \\(String(describing: platform))\")\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try await self.imageStore.save(references: [reference], out: tempDir, platform: platform)\n let writer = try ArchiveWriter(format: .pax, filter: .none, file: out)\n try writer.archiveDirectory(tempDir)\n try writer.finishEncoding()\n }\n\n public func load(from tarFile: URL) async throws -> [ImageDescription] {\n self.log.info(\"ImagesService: \\(#function) from: \\(tarFile.absolutePath())\")\n let reader = try ArchiveReader(file: tarFile)\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try reader.extractContents(to: tempDir)\n let loaded = try await self.imageStore.load(from: tempDir)\n var images: [ImageDescription] = []\n for image in loaded {\n images.append(image.description.fromCZ)\n }\n return images\n }\n\n public func prune() async throws -> ([String], UInt64) {\n let images = try await self._list()\n let freedSnapshotBytes = try await self.snapshotStore.clean(keepingSnapshotsFor: images)\n let (deleted, freedContentBytes) = try await self.imageStore.prune()\n return (deleted, freedContentBytes + freedSnapshotBytes)\n }\n}\n\n// MARK: Image Snapshot Methods\n\nextension ImagesService {\n public func unpack(description: ImageDescription, platform: Platform?, progressUpdate: ProgressUpdateHandler?) async throws {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n try await self.snapshotStore.unpack(image: img, platform: platform, progressUpdate: progressUpdate)\n }\n\n public func deleteImageSnapshot(description: ImageDescription, platform: Platform?) async throws {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n try await self.snapshotStore.delete(for: img, platform: platform)\n }\n\n public func getImageSnapshot(description: ImageDescription, platform: Platform) async throws -> Filesystem {\n self.log.info(\"ImagesService: \\(#function) - description: \\(description), platform: \\(String(describing: platform))\")\n let img = try await self._get(description)\n return try await self.snapshotStore.get(for: img, platform: platform)\n }\n}\n\n// MARK: Static Methods\n\nextension ImagesService {\n private static func withAuthentication(\n ref: String, _ body: @Sendable @escaping (_ auth: Authentication?) async throws -> T?\n ) async throws -> T? {\n var authentication: Authentication?\n let ref = try Reference.parse(ref)\n guard let host = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"No host specified in image reference: \\(ref)\")\n }\n authentication = Self.authenticationFromEnv(host: host)\n if let authentication {\n return try await body(authentication)\n }\n let keychain = KeychainHelper(id: Self.keychainID)\n do {\n authentication = try keychain.lookup(domain: host)\n } catch let err as KeychainHelper.Error {\n guard case .keyNotFound = err else {\n throw ContainerizationError(.internalError, message: \"Error querying keychain for \\(host)\", cause: err)\n }\n }\n do {\n return try await body(authentication)\n } catch let err as RegistryClient.Error {\n guard case .invalidStatus(_, let status, _) = err else {\n throw err\n }\n guard status == .unauthorized || status == .forbidden else {\n throw err\n }\n guard authentication != nil else {\n throw ContainerizationError(.internalError, message: \"\\(String(describing: err)). No credentials found for host \\(host)\")\n }\n throw err\n }\n }\n\n private static func authenticationFromEnv(host: String) -> Authentication? {\n let env = ProcessInfo.processInfo.environment\n guard env[\"CONTAINER_REGISTRY_HOST\"] == host else {\n return nil\n }\n guard let user = env[\"CONTAINER_REGISTRY_USER\"], let password = env[\"CONTAINER_REGISTRY_TOKEN\"] else {\n return nil\n }\n return BasicAuthentication(username: user, password: password)\n }\n}\n\nextension ImageDescription {\n public var toCZ: Containerization.Image.Description {\n .init(reference: self.reference, descriptor: self.descriptor)\n }\n}\n\nextension Containerization.Image.Description {\n public var fromCZ: ImageDescription {\n .init(\n reference: self.reference,\n descriptor: self.descriptor\n )\n }\n}\n"], ["/container/Sources/CLI/RunCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Foundation\nimport NIOCore\nimport NIOPosix\nimport TerminalProgress\n\nextension Application {\n struct ContainerRunCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"run\",\n abstract: \"Run a container\")\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var resourceFlags: Flags.Resource\n\n @OptionGroup\n var managementFlags: Flags.Management\n\n @OptionGroup\n var registryFlags: Flags.Registry\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Argument(help: \"Image name\")\n var image: String\n\n @Argument(parsing: .captureForPassthrough, help: \"Container init process arguments\")\n var arguments: [String] = []\n\n func run() async throws {\n var exitCode: Int32 = 127\n let id = Utility.createContainerID(name: self.managementFlags.name)\n\n var progressConfig: ProgressConfig\n if progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 6\n )\n }\n\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n try Utility.validEntityName(id)\n\n // Check if container with id already exists.\n let existing = try? await ClientContainer.get(id: id)\n guard existing == nil else {\n throw ContainerizationError(\n .exists,\n message: \"container with id \\(id) already exists\"\n )\n }\n\n let ck = try await Utility.containerConfigFromFlags(\n id: id,\n image: image,\n arguments: arguments,\n process: processFlags,\n management: managementFlags,\n resource: resourceFlags,\n registry: registryFlags,\n progressUpdate: progress.handler\n )\n\n progress.set(description: \"Starting container\")\n\n let options = ContainerCreateOptions(autoRemove: managementFlags.remove)\n let container = try await ClientContainer.create(\n configuration: ck.0,\n options: options,\n kernel: ck.1\n )\n\n let detach = self.managementFlags.detach\n\n let process = try await container.bootstrap()\n progress.finish()\n\n do {\n let io = try ProcessIO.create(\n tty: self.processFlags.tty,\n interactive: self.processFlags.interactive,\n detach: detach\n )\n\n if !self.managementFlags.cidfile.isEmpty {\n let path = self.managementFlags.cidfile\n let data = id.data(using: .utf8)\n var attributes = [FileAttributeKey: Any]()\n attributes[.posixPermissions] = 0o644\n let success = FileManager.default.createFile(\n atPath: path,\n contents: data,\n attributes: attributes\n )\n guard success else {\n throw ContainerizationError(\n .internalError, message: \"failed to create cidfile at \\(path): \\(errno)\")\n }\n }\n\n if detach {\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n print(id)\n return\n }\n\n if !self.processFlags.tty {\n var handler = SignalThreshold(threshold: 3, signals: [SIGINT, SIGTERM])\n handler.start {\n print(\"Received 3 SIGINT/SIGTERM's, forcefully exiting.\")\n Darwin.exit(1)\n }\n }\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to run container: \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n\nstruct ProcessIO {\n let stdin: Pipe?\n let stdout: Pipe?\n let stderr: Pipe?\n var ioTracker: IoTracker?\n\n struct IoTracker {\n let stream: AsyncStream\n let cont: AsyncStream.Continuation\n let configuredStreams: Int\n }\n\n let stdio: [FileHandle?]\n\n let console: Terminal?\n\n func closeAfterStart() throws {\n try stdin?.fileHandleForReading.close()\n try stdout?.fileHandleForWriting.close()\n try stderr?.fileHandleForWriting.close()\n }\n\n func close() throws {\n try console?.reset()\n }\n\n static func create(tty: Bool, interactive: Bool, detach: Bool) throws -> ProcessIO {\n let current: Terminal? = try {\n if !tty || !interactive {\n return nil\n }\n let current = try Terminal.current\n try current.setraw()\n return current\n }()\n\n var stdio = [FileHandle?](repeating: nil, count: 3)\n\n let stdin: Pipe? = {\n if !interactive && !tty {\n return nil\n }\n return Pipe()\n }()\n\n if let stdin {\n if interactive {\n let pin = FileHandle.standardInput\n let stdinOSFile = OSFile(fd: pin.fileDescriptor)\n let pipeOSFile = OSFile(fd: stdin.fileHandleForWriting.fileDescriptor)\n try stdinOSFile.makeNonBlocking()\n nonisolated(unsafe) let buf = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n\n pin.readabilityHandler = { _ in\n Self.streamStdin(\n from: stdinOSFile,\n to: pipeOSFile,\n buffer: buf,\n ) {\n pin.readabilityHandler = nil\n buf.deallocate()\n try? stdin.fileHandleForWriting.close()\n }\n }\n }\n stdio[0] = stdin.fileHandleForReading\n }\n\n let stdout: Pipe? = {\n if detach {\n return nil\n }\n return Pipe()\n }()\n\n var configuredStreams = 0\n let (stream, cc) = AsyncStream.makeStream()\n if let stdout {\n configuredStreams += 1\n let pout: FileHandle = {\n if let current {\n return current.handle\n }\n return .standardOutput\n }()\n\n let rout = stdout.fileHandleForReading\n rout.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n rout.readabilityHandler = nil\n cc.yield()\n return\n }\n try! pout.write(contentsOf: data)\n }\n stdio[1] = stdout.fileHandleForWriting\n }\n\n let stderr: Pipe? = {\n if detach || tty {\n return nil\n }\n return Pipe()\n }()\n if let stderr {\n configuredStreams += 1\n let perr: FileHandle = .standardError\n let rerr = stderr.fileHandleForReading\n rerr.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n rerr.readabilityHandler = nil\n cc.yield()\n return\n }\n try! perr.write(contentsOf: data)\n }\n stdio[2] = stderr.fileHandleForWriting\n }\n\n var ioTracker: IoTracker? = nil\n if configuredStreams > 0 {\n ioTracker = .init(stream: stream, cont: cc, configuredStreams: configuredStreams)\n }\n\n return .init(\n stdin: stdin,\n stdout: stdout,\n stderr: stderr,\n ioTracker: ioTracker,\n stdio: stdio,\n console: current\n )\n }\n\n static func streamStdin(\n from: OSFile,\n to: OSFile,\n buffer: UnsafeMutableBufferPointer,\n onErrorOrEOF: () -> Void,\n ) {\n while true {\n let (bytesRead, action) = from.read(buffer)\n if bytesRead > 0 {\n let view = UnsafeMutableBufferPointer(\n start: buffer.baseAddress,\n count: bytesRead\n )\n\n let (bytesWritten, _) = to.write(view)\n if bytesWritten != bytesRead {\n onErrorOrEOF()\n return\n }\n }\n\n switch action {\n case .error(_), .eof, .brokenPipe:\n onErrorOrEOF()\n return\n case .again:\n return\n case .success:\n break\n }\n }\n }\n\n public func wait() async throws {\n guard let ioTracker = self.ioTracker else {\n return\n }\n do {\n try await Timeout.run(seconds: 3) {\n var counter = ioTracker.configuredStreams\n for await _ in ioTracker.stream {\n counter -= 1\n if counter == 0 {\n ioTracker.cont.finish()\n break\n }\n }\n }\n } catch {\n log.error(\"Timeout waiting for IO to complete : \\(error)\")\n throw error\n }\n }\n}\n\nstruct OSFile: Sendable {\n private let fd: Int32\n\n enum IOAction: Equatable {\n case eof\n case again\n case success\n case brokenPipe\n case error(_ errno: Int32)\n }\n\n init(fd: Int32) {\n self.fd = fd\n }\n\n init(handle: FileHandle) {\n self.fd = handle.fileDescriptor\n }\n\n func makeNonBlocking() throws {\n let flags = fcntl(fd, F_GETFL)\n guard flags != -1 else {\n throw POSIXError.fromErrno()\n }\n\n if fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1 {\n throw POSIXError.fromErrno()\n }\n }\n\n func write(_ buffer: UnsafeMutableBufferPointer) -> (wrote: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesWrote: Int = 0\n while true {\n let n = Darwin.write(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesWrote),\n buffer.count - bytesWrote\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesWrote, .again)\n }\n return (bytesWrote, .error(errno))\n }\n\n if n == 0 {\n return (bytesWrote, .brokenPipe)\n }\n\n bytesWrote += n\n if bytesWrote < buffer.count {\n continue\n }\n return (bytesWrote, .success)\n }\n }\n\n func read(_ buffer: UnsafeMutableBufferPointer) -> (read: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesRead: Int = 0\n while true {\n let n = Darwin.read(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesRead),\n buffer.count - bytesRead\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesRead, .again)\n }\n return (bytesRead, .error(errno))\n }\n\n if n == 0 {\n return (bytesRead, .eof)\n }\n\n bytesRead += n\n if bytesRead < buffer.count {\n continue\n }\n return (bytesRead, .success)\n }\n }\n}\n"], ["/container/Sources/Helpers/NetworkVmnet/NetworkVmnetHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerLog\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\n@main\nstruct NetworkVmnetHelper: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"container-network-vmnet\",\n abstract: \"XPC service for managing a vmnet network\",\n version: releaseVersion(),\n subcommands: [\n Start.self\n ]\n )\n}\n\nextension NetworkVmnetHelper {\n struct Start: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Starts the network plugin\"\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .long, help: \"XPC service identifier\")\n var serviceIdentifier: String\n\n @Option(name: .shortAndLong, help: \"Network identifier\")\n var id: String\n\n @Option(name: .shortAndLong, help: \"CIDR address for the subnet\")\n var subnet: String?\n\n func run() async throws {\n let commandName = NetworkVmnetHelper._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n\n do {\n log.info(\"configuring XPC server\")\n let subnet = try self.subnet.map { try CIDRAddress($0) }\n let configuration = NetworkConfiguration(id: id, mode: .nat, subnet: subnet?.description)\n let network = try Self.createNetwork(configuration: configuration, log: log)\n try await network.start()\n let server = try await NetworkService(network: network, log: log)\n let xpc = XPCServer(\n identifier: serviceIdentifier,\n routes: [\n NetworkRoutes.state.rawValue: server.state,\n NetworkRoutes.allocate.rawValue: server.allocate,\n NetworkRoutes.deallocate.rawValue: server.deallocate,\n NetworkRoutes.lookup.rawValue: server.lookup,\n NetworkRoutes.disableAllocator.rawValue: server.disableAllocator,\n ],\n log: log\n )\n\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n NetworkVmnetHelper.exit(withError: error)\n }\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"NetworkVmnetHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n log[metadataKey: \"id\"] = \"\\(id)\"\n return log\n }\n\n private static func createNetwork(configuration: NetworkConfiguration, log: Logger) throws -> Network {\n guard #available(macOS 26, *) else {\n return try AllocationOnlyVmnetNetwork(configuration: configuration, log: log)\n }\n\n return try ReservedVmnetNetwork(configuration: configuration, log: log)\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\n\npublic struct XPCClient: Sendable {\n private nonisolated(unsafe) let connection: xpc_connection_t\n private let q: DispatchQueue?\n private let service: String\n\n public init(service: String, queue: DispatchQueue? = nil) {\n let connection = xpc_connection_create_mach_service(service, queue, 0)\n self.connection = connection\n self.q = queue\n self.service = service\n\n xpc_connection_set_event_handler(connection) { _ in }\n xpc_connection_set_target_queue(connection, self.q)\n xpc_connection_activate(connection)\n }\n}\n\nextension XPCClient {\n /// Close the underlying XPC connection.\n public func close() {\n xpc_connection_cancel(connection)\n }\n\n /// Returns the pid of process to which we have a connection.\n /// Note: `xpc_connection_get_pid` returns 0 if no activity\n /// has taken place on the connection prior to it being called.\n public func remotePid() -> pid_t {\n xpc_connection_get_pid(self.connection)\n }\n\n /// Send the provided message to the service.\n @discardableResult\n public func send(_ message: XPCMessage, responseTimeout: Duration? = nil) async throws -> XPCMessage {\n try await withThrowingTaskGroup(of: XPCMessage.self, returning: XPCMessage.self) { group in\n if let responseTimeout {\n group.addTask {\n try await Task.sleep(for: responseTimeout)\n let route = message.string(key: XPCMessage.routeKey) ?? \"nil\"\n throw ContainerizationError(.internalError, message: \"XPC timeout for request to \\(self.service)/\\(route)\")\n }\n }\n\n group.addTask {\n try await withCheckedThrowingContinuation { cont in\n xpc_connection_send_message_with_reply(self.connection, message.underlying, nil) { reply in\n do {\n let message = try self.parseReply(reply)\n cont.resume(returning: message)\n } catch {\n cont.resume(throwing: error)\n }\n }\n }\n }\n\n let response = try await group.next()\n // once one task has finished, cancel the rest.\n group.cancelAll()\n // we don't really care about the second error here\n // as it's most likely a `CancellationError`.\n try? await group.waitForAll()\n\n guard let response else {\n throw ContainerizationError(.invalidState, message: \"failed to receive XPC response\")\n }\n return response\n }\n }\n\n private func parseReply(_ reply: xpc_object_t) throws -> XPCMessage {\n switch xpc_get_type(reply) {\n case XPC_TYPE_ERROR:\n var code = ContainerizationError.Code.invalidState\n if reply.connectionError {\n code = .interrupted\n }\n throw ContainerizationError(\n code,\n message: \"XPC connection error: \\(reply.errorDescription ?? \"unknown\")\"\n )\n case XPC_TYPE_DICTIONARY:\n let message = XPCMessage(object: reply)\n // check errors from our protocol\n try message.error()\n return message\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(reply))\")\n }\n }\n}\n\n#endif\n"], ["/container/Sources/Helpers/Images/ImagesHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CVersion\nimport ContainerImagesService\nimport ContainerImagesServiceClient\nimport ContainerLog\nimport ContainerXPC\nimport Containerization\nimport Foundation\nimport Logging\n\n@main\nstruct ImagesHelper: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"container-core-images\",\n abstract: \"XPC service for managing OCI images\",\n version: releaseVersion(),\n subcommands: [\n Start.self\n ]\n )\n}\n\nextension ImagesHelper {\n struct Start: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Starts the image plugin\"\n )\n\n @Flag(name: .long, help: \"Enable debug logging\")\n var debug = false\n\n @Option(name: .long, help: \"XPC service prefix\")\n var serviceIdentifier: String = \"com.apple.container.core.container-core-images\"\n\n @Option(name: .shortAndLong, help: \"Daemon root directory\")\n var root = Self.appRoot.path\n\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.container\")\n }()\n\n private static let unpackStrategy = SnapshotStore.defaultUnpackStrategy\n\n func run() async throws {\n let commandName = ImagesHelper._commandName\n let log = setupLogger()\n log.info(\"starting \\(commandName)\")\n defer {\n log.info(\"stopping \\(commandName)\")\n }\n do {\n log.info(\"configuring XPC server\")\n let root = URL(filePath: root)\n var routes = [String: XPCServer.RouteHandler]()\n try self.initializeContentService(root: root, log: log, routes: &routes)\n try self.initializeImagesService(root: root, log: log, routes: &routes)\n let xpc = XPCServer(\n identifier: serviceIdentifier,\n routes: routes,\n log: log\n )\n log.info(\"starting XPC server\")\n try await xpc.listen()\n } catch {\n log.error(\"\\(commandName) failed\", metadata: [\"error\": \"\\(error)\"])\n ImagesHelper.exit(withError: error)\n }\n }\n\n private func initializeImagesService(root: URL, log: Logger, routes: inout [String: XPCServer.RouteHandler]) throws {\n let contentStore = RemoteContentStoreClient()\n let imageStore = try ImageStore(path: root, contentStore: contentStore)\n let snapshotStore = try SnapshotStore(path: root, unpackStrategy: Self.unpackStrategy, log: log)\n let service = try ImagesService(contentStore: contentStore, imageStore: imageStore, snapshotStore: snapshotStore, log: log)\n let harness = ImagesServiceHarness(service: service, log: log)\n\n routes[ImagesServiceXPCRoute.imagePull.rawValue] = harness.pull\n routes[ImagesServiceXPCRoute.imageList.rawValue] = harness.list\n routes[ImagesServiceXPCRoute.imageDelete.rawValue] = harness.delete\n routes[ImagesServiceXPCRoute.imageTag.rawValue] = harness.tag\n routes[ImagesServiceXPCRoute.imagePush.rawValue] = harness.push\n routes[ImagesServiceXPCRoute.imageSave.rawValue] = harness.save\n routes[ImagesServiceXPCRoute.imageLoad.rawValue] = harness.load\n routes[ImagesServiceXPCRoute.imageUnpack.rawValue] = harness.unpack\n routes[ImagesServiceXPCRoute.imagePrune.rawValue] = harness.prune\n routes[ImagesServiceXPCRoute.snapshotDelete.rawValue] = harness.deleteSnapshot\n routes[ImagesServiceXPCRoute.snapshotGet.rawValue] = harness.getSnapshot\n }\n\n private func initializeContentService(root: URL, log: Logger, routes: inout [String: XPCServer.RouteHandler]) throws {\n let service = try ContentStoreService(root: root, log: log)\n let harness = ContentServiceHarness(service: service, log: log)\n\n routes[ImagesServiceXPCRoute.contentClean.rawValue] = harness.clean\n routes[ImagesServiceXPCRoute.contentGet.rawValue] = harness.get\n routes[ImagesServiceXPCRoute.contentDelete.rawValue] = harness.delete\n routes[ImagesServiceXPCRoute.contentIngestStart.rawValue] = harness.newIngestSession\n routes[ImagesServiceXPCRoute.contentIngestCancel.rawValue] = harness.cancelIngestSession\n routes[ImagesServiceXPCRoute.contentIngestComplete.rawValue] = harness.completeIngestSession\n }\n\n private func setupLogger() -> Logger {\n LoggingSystem.bootstrap { label in\n OSLogHandler(\n label: label,\n category: \"ImagesHelper\"\n )\n }\n var log = Logger(label: \"com.apple.container\")\n if debug {\n log.logLevel = .debug\n }\n return log\n }\n }\n\n private static func releaseVersion() -> String {\n (Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String) ?? get_release_version().map { String(cString: $0) } ?? \"0.0.0\"\n }\n}\n"], ["/container/Sources/ContainerXPC/XPCServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport Foundation\nimport Logging\nimport os\nimport Synchronization\n\npublic struct XPCServer: Sendable {\n public typealias RouteHandler = @Sendable (XPCMessage) async throws -> XPCMessage\n\n private let routes: [String: RouteHandler]\n // Access to `connection` is protected by a lock\n private nonisolated(unsafe) let connection: xpc_connection_t\n private let lock = NSLock()\n\n let log: Logging.Logger\n\n public init(identifier: String, routes: [String: RouteHandler], log: Logging.Logger) {\n let connection = xpc_connection_create_mach_service(\n identifier,\n nil,\n UInt64(XPC_CONNECTION_MACH_SERVICE_LISTENER))\n\n self.routes = routes\n self.connection = connection\n self.log = log\n }\n\n public func listen() async throws {\n let connections = AsyncStream { cont in\n lock.withLock {\n xpc_connection_set_event_handler(self.connection) { object in\n switch xpc_get_type(object) {\n case XPC_TYPE_CONNECTION:\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n cont.yield(object)\n case XPC_TYPE_ERROR:\n if object.connectionError {\n cont.finish()\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(object))\")\n }\n }\n }\n }\n\n defer {\n lock.withLock {\n xpc_connection_cancel(self.connection)\n }\n }\n\n lock.withLock {\n xpc_connection_activate(self.connection)\n }\n try await withThrowingDiscardingTaskGroup { group in\n for await conn in connections {\n // `conn` isn't used concurrently.\n nonisolated(unsafe) let conn = conn\n let added = group.addTaskUnlessCancelled { @Sendable in\n try await self.handleClientConnection(connection: conn)\n xpc_connection_cancel(conn)\n }\n\n if !added {\n break\n }\n }\n\n group.cancelAll()\n }\n }\n\n func handleClientConnection(connection: xpc_connection_t) async throws {\n let replySent = Mutex(false)\n\n let objects = AsyncStream { cont in\n xpc_connection_set_event_handler(connection) { object in\n switch xpc_get_type(object) {\n case XPC_TYPE_DICTIONARY:\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n cont.yield(object)\n case XPC_TYPE_ERROR:\n if object.connectionError {\n cont.finish()\n }\n if !(replySent.withLock({ $0 }) && object.connectionClosed) {\n // When a xpc connection is closed, the framework sends a final XPC_ERROR_CONNECTION_INVALID message.\n // We can ignore this if we know we have already handled the request.\n self.log.error(\"xpc client handler connection error \\(object.errorDescription ?? \"no description\")\")\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(object))\")\n }\n }\n }\n defer {\n xpc_connection_cancel(connection)\n }\n\n xpc_connection_activate(connection)\n try await withThrowingDiscardingTaskGroup { group in\n // `connection` isn't used concurrently.\n nonisolated(unsafe) let connection = connection\n for await object in objects {\n // `object` isn't used concurrently.\n nonisolated(unsafe) let object = object\n let added = group.addTaskUnlessCancelled { @Sendable in\n try await self.handleMessage(connection: connection, object: object)\n replySent.withLock { $0 = true }\n }\n if !added {\n break\n }\n }\n group.cancelAll()\n }\n }\n\n func handleMessage(connection: xpc_connection_t, object: xpc_object_t) async throws {\n guard let route = object.route else {\n log.error(\"empty route\")\n return\n }\n\n if let handler = routes[route] {\n let message = XPCMessage(object: object)\n do {\n let response = try await handler(message)\n xpc_connection_send_message(connection, response.underlying)\n } catch let error as ContainerizationError {\n let reply = message.reply()\n log.error(\"handler for \\(route) threw error \\(error)\")\n reply.set(error: error)\n xpc_connection_send_message(connection, reply.underlying)\n } catch {\n let reply = message.reply()\n log.error(\"handler for \\(route) threw error \\(error)\")\n let err = ContainerizationError(.unknown, message: String(describing: error))\n reply.set(error: err)\n xpc_connection_send_message(connection, reply.underlying)\n }\n }\n }\n}\n\nextension xpc_object_t {\n var route: String? {\n let croute = xpc_dictionary_get_string(self, XPCMessage.routeKey)\n guard let croute else {\n return nil\n }\n return String(cString: croute)\n }\n\n var connectionError: Bool {\n precondition(isError, \"Not an error\")\n return xpc_equal(self, XPC_ERROR_CONNECTION_INVALID) || xpc_equal(self, XPC_ERROR_CONNECTION_INTERRUPTED)\n }\n\n var connectionClosed: Bool {\n precondition(isError, \"Not an error\")\n return xpc_equal(self, XPC_ERROR_CONNECTION_INVALID)\n }\n\n var isError: Bool {\n xpc_get_type(self) == XPC_TYPE_ERROR\n }\n\n var errorDescription: String? {\n precondition(isError, \"Not an error\")\n let cstring = xpc_dictionary_get_string(self, XPC_ERROR_KEY_DESCRIPTION)\n guard let cstring else {\n return nil\n }\n return String(cString: cstring)\n }\n}\n\n#endif\n"], ["/container/Sources/CLI/Image/ImageList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ListImageOptions: ParsableArguments {\n @Flag(name: .shortAndLong, help: \"Only output the image name\")\n var quiet = false\n\n @Flag(name: .shortAndLong, help: \"Verbose output\")\n var verbose = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n }\n\n struct ListImageImplementation {\n static private func createHeader() -> [[String]] {\n [[\"NAME\", \"TAG\", \"DIGEST\"]]\n }\n\n static private func createVerboseHeader() -> [[String]] {\n [[\"NAME\", \"TAG\", \"INDEX DIGEST\", \"OS\", \"ARCH\", \"VARIANT\", \"SIZE\", \"CREATED\", \"MANIFEST DIGEST\"]]\n }\n\n static private func printImagesVerbose(images: [ClientImage]) async throws {\n\n var rows = createVerboseHeader()\n for image in images {\n let formatter = ByteCountFormatter()\n for descriptor in try await image.index().manifests {\n // Don't list attestation manifests\n if let referenceType = descriptor.annotations?[\"vnd.docker.reference.type\"],\n referenceType == \"attestation-manifest\"\n {\n continue\n }\n\n guard let platform = descriptor.platform else {\n continue\n }\n\n let os = platform.os\n let arch = platform.architecture\n let variant = platform.variant ?? \"\"\n\n var config: ContainerizationOCI.Image\n var manifest: ContainerizationOCI.Manifest\n do {\n config = try await image.config(for: platform)\n manifest = try await image.manifest(for: platform)\n } catch {\n continue\n }\n\n let created = config.created ?? \"\"\n let size = descriptor.size + manifest.config.size + manifest.layers.reduce(0, { (l, r) in l + r.size })\n let formattedSize = formatter.string(fromByteCount: size)\n\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n let reference = try ContainerizationOCI.Reference.parse(processedReferenceString)\n let row = [\n reference.name,\n reference.tag ?? \"\",\n Utility.trimDigest(digest: image.descriptor.digest),\n os,\n arch,\n variant,\n formattedSize,\n created,\n Utility.trimDigest(digest: descriptor.digest),\n ]\n rows.append(row)\n }\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n\n static private func printImages(images: [ClientImage], format: ListFormat, options: ListImageOptions) async throws {\n var images = images\n images.sort {\n $0.reference < $1.reference\n }\n\n if format == .json {\n let data = try JSONEncoder().encode(images.map { $0.description })\n print(String(data: data, encoding: .utf8)!)\n return\n }\n\n if options.quiet {\n try images.forEach { image in\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n print(processedReferenceString)\n }\n return\n }\n\n if options.verbose {\n try await Self.printImagesVerbose(images: images)\n return\n }\n\n var rows = createHeader()\n for image in images {\n let processedReferenceString = try ClientImage.denormalizeReference(image.reference)\n let reference = try ContainerizationOCI.Reference.parse(processedReferenceString)\n rows.append([\n reference.name,\n reference.tag ?? \"\",\n Utility.trimDigest(digest: image.descriptor.digest),\n ])\n }\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n\n static func validate(options: ListImageOptions) throws {\n if options.quiet && options.verbose {\n throw ContainerizationError(.invalidArgument, message: \"Cannot use flag --quite and --verbose together\")\n }\n let modifier = options.quiet || options.verbose\n if modifier && options.format == .json {\n throw ContainerizationError(.invalidArgument, message: \"Cannot use flag --quite or --verbose along with --format json\")\n }\n }\n\n static func listImages(options: ListImageOptions) async throws {\n let images = try await ClientImage.list().filter { img in\n !Utility.isInfraImage(name: img.reference)\n }\n try await printImages(images: images, format: options.format, options: options)\n }\n }\n\n struct ImageList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List images\",\n aliases: [\"ls\"])\n\n @OptionGroup\n var options: ListImageOptions\n\n mutating func run() async throws {\n try ListImageImplementation.validate(options: options)\n try await ListImageImplementation.listImages(options: options)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/Filesystem.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Options to pass to a mount call.\npublic typealias MountOptions = [String]\n\nextension MountOptions {\n /// Returns true if the Filesystem should be consumed as read-only.\n public var readonly: Bool {\n self.contains(\"ro\")\n }\n}\n\n/// A host filesystem that will be attached to the sandbox for use.\n///\n/// A filesystem will be mounted automatically when starting the sandbox\n/// or container.\npublic struct Filesystem: Sendable, Codable {\n /// Type of caching to perform at the host level.\n public enum CacheMode: Sendable, Codable {\n case on\n case off\n case auto\n }\n\n /// Sync mode to perform at the host level.\n public enum SyncMode: Sendable, Codable {\n case full\n case fsync\n case nosync\n }\n\n /// The type of filesystem attachment for the sandbox.\n public enum FSType: Sendable, Codable, Equatable {\n package enum VirtiofsType: String, Sendable, Codable, Equatable {\n // This is a virtiofs share for the rootfs of a sandbox.\n case rootfs\n // Data share. This is what all virtiofs shares for anything besides\n // the rootfs for a sandbox will be.\n case data\n }\n\n case block(format: String, cache: CacheMode, sync: SyncMode)\n case virtiofs\n case tmpfs\n }\n\n /// Type of the filesystem.\n public var type: FSType\n /// Source of the filesystem.\n public var source: String\n /// Destination where the filesystem should be mounted.\n public var destination: String\n /// Mount options applied when mounting the filesystem.\n public var options: MountOptions\n\n public init() {\n self.type = .tmpfs\n self.source = \"\"\n self.destination = \"\"\n self.options = []\n }\n\n public init(type: FSType, source: String, destination: String, options: MountOptions) {\n self.type = type\n self.source = source\n self.destination = destination\n self.options = options\n }\n\n /// A block based filesystem.\n public static func block(\n format: String, source: String, destination: String, options: MountOptions, cache: CacheMode = .auto,\n sync: SyncMode = .full\n ) -> Filesystem {\n .init(\n type: .block(format: format, cache: cache, sync: sync),\n source: URL(fileURLWithPath: source).absolutePath(),\n destination: destination,\n options: options\n )\n }\n\n /// A vritiofs backed filesystem providing a directory.\n public static func virtiofs(source: String, destination: String, options: MountOptions) -> Filesystem {\n .init(\n type: .virtiofs,\n source: URL(fileURLWithPath: source).absolutePath(),\n destination: destination,\n options: options\n )\n }\n\n public static func tmpfs(destination: String, options: MountOptions) -> Filesystem {\n .init(\n type: .tmpfs,\n source: \"tmpfs\",\n destination: destination,\n options: options\n )\n }\n\n /// Returns true if the Filesystem is backed by a block device.\n public var isBlock: Bool {\n switch type {\n case .block(_, _, _): true\n default: false\n }\n }\n\n /// Returns true if the Filesystem is backed by a in-memory mount type.\n public var isTmpfs: Bool {\n switch type {\n case .tmpfs: true\n default: false\n }\n }\n\n /// Returns true if the Filesystem is backed by virtioFS.\n public var isVirtiofs: Bool {\n switch type {\n case .virtiofs: true\n default: false\n }\n }\n\n /// Clone the Filesystem to the provided path.\n ///\n /// This uses `clonefile` to provide a copy-on-write copy of the Filesystem.\n public func clone(to: String) throws -> Self {\n let fm = FileManager.default\n let src = self.source\n try fm.copyItem(atPath: src, toPath: to)\n return .init(type: self.type, source: to, destination: self.destination, options: self.options)\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ContentServiceHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\n\npublic struct ContentServiceHarness: Sendable {\n private let log: Logging.Logger\n private let service: ContentStoreService\n\n public init(service: ContentStoreService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n public func get(_ message: XPCMessage) async throws -> XPCMessage {\n let d = message.string(key: .digest)\n guard let d else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n guard let path = try await service.get(digest: d) else {\n let err = ContainerizationError(.notFound, message: \"digest \\(d) not found\")\n let reply = message.reply()\n reply.set(error: err)\n return reply\n }\n let reply = message.reply()\n reply.set(key: .contentPath, value: path.path(percentEncoded: false))\n return reply\n }\n\n @Sendable\n public func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .digests)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n let digests = try JSONDecoder().decode([String].self, from: data)\n let (deleted, size) = try await self.service.delete(digests: digests)\n let d = try JSONEncoder().encode(deleted)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n reply.set(key: .size, value: size)\n return reply\n }\n\n @Sendable\n public func clean(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .digests)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"missing digest\")\n }\n let digests = try JSONDecoder().decode([String].self, from: data)\n let (deleted, size) = try await self.service.delete(keeping: digests)\n let d = try JSONEncoder().encode(deleted)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n reply.set(key: .size, value: size)\n return reply\n }\n\n @Sendable\n public func newIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let session = try await self.service.newIngestSession()\n let id = session.id\n let dir = session.ingestDir\n let reply = message.reply()\n reply.set(key: .directory, value: dir.path(percentEncoded: false))\n reply.set(key: .ingestSessionId, value: id)\n return reply\n }\n\n @Sendable\n public func cancelIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .ingestSessionId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"missing ingest session id\")\n }\n try await self.service.cancelIngestSession(id)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func completeIngestSession(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .ingestSessionId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"missing ingest session id\")\n }\n let ingested = try await self.service.completeIngestSession(id)\n let d = try JSONEncoder().encode(ingested)\n let reply = message.reply()\n reply.set(key: .digests, value: d)\n return reply\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\npublic actor NetworkService: Sendable {\n private let network: any Network\n private let log: Logger?\n private var allocator: AttachmentAllocator\n\n /// Set up a network service for the specified network.\n public init(\n network: any Network,\n log: Logger? = nil\n ) async throws {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let subnet = try CIDRAddress(status.address)\n\n let size = Int(subnet.upper.value - subnet.lower.value - 3)\n self.allocator = try AttachmentAllocator(lower: subnet.lower.value + 2, size: size)\n self.network = network\n self.log = log\n }\n\n @Sendable\n public func state(_ message: XPCMessage) async throws -> XPCMessage {\n let reply = message.reply()\n let state = await network.state\n try reply.setState(state)\n return reply\n }\n\n @Sendable\n public func allocate(_ message: XPCMessage) async throws -> XPCMessage {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let hostname = try message.hostname()\n let index = try await allocator.allocate(hostname: hostname)\n let subnet = try CIDRAddress(status.address)\n let ip = IPv4Address(fromValue: index)\n let attachment = Attachment(\n network: state.id,\n hostname: hostname,\n address: try CIDRAddress(ip, prefixLength: subnet.prefixLength).description,\n gateway: status.gateway\n )\n log?.info(\n \"allocated attachment\",\n metadata: [\n \"hostname\": \"\\(hostname)\",\n \"address\": \"\\(attachment.address)\",\n \"gateway\": \"\\(attachment.gateway)\",\n ])\n let reply = message.reply()\n try reply.setAttachment(attachment)\n try network.withAdditionalData {\n if let additionalData = $0 {\n try reply.setAdditionalData(additionalData.underlying)\n }\n }\n return reply\n }\n\n @Sendable\n public func deallocate(_ message: XPCMessage) async throws -> XPCMessage {\n let hostname = try message.hostname()\n try await allocator.deallocate(hostname: hostname)\n log?.info(\"released attachments\", metadata: [\"hostname\": \"\\(hostname)\"])\n return message.reply()\n }\n\n @Sendable\n public func lookup(_ message: XPCMessage) async throws -> XPCMessage {\n let state = await network.state\n guard case .running(_, let status) = state else {\n throw ContainerizationError(.invalidState, message: \"invalid network state - network \\(state.id) must be running\")\n }\n\n let hostname = try message.hostname()\n let index = try await allocator.lookup(hostname: hostname)\n let reply = message.reply()\n guard let index else {\n return reply\n }\n\n let address = IPv4Address(fromValue: index)\n let subnet = try CIDRAddress(status.address)\n let attachment = Attachment(\n network: state.id,\n hostname: hostname,\n address: try CIDRAddress(address, prefixLength: subnet.prefixLength).description,\n gateway: status.gateway\n )\n log?.debug(\n \"lookup attachment\",\n metadata: [\n \"hostname\": \"\\(hostname)\",\n \"address\": \"\\(address)\",\n ])\n try reply.setAttachment(attachment)\n return reply\n }\n\n @Sendable\n public func disableAllocator(_ message: XPCMessage) async throws -> XPCMessage {\n let success = await allocator.disableAllocator()\n log?.info(\"attempted allocator disable\", metadata: [\"success\": \"\\(success)\"])\n let reply = message.reply()\n reply.setAllocatorDisabled(success)\n return reply\n }\n}\n\nextension XPCMessage {\n fileprivate func setAdditionalData(_ additionalData: xpc_object_t) throws {\n xpc_dictionary_set_value(self.underlying, NetworkKeys.additionalData.rawValue, additionalData)\n }\n\n fileprivate func setAllocatorDisabled(_ allocatorDisabled: Bool) {\n self.set(key: NetworkKeys.allocatorDisabled.rawValue, value: allocatorDisabled)\n }\n\n fileprivate func setAttachment(_ attachment: Attachment) throws {\n let data = try JSONEncoder().encode(attachment)\n self.set(key: NetworkKeys.attachment.rawValue, value: data)\n }\n\n fileprivate func setState(_ state: NetworkState) throws {\n let data = try JSONEncoder().encode(state)\n self.set(key: NetworkKeys.state.rawValue, value: data)\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ProcessConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Configuration data for an executable Process.\npublic struct ProcessConfiguration: Sendable, Codable {\n /// The on disk path to the executable binary.\n public var executable: String\n /// Arguments passed to the Process.\n public var arguments: [String]\n /// Environment variables for the Process.\n public var environment: [String]\n /// The current working directory (cwd) for the Process.\n public var workingDirectory: String\n /// A boolean value indicating if a Terminal or PTY device should\n /// be attached to the Process's Standard I/O.\n public var terminal: Bool\n /// The User a Process should execute under.\n public var user: User\n /// Supplemental groups for the Process.\n public var supplementalGroups: [UInt32]\n /// Rlimits for the Process.\n public var rlimits: [Rlimit]\n\n /// Rlimits for Processes.\n public struct Rlimit: Sendable, Codable {\n /// The Rlimit type of the Process.\n ///\n /// Values include standard Rlimit resource types, i.e. RLIMIT_NPROC, RLIMIT_NOFILE, ...\n public let limit: String\n /// The soft limit of the Process\n public let soft: UInt64\n /// The hard or max limit of the Process.\n public let hard: UInt64\n\n public init(limit: String, soft: UInt64, hard: UInt64) {\n self.limit = limit\n self.soft = soft\n self.hard = hard\n }\n }\n\n /// The User information for a Process.\n public enum User: Sendable, Codable, CustomStringConvertible {\n /// Given the raw user string of the form or or lookup the uid/gid within\n /// the container before setting it for the Process.\n case raw(userString: String)\n /// Set the provided uid/gid for the Process.\n case id(uid: UInt32, gid: UInt32)\n\n public var description: String {\n switch self {\n case .id(let uid, let gid):\n return \"\\(uid):\\(gid)\"\n case .raw(let name):\n return name\n }\n }\n }\n\n public init(\n executable: String,\n arguments: [String],\n environment: [String],\n workingDirectory: String = \"/\",\n terminal: Bool = false,\n user: User = .id(uid: 0, gid: 0),\n supplementalGroups: [UInt32] = [],\n rlimits: [Rlimit] = []\n ) {\n self.executable = executable\n self.arguments = arguments\n self.environment = environment\n self.workingDirectory = workingDirectory\n self.terminal = terminal\n self.user = user\n self.supplementalGroups = supplementalGroups\n self.rlimits = rlimits\n }\n}\n"], ["/container/Sources/ContainerBuild/Globber.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic class Globber {\n let input: URL\n var results: Set = .init()\n\n public init(_ input: URL) {\n self.input = input\n }\n\n public func match(_ pattern: String) throws {\n let adjustedPattern =\n pattern\n .replacingOccurrences(of: #\"^\\./(?=.)\"#, with: \"\", options: .regularExpression)\n .replacingOccurrences(of: \"^\\\\.[/]?$\", with: \"*\", options: .regularExpression)\n .replacingOccurrences(of: \"\\\\*{2,}[/]\", with: \"*/**/\", options: .regularExpression)\n .replacingOccurrences(of: \"[/]\\\\*{2,}([^/])\", with: \"/**/*$1\", options: .regularExpression)\n .replacingOccurrences(of: \"^\\\\*{2,}([^/])\", with: \"**/*$1\", options: .regularExpression)\n\n for child in input.children {\n try self.match(input: child, components: adjustedPattern.split(separator: \"/\").map(String.init))\n }\n }\n\n private func match(input: URL, components: [String]) throws {\n if components.isEmpty {\n var dir = input.standardizedFileURL\n\n while dir != self.input.standardizedFileURL {\n results.insert(dir)\n guard dir.pathComponents.count > 1 else { break }\n dir.deleteLastPathComponent()\n }\n return input.childrenRecursive.forEach { results.insert($0) }\n }\n\n let head = components.first ?? \"\"\n let tail = components.tail\n\n if head == \"**\" {\n var tail: [String] = tail\n while tail.first == \"**\" {\n tail = tail.tail\n }\n try self.match(input: input, components: tail)\n for child in input.children {\n try self.match(input: child, components: components)\n }\n return\n }\n\n if try glob(input.lastPathComponent, head) {\n try self.match(input: input, components: tail)\n\n for child in input.children where try glob(child.lastPathComponent, tail.first ?? \"\") {\n try self.match(input: child, components: tail)\n }\n return\n }\n }\n\n func glob(_ input: String, _ pattern: String) throws -> Bool {\n let regexPattern =\n \"^\"\n + NSRegularExpression.escapedPattern(for: pattern)\n .replacingOccurrences(of: \"\\\\*\", with: \"[^/]*\")\n .replacingOccurrences(of: \"\\\\?\", with: \"[^/]\")\n .replacingOccurrences(of: \"[\\\\^\", with: \"[^\")\n .replacingOccurrences(of: \"\\\\[\", with: \"[\")\n .replacingOccurrences(of: \"\\\\]\", with: \"]\") + \"$\"\n\n // validate the regex pattern created\n let _ = try Regex(regexPattern)\n return input.range(of: regexPattern, options: .regularExpression) != nil\n }\n}\n\nextension URL {\n var children: [URL] {\n\n (try? FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil))\n ?? []\n }\n\n var childrenRecursive: [URL] {\n var results: [URL] = []\n if let enumerator = FileManager.default.enumerator(\n at: self, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey])\n {\n while let child = enumerator.nextObject() as? URL {\n results.append(child)\n }\n }\n return [self] + results\n }\n}\n\nextension [String] {\n var tail: [String] {\n if self.count <= 1 {\n return []\n }\n return Array(self.dropFirst())\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationExtras\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct NetworkList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List networks\",\n aliases: [\"ls\"])\n\n @Flag(name: .shortAndLong, help: \"Only output the network name\")\n var quiet = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let networks = try await ClientNetwork.list()\n try printNetworks(networks: networks, format: format)\n }\n\n private func createHeader() -> [[String]] {\n [[\"NETWORK\", \"STATE\", \"SUBNET\"]]\n }\n\n private func printNetworks(networks: [NetworkState], format: ListFormat) throws {\n if format == .json {\n let printables = networks.map {\n PrintableNetwork($0)\n }\n let data = try JSONEncoder().encode(printables)\n print(String(data: data, encoding: .utf8)!)\n\n return\n }\n\n if self.quiet {\n networks.forEach {\n print($0.id)\n }\n return\n }\n\n var rows = createHeader()\n for network in networks {\n rows.append(network.asRow)\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n }\n}\n\nextension NetworkState {\n var asRow: [String] {\n switch self {\n case .created(_):\n return [self.id, self.state, \"none\"]\n case .running(_, let status):\n return [self.id, self.state, status.address]\n }\n }\n}\n\nstruct PrintableNetwork: Codable {\n let id: String\n let state: String\n let config: NetworkConfiguration\n let status: NetworkStatus?\n\n init(_ network: NetworkState) {\n self.id = network.id\n self.state = network.state\n switch network {\n case .created(let config):\n self.config = config\n self.status = nil\n case .running(let config, let status):\n self.config = config\n self.status = status\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientProcess.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport NIOCore\nimport NIOPosix\nimport TerminalProgress\n\n/// A protocol that defines the methods and data members available to a process\n/// started inside of a container.\npublic protocol ClientProcess: Sendable {\n /// Identifier for the process.\n var id: String { get }\n\n /// Start the underlying process inside of the container.\n func start(_ stdio: [FileHandle?]) async throws\n /// Send a terminal resize request to the process `id`.\n func resize(_ size: Terminal.Size) async throws\n /// Send or \"kill\" a signal to the process `id`.\n /// Kill does not wait for the process to exit, it only delivers the signal.\n func kill(_ signal: Int32) async throws\n /// Wait for the process `id` to complete and return its exit code.\n /// This method blocks until the process exits and the code is obtained.\n func wait() async throws -> Int32\n}\n\nstruct ClientProcessImpl: ClientProcess, Sendable {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n /// Identifier of the container.\n public let containerId: String\n\n private let client: SandboxClient\n\n /// Identifier of a process. That is running inside of a container.\n /// This field is nil if the process this objects refers to is the\n /// init process of the container.\n public let processId: String?\n\n public var id: String {\n processId ?? containerId\n }\n\n init(containerId: String, processId: String? = nil, client: SandboxClient) {\n self.containerId = containerId\n self.processId = processId\n self.client = client\n }\n\n /// Start the container and return the initial process.\n public func start(_ stdio: [FileHandle?]) async throws {\n do {\n let client = self.client\n try await client.startProcess(self.id, stdio: stdio)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to start container\",\n cause: error\n )\n }\n }\n\n public func kill(_ signal: Int32) async throws {\n do {\n\n let client = self.client\n try await client.kill(self.id, signal: Int64(signal))\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill process\",\n cause: error\n )\n }\n }\n\n public func resize(_ size: ContainerizationOS.Terminal.Size) async throws {\n do {\n\n let client = self.client\n try await client.resize(self.id, size: size)\n\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to resize process\",\n cause: error\n )\n }\n }\n\n public func wait() async throws -> Int32 {\n do {\n let client = self.client\n return try await client.wait(self.id)\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to wait on process\",\n cause: error\n )\n }\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/HostTableResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\n\n/// Handler that uses table lookup to resolve hostnames.\npublic struct HostTableResolver: DNSHandler {\n public let hosts4: [String: IPv4]\n private let ttl: UInt32\n\n public init(hosts4: [String: IPv4], ttl: UInt32 = 300) {\n self.hosts4 = hosts4\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n let record: ResourceRecord?\n switch question.type {\n case ResourceRecordType.host:\n record = answerHost(question: question)\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n\n guard let record else {\n return nil\n }\n\n return Message(\n id: query.id,\n type: .response,\n returnCode: .noError,\n questions: query.questions,\n answers: [record]\n )\n }\n\n private func answerHost(question: Question) -> ResourceRecord? {\n guard let ip = hosts4[question.name] else {\n return nil\n }\n\n return HostRecord(name: question.name, ttl: ttl, ip: ip)\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A configuration for displaying a progress bar.\npublic struct ProgressConfig: Sendable {\n /// The file handle for progress updates.\n let terminal: FileHandle\n /// The initial description of the progress bar.\n let initialDescription: String\n /// The initial additional description of the progress bar.\n let initialSubDescription: String\n /// The initial items name (e.g., \"files\").\n let initialItemsName: String\n /// A flag indicating whether to show a spinner (e.g., \"⠋\").\n /// The spinner is hidden when a progress bar is shown.\n public let showSpinner: Bool\n /// A flag indicating whether to show tasks and total tasks (e.g., \"[1]\" or \"[1/3]\").\n public let showTasks: Bool\n /// A flag indicating whether to show the description (e.g., \"Downloading...\").\n public let showDescription: Bool\n /// A flag indicating whether to show a percentage (e.g., \"100%\").\n /// The percentage is hidden when no total size and total items are set.\n public let showPercent: Bool\n /// A flag indicating whether to show a progress bar (e.g., \"|███ |\").\n /// The progress bar is hidden when no total size and total items are set.\n public let showProgressBar: Bool\n /// A flag indicating whether to show items and total items (e.g., \"(22 it)\" or \"(22/22 it)\").\n public let showItems: Bool\n /// A flag indicating whether to show a size and a total size (e.g., \"(22 MB)\" or \"(22/22 MB)\").\n public let showSize: Bool\n /// A flag indicating whether to show a speed (e.g., \"(4.834 MB/s)\").\n /// The speed is combined with the size and total size (e.g., \"(22/22 MB, 4.834 MB/s)\").\n /// The speed is hidden when no total size is set.\n public let showSpeed: Bool\n /// A flag indicating whether to show the elapsed time (e.g., \"[4s]\").\n public let showTime: Bool\n /// The flag indicating whether to ignore small size values (less than 1 MB). For example, this may help to avoid reaching 100% after downloading metadata before downloading content.\n public let ignoreSmallSize: Bool\n /// The initial total tasks of the progress bar.\n let initialTotalTasks: Int?\n /// The initial total size of the progress bar.\n let initialTotalSize: Int64?\n /// The initial total items of the progress bar.\n let initialTotalItems: Int?\n /// The width of the progress bar in characters.\n public let width: Int\n /// The theme of the progress bar.\n public let theme: ProgressTheme\n /// The flag indicating whether to clear the progress bar before resetting the cursor.\n public let clearOnFinish: Bool\n /// The flag indicating whether to update the progress bar.\n public let disableProgressUpdates: Bool\n /// Creates a new instance of `ProgressConfig`.\n /// - Parameters:\n /// - terminal: The file handle for progress updates. The default value is `FileHandle.standardError`.\n /// - description: The initial description of the progress bar. The default value is `\"\"`.\n /// - subDescription: The initial additional description of the progress bar. The default value is `\"\"`.\n /// - itemsName: The initial items name. The default value is `\"it\"`.\n /// - showSpinner: A flag indicating whether to show a spinner. The default value is `true`.\n /// - showTasks: A flag indicating whether to show tasks and total tasks. The default value is `false`.\n /// - showDescription: A flag indicating whether to show the description. The default value is `true`.\n /// - showPercent: A flag indicating whether to show a percentage. The default value is `true`.\n /// - showProgressBar: A flag indicating whether to show a progress bar. The default value is `false`.\n /// - showItems: A flag indicating whether to show items and a total items. The default value is `false`.\n /// - showSize: A flag indicating whether to show a size and a total size. The default value is `true`.\n /// - showSpeed: A flag indicating whether to show a speed. The default value is `true`.\n /// - showTime: A flag indicating whether to show the elapsed time. The default value is `true`.\n /// - ignoreSmallSize: A flag indicating whether to ignore small size values. The default value is `false`.\n /// - totalTasks: The initial total tasks of the progress bar. The default value is `nil`.\n /// - totalItems: The initial total items of the progress bar. The default value is `nil`.\n /// - totalSize: The initial total size of the progress bar. The default value is `nil`.\n /// - width: The width of the progress bar in characters. The default value is `120`.\n /// - theme: The theme of the progress bar. The default value is `nil`.\n /// - clearOnFinish: The flag indicating whether to clear the progress bar before resetting the cursor. The default is `true`.\n /// - disableProgressUpdates: The flag indicating whether to update the progress bar. The default is `false`.\n public init(\n terminal: FileHandle = .standardError,\n description: String = \"\",\n subDescription: String = \"\",\n itemsName: String = \"it\",\n showSpinner: Bool = true,\n showTasks: Bool = false,\n showDescription: Bool = true,\n showPercent: Bool = true,\n showProgressBar: Bool = false,\n showItems: Bool = false,\n showSize: Bool = true,\n showSpeed: Bool = true,\n showTime: Bool = true,\n ignoreSmallSize: Bool = false,\n totalTasks: Int? = nil,\n totalItems: Int? = nil,\n totalSize: Int64? = nil,\n width: Int = 120,\n theme: ProgressTheme? = nil,\n clearOnFinish: Bool = true,\n disableProgressUpdates: Bool = false\n ) throws {\n if let totalTasks {\n guard totalTasks > 0 else {\n throw Error.invalid(\"totalTasks must be greater than zero\")\n }\n }\n if let totalItems {\n guard totalItems > 0 else {\n throw Error.invalid(\"totalItems must be greater than zero\")\n }\n }\n if let totalSize {\n guard totalSize > 0 else {\n throw Error.invalid(\"totalSize must be greater than zero\")\n }\n }\n\n self.terminal = terminal\n self.initialDescription = description\n self.initialSubDescription = subDescription\n self.initialItemsName = itemsName\n\n self.showSpinner = showSpinner\n self.showTasks = showTasks\n self.showDescription = showDescription\n self.showPercent = showPercent\n self.showProgressBar = showProgressBar\n self.showItems = showItems\n self.showSize = showSize\n self.showSpeed = showSpeed\n self.showTime = showTime\n\n self.ignoreSmallSize = ignoreSmallSize\n self.initialTotalTasks = totalTasks\n self.initialTotalItems = totalItems\n self.initialTotalSize = totalSize\n\n self.width = width\n self.theme = theme ?? DefaultProgressTheme()\n self.clearOnFinish = clearOnFinish\n self.disableProgressUpdates = disableProgressUpdates\n }\n}\n\nextension ProgressConfig {\n /// An enumeration of errors that can occur when creating a `ProgressConfig`.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalid(String)\n\n /// The description of the error.\n public var description: String {\n switch self {\n case .invalid(let reason):\n return \"Failed to validate config (\\(reason))\"\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/RequestScheme.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\n\n/// The URL scheme to be used for a HTTP request.\npublic enum RequestScheme: String, Sendable {\n case http = \"http\"\n case https = \"https\"\n\n case auto = \"auto\"\n\n public init(_ rawValue: String) throws {\n switch rawValue {\n case RequestScheme.http.rawValue:\n self = .http\n case RequestScheme.https.rawValue:\n self = .https\n case RequestScheme.auto.rawValue:\n self = .auto\n default:\n throw ContainerizationError(.invalidArgument, message: \"Unsupported scheme \\(rawValue)\")\n }\n }\n\n /// Returns the prescribed protocol to use while making a HTTP request to a webserver\n /// - Parameter host: The domain or IP address of the webserver\n /// - Returns: RequestScheme\n package func schemeFor(host: String) throws -> Self {\n guard host.count > 0 else {\n throw ContainerizationError(.invalidArgument, message: \"Host cannot be empty\")\n }\n switch self {\n case .http, .https:\n return self\n case .auto:\n return Self.isInternalHost(host: host) ? .http : .https\n }\n }\n\n /// Checks if the given `host` string is a private IP address\n /// or a domain typically reachable only on the local system.\n private static func isInternalHost(host: String) -> Bool {\n if host.hasPrefix(\"localhost\") || host.hasPrefix(\"127.\") {\n return true\n }\n if host.hasPrefix(\"192.168.\") || host.hasPrefix(\"10.\") {\n return true\n }\n let regex = \"(^172\\\\.1[6-9]\\\\.)|(^172\\\\.2[0-9]\\\\.)|(^172\\\\.3[0-1]\\\\.)\"\n if host.range(of: regex, options: .regularExpression) != nil {\n return true\n }\n let dnsDomain = ClientDefaults.get(key: .defaultDNSDomain)\n if host.hasSuffix(\".\\(dnsDomain)\") {\n return true\n }\n return false\n }\n}\n"], ["/container/Sources/ContainerLog/OSLogHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\nimport Logging\nimport os\n\nimport struct Logging.Logger\n\npublic struct OSLogHandler: LogHandler {\n private let logger: os.Logger\n\n public var logLevel: Logger.Level = .info\n private var formattedMetadata: String?\n\n public var metadata = Logger.Metadata() {\n didSet {\n self.formattedMetadata = self.formatMetadata(self.metadata)\n }\n }\n\n public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? {\n get {\n self.metadata[metadataKey]\n }\n set {\n self.metadata[metadataKey] = newValue\n }\n }\n\n public init(label: String, category: String) {\n self.logger = os.Logger(subsystem: label, category: category)\n }\n}\n\nextension OSLogHandler {\n public func log(\n level: Logger.Level,\n message: Logger.Message,\n metadata: Logger.Metadata?,\n source: String,\n file: String,\n function: String,\n line: UInt\n ) {\n var formattedMetadata = self.formattedMetadata\n if let metadataOverride = metadata, !metadataOverride.isEmpty {\n formattedMetadata = self.formatMetadata(\n self.metadata.merging(metadataOverride) {\n $1\n }\n )\n }\n\n var finalMessage = message.description\n if let formattedMetadata {\n finalMessage += \" \" + formattedMetadata\n }\n\n self.logger.log(\n level: level.toOSLogLevel(),\n \"\\(finalMessage, privacy: .public)\"\n )\n }\n\n private func formatMetadata(_ metadata: Logger.Metadata) -> String? {\n if metadata.isEmpty {\n return nil\n }\n return metadata.map {\n \"[\\($0)=\\($1)]\"\n }.joined(separator: \" \")\n }\n}\n\nextension Logger.Level {\n func toOSLogLevel() -> OSLogType {\n switch self {\n case .debug, .trace:\n return .debug\n case .info:\n return .info\n case .notice:\n return .default\n case .error, .warning:\n return .error\n case .critical:\n return .fault\n }\n }\n}\n"], ["/container/Sources/CLI/DefaultCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\n\nstruct DefaultCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: nil,\n shouldDisplay: false\n )\n\n @OptionGroup(visibility: .hidden)\n var global: Flags.Global\n\n @Argument(parsing: .captureForPassthrough)\n var remaining: [String] = []\n\n func run() async throws {\n // See if we have a possible plugin command.\n guard let command = remaining.first else {\n Application.printModifiedHelpText()\n return\n }\n\n // Check for edge cases and unknown options to match the behavior in the absence of plugins.\n if command.isEmpty {\n throw ValidationError(\"Unknown argument '\\(command)'\")\n } else if command.starts(with: \"-\") {\n throw ValidationError(\"Unknown option '\\(command)'\")\n }\n\n let pluginLoader = Application.pluginLoader\n guard let plugin = pluginLoader.findPlugin(name: command), plugin.config.isCLI else {\n throw ValidationError(\"failed to find plugin named container-\\(command)\")\n }\n // Exec performs execvp (with no fork).\n try plugin.exec(args: remaining)\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+Terminal.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nenum EscapeSequence {\n static let hideCursor = \"\\u{001B}[?25l\"\n static let showCursor = \"\\u{001B}[?25h\"\n static let moveUp = \"\\u{001B}[1A\"\n}\n\nextension ProgressBar {\n private var terminalWidth: Int {\n guard\n let terminalHandle = term,\n let terminal = try? Terminal(descriptor: terminalHandle.fileDescriptor)\n else {\n return 0\n }\n\n let terminalWidth = (try? Int(terminal.size.width)) ?? 0\n return terminalWidth\n }\n\n /// Clears the progress bar and resets the cursor.\n public func clearAndResetCursor() {\n clear()\n resetCursor()\n }\n\n /// Clears the progress bar.\n public func clear() {\n displayText(\"\")\n }\n\n /// Resets the cursor.\n public func resetCursor() {\n display(EscapeSequence.showCursor)\n }\n\n func display(_ text: String) {\n guard let term else {\n return\n }\n termQueue.sync {\n try? term.write(contentsOf: Data(text.utf8))\n try? term.synchronize()\n }\n }\n\n func displayText(_ text: String, terminating: String = \"\\r\") {\n var text = text\n\n // Clears previously printed characters if the new string is shorter.\n text += String(repeating: \" \", count: max(printedWidth - text.count, 0))\n printedWidth = text.count\n state.withLock {\n $0.output = text\n }\n\n // Clears previously printed lines.\n var lines = \"\"\n if terminating.hasSuffix(\"\\r\") && terminalWidth > 0 {\n let lineCount = (text.count - 1) / terminalWidth\n for _ in 0.. XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.load(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func get(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n let plugin = try await service.get(name: name)\n let data = try JSONEncoder().encode(plugin)\n\n let reply = message.reply()\n reply.set(key: .plugin, value: data)\n return reply\n }\n\n @Sendable\n func restart(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.restart(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func unload(_ message: XPCMessage) async throws -> XPCMessage {\n let name = message.string(key: .pluginName)\n guard let name else {\n throw ContainerizationError(.invalidArgument, message: \"no plugin name found\")\n }\n\n try await service.unload(name: name)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let plugins = try await service.list()\n\n let data = try JSONEncoder().encode(plugins)\n\n let reply = message.reply()\n reply.set(key: .plugins, value: data)\n return reply\n }\n}\n"], ["/container/Sources/APIServer/Kernel/KernelHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nstruct KernelHarness {\n private let log: Logging.Logger\n private let service: KernelService\n\n init(service: KernelService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n public func install(_ message: XPCMessage) async throws -> XPCMessage {\n let kernelFilePath = try message.kernelFilePath()\n let platform = try message.platform()\n\n guard let kernelTarUrl = try message.kernelTarURL() else {\n // We have been given a path to a kernel binary on disk\n guard let kernelFile = URL(string: kernelFilePath) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid kernel file path: \\(kernelFilePath)\")\n }\n try await self.service.installKernel(kernelFile: kernelFile, platform: platform)\n return message.reply()\n }\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await self.service.installKernelFrom(tar: kernelTarUrl, kernelFilePath: kernelFilePath, platform: platform, progressUpdate: progressUpdateService?.handler)\n return message.reply()\n }\n\n public func getDefaultKernel(_ message: XPCMessage) async throws -> XPCMessage {\n guard let platformData = message.dataNoCopy(key: .systemPlatform) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing SystemPlatform\")\n }\n let platform = try JSONDecoder().decode(SystemPlatform.self, from: platformData)\n let kernel = try await self.service.getDefaultKernel(platform: platform)\n let reply = message.reply()\n let data = try JSONEncoder().encode(kernel)\n reply.set(key: .kernel, value: data)\n return reply\n }\n}\n\nextension XPCMessage {\n fileprivate func platform() throws -> SystemPlatform {\n guard let platformData = self.dataNoCopy(key: .systemPlatform) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing SystemPlatform in XPC Message\")\n }\n let platform = try JSONDecoder().decode(SystemPlatform.self, from: platformData)\n return platform\n }\n\n fileprivate func kernelFilePath() throws -> String {\n guard let kernelFilePath = self.string(key: .kernelFilePath) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing kernel file path in XPC Message\")\n }\n return kernelFilePath\n }\n\n fileprivate func kernelTarURL() throws -> URL? {\n guard let kernelTarURLString = self.string(key: .kernelTarURL) else {\n return nil\n }\n guard let k = URL(string: kernelTarURLString) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse URL from \\(kernelTarURLString)\")\n }\n return k\n }\n}\n"], ["/container/Sources/ContainerBuild/Builder.grpc.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n// DO NOT EDIT.\n// swift-format-ignore-file\n//\n// Generated by the protocol buffer compiler.\n// Source: Builder.proto\n//\nimport GRPC\nimport NIO\nimport NIOConcurrencyHelpers\nimport SwiftProtobuf\n\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// Usage: instantiate `Com_Apple_Container_Build_V1_BuilderClient`, then call methods of this protocol to make API calls.\npublic protocol Com_Apple_Container_Build_V1_BuilderClientProtocol: GRPCClient {\n var serviceName: String { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? { get }\n\n func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func performBuild(\n callOptions: CallOptions?,\n handler: @escaping (Com_Apple_Container_Build_V1_ServerStream) -> Void\n ) -> BidirectionalStreamingCall\n\n func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n}\n\nextension Com_Apple_Container_Build_V1_BuilderClientProtocol {\n public var serviceName: String {\n return \"com.apple.container.build.v1.Builder\"\n }\n\n /// Create a build request.\n ///\n /// - Parameters:\n /// - request: Request to send to CreateBuild.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n ///\n /// Callers should use the `send` method on the returned object to send messages\n /// to the server. The caller should send an `.end` after the final message has been sent.\n ///\n /// - Parameters:\n /// - callOptions: Call options.\n /// - handler: A closure called when each response is received from the server.\n /// - Returns: A `ClientStreamingCall` with futures for the metadata and status.\n public func performBuild(\n callOptions: CallOptions? = nil,\n handler: @escaping (Com_Apple_Container_Build_V1_ServerStream) -> Void\n ) -> BidirectionalStreamingCall {\n return self.makeBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n handler: handler\n )\n }\n\n /// Unary call to Info\n ///\n /// - Parameters:\n /// - request: Request to send to Info.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(*, deprecated)\nextension Com_Apple_Container_Build_V1_BuilderClient: @unchecked Sendable {}\n\n@available(*, deprecated, renamed: \"Com_Apple_Container_Build_V1_BuilderNIOClient\")\npublic final class Com_Apple_Container_Build_V1_BuilderClient: Com_Apple_Container_Build_V1_BuilderClientProtocol {\n private let lock = Lock()\n private var _defaultCallOptions: CallOptions\n private var _interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n public let channel: GRPCChannel\n public var defaultCallOptions: CallOptions {\n get { self.lock.withLock { return self._defaultCallOptions } }\n set { self.lock.withLockVoid { self._defaultCallOptions = newValue } }\n }\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? {\n get { self.lock.withLock { return self._interceptors } }\n set { self.lock.withLockVoid { self._interceptors = newValue } }\n }\n\n /// Creates a client for the com.apple.container.build.v1.Builder service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self._defaultCallOptions = defaultCallOptions\n self._interceptors = interceptors\n }\n}\n\npublic struct Com_Apple_Container_Build_V1_BuilderNIOClient: Com_Apple_Container_Build_V1_BuilderClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n\n /// Creates a client for the com.apple.container.build.v1.Builder service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol: GRPCClient {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? { get }\n\n func makeCreateBuildCall(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makePerformBuildCall(\n callOptions: CallOptions?\n ) -> GRPCAsyncBidirectionalStreamingCall\n\n func makeInfoCall(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Container_Build_V1_BuilderClientMetadata.serviceDescriptor\n }\n\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? {\n return nil\n }\n\n public func makeCreateBuildCall(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n public func makePerformBuildCall(\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncBidirectionalStreamingCall {\n return self.makeAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func makeInfoCall(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public func createBuild(\n _ request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Container_Build_V1_CreateBuildResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? []\n )\n }\n\n public func performBuild(\n _ requests: RequestStream,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncResponseStream where RequestStream: Sequence, RequestStream.Element == Com_Apple_Container_Build_V1_ClientStream {\n return self.performAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n requests: requests,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func performBuild(\n _ requests: RequestStream,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncResponseStream where RequestStream: AsyncSequence & Sendable, RequestStream.Element == Com_Apple_Container_Build_V1_ClientStream {\n return self.performAsyncBidirectionalStreamingCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild.path,\n requests: requests,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? []\n )\n }\n\n public func info(\n _ request: Com_Apple_Container_Build_V1_InfoRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Container_Build_V1_InfoResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeInfoInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic struct Com_Apple_Container_Build_V1_BuilderAsyncClient: Com_Apple_Container_Build_V1_BuilderAsyncClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol?\n\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\npublic protocol Com_Apple_Container_Build_V1_BuilderClientInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when invoking 'createBuild'.\n func makeCreateBuildInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'performBuild'.\n func makePerformBuildInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'info'.\n func makeInfoInterceptors() -> [ClientInterceptor]\n}\n\npublic enum Com_Apple_Container_Build_V1_BuilderClientMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"Builder\",\n fullName: \"com.apple.container.build.v1.Builder\",\n methods: [\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.createBuild,\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.performBuild,\n Com_Apple_Container_Build_V1_BuilderClientMetadata.Methods.info,\n ]\n )\n\n public enum Methods {\n public static let createBuild = GRPCMethodDescriptor(\n name: \"CreateBuild\",\n path: \"/com.apple.container.build.v1.Builder/CreateBuild\",\n type: GRPCCallType.unary\n )\n\n public static let performBuild = GRPCMethodDescriptor(\n name: \"PerformBuild\",\n path: \"/com.apple.container.build.v1.Builder/PerformBuild\",\n type: GRPCCallType.bidirectionalStreaming\n )\n\n public static let info = GRPCMethodDescriptor(\n name: \"Info\",\n path: \"/com.apple.container.build.v1.Builder/Info\",\n type: GRPCCallType.unary\n )\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// To build a server, implement a class that conforms to this protocol.\npublic protocol Com_Apple_Container_Build_V1_BuilderProvider: CallHandlerProvider {\n var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? { get }\n\n /// Create a build request.\n func createBuild(request: Com_Apple_Container_Build_V1_CreateBuildRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n func performBuild(context: StreamingResponseCallContext) -> EventLoopFuture<(StreamEvent) -> Void>\n\n func info(request: Com_Apple_Container_Build_V1_InfoRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n}\n\nextension Com_Apple_Container_Build_V1_BuilderProvider {\n public var serviceName: Substring {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor.fullName[...]\n }\n\n /// Determines, calls and returns the appropriate request handler, depending on the request's method.\n /// Returns nil for methods not handled by this service.\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"CreateBuild\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? [],\n userFunction: self.createBuild(request:context:)\n )\n\n case \"PerformBuild\":\n return BidirectionalStreamingServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n observerFactory: self.performBuild(context:)\n )\n\n case \"Info\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeInfoInterceptors() ?? [],\n userFunction: self.info(request:context:)\n )\n\n default:\n return nil\n }\n }\n}\n\n/// Builder service implements APIs for performing an image build with\n/// Container image builder agent.\n///\n/// To perform a build:\n///\n/// 1. CreateBuild to create a new build\n/// 2. StartBuild to start the build execution where client and server\n/// both have a stream for exchanging data during the build.\n///\n/// The client may send:\n/// a) signal packet to signal to the build process (e.g. SIGINT)\n///\n/// b) command packet for executing a command in the build file on the\n/// server\n/// NOTE: the server will need to switch on the command to determine the\n/// type of command to execute (e.g. RUN, ENV, etc.)\n///\n/// c) transfer build data either to or from the server\n/// - INTO direction is for sending build data to the server at specific\n/// location (e.g. COPY)\n/// - OUTOF direction is for copying build data from the server to be\n/// used in subsequent build stages\n///\n/// d) transfer image content data either to or from the server\n/// - INTO direction is for sending inherited image content data to the\n/// server's local content store\n/// - OUTOF direction is for copying successfully built OCI image from\n/// the server to the client\n///\n/// The server may send:\n/// a) stdio packet for the build progress\n///\n/// b) build error indicating unsuccessful build\n///\n/// c) command complete packet indicating a command has finished executing\n///\n/// d) handle transfer build data either to or from the client\n///\n/// e) handle transfer image content data either to or from the client\n///\n///\n/// NOTE: The build data and image content data transfer is ALWAYS initiated\n/// by the client.\n///\n/// Sequence for transferring from the client to the server:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'INTO',\n/// destination path, and first chunk of data\n/// 2. server starts to receive the data and stream to a temporary file\n/// 3. client continues to send all chunks of data until last chunk, which\n/// client will\n/// send with 'complete' set to true\n/// 4. server continues to receive until the last chunk with 'complete' set\n/// to true,\n/// server will finish writing the last chunk and un-archive the\n/// temporary file to the destination path\n/// 5. server completes the transfer by sending a last\n/// BuildTransfer/ImageTransfer with\n/// 'complete' set to true\n/// 6. client waits for the last BuildTransfer/ImageTransfer with 'complete'\n/// set to true\n/// before proceeding with the rest of the commands\n///\n/// Sequence for transferring from the server to the client:\n/// 1. client send a BuildTransfer/ImageTransfer request with ID, direction\n/// of 'OUTOF',\n/// source path, and empty data\n/// 2. server archives the data at source path, and starts to send chunks to\n/// the client\n/// 3. server continues to send all chunks until last chunk, which server\n/// will send with\n/// 'complete' set to true\n/// 4. client starts to receive the data and stream to a temporary file\n/// 5. client continues to receive until the last chunk with 'complete' set\n/// to true,\n/// client will finish writing last chunk and un-archive the temporary\n/// file to the destination path\n/// 6. client MAY choose to send one last BuildTransfer/ImageTransfer with\n/// 'complete'\n/// set to true, but NOT required.\n///\n///\n/// NOTE: the client should close the send stream once it has finished\n/// receiving the build output or abandon the current build due to error.\n/// Server should keep the stream open until it receives the EOF that client\n/// has closed the stream, which the server should then close its send stream.\n///\n/// To implement a server, implement an object which conforms to this protocol.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Container_Build_V1_BuilderAsyncProvider: CallHandlerProvider, Sendable {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? { get }\n\n /// Create a build request.\n func createBuild(\n request: Com_Apple_Container_Build_V1_CreateBuildRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Container_Build_V1_CreateBuildResponse\n\n /// Perform the build.\n /// Executes the entire build sequence with attaching input/output\n /// to handling data exchange with the server during the build.\n func performBuild(\n requestStream: GRPCAsyncRequestStream,\n responseStream: GRPCAsyncResponseStreamWriter,\n context: GRPCAsyncServerCallContext\n ) async throws\n\n func info(\n request: Com_Apple_Container_Build_V1_InfoRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Container_Build_V1_InfoResponse\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Container_Build_V1_BuilderAsyncProvider {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor\n }\n\n public var serviceName: Substring {\n return Com_Apple_Container_Build_V1_BuilderServerMetadata.serviceDescriptor.fullName[...]\n }\n\n public var interceptors: Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol? {\n return nil\n }\n\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"CreateBuild\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateBuildInterceptors() ?? [],\n wrapping: { try await self.createBuild(request: $0, context: $1) }\n )\n\n case \"PerformBuild\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makePerformBuildInterceptors() ?? [],\n wrapping: { try await self.performBuild(requestStream: $0, responseStream: $1, context: $2) }\n )\n\n case \"Info\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeInfoInterceptors() ?? [],\n wrapping: { try await self.info(request: $0, context: $1) }\n )\n\n default:\n return nil\n }\n }\n}\n\npublic protocol Com_Apple_Container_Build_V1_BuilderServerInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when handling 'createBuild'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCreateBuildInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'performBuild'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makePerformBuildInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'info'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeInfoInterceptors() -> [ServerInterceptor]\n}\n\npublic enum Com_Apple_Container_Build_V1_BuilderServerMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"Builder\",\n fullName: \"com.apple.container.build.v1.Builder\",\n methods: [\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.createBuild,\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.performBuild,\n Com_Apple_Container_Build_V1_BuilderServerMetadata.Methods.info,\n ]\n )\n\n public enum Methods {\n public static let createBuild = GRPCMethodDescriptor(\n name: \"CreateBuild\",\n path: \"/com.apple.container.build.v1.Builder/CreateBuild\",\n type: GRPCCallType.unary\n )\n\n public static let performBuild = GRPCMethodDescriptor(\n name: \"PerformBuild\",\n path: \"/com.apple.container.build.v1.Builder/PerformBuild\",\n type: GRPCCallType.bidirectionalStreaming\n )\n\n public static let info = GRPCMethodDescriptor(\n name: \"Info\",\n path: \"/com.apple.container.build.v1.Builder/Info\",\n type: GRPCCallType.unary\n )\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/ReservedVmnetNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport Dispatch\nimport Foundation\nimport Logging\nimport SendableProperty\nimport SystemConfiguration\nimport XPC\nimport vmnet\n\n/// Creates a vmnet network with reservation APIs.\n@available(macOS 26, *)\npublic final class ReservedVmnetNetwork: Network {\n @SendablePropertyUnchecked\n private var _state: NetworkState\n private let log: Logger\n\n @SendableProperty\n private var network: vmnet_network_ref?\n @SendableProperty\n private var interface: interface_ref?\n private let networkLock = NSLock()\n\n /// Configure a bridge network that allows external system access using\n /// network address translation.\n public init(\n configuration: NetworkConfiguration,\n log: Logger\n ) throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.unsupported, message: \"invalid network mode \\(configuration.mode)\")\n }\n\n log.info(\"creating vmnet network\")\n self.log = log\n _state = .created(configuration)\n log.info(\"created vmnet network\")\n }\n\n public var state: NetworkState {\n get async { _state }\n }\n\n public nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws {\n try networkLock.withLock {\n try handler(network.map { try Self.serialize_network_ref(ref: $0) })\n }\n }\n\n public func start() async throws {\n guard case .created(let configuration) = _state else {\n throw ContainerizationError(.invalidArgument, message: \"cannot start network that is in \\(_state.state) state\")\n }\n\n try startNetwork(configuration: configuration, log: log)\n }\n\n private static func serialize_network_ref(ref: vmnet_network_ref) throws -> XPCMessage {\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let refObject = vmnet_network_copy_serialization(ref, &status) else {\n throw ContainerizationError(.invalidArgument, message: \"cannot serialize vmnet_network_ref to XPC object, status \\(status)\")\n }\n return XPCMessage(object: refObject)\n }\n\n private func startNetwork(configuration: NetworkConfiguration, log: Logger) throws {\n log.info(\n \"starting vmnet network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n ]\n )\n let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName)\n let subnetText = configuration.subnet ?? suite?.string(forKey: \"network.subnet\")\n\n // with the reservation API, subnet priority is CLI argument, UserDefault, auto\n let subnet = try subnetText.map { try CIDRAddress($0) }\n\n // set up the vmnet configuration\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let vmnetConfiguration = vmnet_network_configuration_create(vmnet.operating_modes_t.VMNET_SHARED_MODE, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet config with status \\(status)\")\n }\n\n vmnet_network_configuration_disable_dhcp(vmnetConfiguration)\n\n // set the subnet if the caller provided one\n if let subnet {\n let gateway = IPv4Address(fromValue: subnet.lower.value + 1)\n var gatewayAddr = in_addr()\n inet_pton(AF_INET, gateway.description, &gatewayAddr)\n let mask = IPv4Address(fromValue: subnet.prefixLength.prefixMask32)\n var maskAddr = in_addr()\n inet_pton(AF_INET, mask.description, &maskAddr)\n log.info(\n \"configuring vmnet subnet\",\n metadata: [\"cidr\": \"\\(subnet)\"]\n )\n let status = vmnet_network_configuration_set_ipv4_subnet(vmnetConfiguration, &gatewayAddr, &maskAddr)\n guard status == .VMNET_SUCCESS else {\n throw ContainerizationError(.internalError, message: \"failed to set subnet \\(subnet) for network \\(configuration.id)\")\n }\n }\n\n // reserve the network\n guard let network = vmnet_network_create(vmnetConfiguration, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet network with status \\(status)\")\n }\n self.network = network\n\n // retrieve the subnet since the caller may not have provided one\n var subnetAddr = in_addr()\n var maskAddr = in_addr()\n vmnet_network_get_ipv4_subnet(network, &subnetAddr, &maskAddr)\n let subnetValue = UInt32(bigEndian: subnetAddr.s_addr)\n let maskValue = UInt32(bigEndian: maskAddr.s_addr)\n let lower = IPv4Address(fromValue: subnetValue & maskValue)\n let upper = IPv4Address(fromValue: lower.value + ~maskValue)\n let runningSubnet = try CIDRAddress(lower: lower, upper: upper)\n let runningGateway = IPv4Address(fromValue: runningSubnet.lower.value + 1)\n self._state = .running(configuration, NetworkStatus(address: runningSubnet.description, gateway: runningGateway.description))\n log.info(\n \"started vmnet network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n \"cidr\": \"\\(runningSubnet)\",\n ]\n )\n }\n}\n"], ["/container/Sources/CLI/Registry/Login.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Login: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: \"Login to a registry\"\n )\n\n @Option(name: .shortAndLong, help: \"Username\")\n var username: String = \"\"\n\n @Flag(help: \"Take the password from stdin\")\n var passwordStdin: Bool = false\n\n @Argument(help: \"Registry server name\")\n var server: String\n\n @OptionGroup\n var registry: Flags.Registry\n\n func run() async throws {\n var username = self.username\n var password = \"\"\n if passwordStdin {\n if username == \"\" {\n throw ContainerizationError(\n .invalidArgument, message: \"must provide --username with --password-stdin\")\n }\n guard let passwordData = try FileHandle.standardInput.readToEnd() else {\n throw ContainerizationError(.invalidArgument, message: \"failed to read password from stdin\")\n }\n password = String(decoding: passwordData, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)\n }\n let keychain = KeychainHelper(id: Constants.keychainID)\n if username == \"\" {\n username = try keychain.userPrompt(domain: server)\n }\n if password == \"\" {\n password = try keychain.passwordPrompt()\n print()\n }\n\n let server = Reference.resolveDomain(domain: server)\n let scheme = try RequestScheme(registry.scheme).schemeFor(host: server)\n let _url = \"\\(scheme)://\\(server)\"\n guard let url = URL(string: _url) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n guard let host = url.host else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid host \\(server)\")\n }\n\n let client = RegistryClient(\n host: host,\n scheme: scheme.rawValue,\n port: url.port,\n authentication: BasicAuthentication(username: username, password: password),\n retryOptions: .init(\n maxRetries: 10,\n retryInterval: 300_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n )\n try await client.ping()\n try keychain.save(domain: server, username: username, password: password)\n print(\"Login succeeded\")\n }\n }\n}\n"], ["/container/Sources/APIServer/Networks/NetworksHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nstruct NetworksHarness: Sendable {\n let log: Logging.Logger\n let service: NetworksService\n\n init(service: NetworksService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let containers = try await service.list()\n let data = try JSONEncoder().encode(containers)\n\n let reply = message.reply()\n reply.set(key: .networkStates, value: data)\n return reply\n }\n\n @Sendable\n func create(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .networkConfig)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"network configuration cannot be empty\")\n }\n\n let config = try JSONDecoder().decode(NetworkConfiguration.self, from: data)\n let networkState = try await service.create(configuration: config)\n\n let networkData = try JSONEncoder().encode(networkState)\n\n let reply = message.reply()\n reply.set(key: .networkState, value: networkData)\n return reply\n }\n\n @Sendable\n func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .networkId)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"id cannot be empty\")\n }\n try await service.delete(id: id)\n\n return message.reply()\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildImageResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport GRPC\nimport Logging\n\nstruct BuildImageResolver: BuildPipelineHandler {\n let contentStore: ContentStore\n\n public init(_ contentStore: ContentStore) throws {\n self.contentStore = contentStore\n }\n\n func accept(_ packet: ServerStream) throws -> Bool {\n guard let imageTransfer = packet.getImageTransfer() else {\n return false\n }\n guard imageTransfer.stage() == \"resolver\" else {\n return false\n }\n guard imageTransfer.method() == \"/resolve\" else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard let imageTransfer = packet.getImageTransfer() else {\n throw Error.imageTransferMissing\n }\n guard let ref = imageTransfer.ref() else {\n throw Error.tagMissing\n }\n\n guard let platform = try imageTransfer.platform() else {\n throw Error.platformMissing\n }\n\n let img = try await {\n guard let img = try? await ClientImage.pull(reference: ref, platform: platform) else {\n return try await ClientImage.fetch(reference: ref, platform: platform)\n }\n return img\n }()\n\n let index: Index = try await img.index()\n let buildID = packet.buildID\n let platforms = index.manifests.compactMap { $0.platform }\n for pl in platforms {\n if pl == platform {\n let manifest = try await img.manifest(for: pl)\n guard let ociImage: ContainerizationOCI.Image = try await self.contentStore.get(digest: manifest.config.digest) else {\n continue\n }\n let enc = JSONEncoder()\n let data = try enc.encode(ociImage)\n let transfer = try ImageTransfer(\n id: imageTransfer.id,\n digest: img.descriptor.digest,\n ref: ref,\n platform: platform.description,\n data: data\n )\n var response = ClientStream()\n response.buildID = buildID\n response.imageTransfer = transfer\n response.packetType = .imageTransfer(transfer)\n sender.yield(response)\n return\n }\n }\n throw Error.unknownPlatformForImage(platform.description, ref)\n }\n}\n\nextension ImageTransfer {\n fileprivate init(id: String, digest: String, ref: String, platform: String, data: Data) throws {\n self.init()\n self.id = id\n self.tag = digest\n self.metadata = [\n \"os\": \"linux\",\n \"stage\": \"resolver\",\n \"method\": \"/resolve\",\n \"ref\": ref,\n \"platform\": platform,\n ]\n self.complete = true\n self.direction = .into\n self.data = data\n }\n}\n\nextension BuildImageResolver {\n enum Error: Swift.Error, CustomStringConvertible {\n case imageTransferMissing\n case tagMissing\n case platformMissing\n case imageNameMissing\n case imageTagMissing\n case imageNotFound\n case indexDigestMissing(String)\n case unknownRegistry(String)\n case digestIsNotIndex(String)\n case digestIsNotManifest(String)\n case unknownPlatformForImage(String, String)\n\n var description: String {\n switch self {\n case .imageTransferMissing:\n return \"imageTransfer is missing\"\n case .tagMissing:\n return \"tag parameter missing in metadata\"\n case .platformMissing:\n return \"platform parameter missing in metadata\"\n case .imageNameMissing:\n return \"image name missing in $ref parameter\"\n case .imageTagMissing:\n return \"image tag missing in $ref parameter\"\n case .imageNotFound:\n return \"image not found\"\n case .indexDigestMissing(let ref):\n return \"index digest is missing for image: \\(ref)\"\n case .unknownRegistry(let registry):\n return \"registry \\(registry) is unknown\"\n case .digestIsNotIndex(let digest):\n return \"digest \\(digest) is not a descriptor to an index\"\n case .digestIsNotManifest(let digest):\n return \"digest \\(digest) is not a descriptor to a manifest\"\n case .unknownPlatformForImage(let platform, let ref):\n return \"platform \\(platform) for image \\(ref) not found\"\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationExtras\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ContainerList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List containers\",\n aliases: [\"ls\"])\n\n @Flag(name: .shortAndLong, help: \"Show stopped containers as well\")\n var all = false\n\n @Flag(name: .shortAndLong, help: \"Only output the container ID\")\n var quiet = false\n\n @Option(name: .long, help: \"Format of the output\")\n var format: ListFormat = .table\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let containers = try await ClientContainer.list()\n try printContainers(containers: containers, format: format)\n }\n\n private func createHeader() -> [[String]] {\n [[\"ID\", \"IMAGE\", \"OS\", \"ARCH\", \"STATE\", \"ADDR\"]]\n }\n\n private func printContainers(containers: [ClientContainer], format: ListFormat) throws {\n if format == .json {\n let printables = containers.map {\n PrintableContainer($0)\n }\n let data = try JSONEncoder().encode(printables)\n print(String(data: data, encoding: .utf8)!)\n\n return\n }\n\n if self.quiet {\n containers.forEach {\n if !self.all && $0.status != .running {\n return\n }\n print($0.id)\n }\n return\n }\n\n var rows = createHeader()\n for container in containers {\n if !self.all && container.status != .running {\n continue\n }\n rows.append(container.asRow)\n }\n\n let formatter = TableOutput(rows: rows)\n print(formatter.format())\n }\n }\n}\n\nextension ClientContainer {\n var asRow: [String] {\n [\n self.id,\n self.configuration.image.reference,\n self.configuration.platform.os,\n self.configuration.platform.architecture,\n self.status.rawValue,\n self.networks.compactMap { try? CIDRAddress($0.address).address.description }.joined(separator: \",\"),\n ]\n }\n}\n\nstruct PrintableContainer: Codable {\n let status: RuntimeStatus\n let configuration: ContainerConfiguration\n let networks: [Attachment]\n\n init(_ container: ClientContainer) {\n self.status = container.status\n self.configuration = container.configuration\n self.networks = container.networks\n }\n}\n"], ["/container/Sources/ContainerClient/XPC+.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\n/// Keys for XPC fields.\npublic enum XPCKeys: String {\n /// Route key.\n case route\n /// Container array key.\n case containers\n /// ID key.\n case id\n // ID for a process.\n case processIdentifier\n /// Container configuration key.\n case containerConfig\n /// Container options key.\n case containerOptions\n /// Vsock port number key.\n case port\n /// Exit code for a process\n case exitCode\n /// An event that occurred in a container\n case containerEvent\n /// Error key.\n case error\n /// FD to a container resource key.\n case fd\n /// FDs pointing to container logs key.\n case logs\n /// Options for stopping a container key.\n case stopOptions\n /// Plugins\n case pluginName\n case plugins\n case plugin\n\n /// Health check request.\n case ping\n\n /// Process request keys.\n case signal\n case snapshot\n case stdin\n case stdout\n case stderr\n case status\n case width\n case height\n case processConfig\n\n /// Update progress\n case progressUpdateEndpoint\n case progressUpdateSetDescription\n case progressUpdateSetSubDescription\n case progressUpdateSetItemsName\n case progressUpdateAddTasks\n case progressUpdateSetTasks\n case progressUpdateAddTotalTasks\n case progressUpdateSetTotalTasks\n case progressUpdateAddItems\n case progressUpdateSetItems\n case progressUpdateAddTotalItems\n case progressUpdateSetTotalItems\n case progressUpdateAddSize\n case progressUpdateSetSize\n case progressUpdateAddTotalSize\n case progressUpdateSetTotalSize\n\n /// Network\n case networkId\n case networkConfig\n case networkState\n case networkStates\n\n /// Kernel\n case kernel\n case kernelTarURL\n case kernelFilePath\n case systemPlatform\n}\n\npublic enum XPCRoute: String {\n case listContainer\n case createContainer\n case deleteContainer\n case containerLogs\n case containerEvent\n\n case pluginLoad\n case pluginGet\n case pluginRestart\n case pluginUnload\n case pluginList\n\n case networkCreate\n case networkDelete\n case networkList\n\n case ping\n\n case installKernel\n case getDefaultKernel\n}\n\nextension XPCMessage {\n public init(route: XPCRoute) {\n self.init(route: route.rawValue)\n }\n\n public func data(key: XPCKeys) -> Data? {\n data(key: key.rawValue)\n }\n\n public func dataNoCopy(key: XPCKeys) -> Data? {\n dataNoCopy(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Data) {\n set(key: key.rawValue, value: value)\n }\n\n public func string(key: XPCKeys) -> String? {\n string(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: String) {\n set(key: key.rawValue, value: value)\n }\n\n public func bool(key: XPCKeys) -> Bool {\n bool(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Bool) {\n set(key: key.rawValue, value: value)\n }\n\n public func uint64(key: XPCKeys) -> UInt64 {\n uint64(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: UInt64) {\n set(key: key.rawValue, value: value)\n }\n\n public func int64(key: XPCKeys) -> Int64 {\n int64(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: Int64) {\n set(key: key.rawValue, value: value)\n }\n\n public func int(key: XPCKeys) -> Int {\n Int(int64(key: key.rawValue))\n }\n\n public func set(key: XPCKeys, value: Int) {\n set(key: key.rawValue, value: Int64(value))\n }\n\n public func fileHandle(key: XPCKeys) -> FileHandle? {\n fileHandle(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: FileHandle) {\n set(key: key.rawValue, value: value)\n }\n\n public func fileHandles(key: XPCKeys) -> [FileHandle]? {\n fileHandles(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: [FileHandle]) throws {\n try set(key: key.rawValue, value: value)\n }\n\n public func endpoint(key: XPCKeys) -> xpc_endpoint_t? {\n endpoint(key: key.rawValue)\n }\n\n public func set(key: XPCKeys, value: xpc_endpoint_t) {\n set(key: key.rawValue, value: value)\n }\n}\n\n#endif\n"], ["/container/Sources/SocketForwarder/UDPForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\nimport Synchronization\n\n// Proxy backend for a single client address (clientIP, clientPort).\nprivate final class UDPProxyBackend: ChannelInboundHandler, Sendable {\n typealias InboundIn = AddressedEnvelope\n typealias OutboundOut = AddressedEnvelope\n\n private struct State {\n var queuedPayloads: Deque\n var channel: (any Channel)?\n }\n\n private let clientAddress: SocketAddress\n private let serverAddress: SocketAddress\n private let frontendChannel: any Channel\n private let log: Logger?\n private let state: Mutex\n\n init(clientAddress: SocketAddress, serverAddress: SocketAddress, frontendChannel: any Channel, log: Logger? = nil) {\n self.clientAddress = clientAddress\n self.serverAddress = serverAddress\n self.frontendChannel = frontendChannel\n self.log = log\n let state = State(queuedPayloads: Deque(), channel: nil)\n self.state = Mutex(state)\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n // relay data from server to client.\n let inbound = self.unwrapInboundIn(data)\n let outbound = OutboundOut(remoteAddress: self.clientAddress, data: inbound.data)\n self.log?.trace(\"backend - writing datagram to client\")\n _ = self.frontendChannel.writeAndFlush(outbound)\n }\n\n func channelActive(context: ChannelHandlerContext) {\n state.withLock {\n if !$0.queuedPayloads.isEmpty {\n self.log?.trace(\"backend - writing \\($0.queuedPayloads.count) queued datagrams to server\")\n while let queuedData = $0.queuedPayloads.popFirst() {\n let outbound: UDPProxyBackend.OutboundOut = OutboundOut(remoteAddress: self.serverAddress, data: queuedData)\n _ = context.channel.writeAndFlush(outbound)\n }\n }\n $0.channel = context.channel\n }\n }\n\n func write(data: ByteBuffer) {\n // change package remote address from proxy server to real server\n state.withLock {\n if let channel = $0.channel {\n // channel has been initialized, so relay any queued packets, along with this one to outbound\n self.log?.trace(\"backend - writing datagram to server\")\n let outbound: UDPProxyBackend.OutboundOut = OutboundOut(remoteAddress: self.serverAddress, data: data)\n _ = channel.writeAndFlush(outbound)\n } else {\n // channel is initializing, queue\n self.log?.trace(\"backend - queuing datagram\")\n $0.queuedPayloads.append(data)\n }\n }\n }\n\n func close() {\n state.withLock {\n guard let channel = $0.channel else {\n self.log?.warning(\"backend - close on inactive channel\")\n return\n }\n _ = channel.close()\n }\n }\n}\n\nprivate struct ProxyContext {\n public let proxy: UDPProxyBackend\n public let closeFuture: EventLoopFuture\n}\n\nprivate final class UDPProxyFrontend: ChannelInboundHandler, Sendable {\n typealias InboundIn = AddressedEnvelope\n typealias OutboundOut = AddressedEnvelope\n private let maxProxies = UInt(256)\n\n private let proxyAddress: SocketAddress\n private let serverAddress: SocketAddress\n private let eventLoopGroup: any EventLoopGroup\n private let log: Logger?\n\n private let proxies: Mutex>\n\n init(proxyAddress: SocketAddress, serverAddress: SocketAddress, eventLoopGroup: any EventLoopGroup, log: Logger? = nil) {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.proxies = Mutex(LRUCache(size: maxProxies))\n self.log = log\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n let inbound = self.unwrapInboundIn(data)\n\n guard let clientIP = inbound.remoteAddress.ipAddress else {\n log?.error(\"frontend - no client IP address in inbound payload\")\n return\n }\n\n guard let clientPort = inbound.remoteAddress.port else {\n log?.error(\"frontend - no client port in inbound payload\")\n return\n }\n\n let key = \"\\(clientIP):\\(clientPort)\"\n do {\n try proxies.withLock {\n if let context = $0.get(key) {\n context.proxy.write(data: inbound.data)\n } else {\n self.log?.trace(\"frontend - creating backend\")\n let proxy = UDPProxyBackend(\n clientAddress: inbound.remoteAddress,\n serverAddress: self.serverAddress,\n frontendChannel: context.channel,\n log: log\n )\n let proxyAddress = try SocketAddress(ipAddress: \"0.0.0.0\", port: 0)\n let proxyToServerFuture = DatagramBootstrap(group: self.eventLoopGroup)\n .channelInitializer {\n self.log?.trace(\"frontend - initializing backend\")\n return $0.pipeline.addHandler(proxy)\n }\n .bind(to: proxyAddress)\n .flatMap { $0.closeFuture }\n let context = ProxyContext(proxy: proxy, closeFuture: proxyToServerFuture)\n if let (_, evictedContext) = $0.put(key: key, value: context) {\n self.log?.trace(\"frontend - closing evicted backend\")\n evictedContext.proxy.close()\n }\n\n proxy.write(data: inbound.data)\n }\n }\n } catch {\n log?.error(\"server handler - backend channel creation failed with error: \\(error)\")\n return\n }\n }\n}\n\npublic struct UDPForwarder: SocketForwarder {\n private let proxyAddress: SocketAddress\n\n private let serverAddress: SocketAddress\n\n private let eventLoopGroup: any EventLoopGroup\n\n private let log: Logger?\n\n public init(\n proxyAddress: SocketAddress,\n serverAddress: SocketAddress,\n eventLoopGroup: any EventLoopGroup,\n log: Logger? = nil\n ) throws {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.log = log\n }\n\n public func run() throws -> EventLoopFuture {\n self.log?.trace(\"frontend - creating channel\")\n let proxyToServerHandler = UDPProxyFrontend(\n proxyAddress: proxyAddress,\n serverAddress: serverAddress,\n eventLoopGroup: self.eventLoopGroup,\n log: log\n )\n let bootstrap = DatagramBootstrap(group: self.eventLoopGroup)\n .channelInitializer { serverChannel in\n self.log?.trace(\"frontend - initializing channel\")\n return serverChannel.pipeline.addHandler(proxyToServerHandler)\n }\n return\n bootstrap\n .bind(to: proxyAddress)\n .flatMap { $0.eventLoop.makeSucceededFuture(SocketForwarderResult(channel: $0)) }\n }\n}\n"], ["/container/Sources/ContainerClient/TableOutput.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct TableOutput {\n private let rows: [[String]]\n private let spacing: Int\n\n public init(\n rows: [[String]],\n spacing: Int = 2\n ) {\n self.rows = rows\n self.spacing = spacing\n }\n\n public func format() -> String {\n var output = \"\"\n let maxLengths = self.maxLength()\n\n for rowIndex in 0.. [Int: Int] {\n var output: [Int: Int] = [:]\n for row in self.rows {\n for (i, column) in row.enumerated() {\n let currentMax = output[i] ?? 0\n output[i] = (column.count > currentMax) ? column.count : currentMax\n }\n }\n return output\n }\n}\n"], ["/container/Sources/ContainerClient/Flags.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationError\nimport Foundation\n\npublic struct Flags {\n public struct Global: ParsableArguments {\n public init() {}\n\n @Flag(name: .long, help: \"Enable debug output [environment: CONTAINER_DEBUG]\")\n public var debug = false\n }\n\n public struct Process: ParsableArguments {\n public init() {}\n\n @Option(\n name: [.customLong(\"cwd\"), .customShort(\"w\"), .customLong(\"workdir\")],\n help: \"Current working directory for the container\")\n public var cwd: String?\n\n @Option(name: [.customLong(\"env\"), .customShort(\"e\")], help: \"Set environment variables\")\n public var env: [String] = []\n\n @Option(name: .customLong(\"env-file\"), help: \"Read in a file of environment variables\")\n public var envFile: [String] = []\n\n @Option(name: .customLong(\"uid\"), help: \"Set the uid for the process\")\n public var uid: UInt32?\n\n @Option(name: .customLong(\"gid\"), help: \"Set the gid for the process\")\n public var gid: UInt32?\n\n @Flag(name: [.customLong(\"interactive\"), .customShort(\"i\")], help: \"Keep Stdin open even if not attached\")\n public var interactive = false\n\n @Flag(name: [.customLong(\"tty\"), .customShort(\"t\")], help: \"Open a tty with the process\")\n public var tty = false\n\n @Option(name: [.customLong(\"user\"), .customShort(\"u\")], help: \"Set the user for the process\")\n public var user: String?\n }\n\n public struct Resource: ParsableArguments {\n public init() {}\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n public var cpus: Int64?\n\n @Option(\n name: [.customLong(\"memory\"), .customShort(\"m\")],\n help:\n \"Amount of memory in bytes, kilobytes (K), megabytes (M), or gigabytes (G) for the container, with MB granularity (for example, 1024K will result in 1MB being allocated for the container)\"\n )\n public var memory: String?\n }\n\n public struct Registry: ParsableArguments {\n public init() {}\n\n public init(scheme: String) {\n self.scheme = scheme\n }\n\n @Option(help: \"Scheme to use when connecting to the container registry. One of (http, https, auto)\")\n public var scheme: String = \"auto\"\n }\n\n public struct Management: ParsableArguments {\n public init() {}\n\n @Flag(name: [.customLong(\"detach\"), .short], help: \"Run the container and detach from the process\")\n public var detach = false\n\n @Option(name: .customLong(\"entrypoint\"), help: \"Override the entrypoint of the image\")\n public var entryPoint: String?\n\n @Option(name: .customLong(\"mount\"), help: \"Add a mount to the container (type=<>,source=<>,target=<>,readonly)\")\n public var mounts: [String] = []\n\n @Option(name: [.customLong(\"publish\"), .short], help: \"Publish a port from container to host (format: [host-ip:]host-port:container-port[/protocol])\")\n public var publishPorts: [String] = []\n\n @Option(name: .customLong(\"publish-socket\"), help: \"Publish a socket from container to host (format: host_path:container_path)\")\n public var publishSockets: [String] = []\n\n @Option(name: .customLong(\"tmpfs\"), help: \"Add a tmpfs mount to the container at the given path\")\n public var tmpFs: [String] = []\n\n @Option(name: .customLong(\"name\"), help: \"Assign a name to the container. If excluded will be a generated UUID\")\n public var name: String?\n\n @Flag(name: [.customLong(\"remove\"), .customLong(\"rm\")], help: \"Remove the container after it stops\")\n public var remove = false\n\n @Option(name: .customLong(\"os\"), help: \"Set OS if image can target multiple operating systems\")\n public var os = \"linux\"\n\n @Option(\n name: [.customLong(\"arch\"), .short], help: \"Set arch if image can target multiple architectures\")\n public var arch: String = Arch.hostArchitecture().rawValue\n\n @Option(name: [.customLong(\"volume\"), .short], help: \"Bind mount a volume into the container\")\n public var volumes: [String] = []\n\n @Option(\n name: [.customLong(\"kernel\"), .short], help: \"Set a custom kernel path\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n public var kernel: String?\n\n @Option(name: [.customLong(\"network\")], help: \"Attach the container to a network\")\n public var networks: [String] = []\n\n @Option(name: .customLong(\"cidfile\"), help: \"Write the container ID to the path provided\")\n public var cidfile = \"\"\n\n @Flag(name: [.customLong(\"no-dns\")], help: \"Do not configure DNS in the container\")\n public var dnsDisabled = false\n\n @Option(name: .customLong(\"dns\"), help: \"DNS nameserver IP address\")\n public var dnsNameservers: [String] = []\n\n @Option(name: .customLong(\"dns-domain\"), help: \"Default DNS domain\")\n public var dnsDomain: String? = nil\n\n @Option(name: .customLong(\"dns-search\"), help: \"DNS search domains\")\n public var dnsSearchDomains: [String] = []\n\n @Option(name: .customLong(\"dns-option\"), help: \"DNS options\")\n public var dnsOptions: [String] = []\n\n @Option(name: [.customLong(\"label\"), .short], help: \"Add a key=value label to the container\")\n public var labels: [String] = []\n }\n\n public struct Progress: ParsableArguments {\n public init() {}\n\n public init(disableProgressUpdates: Bool) {\n self.disableProgressUpdates = disableProgressUpdates\n }\n\n @Flag(name: .customLong(\"disable-progress-updates\"), help: \"Disable progress bar updates\")\n public var disableProgressUpdates = false\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct NetworkDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete one or more networks\",\n aliases: [\"rm\"])\n\n @Flag(name: .shortAndLong, help: \"Remove all networks\")\n var all = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Network names\")\n var networkNames: [String] = []\n\n func validate() throws {\n if networkNames.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no networks specified and --all not supplied\")\n }\n if networkNames.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument,\n message: \"explicitly supplied network name(s) conflict with the --all flag\"\n )\n }\n }\n\n mutating func run() async throws {\n let uniqueNetworkNames = Set(networkNames)\n let networks: [NetworkState]\n\n if all {\n networks = try await ClientNetwork.list()\n } else {\n networks = try await ClientNetwork.list()\n .filter { c in\n uniqueNetworkNames.contains(c.id)\n }\n\n // If one of the networks requested isn't present lets throw. We don't need to do\n // this for --all as --all should be perfectly usable with no networks to remove,\n // otherwise it'd be quite clunky.\n if networks.count != uniqueNetworkNames.count {\n let missing = uniqueNetworkNames.filter { id in\n !networks.contains { n in\n n.id == id\n }\n }\n throw ContainerizationError(\n .notFound,\n message: \"failed to delete one or more networks: \\(missing)\"\n )\n }\n }\n\n if uniqueNetworkNames.contains(ClientNetwork.defaultNetworkName) {\n throw ContainerizationError(\n .invalidArgument,\n message: \"cannot delete the default network\"\n )\n }\n\n var failed = [String]()\n try await withThrowingTaskGroup(of: NetworkState?.self) { group in\n for network in networks {\n group.addTask {\n do {\n // delete atomically disables the IP allocator, then deletes\n // the allocator disable fails if any IPs are still in use\n try await ClientNetwork.delete(id: network.id)\n print(network.id)\n return nil\n } catch {\n log.error(\"failed to delete network \\(network.id): \\(error)\")\n return network\n }\n }\n }\n\n for try await network in group {\n guard let network else {\n continue\n }\n failed.append(network.id)\n }\n }\n\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"delete failed for one or more networks: \\(failed)\")\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderStatus: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"status\"\n config._superCommandName = \"builder\"\n config.abstract = \"Print builder status\"\n config.usage = \"\\n\\t builder status [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Flag(name: .long, help: ArgumentHelp(\"Display detailed status in json format\"))\n var json: Bool = false\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n if json {\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.prettyPrinted, .sortedKeys]\n let jsonData = try encoder.encode(container)\n\n guard let jsonString = String(data: jsonData, encoding: .utf8) else {\n throw ContainerizationError(.internalError, message: \"failed to encode BuildKit container as json\")\n }\n print(jsonString)\n return\n }\n\n let image = container.configuration.image.reference\n let resources = container.configuration.resources\n let cpus = resources.cpus\n let memory = resources.memoryInBytes / (1024 * 1024) // bytes to MB\n let addr = \"\"\n\n print(\"ID IMAGE STATE ADDR CPUS MEMORY\")\n print(\"\\(container.id) \\(image) \\(container.status.rawValue.uppercased()) \\(addr) \\(cpus) \\(memory) MB\")\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n print(\"builder is not running\")\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildPipelineHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport GRPC\nimport NIO\n\nprotocol BuildPipelineHandler: Sendable {\n func accept(_ packet: ServerStream) throws -> Bool\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws\n}\n\npublic actor BuildPipeline {\n let handlers: [BuildPipelineHandler]\n public init(_ config: Builder.BuildConfig) async throws {\n self.handlers =\n [\n try BuildFSSync(URL(filePath: config.contextDir)),\n try BuildRemoteContentProxy(config.contentStore),\n try BuildImageResolver(config.contentStore),\n try BuildStdio(quiet: config.quiet, output: config.terminal?.handle ?? FileHandle.standardError),\n ]\n }\n\n public func run(\n sender: AsyncStream.Continuation,\n receiver: GRPCAsyncResponseStream\n ) async throws {\n defer { sender.finish() }\n try await untilFirstError { group in\n for try await packet in receiver {\n try Task.checkCancellation()\n for handler in self.handlers {\n try Task.checkCancellation()\n guard try handler.accept(packet) else {\n continue\n }\n try Task.checkCancellation()\n try await handler.handle(sender, packet)\n break\n }\n }\n }\n }\n\n /// untilFirstError() throws when any one of its submitted tasks fail.\n /// This is useful for asynchronous packet processing scenarios which\n /// have the following 3 requirements:\n /// - the packet should be processed without blocking I/O\n /// - the packet stream is never-ending\n /// - when the first task fails, the error needs to be propagated to the caller\n ///\n /// Usage:\n ///\n /// ```\n /// try await untilFirstError { group in\n /// for try await packet in receiver {\n /// group.addTask {\n /// try await handler.handle(sender, packet)\n /// }\n /// }\n /// }\n /// ```\n ///\n ///\n /// WithThrowingTaskGroup cannot accomplish this because it\n /// doesn't provide a mechanism to exit when one of the tasks fail\n /// before all the tasks have been added. i.e. it is more suitable for\n /// tasks that are limited. Here's a sample code where withThrowingTaskGroup\n /// doesn't solve the problem:\n ///\n /// ```\n /// withThrowingTaskGroup { group in\n /// for try await packet in receiver {\n /// group.addTask {\n /// /* process packet */\n /// }\n /// } /* this loop blocks forever waiting for more packets */\n /// try await group.next() /* this never gets called */\n /// }\n /// ```\n /// The above closure never returns even when a handler encounters an error\n /// because the blocking operation `try await group.next()` cannot be\n /// called while iterating over the receiver stream.\n private func untilFirstError(body: @Sendable @escaping (UntilFirstError) async throws -> Void) async throws {\n let group = try await UntilFirstError()\n var taskContinuation: AsyncStream>.Continuation?\n let tasks = AsyncStream> { continuation in\n taskContinuation = continuation\n }\n guard let taskContinuation else {\n throw NSError(\n domain: \"untilFirstError\",\n code: 1,\n userInfo: [NSLocalizedDescriptionKey: \"Failed to initialize task continuation\"])\n }\n defer { taskContinuation.finish() }\n let stream = AsyncStream { continuation in\n let processTasks = Task {\n let taskStream = await group.tasks()\n defer {\n continuation.finish()\n }\n for await item in taskStream {\n try Task.checkCancellation()\n let addedTask = Task {\n try Task.checkCancellation()\n do {\n try await item()\n } catch {\n continuation.yield(error)\n await group.continuation?.finish()\n throw error\n }\n }\n taskContinuation.yield(addedTask)\n }\n }\n taskContinuation.yield(processTasks)\n\n let mainTask = Task { @Sendable in\n defer {\n continuation.finish()\n processTasks.cancel()\n taskContinuation.finish()\n }\n do {\n try Task.checkCancellation()\n try await body(group)\n } catch {\n continuation.yield(error)\n await group.continuation?.finish()\n throw error\n }\n }\n taskContinuation.yield(mainTask)\n }\n\n // when the first handler fails, cancel all tasks and throw error\n for await item in stream {\n try Task.checkCancellation()\n Task {\n for await task in tasks {\n task.cancel()\n }\n }\n throw item\n }\n // if none of the handlers fail, wait for all subtasks to complete\n for await task in tasks {\n try Task.checkCancellation()\n try await task.value\n }\n }\n\n private actor UntilFirstError {\n var stream: AsyncStream<@Sendable () async throws -> Void>?\n var continuation: AsyncStream<@Sendable () async throws -> Void>.Continuation?\n\n init() async throws {\n self.stream = AsyncStream { cont in\n self.continuation = cont\n }\n guard let _ = continuation else {\n throw NSError()\n }\n }\n\n func addTask(body: @Sendable @escaping () async throws -> Void) {\n if !Task.isCancelled {\n self.continuation?.yield(body)\n }\n }\n\n func tasks() -> AsyncStream<@Sendable () async throws -> Void> {\n self.stream!\n }\n }\n}\n"], ["/container/Sources/APIServer/Containers/ContainersHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nstruct ContainersHarness {\n let log: Logging.Logger\n let service: ContainersService\n\n init(service: ContainersService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n func list(_ message: XPCMessage) async throws -> XPCMessage {\n let containers = try await service.list()\n let data = try JSONEncoder().encode(containers)\n\n let reply = message.reply()\n reply.set(key: .containers, value: data)\n return reply\n }\n\n @Sendable\n func create(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .containerConfig)\n guard let data else {\n throw ContainerizationError(.invalidArgument, message: \"container configuration cannot be empty\")\n }\n let kdata = message.dataNoCopy(key: .kernel)\n guard let kdata else {\n throw ContainerizationError(.invalidArgument, message: \"kernel cannot be empty\")\n }\n let odata = message.dataNoCopy(key: .containerOptions)\n var options: ContainerCreateOptions = .default\n if let odata {\n options = try JSONDecoder().decode(ContainerCreateOptions.self, from: odata)\n }\n let config = try JSONDecoder().decode(ContainerConfiguration.self, from: data)\n let kernel = try JSONDecoder().decode(Kernel.self, from: kdata)\n\n try await service.create(configuration: config, kernel: kernel, options: options)\n return message.reply()\n }\n\n @Sendable\n func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .id)\n guard let id else {\n throw ContainerizationError(.invalidArgument, message: \"id cannot be empty\")\n }\n try await service.delete(id: id)\n return message.reply()\n }\n\n @Sendable\n func logs(_ message: XPCMessage) async throws -> XPCMessage {\n let id = message.string(key: .id)\n guard let id else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"id cannot be empty\"\n )\n }\n let fds = try await service.logs(id: id)\n let reply = message.reply()\n try reply.set(key: .logs, value: fds)\n return reply\n }\n\n @Sendable\n func eventHandler(_ message: XPCMessage) async throws -> XPCMessage {\n let event = try message.containerEvent()\n try await service.handleContainerEvents(event: event)\n return message.reply()\n }\n}\n\nextension XPCMessage {\n public func containerEvent() throws -> ContainerEvent {\n guard let data = self.dataNoCopy(key: .containerEvent) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing container event data\")\n }\n let event = try JSONDecoder().decode(ContainerEvent.self, from: data)\n return event\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerLogs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Darwin\nimport Dispatch\nimport Foundation\n\nextension Application {\n struct ContainerLogs: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"logs\",\n abstract: \"Fetch container stdio or boot logs\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Flag(name: .shortAndLong, help: \"Follow log output\")\n var follow: Bool = false\n\n @Flag(name: .long, help: \"Display the boot log for the container instead of stdio\")\n var boot: Bool = false\n\n @Option(name: [.customShort(\"n\")], help: \"Number of lines to show from the end of the logs. If not provided this will print all of the logs\")\n var numLines: Int?\n\n @Argument(help: \"Container to fetch logs for\")\n var container: String\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: container)\n let fhs = try await container.logs()\n let fileHandle = boot ? fhs[1] : fhs[0]\n\n try await Self.tail(\n fh: fileHandle,\n n: numLines,\n follow: follow\n )\n } catch {\n throw ContainerizationError(\n .invalidArgument,\n message: \"failed to fetch container logs for \\(container): \\(error)\"\n )\n }\n }\n\n private static func tail(\n fh: FileHandle,\n n: Int?,\n follow: Bool\n ) async throws {\n if let n {\n var buffer = Data()\n let size = try fh.seekToEnd()\n var offset = size\n var lines: [String] = []\n\n while offset > 0, lines.count < n {\n let readSize = min(1024, offset)\n offset -= readSize\n try fh.seek(toOffset: offset)\n\n let data = fh.readData(ofLength: Int(readSize))\n buffer.insert(contentsOf: data, at: 0)\n\n if let chunk = String(data: buffer, encoding: .utf8) {\n lines = chunk.components(separatedBy: .newlines)\n lines = lines.filter { !$0.isEmpty }\n }\n }\n\n lines = Array(lines.suffix(n))\n for line in lines {\n print(line)\n }\n } else {\n // Fast path if all they want is the full file.\n guard let data = try fh.readToEnd() else {\n // Seems you get nil if it's a zero byte read, or you\n // try and read from dev/null.\n return\n }\n guard let str = String(data: data, encoding: .utf8) else {\n throw ContainerizationError(\n .internalError,\n message: \"failed to convert container logs to utf8\"\n )\n }\n print(str.trimmingCharacters(in: .newlines))\n }\n\n fflush(stdout)\n if follow {\n setbuf(stdout, nil)\n try await Self.followFile(fh: fh)\n }\n }\n\n private static func followFile(fh: FileHandle) async throws {\n _ = try fh.seekToEnd()\n let stream = AsyncStream { cont in\n fh.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n // Triggers on container restart - can exit here as well\n do {\n _ = try fh.seekToEnd() // To continue streaming existing truncated log files\n } catch {\n fh.readabilityHandler = nil\n cont.finish()\n return\n }\n }\n if let str = String(data: data, encoding: .utf8), !str.isEmpty {\n var lines = str.components(separatedBy: .newlines)\n lines = lines.filter { !$0.isEmpty }\n for line in lines {\n cont.yield(line)\n }\n }\n }\n }\n\n for await line in stream {\n print(line)\n }\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+State.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension ProgressBar {\n /// A configuration struct for the progress bar.\n public struct State {\n /// A flag indicating whether the progress bar is finished.\n public var finished = false\n var iteration = 0\n private let speedInterval: DispatchTimeInterval = .seconds(1)\n\n var description: String\n var subDescription: String\n var itemsName: String\n\n var tasks: Int\n var totalTasks: Int?\n\n var items: Int\n var totalItems: Int?\n\n private var sizeUpdateTime: DispatchTime?\n private var sizeUpdateValue: Int64 = 0\n var size: Int64 {\n didSet {\n calculateSizeSpeed()\n }\n }\n var totalSize: Int64?\n private var sizeUpdateSpeed: String?\n var sizeSpeed: String? {\n guard sizeUpdateTime == nil || sizeUpdateTime! > .now() - speedInterval - speedInterval else {\n return Int64(0).formattedSizeSpeed(from: startTime)\n }\n return sizeUpdateSpeed\n }\n var averageSizeSpeed: String {\n size.formattedSizeSpeed(from: startTime)\n }\n\n var percent: String {\n var value = 0\n if let totalSize, totalSize > 0 {\n value = Int(size * 100 / totalSize)\n } else if let totalItems, totalItems > 0 {\n value = Int(items * 100 / totalItems)\n }\n value = min(value, 100)\n return \"\\(value)%\"\n }\n\n var startTime: DispatchTime\n var output = \"\"\n\n init(\n description: String = \"\", subDescription: String = \"\", itemsName: String = \"\", tasks: Int = 0, totalTasks: Int? = nil, items: Int = 0, totalItems: Int? = nil,\n size: Int64 = 0, totalSize: Int64? = nil, startTime: DispatchTime = .now()\n ) {\n self.description = description\n self.subDescription = subDescription\n self.itemsName = itemsName\n self.tasks = tasks\n self.totalTasks = totalTasks\n self.items = items\n self.totalItems = totalItems\n self.size = size\n self.totalSize = totalSize\n self.startTime = startTime\n }\n\n private mutating func calculateSizeSpeed() {\n if sizeUpdateTime == nil || sizeUpdateTime! < .now() - speedInterval {\n let partSize = size - sizeUpdateValue\n let partStartTime = sizeUpdateTime ?? startTime\n let partSizeSpeed = partSize.formattedSizeSpeed(from: partStartTime)\n self.sizeUpdateSpeed = partSizeSpeed\n\n sizeUpdateTime = .now()\n sizeUpdateValue = size\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct ContainerDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete one or more containers\",\n aliases: [\"rm\"])\n\n @Flag(name: .shortAndLong, help: \"Force the removal of one or more running containers\")\n var force = false\n\n @Flag(name: .shortAndLong, help: \"Remove all containers\")\n var all = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Container IDs/names\")\n var containerIDs: [String] = []\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument,\n message: \"explicitly supplied container ID(s) conflict with the --all flag\"\n )\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n var containers = [ClientContainer]()\n\n if all {\n containers = try await ClientContainer.list()\n } else {\n let ctrs = try await ClientContainer.list()\n containers = ctrs.filter { c in\n set.contains(c.id)\n }\n // If one of the containers requested isn't present, let's throw. We don't need to do\n // this for --all as --all should be perfectly usable with no containers to remove; otherwise,\n // it'd be quite clunky.\n if containers.count != set.count {\n let missing = set.filter { id in\n !containers.contains { c in\n c.id == id\n }\n }\n throw ContainerizationError(\n .notFound,\n message: \"failed to delete one or more containers: \\(missing)\"\n )\n }\n }\n\n var failed = [String]()\n let force = self.force\n let all = self.all\n try await withThrowingTaskGroup(of: ClientContainer?.self) { group in\n for container in containers {\n group.addTask {\n do {\n // First we need to find if the container supports auto-remove\n // and if so we need to skip deletion.\n if container.status == .running {\n if !force {\n // We don't want to error if the user just wants all containers deleted.\n // It's implied we'll skip containers we can't actually delete.\n if all {\n return nil\n }\n throw ContainerizationError(.invalidState, message: \"container is running\")\n }\n let stopOpts = ContainerStopOptions(\n timeoutInSeconds: 5,\n signal: SIGKILL\n )\n try await container.stop(opts: stopOpts)\n }\n try await container.delete()\n print(container.id)\n return nil\n } catch {\n log.error(\"failed to delete container \\(container.id): \\(error)\")\n return container\n }\n }\n }\n\n for try await ctr in group {\n guard let ctr else {\n continue\n }\n failed.append(ctr.id)\n }\n }\n\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"delete failed for one or more containers: \\(failed)\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildAPI+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationOCI\n\npublic typealias IO = Com_Apple_Container_Build_V1_IO\npublic typealias InfoRequest = Com_Apple_Container_Build_V1_InfoRequest\npublic typealias InfoResponse = Com_Apple_Container_Build_V1_InfoResponse\npublic typealias ClientStream = Com_Apple_Container_Build_V1_ClientStream\npublic typealias ServerStream = Com_Apple_Container_Build_V1_ServerStream\npublic typealias ImageTransfer = Com_Apple_Container_Build_V1_ImageTransfer\npublic typealias BuildTransfer = Com_Apple_Container_Build_V1_BuildTransfer\npublic typealias BuilderClient = Com_Apple_Container_Build_V1_BuilderNIOClient\npublic typealias BuilderClientAsync = Com_Apple_Container_Build_V1_BuilderAsyncClient\npublic typealias BuilderClientProtocol = Com_Apple_Container_Build_V1_BuilderClientProtocol\npublic typealias BuilderClientAsyncProtocol = Com_Apple_Container_Build_V1_BuilderAsyncClient\n\nextension BuildTransfer {\n func stage() -> String? {\n let stage = self.metadata[\"stage\"]\n return stage == \"\" ? nil : stage\n }\n\n func method() -> String? {\n let method = self.metadata[\"method\"]\n return method == \"\" ? nil : method\n }\n\n func includePatterns() -> [String]? {\n guard let includePatternsString = self.metadata[\"include-patterns\"] else {\n return nil\n }\n return includePatternsString == \"\" ? nil : includePatternsString.components(separatedBy: \",\")\n }\n\n func followPaths() -> [String]? {\n guard let followPathString = self.metadata[\"followpaths\"] else {\n return nil\n }\n return followPathString == \"\" ? nil : followPathString.components(separatedBy: \",\")\n }\n\n func mode() -> String? {\n self.metadata[\"mode\"]\n }\n\n func size() -> Int? {\n guard let sizeStr = self.metadata[\"size\"] else {\n return nil\n }\n return sizeStr == \"\" ? nil : Int(sizeStr)\n }\n\n func offset() -> UInt64? {\n guard let offsetStr = self.metadata[\"offset\"] else {\n return nil\n }\n return offsetStr == \"\" ? nil : UInt64(offsetStr)\n }\n\n func len() -> Int? {\n guard let lenStr = self.metadata[\"length\"] else {\n return nil\n }\n return lenStr == \"\" ? nil : Int(lenStr)\n }\n}\n\nextension ImageTransfer {\n func stage() -> String? {\n self.metadata[\"stage\"]\n }\n\n func method() -> String? {\n self.metadata[\"method\"]\n }\n\n func ref() -> String? {\n self.metadata[\"ref\"]\n }\n\n func platform() throws -> Platform? {\n let metadata = self.metadata\n guard let platform = metadata[\"platform\"] else {\n return nil\n }\n return try Platform(from: platform)\n }\n\n func mode() -> String? {\n self.metadata[\"mode\"]\n }\n\n func size() -> Int? {\n let metadata = self.metadata\n guard let sizeStr = metadata[\"size\"] else {\n return nil\n }\n return Int(sizeStr)\n }\n\n func len() -> Int? {\n let metadata = self.metadata\n guard let lenStr = metadata[\"length\"] else {\n return nil\n }\n return Int(lenStr)\n }\n\n func offset() -> UInt64? {\n let metadata = self.metadata\n guard let offsetStr = metadata[\"offset\"] else {\n return nil\n }\n return UInt64(offsetStr)\n }\n}\n\nextension ServerStream {\n func getImageTransfer() -> ImageTransfer? {\n if case .imageTransfer(let v) = self.packetType {\n return v\n }\n return nil\n }\n\n func getBuildTransfer() -> BuildTransfer? {\n if case .buildTransfer(let v) = self.packetType {\n return v\n }\n return nil\n }\n\n func getIO() -> IO? {\n if case .io(let v) = self.packetType {\n return v\n }\n return nil\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressTaskCoordinator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that represents a task whose progress is being monitored.\npublic struct ProgressTask: Sendable, Equatable {\n private var id = UUID()\n private var coordinator: ProgressTaskCoordinator\n\n init(manager: ProgressTaskCoordinator) {\n self.coordinator = manager\n }\n\n static public func == (lhs: ProgressTask, rhs: ProgressTask) -> Bool {\n lhs.id == rhs.id\n }\n\n /// Returns `true` if this task is the currently active task, `false` otherwise.\n public func isCurrent() async -> Bool {\n guard let currentTask = await coordinator.currentTask else {\n return false\n }\n return currentTask == self\n }\n}\n\n/// A type that coordinates progress tasks to ignore updates from completed tasks.\npublic actor ProgressTaskCoordinator {\n var currentTask: ProgressTask?\n\n /// Creates an instance of `ProgressTaskCoordinator`.\n public init() {}\n\n /// Returns a new task that should be monitored for progress updates.\n public func startTask() -> ProgressTask {\n let newTask = ProgressTask(manager: self)\n currentTask = newTask\n return newTask\n }\n\n /// Performs cleanup when the monitored tasks complete.\n public func finish() {\n currentTask = nil\n }\n\n /// Returns a handler that updates the progress of a given task.\n /// - Parameters:\n /// - task: The task whose progress is being updated.\n /// - progressUpdate: The handler to invoke when progress updates are received.\n public static func handler(for task: ProgressTask, from progressUpdate: @escaping ProgressUpdateHandler) -> ProgressUpdateHandler {\n { events in\n // Ignore updates from completed tasks.\n if await task.isCurrent() {\n await progressUpdate(events)\n }\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/AllocationOnlyVmnetNetwork.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\npublic actor AllocationOnlyVmnetNetwork: Network {\n private let log: Logger\n private var _state: NetworkState\n\n /// Configure a bridge network that allows external system access using\n /// network address translation.\n public init(\n configuration: NetworkConfiguration,\n log: Logger\n ) throws {\n guard configuration.mode == .nat else {\n throw ContainerizationError(.unsupported, message: \"invalid network mode \\(configuration.mode)\")\n }\n\n guard configuration.subnet == nil else {\n throw ContainerizationError(.unsupported, message: \"subnet assignment is not yet implemented\")\n }\n\n self.log = log\n self._state = .created(configuration)\n }\n\n public var state: NetworkState {\n self._state\n }\n\n public nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws {\n try handler(nil)\n }\n\n public func start() async throws {\n guard case .created(let configuration) = _state else {\n throw ContainerizationError(.invalidState, message: \"cannot start network \\(_state.id) in \\(_state.state) state\")\n }\n var defaultSubnet = \"192.168.64.1/24\"\n\n log.info(\n \"starting allocation-only network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(NetworkMode.nat.rawValue)\",\n ]\n )\n\n if let suite = UserDefaults.init(suiteName: UserDefaults.appSuiteName) {\n // TODO: Make the suiteName a constant defined in ClientDefaults and use that.\n // This will need some re-working of dependencies between NetworkService and Client\n defaultSubnet = suite.string(forKey: \"network.subnet\") ?? defaultSubnet\n }\n\n let subnet = try CIDRAddress(defaultSubnet)\n let gateway = IPv4Address(fromValue: subnet.lower.value + 1)\n self._state = .running(configuration, NetworkStatus(address: subnet.description, gateway: gateway.description))\n log.info(\n \"started allocation-only network\",\n metadata: [\n \"id\": \"\\(configuration.id)\",\n \"mode\": \"\\(configuration.mode)\",\n \"cidr\": \"\\(defaultSubnet)\",\n ]\n )\n }\n}\n"], ["/container/Sources/CLI/System/SystemLogs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport OSLog\n\nextension Application {\n struct SystemLogs: AsyncParsableCommand {\n static let subsystem = \"com.apple.container\"\n\n static let configuration = CommandConfiguration(\n commandName: \"logs\",\n abstract: \"Fetch system logs for `container` services\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(\n name: .long,\n help: \"Fetch logs starting from the specified time period (minus the current time); supported formats: m, h, d\"\n )\n var last: String = \"5m\"\n\n @Flag(name: .shortAndLong, help: \"Follow log output\")\n var follow: Bool = false\n\n func run() async throws {\n let process = Process()\n let sigHandler = AsyncSignalHandler.create(notify: [SIGINT, SIGTERM])\n\n Task {\n for await _ in sigHandler.signals {\n process.terminate()\n Darwin.exit(0)\n }\n }\n\n do {\n var args = [\"log\"]\n args.append(self.follow ? \"stream\" : \"show\")\n args.append(contentsOf: [\"--info\", \"--debug\"])\n if !self.follow {\n args.append(contentsOf: [\"--last\", last])\n }\n args.append(contentsOf: [\"--predicate\", \"subsystem = 'com.apple.container'\"])\n\n process.launchPath = \"/usr/bin/env\"\n process.arguments = args\n\n process.standardOutput = FileHandle.standardOutput\n process.standardError = FileHandle.standardError\n\n try process.run()\n process.waitUntilExit()\n } catch {\n throw ContainerizationError(\n .invalidArgument,\n message: \"failed to system logs: \\(error)\"\n )\n }\n throw ArgumentParser.ExitCode(process.terminationStatus)\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Server/ImagesServiceHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerImagesServiceClient\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\npublic struct ImagesServiceHarness: Sendable {\n let log: Logging.Logger\n let service: ImagesService\n\n public init(service: ImagesService, log: Logging.Logger) {\n self.log = log\n self.service = service\n }\n\n @Sendable\n public func pull(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let insecure = message.bool(key: .insecureFlag)\n\n let progressUpdateService = ProgressUpdateService(message: message)\n let imageDescription = try await service.pull(reference: ref, platform: platform, insecure: insecure, progressUpdate: progressUpdateService?.handler)\n\n let imageData = try JSONEncoder().encode(imageDescription)\n let reply = message.reply()\n reply.set(key: .imageDescription, value: imageData)\n return reply\n }\n\n @Sendable\n public func push(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let insecure = message.bool(key: .insecureFlag)\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await service.push(reference: ref, platform: platform, insecure: insecure, progressUpdate: progressUpdateService?.handler)\n\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func tag(_ message: XPCMessage) async throws -> XPCMessage {\n let old = message.string(key: .imageReference)\n guard let old else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let new = message.string(key: .imageNewReference)\n guard let new else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing new image reference\"\n )\n }\n let newDescription = try await service.tag(old: old, new: new)\n let descData = try JSONEncoder().encode(newDescription)\n let reply = message.reply()\n reply.set(key: .imageDescription, value: descData)\n return reply\n }\n\n @Sendable\n public func list(_ message: XPCMessage) async throws -> XPCMessage {\n let images = try await service.list()\n let imageData = try JSONEncoder().encode(images)\n let reply = message.reply()\n reply.set(key: .imageDescriptions, value: imageData)\n return reply\n }\n\n @Sendable\n public func delete(_ message: XPCMessage) async throws -> XPCMessage {\n let ref = message.string(key: .imageReference)\n guard let ref else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image reference\"\n )\n }\n let garbageCollect = message.bool(key: .garbageCollect)\n try await self.service.delete(reference: ref, garbageCollect: garbageCollect)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func save(_ message: XPCMessage) async throws -> XPCMessage {\n let data = message.dataNoCopy(key: .imageDescription)\n guard let data else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let imageDescription = try JSONDecoder().decode(ImageDescription.self, from: data)\n\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform? = nil\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n let out = message.string(key: .filePath)\n guard let out else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing output file path\"\n )\n }\n try await service.save(reference: imageDescription.reference, out: URL(filePath: out), platform: platform)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func load(_ message: XPCMessage) async throws -> XPCMessage {\n let input = message.string(key: .filePath)\n guard let input else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing input file path\"\n )\n }\n let images = try await service.load(from: URL(filePath: input))\n let data = try JSONEncoder().encode(images)\n let reply = message.reply()\n reply.set(key: .imageDescriptions, value: data)\n return reply\n }\n\n @Sendable\n public func prune(_ message: XPCMessage) async throws -> XPCMessage {\n let (deleted, size) = try await service.prune()\n let reply = message.reply()\n let data = try JSONEncoder().encode(deleted)\n reply.set(key: .digests, value: data)\n reply.set(key: .size, value: size)\n return reply\n }\n}\n\n// MARK: Image Snapshot Methods\n\nextension ImagesServiceHarness {\n @Sendable\n public func unpack(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing Image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n var platform: Platform?\n if let platformData = message.dataNoCopy(key: .ociPlatform) {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n\n let progressUpdateService = ProgressUpdateService(message: message)\n try await self.service.unpack(description: description, platform: platform, progressUpdate: progressUpdateService?.handler)\n\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func deleteSnapshot(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n let platformData = message.dataNoCopy(key: .ociPlatform)\n var platform: Platform?\n if let platformData {\n platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n }\n try await self.service.deleteImageSnapshot(description: description, platform: platform)\n let reply = message.reply()\n return reply\n }\n\n @Sendable\n public func getSnapshot(_ message: XPCMessage) async throws -> XPCMessage {\n let descriptionData = message.dataNoCopy(key: .imageDescription)\n guard let descriptionData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing image description\"\n )\n }\n let description = try JSONDecoder().decode(ImageDescription.self, from: descriptionData)\n let platformData = message.dataNoCopy(key: .ociPlatform)\n guard let platformData else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"missing OCI platform\"\n )\n }\n let platform = try JSONDecoder().decode(ContainerizationOCI.Platform.self, from: platformData)\n let fs = try await self.service.getImageSnapshot(description: description, platform: platform)\n let fsData = try JSONEncoder().encode(fs)\n let reply = message.reply()\n reply.set(key: .filesystem, value: fsData)\n return reply\n }\n}\n"], ["/container/Sources/APIServer/Kernel/FileDownloader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\ninternal struct FileDownloader {\n public static func downloadFile(url: URL, to destination: URL, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let request = try HTTPClient.Request(url: url)\n\n let delegate = try FileDownloadDelegate(\n path: destination.path(),\n reportHead: {\n let expectedSizeString = $0.headers[\"Content-Length\"].first ?? \"\"\n if let expectedSize = Int64(expectedSizeString) {\n if let progressUpdate {\n Task {\n await progressUpdate([\n .addTotalSize(expectedSize)\n ])\n }\n }\n }\n },\n reportProgress: {\n let receivedBytes = Int64($0.receivedBytes)\n if let progressUpdate {\n Task {\n await progressUpdate([\n .setSize(receivedBytes)\n ])\n }\n }\n })\n\n let client = FileDownloader.createClient()\n _ = try await client.execute(request: request, delegate: delegate).get()\n try await client.shutdown()\n }\n\n private static func createClient() -> HTTPClient {\n var httpConfiguration = HTTPClient.Configuration()\n let proxyConfig: HTTPClient.Configuration.Proxy? = {\n let proxyEnv = ProcessInfo.processInfo.environment[\"HTTP_PROXY\"]\n guard let proxyEnv else {\n return nil\n }\n guard let url = URL(string: proxyEnv), let host = url.host(), let port = url.port else {\n return nil\n }\n return .server(host: host, port: port)\n }()\n httpConfiguration.proxy = proxyConfig\n return HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration)\n }\n}\n"], ["/container/Sources/CLI/System/SystemStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerPlugin\nimport ContainerizationError\nimport Foundation\nimport Logging\n\nextension Application {\n struct SystemStatus: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"status\",\n abstract: \"Show the status of `container` services\"\n )\n\n @Option(name: .shortAndLong, help: \"Launchd prefix for `container` services\")\n var prefix: String = \"com.apple.container.\"\n\n func run() async throws {\n let isRegistered = try ServiceManager.isRegistered(fullServiceLabel: \"\\(prefix)apiserver\")\n if !isRegistered {\n print(\"apiserver is not running and not registered with launchd\")\n Application.exit(withError: ExitCode(1))\n }\n\n // Now ping our friendly daemon. Fail after 10 seconds with no response.\n do {\n print(\"Verifying apiserver is running...\")\n try await ClientHealthCheck.ping(timeout: .seconds(10))\n print(\"apiserver is running\")\n } catch {\n print(\"apiserver is not running\")\n Application.exit(withError: ExitCode(1))\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImageLoad.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ImageLoad: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"load\",\n abstract: \"Load images from an OCI compatible tar archive\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(\n name: .shortAndLong, help: \"Path to the tar archive to load images from\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var input: String\n\n func run() async throws {\n guard FileManager.default.fileExists(atPath: input) else {\n print(\"File does not exist \\(input)\")\n Application.exit(withError: ArgumentParser.ExitCode(1))\n }\n\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n totalTasks: 2\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Loading tar archive\")\n let loaded = try await ClientImage.load(from: input)\n\n let taskManager = ProgressTaskCoordinator()\n let unpackTask = await taskManager.startTask()\n progress.set(description: \"Unpacking image\")\n progress.set(itemsName: \"entries\")\n for image in loaded {\n try await image.unpack(platform: nil, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progress.handler))\n }\n await taskManager.finish()\n progress.finish()\n print(\"Loaded images:\")\n for image in loaded {\n print(image.reference)\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientKernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\npublic struct ClientKernel {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n}\n\nextension ClientKernel {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public static func installKernel(kernelFilePath: String, platform: SystemPlatform) async throws {\n let client = newClient()\n let message = XPCMessage(route: .installKernel)\n\n message.set(key: .kernelFilePath, value: kernelFilePath)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n try await client.send(message)\n }\n\n public static func installKernelFromTar(tarFile: String, kernelFilePath: String, platform: SystemPlatform, progressUpdate: ProgressUpdateHandler? = nil) async throws {\n let client = newClient()\n let message = XPCMessage(route: .installKernel)\n\n message.set(key: .kernelTarURL, value: tarFile)\n message.set(key: .kernelFilePath, value: kernelFilePath)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n\n var progressUpdateClient: ProgressUpdateClient?\n if let progressUpdate {\n progressUpdateClient = await ProgressUpdateClient(for: progressUpdate, request: message)\n }\n\n try await client.send(message)\n await progressUpdateClient?.finish()\n }\n\n @discardableResult\n public static func getDefaultKernel(for platform: SystemPlatform) async throws -> Kernel {\n let client = newClient()\n let message = XPCMessage(route: .getDefaultKernel)\n\n let platformData = try JSONEncoder().encode(platform)\n message.set(key: .systemPlatform, value: platformData)\n do {\n let reply = try await client.send(message)\n guard let kData = reply.dataNoCopy(key: .kernel) else {\n throw ContainerizationError(.internalError, message: \"Missing kernel data from XPC response\")\n }\n\n let kernel = try JSONDecoder().decode(Kernel.self, from: kData)\n return kernel\n } catch let err as ContainerizationError {\n guard err.isCode(.notFound) else {\n throw err\n }\n throw ContainerizationError(\n .notFound, message: \"Default kernel not configured for architecture \\(platform.architecture). Please use the `container system kernel set` command to configure it\")\n }\n }\n}\n\nextension SystemPlatform {\n public static var current: SystemPlatform {\n switch Platform.current.architecture {\n case \"arm64\":\n return .linuxArm\n case \"amd64\":\n return .linuxAmd\n default:\n fatalError(\"Unknown architecture\")\n }\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/ImageServiceXPCKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\n/// Keys for XPC fields.\npublic enum ImagesServiceXPCKeys: String {\n case fd\n /// FDs pointing to container logs key.\n case logs\n /// Path to a file on disk key.\n case filePath\n\n /// Images\n case imageReference\n case imageNewReference\n case imageDescription\n case imageDescriptions\n case filesystem\n case ociPlatform\n case insecureFlag\n case garbageCollect\n\n /// ContentStore\n case digest\n case digests\n case directory\n case contentPath\n case size\n case ingestSessionId\n}\n\nextension XPCMessage {\n public func set(key: ImagesServiceXPCKeys, value: String) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: UInt64) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: Data) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func set(key: ImagesServiceXPCKeys, value: Bool) {\n self.set(key: key.rawValue, value: value)\n }\n\n public func string(key: ImagesServiceXPCKeys) -> String? {\n self.string(key: key.rawValue)\n }\n\n public func data(key: ImagesServiceXPCKeys) -> Data? {\n self.data(key: key.rawValue)\n }\n\n public func dataNoCopy(key: ImagesServiceXPCKeys) -> Data? {\n self.dataNoCopy(key: key.rawValue)\n }\n\n public func uint64(key: ImagesServiceXPCKeys) -> UInt64 {\n self.uint64(key: key.rawValue)\n }\n\n public func bool(key: ImagesServiceXPCKeys) -> Bool {\n self.bool(key: key.rawValue)\n }\n}\n\n#endif\n"], ["/container/Sources/Services/ContainerImagesService/Server/ContentStoreService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerImagesServiceClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\npublic actor ContentStoreService {\n private let log: Logger\n private let contentStore: LocalContentStore\n private let root: URL\n\n public init(root: URL, log: Logger) throws {\n try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)\n self.root = root.appendingPathComponent(\"content\")\n self.contentStore = try LocalContentStore(path: self.root)\n self.log = log\n }\n\n public func get(digest: String) async throws -> URL? {\n self.log.trace(\"ContentStoreService: \\(#function) digest \\(digest)\")\n return try await self.contentStore.get(digest: digest)?.path\n }\n\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n self.log.debug(\"ContentStoreService: \\(#function) digests \\(digests)\")\n return try await self.contentStore.delete(digests: digests)\n }\n\n @discardableResult\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n self.log.debug(\"ContentStoreService: \\(#function) digests \\(keeping)\")\n return try await self.contentStore.delete(keeping: keeping)\n }\n\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n self.log.debug(\"ContentStoreService: \\(#function)\")\n return try await self.contentStore.newIngestSession()\n }\n\n public func completeIngestSession(_ id: String) async throws -> [String] {\n self.log.debug(\"ContentStoreService: \\(#function) id \\(id)\")\n return try await self.contentStore.completeIngestSession(id)\n }\n\n public func cancelIngestSession(_ id: String) async throws {\n self.log.debug(\"ContentStoreService: \\(#function) id \\(id)\")\n return try await self.contentStore.cancelIngestSession(id)\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct ContainerStop: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"stop\",\n abstract: \"Stop one or more running containers\")\n\n @Flag(name: .shortAndLong, help: \"Stop all running containers\")\n var all = false\n\n @Option(name: .shortAndLong, help: \"Signal to send the container(s)\")\n var signal: String = \"SIGTERM\"\n\n @Option(name: .shortAndLong, help: \"Seconds to wait before killing the container(s)\")\n var time: Int32 = 5\n\n @Argument\n var containerIDs: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(\n .invalidArgument, message: \"explicitly supplied container IDs conflicts with the --all flag\")\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n var containers = [ClientContainer]()\n if self.all {\n containers = try await ClientContainer.list()\n } else {\n containers = try await ClientContainer.list().filter { c in\n set.contains(c.id)\n }\n }\n\n let opts = ContainerStopOptions(\n timeoutInSeconds: self.time,\n signal: try Signals.parseSignal(self.signal)\n )\n let failed = try await Self.stopContainers(containers: containers, stopOptions: opts)\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"stop failed for one or more containers \\(failed.joined(separator: \",\"))\")\n }\n }\n\n static func stopContainers(containers: [ClientContainer], stopOptions: ContainerStopOptions) async throws -> [String] {\n var failed: [String] = []\n try await withThrowingTaskGroup(of: ClientContainer?.self) { group in\n for container in containers {\n group.addTask {\n do {\n try await container.stop(opts: stopOptions)\n print(container.id)\n return nil\n } catch {\n log.error(\"failed to stop container \\(container.id): \\(error)\")\n return container\n }\n }\n }\n\n for try await ctr in group {\n guard let ctr else {\n continue\n }\n failed.append(ctr.id)\n }\n }\n\n return failed\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\n\npublic struct ContainerConfiguration: Sendable, Codable {\n /// Identifier for the container.\n public var id: String\n /// Image used to create the container.\n public var image: ImageDescription\n /// External mounts to add to the container.\n public var mounts: [Filesystem] = []\n /// Ports to publish from container to host.\n public var publishedPorts: [PublishPort] = []\n /// Sockets to publish from container to host.\n public var publishedSockets: [PublishSocket] = []\n /// Key/Value labels for the container.\n public var labels: [String: String] = [:]\n /// System controls for the container.\n public var sysctls: [String: String] = [:]\n /// The networks the container will be added to.\n public var networks: [String] = []\n /// The DNS configuration for the container.\n public var dns: DNSConfiguration? = nil\n /// Whether to enable rosetta x86-64 translation for the container.\n public var rosetta: Bool = false\n /// The hostname for the container.\n public var hostname: String? = nil\n /// Initial or main process of the container.\n public var initProcess: ProcessConfiguration\n /// Platform for the container\n public var platform: ContainerizationOCI.Platform = .current\n /// Resource values for the container.\n public var resources: Resources = .init()\n /// Name of the runtime that supports the container\n public var runtimeHandler: String = \"container-runtime-linux\"\n\n enum CodingKeys: String, CodingKey {\n case id\n case image\n case mounts\n case publishedPorts\n case publishedSockets\n case labels\n case sysctls\n case networks\n case dns\n case rosetta\n case hostname\n case initProcess\n case platform\n case resources\n case runtimeHandler\n }\n\n /// Create a configuration from the supplied Decoder, initializing missing\n /// values where possible to reasonable defaults.\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n id = try container.decode(String.self, forKey: .id)\n image = try container.decode(ImageDescription.self, forKey: .image)\n mounts = try container.decodeIfPresent([Filesystem].self, forKey: .mounts) ?? []\n publishedPorts = try container.decodeIfPresent([PublishPort].self, forKey: .publishedPorts) ?? []\n publishedSockets = try container.decodeIfPresent([PublishSocket].self, forKey: .publishedSockets) ?? []\n labels = try container.decodeIfPresent([String: String].self, forKey: .labels) ?? [:]\n sysctls = try container.decodeIfPresent([String: String].self, forKey: .sysctls) ?? [:]\n networks = try container.decodeIfPresent([String].self, forKey: .networks) ?? []\n dns = try container.decodeIfPresent(DNSConfiguration.self, forKey: .dns)\n rosetta = try container.decodeIfPresent(Bool.self, forKey: .rosetta) ?? false\n hostname = try container.decodeIfPresent(String.self, forKey: .hostname)\n initProcess = try container.decode(ProcessConfiguration.self, forKey: .initProcess)\n platform = try container.decodeIfPresent(ContainerizationOCI.Platform.self, forKey: .platform) ?? .current\n resources = try container.decodeIfPresent(Resources.self, forKey: .resources) ?? .init()\n runtimeHandler = try container.decodeIfPresent(String.self, forKey: .runtimeHandler) ?? \"container-runtime-linux\"\n }\n\n public struct DNSConfiguration: Sendable, Codable {\n public static let defaultNameservers = [\"1.1.1.1\"]\n\n public let nameservers: [String]\n public let domain: String?\n public let searchDomains: [String]\n public let options: [String]\n\n public init(\n nameservers: [String] = defaultNameservers,\n domain: String? = nil,\n searchDomains: [String] = [],\n options: [String] = []\n ) {\n self.nameservers = nameservers\n self.domain = domain\n self.searchDomains = searchDomains\n self.options = options\n }\n }\n\n /// Resources like cpu, memory, and storage quota.\n public struct Resources: Sendable, Codable {\n /// Number of CPU cores allocated.\n public var cpus: Int = 4\n /// Memory in bytes allocated.\n public var memoryInBytes: UInt64 = 1024.mib()\n /// Storage quota/size in bytes.\n public var storage: UInt64?\n\n public init() {}\n }\n\n public init(\n id: String,\n image: ImageDescription,\n process: ProcessConfiguration\n ) {\n self.id = id\n self.image = image\n self.initProcess = process\n }\n}\n"], ["/container/Sources/CLI/Registry/RegistryDefault.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct RegistryDefault: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"default\",\n abstract: \"Manage the default image registry\",\n subcommands: [\n DefaultSetCommand.self,\n DefaultUnsetCommand.self,\n DefaultInspectCommand.self,\n ]\n )\n }\n\n struct DefaultSetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default registry\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @Argument\n var host: String\n\n func run() async throws {\n let scheme = try RequestScheme(registry.scheme).schemeFor(host: host)\n\n let _url = \"\\(scheme)://\\(host)\"\n guard let url = URL(string: _url), let domain = url.host() else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n let resolvedDomain = Reference.resolveDomain(domain: domain)\n let client = RegistryClient(host: resolvedDomain, scheme: scheme.rawValue, port: url.port)\n do {\n try await client.ping()\n } catch let err as RegistryClient.Error {\n switch err {\n case .invalidStatus(url: _, .unauthorized, _), .invalidStatus(url: _, .forbidden, _):\n break\n default:\n throw err\n }\n }\n ClientDefaults.set(value: host, key: .defaultRegistryDomain)\n print(\"Set default registry to \\(host)\")\n }\n }\n\n struct DefaultUnsetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"unset\",\n abstract: \"Unset the default registry\",\n aliases: [\"clear\"]\n )\n\n func run() async throws {\n ClientDefaults.unset(key: .defaultRegistryDomain)\n print(\"Unset the default registry domain\")\n }\n }\n\n struct DefaultInspectCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display the default registry domain\"\n )\n\n func run() async throws {\n print(ClientDefaults.get(key: .defaultRegistryDomain))\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerExec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct ContainerExec: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"exec\",\n abstract: \"Run a new command in a running container\")\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Running containers ID\")\n var containerID: String\n\n @Argument(parsing: .captureForPassthrough, help: \"New process arguments\")\n var arguments: [String]\n\n func run() async throws {\n var exitCode: Int32 = 127\n let container = try await ClientContainer.get(id: containerID)\n try ensureRunning(container: container)\n\n let stdin = self.processFlags.interactive\n let tty = self.processFlags.tty\n\n var config = container.configuration.initProcess\n config.executable = arguments.first!\n config.arguments = [String](self.arguments.dropFirst())\n config.terminal = tty\n config.environment.append(\n contentsOf: try Parser.allEnv(\n imageEnvs: [],\n envFiles: self.processFlags.envFile,\n envs: self.processFlags.env\n ))\n\n if let cwd = self.processFlags.cwd {\n config.workingDirectory = cwd\n }\n\n let defaultUser = config.user\n let (user, additionalGroups) = Parser.user(\n user: processFlags.user, uid: processFlags.uid,\n gid: processFlags.gid, defaultUser: defaultUser)\n config.user = user\n config.supplementalGroups.append(contentsOf: additionalGroups)\n\n do {\n let io = try ProcessIO.create(tty: tty, interactive: stdin, detach: false)\n\n if !self.processFlags.tty {\n var handler = SignalThreshold(threshold: 3, signals: [SIGINT, SIGTERM])\n handler.start {\n print(\"Received 3 SIGINT/SIGTERM's, forcefully exiting.\")\n Darwin.exit(1)\n }\n }\n\n let process = try await container.createProcess(\n id: UUID().uuidString.lowercased(),\n configuration: config)\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to exec process \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/ExitMonitor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport Logging\n\n/// Track when long running work exits, and notify the caller via a callback.\npublic actor ExitMonitor {\n /// A callback that receives the client identifier and exit code.\n public typealias ExitCallback = @Sendable (String, Int32) async throws -> Void\n\n /// A function that waits for work to complete, returning an exit code.\n public typealias WaitHandler = @Sendable () async throws -> Int32\n\n /// Create a new monitor.\n ///\n /// - Parameters:\n /// - log: The destination for log messages.\n public init(log: Logger? = nil) {\n self.log = log\n }\n\n private var exitCallbacks: [String: ExitCallback] = [:]\n private var runningTasks: [String: Task] = [:]\n private let log: Logger?\n\n /// Remove tracked work from the monitor.\n ///\n /// - Parameters:\n /// - id: The client identifier for the tracked work.\n public func stopTracking(id: String) async {\n if let task = self.runningTasks[id] {\n task.cancel()\n }\n exitCallbacks.removeValue(forKey: id)\n runningTasks.removeValue(forKey: id)\n }\n\n /// Register long running work so that the monitor invokes\n /// a callback when the work completes.\n ///\n /// - Parameters:\n /// - id: The client identifier for the work.\n /// - onExit: The callback to invoke when the work completes.\n public func registerProcess(id: String, onExit: @escaping ExitCallback) async throws {\n guard self.exitCallbacks[id] == nil else {\n throw ContainerizationError(.invalidState, message: \"ExitMonitor already setup for process \\(id)\")\n }\n self.exitCallbacks[id] = onExit\n }\n\n /// Await the completion of previously registered item of work.\n ///\n /// - Parameters:\n /// - id: The client identifier for the work.\n /// - waitingOn: A function that waits for the work to complete,\n /// and then returns an exit code.\n public func track(id: String, waitingOn: @escaping WaitHandler) async throws {\n guard let onExit = self.exitCallbacks[id] else {\n throw ContainerizationError(.invalidState, message: \"ExitMonitor not setup for process \\(id)\")\n }\n guard self.runningTasks[id] == nil else {\n throw ContainerizationError(.invalidState, message: \"Already have a running task tracking process \\(id)\")\n }\n self.runningTasks[id] = Task {\n do {\n let exitStatus = try await waitingOn()\n try await onExit(id, exitStatus)\n } catch {\n self.log?.error(\"WaitHandler for \\(id) threw error \\(String(describing: error))\")\n try? await onExit(id, -1)\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Measurement+Parse.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nprivate let units: [Character: UnitInformationStorage] = [\n \"b\": .bytes,\n \"k\": .kibibytes,\n \"m\": .mebibytes,\n \"g\": .gibibytes,\n \"t\": .tebibytes,\n \"p\": .pebibytes,\n]\n\nextension Measurement {\n public enum ParseError: Swift.Error, CustomStringConvertible {\n case invalidSize\n case invalidSymbol(String)\n\n public var description: String {\n switch self {\n case .invalidSize:\n return \"invalid size\"\n case .invalidSymbol(let symbol):\n return \"invalid symbol: \\(symbol)\"\n }\n }\n }\n\n /// parse the provided string into a measurement that is able to be converted to various byte sizes\n public static func parse(parsing: String) throws -> Measurement {\n let check = \"01234567890. \"\n let i = parsing.lastIndex {\n check.contains($0)\n }\n guard let i else {\n throw ParseError.invalidSize\n }\n let after = parsing.index(after: i)\n let rawValue = parsing[..(value: value, unit: unit)\n }\n\n static func parseUnit(_ unit: String) throws -> Character {\n let s = unit.dropFirst()\n switch s {\n case \"\", \"b\", \"ib\":\n return unit.first ?? \"b\"\n default:\n throw ParseError.invalidSymbol(unit)\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ContainerCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a new container\")\n\n @Argument(help: \"Image name\")\n var image: String\n\n @Argument(help: \"Container init process arguments\")\n var arguments: [String] = []\n\n @OptionGroup\n var processFlags: Flags.Process\n\n @OptionGroup\n var resourceFlags: Flags.Resource\n\n @OptionGroup\n var managementFlags: Flags.Management\n\n @OptionGroup\n var registryFlags: Flags.Registry\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 3\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let id = Utility.createContainerID(name: self.managementFlags.name)\n try Utility.validEntityName(id)\n\n let ck = try await Utility.containerConfigFromFlags(\n id: id,\n image: image,\n arguments: arguments,\n process: processFlags,\n management: managementFlags,\n resource: resourceFlags,\n registry: registryFlags,\n progressUpdate: progress.handler\n )\n\n let options = ContainerCreateOptions(autoRemove: managementFlags.remove)\n let container = try await ClientContainer.create(configuration: ck.0, options: options, kernel: ck.1)\n\n if !self.managementFlags.cidfile.isEmpty {\n let path = self.managementFlags.cidfile\n let data = container.id.data(using: .utf8)\n var attributes = [FileAttributeKey: Any]()\n attributes[.posixPermissions] = 0o644\n let success = FileManager.default.createFile(\n atPath: path,\n contents: data,\n attributes: attributes\n )\n guard success else {\n throw ContainerizationError(\n .internalError, message: \"failed to create cidfile at \\(path): \\(errno)\")\n }\n }\n progress.finish()\n\n print(container.id)\n }\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderDelete: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"delete\"\n config._superCommandName = \"builder\"\n config.abstract = \"Delete builder\"\n config.usage = \"\\n\\t builder delete [command options]\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n @Flag(name: .shortAndLong, help: \"Force delete builder even if it is running\")\n var force = false\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n if container.status != .stopped {\n guard force else {\n throw ContainerizationError(.invalidState, message: \"BuildKit container is not stopped, use --force to override\")\n }\n try await container.stop()\n }\n try await container.delete()\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressBar+Add.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension ProgressBar {\n /// A handler function to update the progress bar.\n /// - Parameter events: The events to handle.\n public func handler(_ events: [ProgressUpdateEvent]) {\n for event in events {\n switch event {\n case .setDescription(let description):\n set(description: description)\n case .setSubDescription(let subDescription):\n set(subDescription: subDescription)\n case .setItemsName(let itemsName):\n set(itemsName: itemsName)\n case .addTasks(let tasks):\n add(tasks: tasks)\n case .setTasks(let tasks):\n set(tasks: tasks)\n case .addTotalTasks(let totalTasks):\n add(totalTasks: totalTasks)\n case .setTotalTasks(let totalTasks):\n set(totalTasks: totalTasks)\n case .addSize(let size):\n add(size: size)\n case .setSize(let size):\n set(size: size)\n case .addTotalSize(let totalSize):\n add(totalSize: totalSize)\n case .setTotalSize(let totalSize):\n set(totalSize: totalSize)\n case .addItems(let items):\n add(items: items)\n case .setItems(let items):\n set(items: items)\n case .addTotalItems(let totalItems):\n add(totalItems: totalItems)\n case .setTotalItems(let totalItems):\n set(totalItems: totalItems)\n case .custom:\n // Custom events are handled by the client.\n break\n }\n }\n }\n\n /// Performs a check to see if the progress bar should be finished.\n public func checkIfFinished() {\n let state = self.state.withLock { $0 }\n\n var finished = true\n var defined = false\n if let totalTasks = state.totalTasks, totalTasks > 0 {\n // For tasks, we're showing the current task rather than the number of completed tasks.\n finished = finished && state.tasks == totalTasks\n defined = true\n }\n if let totalItems = state.totalItems, totalItems > 0 {\n finished = finished && state.items == totalItems\n defined = true\n }\n if let totalSize = state.totalSize, totalSize > 0 {\n finished = finished && state.size == totalSize\n defined = true\n }\n if defined && finished {\n finish()\n }\n }\n\n /// Sets the current tasks.\n /// - Parameter newTasks: The current tasks to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(tasks newTasks: Int, render: Bool = true) {\n state.withLock { $0.tasks = newTasks }\n if render {\n self.render()\n }\n checkIfFinished()\n }\n\n /// Performs an addition to the current tasks.\n /// - Parameter delta: The tasks to add to the current tasks.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(tasks delta: Int, render: Bool = true) {\n state.withLock {\n let newTasks = $0.tasks + delta\n $0.tasks = newTasks\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total tasks.\n /// - Parameter newTotalTasks: The total tasks to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalTasks newTotalTasks: Int, render: Bool = true) {\n state.withLock { $0.totalTasks = newTotalTasks }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total tasks.\n /// - Parameter delta: The tasks to add to the total tasks.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalTasks delta: Int, render: Bool = true) {\n state.withLock {\n let totalTasks = $0.totalTasks ?? 0\n let newTotalTasks = totalTasks + delta\n $0.totalTasks = newTotalTasks\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the items name.\n /// - Parameter newItemsName: The current items to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(itemsName newItemsName: String, render: Bool = true) {\n state.withLock { $0.itemsName = newItemsName }\n if render {\n self.render()\n }\n }\n\n /// Sets the current items.\n /// - Parameter newItems: The current items to set.\n public func set(items newItems: Int, render: Bool = true) {\n state.withLock { $0.items = newItems }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the current items.\n /// - Parameter delta: The items to add to the current items.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(items delta: Int, render: Bool = true) {\n state.withLock {\n let newItems = $0.items + delta\n $0.items = newItems\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total items.\n /// - Parameter newTotalItems: The total items to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalItems newTotalItems: Int, render: Bool = true) {\n state.withLock { $0.totalItems = newTotalItems }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total items.\n /// - Parameter delta: The items to add to the total items.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalItems delta: Int, render: Bool = true) {\n state.withLock {\n let totalItems = $0.totalItems ?? 0\n let newTotalItems = totalItems + delta\n $0.totalItems = newTotalItems\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the current size.\n /// - Parameter newSize: The current size to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(size newSize: Int64, render: Bool = true) {\n state.withLock { $0.size = newSize }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the current size.\n /// - Parameter delta: The size to add to the current size.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(size delta: Int64, render: Bool = true) {\n state.withLock {\n let newSize = $0.size + delta\n $0.size = newSize\n }\n if render {\n self.render()\n }\n }\n\n /// Sets the total size.\n /// - Parameter newTotalSize: The total size to set.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func set(totalSize newTotalSize: Int64, render: Bool = true) {\n state.withLock { $0.totalSize = newTotalSize }\n if render {\n self.render()\n }\n }\n\n /// Performs an addition to the total size.\n /// - Parameter delta: The size to add to the total size.\n /// - Parameter render: The flag indicating whether the progress bar has to render after the update.\n public func add(totalSize delta: Int64, render: Bool = true) {\n state.withLock {\n let totalSize = $0.totalSize ?? 0\n let newTotalSize = totalSize + delta\n $0.totalSize = newTotalSize\n }\n if render {\n self.render()\n }\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/StandardQueryValidator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Pass standard queries to a delegate handler.\npublic struct StandardQueryValidator: DNSHandler {\n private let handler: DNSHandler\n\n /// Create the handler.\n /// - Parameter delegate: the handler that receives valid queries\n public init(handler: DNSHandler) {\n self.handler = handler\n }\n\n /// Ensures the query is valid before forwarding it to the delegate.\n /// - Parameter msg: the query message\n /// - Returns: the delegate response if the query is valid, and an\n /// error response otherwise\n public func answer(query: Message) async throws -> Message? {\n // Reject response messages.\n guard query.type == .query else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions\n )\n }\n\n // Standard DNS servers handle only query operations.\n guard query.operationCode == .query else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions\n )\n }\n\n // Standard DNS servers only handle messages with exactly one question.\n guard query.questions.count == 1 else {\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions\n )\n }\n\n return try await handler.answer(query: query)\n }\n}\n"], ["/container/Sources/ContainerBuild/BuildStdio.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIO\n\nactor BuildStdio: BuildPipelineHandler {\n public let quiet: Bool\n public let handle: FileHandle\n\n init(quiet: Bool = false, output: FileHandle = FileHandle.standardError) throws {\n self.quiet = quiet\n self.handle = output\n }\n\n nonisolated func accept(_ packet: ServerStream) throws -> Bool {\n guard let _ = packet.getIO() else {\n return false\n }\n return true\n }\n\n func handle(_ sender: AsyncStream.Continuation, _ packet: ServerStream) async throws {\n guard !quiet else {\n return\n }\n guard let io = packet.getIO() else {\n throw Error.ioMissing\n }\n if let cmdString = try TerminalCommand().json() {\n var response = ClientStream()\n response.buildID = packet.buildID\n response.command = .init()\n response.command.id = packet.buildID\n response.command.command = cmdString\n sender.yield(response)\n }\n handle.write(io.data)\n }\n}\n\nextension BuildStdio {\n enum Error: Swift.Error, CustomStringConvertible {\n case ioMissing\n case invalidContinuation\n var description: String {\n switch self {\n case .ioMissing:\n return \"io field missing in packet\"\n case .invalidContinuation:\n return \"continuation could not created\"\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/ProgressUpdateClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\n/// A client that can be used to receive progress updates from a service.\npublic actor ProgressUpdateClient {\n private var endpointConnection: xpc_connection_t?\n private var endpoint: xpc_endpoint_t?\n\n /// Creates a new client for receiving progress updates from a service.\n /// - Parameters:\n /// - progressUpdate: The handler to invoke when progress updates are received.\n /// - request: The XPC message to send the endpoint to connect to.\n public init(for progressUpdate: @escaping ProgressUpdateHandler, request: XPCMessage) async {\n createEndpoint(for: progressUpdate)\n setEndpoint(to: request)\n }\n\n /// Performs a connection setup for receiving progress updates.\n /// - Parameter progressUpdate: The handler to invoke when progress updates are received.\n private func createEndpoint(for progressUpdate: @escaping ProgressUpdateHandler) {\n let endpointConnection = xpc_connection_create(nil, nil)\n // Access to `reversedConnection` is protected by a lock\n nonisolated(unsafe) var reversedConnection: xpc_connection_t?\n let reversedConnectionLock = NSLock()\n xpc_connection_set_event_handler(endpointConnection) { connectionMessage in\n reversedConnectionLock.withLock {\n switch xpc_get_type(connectionMessage) {\n case XPC_TYPE_CONNECTION:\n reversedConnection = connectionMessage\n xpc_connection_set_event_handler(connectionMessage) { updateMessage in\n Self.handleProgressUpdate(updateMessage, progressUpdate: progressUpdate)\n }\n xpc_connection_activate(connectionMessage)\n case XPC_TYPE_ERROR:\n if let reversedConnectionUnwrapped = reversedConnection {\n xpc_connection_cancel(reversedConnectionUnwrapped)\n reversedConnection = nil\n }\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(connectionMessage))\")\n }\n }\n }\n xpc_connection_activate(endpointConnection)\n\n self.endpointConnection = endpointConnection\n self.endpoint = xpc_endpoint_create(endpointConnection)\n }\n\n /// Performs a setup of the progress update endpoint.\n /// - Parameter request: The XPC message containing the endpoint to use.\n private func setEndpoint(to request: XPCMessage) {\n guard let endpoint else {\n return\n }\n request.set(key: .progressUpdateEndpoint, value: endpoint)\n }\n\n /// Performs cleanup of the created connection.\n public func finish() {\n if let endpointConnection {\n xpc_connection_cancel(endpointConnection)\n self.endpointConnection = nil\n }\n }\n\n private static func handleProgressUpdate(_ message: xpc_object_t, progressUpdate: @escaping ProgressUpdateHandler) {\n switch xpc_get_type(message) {\n case XPC_TYPE_DICTIONARY:\n let message = XPCMessage(object: message)\n handleProgressUpdate(message, progressUpdate: progressUpdate)\n case XPC_TYPE_ERROR:\n break\n default:\n fatalError(\"unhandled xpc object type: \\(xpc_get_type(message))\")\n break\n }\n }\n\n private static func handleProgressUpdate(_ message: XPCMessage, progressUpdate: @escaping ProgressUpdateHandler) {\n var events = [ProgressUpdateEvent]()\n\n if let description = message.string(key: .progressUpdateSetDescription) {\n events.append(.setDescription(description))\n }\n if let subDescription = message.string(key: .progressUpdateSetSubDescription) {\n events.append(.setSubDescription(subDescription))\n }\n if let itemsName = message.string(key: .progressUpdateSetItemsName) {\n events.append(.setItemsName(itemsName))\n }\n var tasks = message.int(key: .progressUpdateAddTasks)\n if tasks != 0 {\n events.append(.addTasks(tasks))\n }\n tasks = message.int(key: .progressUpdateSetTasks)\n if tasks != 0 {\n events.append(.setTasks(tasks))\n }\n var totalTasks = message.int(key: .progressUpdateAddTotalTasks)\n if totalTasks != 0 {\n events.append(.addTotalTasks(totalTasks))\n }\n totalTasks = message.int(key: .progressUpdateSetTotalTasks)\n if totalTasks != 0 {\n events.append(.setTotalTasks(totalTasks))\n }\n var items = message.int(key: .progressUpdateAddItems)\n if items != 0 {\n events.append(.addItems(items))\n }\n items = message.int(key: .progressUpdateSetItems)\n if items != 0 {\n events.append(.setItems(items))\n }\n var totalItems = message.int(key: .progressUpdateAddTotalItems)\n if totalItems != 0 {\n events.append(.addTotalItems(totalItems))\n }\n totalItems = message.int(key: .progressUpdateSetTotalItems)\n if totalItems != 0 {\n events.append(.setTotalItems(totalItems))\n }\n var size = message.int64(key: .progressUpdateAddSize)\n if size != 0 {\n events.append(.addSize(size))\n }\n size = message.int64(key: .progressUpdateSetSize)\n if size != 0 {\n events.append(.setSize(size))\n }\n var totalSize = message.int64(key: .progressUpdateAddTotalSize)\n if totalSize != 0 {\n events.append(.addTotalSize(totalSize))\n }\n totalSize = message.int64(key: .progressUpdateSetTotalSize)\n if totalSize != 0 {\n events.append(.setTotalSize(totalSize))\n }\n\n Task {\n await progressUpdate(events)\n }\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/NxDomainResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport DNS\n\n/// Handler that returns NXDOMAIN for all hostnames.\npublic struct NxDomainResolver: DNSHandler {\n private let ttl: UInt32\n\n public init(ttl: UInt32 = 300) {\n self.ttl = ttl\n }\n\n public func answer(query: Message) async throws -> Message? {\n let question = query.questions[0]\n switch question.type {\n case ResourceRecordType.host:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .nonExistentDomain,\n questions: query.questions,\n answers: []\n )\n case ResourceRecordType.nameServer,\n ResourceRecordType.alias,\n ResourceRecordType.startOfAuthority,\n ResourceRecordType.pointer,\n ResourceRecordType.mailExchange,\n ResourceRecordType.text,\n ResourceRecordType.host6,\n ResourceRecordType.service,\n ResourceRecordType.incrementalZoneTransfer,\n ResourceRecordType.standardZoneTransfer,\n ResourceRecordType.all:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n default:\n return Message(\n id: query.id,\n type: .response,\n returnCode: .formatError,\n questions: query.questions,\n answers: []\n )\n }\n }\n}\n"], ["/container/Sources/SocketForwarder/LRUCache.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nstruct KeyExistsError: Error {}\n\nclass LRUCache {\n private class Node {\n fileprivate var prev: Node?\n fileprivate var next: Node?\n fileprivate let key: K\n fileprivate let value: V\n\n init(key: K, value: V) {\n self.prev = nil\n self.next = nil\n self.key = key\n self.value = value\n }\n }\n\n private let size: UInt\n private var head: Node?\n private var tail: Node?\n private var members: [K: Node]\n\n init(size: UInt) {\n self.size = size\n self.head = nil\n self.tail = nil\n self.members = [:]\n }\n\n var count: Int { members.count }\n\n func get(_ key: K) -> V? {\n guard let node = members[key] else {\n return nil\n }\n listRemove(node: node)\n listInsert(node: node, after: tail)\n return node.value\n }\n\n func put(key: K, value: V) -> (K, V)? {\n let node = Node(key: key, value: value)\n var evicted: (K, V)? = nil\n\n if let existingNode = members[key] {\n // evict the replaced node\n listRemove(node: existingNode)\n evicted = (existingNode.key, existingNode.value)\n } else if self.count >= self.size {\n // evict the least recently used node\n evicted = evict()\n }\n\n // insert the new node and return any evicted node\n members[key] = node\n listInsert(node: node, after: tail)\n return evicted\n }\n\n private func evict() -> (K, V)? {\n guard let head else {\n return nil\n }\n let ret = (head.key, head.value)\n listRemove(node: head)\n members.removeValue(forKey: head.key)\n return ret\n }\n\n private func listRemove(node: Node) {\n if let prev = node.prev {\n prev.next = node.next\n } else {\n head = node.next\n }\n if let next = node.next {\n next.prev = node.prev\n } else {\n tail = node.prev\n }\n }\n\n private func listInsert(node: Node, after: Node?) {\n let before: Node?\n if let after {\n before = after.next\n after.next = node\n } else {\n before = head\n head = node\n }\n\n if let before {\n before.prev = node\n } else {\n tail = node\n }\n\n node.prev = after\n node.next = before\n }\n}\n"], ["/container/Sources/CLI/Image/ImageSave.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct ImageSave: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"save\",\n abstract: \"Save an image as an OCI compatible tar archive\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Option(\n name: .shortAndLong, help: \"Path to save the image tar archive\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var output: String\n\n @Argument var reference: String\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let progressConfig = try ProgressConfig(\n description: \"Saving image\"\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let image = try await ClientImage.get(reference: reference)\n try await image.save(out: output, platform: p)\n\n progress.finish()\n print(\"Image saved\")\n }\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/NonisolatedInterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\nimport ContainerizationError\nimport Logging\nimport Virtualization\nimport vmnet\n\n/// Interface strategy for containers that use macOS's custom network feature.\n@available(macOS 26, *)\nstruct NonisolatedInterfaceStrategy: InterfaceStrategy {\n private let log: Logger\n\n public init(log: Logger) {\n self.log = log\n }\n\n public func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) throws -> Interface {\n guard let additionalData else {\n throw ContainerizationError(.invalidState, message: \"network state does not contain custom network reference\")\n }\n\n var status: vmnet_return_t = .VMNET_SUCCESS\n guard let networkRef = vmnet_network_create_with_serialization(additionalData.underlying, &status) else {\n throw ContainerizationError(.invalidState, message: \"cannot deserialize custom network reference, status \\(status)\")\n }\n\n log.info(\"creating NATNetworkInterface with network reference\")\n let gateway = interfaceIndex == 0 ? attachment.gateway : nil\n return NATNetworkInterface(address: attachment.address, gateway: gateway, reference: networkRef)\n }\n}\n"], ["/container/Sources/DNSServer/Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport DNS\nimport Foundation\n\npublic typealias Message = DNS.Message\npublic typealias ResourceRecord = DNS.ResourceRecord\npublic typealias HostRecord = DNS.HostRecord\npublic typealias IPv4 = DNS.IPv4\npublic typealias IPv6 = DNS.IPv6\npublic typealias ReturnCode = DNS.ReturnCode\n\npublic enum DNSResolverError: Swift.Error, CustomStringConvertible {\n case serverError(_ msg: String)\n case invalidHandlerSpec(_ spec: String)\n case unsupportedHandlerType(_ t: String)\n case invalidIP(_ v: String)\n case invalidHandlerOption(_ v: String)\n case handlerConfigError(_ msg: String)\n\n public var description: String {\n switch self {\n case .serverError(let msg):\n return \"server error: \\(msg)\"\n case .invalidHandlerSpec(let msg):\n return \"invalid handler spec: \\(msg)\"\n case .unsupportedHandlerType(let t):\n return \"unsupported handler type specified: \\(t)\"\n case .invalidIP(let ip):\n return \"invalid IP specified: \\(ip)\"\n case .invalidHandlerOption(let v):\n return \"invalid handler option specified: \\(v)\"\n case .handlerConfigError(let msg):\n return \"error configuring handler: \\(msg)\"\n }\n }\n}\n"], ["/container/Sources/CLI/Image/ImageRemove.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct RemoveImageOptions: ParsableArguments {\n @Flag(name: .shortAndLong, help: \"Remove all images\")\n var all: Bool = false\n\n @Argument\n var images: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n }\n\n struct RemoveImageImplementation {\n static func validate(options: RemoveImageOptions) throws {\n if options.images.count == 0 && !options.all {\n throw ContainerizationError(.invalidArgument, message: \"no image specified and --all not supplied\")\n }\n if options.images.count > 0 && options.all {\n throw ContainerizationError(.invalidArgument, message: \"explicitly supplied images conflict with the --all flag\")\n }\n }\n\n static func removeImage(options: RemoveImageOptions) async throws {\n let (found, notFound) = try await {\n if options.all {\n let found = try await ClientImage.list()\n let notFound: [String] = []\n return (found, notFound)\n }\n return try await ClientImage.get(names: options.images)\n }()\n var failures: [String] = notFound\n var didDeleteAnyImage = false\n for image in found {\n guard !Utility.isInfraImage(name: image.reference) else {\n continue\n }\n do {\n try await ClientImage.delete(reference: image.reference, garbageCollect: false)\n print(image.reference)\n didDeleteAnyImage = true\n } catch {\n log.error(\"failed to remove \\(image.reference): \\(error)\")\n failures.append(image.reference)\n }\n }\n let (_, size) = try await ClientImage.pruneImages()\n let formatter = ByteCountFormatter()\n let freed = formatter.string(fromByteCount: Int64(size))\n\n if didDeleteAnyImage {\n print(\"Reclaimed \\(freed) in disk space\")\n }\n if failures.count > 0 {\n throw ContainerizationError(.internalError, message: \"failed to delete one or more images: \\(failures)\")\n }\n }\n }\n\n struct ImageRemove: AsyncParsableCommand {\n @OptionGroup\n var options: RemoveImageOptions\n\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Remove one or more images\",\n aliases: [\"rm\"])\n\n func validate() throws {\n try RemoveImageImplementation.validate(options: options)\n }\n\n mutating func run() async throws {\n try await RemoveImageImplementation.removeImage(options: options)\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/AttachmentAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\n\nactor AttachmentAllocator {\n private let allocator: any AddressAllocator\n private var hostnames: [String: UInt32] = [:]\n\n init(lower: UInt32, size: Int) throws {\n allocator = try UInt32.rotatingAllocator(\n lower: lower,\n size: UInt32(size)\n )\n }\n\n /// Allocate a network address for a host.\n func allocate(hostname: String) async throws -> UInt32 {\n guard hostnames[hostname] == nil else {\n throw ContainerizationError(.exists, message: \"Hostname \\(hostname) already exists on the network\")\n }\n let index = try allocator.allocate()\n hostnames[hostname] = index\n\n return index\n }\n\n /// Free an allocated network address by hostname.\n func deallocate(hostname: String) async throws {\n if let index = hostnames.removeValue(forKey: hostname) {\n try allocator.release(index)\n }\n }\n\n /// If no addresses are allocated, prevent future allocations and return true.\n func disableAllocator() async -> Bool {\n allocator.disableAllocator()\n }\n\n /// Retrieve the allocator index for a hostname.\n func lookup(hostname: String) async throws -> UInt32? {\n hostnames[hostname]\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePull.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport TerminalProgress\n\nextension Application {\n struct ImagePull: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"pull\",\n abstract: \"Pull an image\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Argument var reference: String\n\n init() {}\n\n init(platform: String? = nil, scheme: String = \"auto\", reference: String, disableProgress: Bool = false) {\n self.global = Flags.Global()\n self.registry = Flags.Registry(scheme: scheme)\n self.progressFlags = Flags.Progress(disableProgressUpdates: disableProgress)\n self.platform = platform\n self.reference = reference\n }\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let scheme = try RequestScheme(registry.scheme)\n\n let processedReference = try ClientImage.normalizeReference(reference)\n\n var progressConfig: ProgressConfig\n if self.progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: self.progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n showTasks: true,\n showItems: true,\n ignoreSmallSize: true,\n totalTasks: 2\n )\n }\n\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n progress.set(description: \"Fetching image\")\n progress.set(itemsName: \"blobs\")\n let taskManager = ProgressTaskCoordinator()\n let fetchTask = await taskManager.startTask()\n let image = try await ClientImage.pull(\n reference: processedReference, platform: p, scheme: scheme, progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progress.handler)\n )\n\n progress.set(description: \"Unpacking image\")\n progress.set(itemsName: \"entries\")\n let unpackTask = await taskManager.startTask()\n try await image.unpack(platform: p, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progress.handler))\n await taskManager.finish()\n progress.finish()\n }\n }\n}\n"], ["/container/Sources/ContainerPlugin/CommandLine+Executable.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension CommandLine {\n public static var executablePathUrl: URL {\n /// _NSGetExecutablePath with a zero-length buffer returns the needed buffer length\n var bufferSize: Int32 = 0\n var buffer = [CChar](repeating: 0, count: Int(bufferSize))\n _ = _NSGetExecutablePath(&buffer, &bufferSize)\n\n /// Create the buffer and get the path\n buffer = [CChar](repeating: 0, count: Int(bufferSize))\n guard _NSGetExecutablePath(&buffer, &bufferSize) == 0 else {\n fatalError(\"UNEXPECTED: failed to get executable path\")\n }\n\n /// Return the path with the executable file component removed the last component and\n let executablePath = String(cString: &buffer)\n return URL(filePath: executablePath)\n }\n}\n"], ["/container/Sources/SocketForwarder/ConnectHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Logging\nimport NIOCore\nimport NIOPosix\n\nfinal class ConnectHandler {\n private var pendingBytes: [NIOAny]\n private let serverAddress: SocketAddress\n private var log: Logger? = nil\n\n init(serverAddress: SocketAddress, log: Logger?) {\n self.pendingBytes = []\n self.serverAddress = serverAddress\n self.log = log\n }\n}\n\nextension ConnectHandler: ChannelInboundHandler {\n typealias InboundIn = ByteBuffer\n typealias OutboundOut = ByteBuffer\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n if self.pendingBytes.isEmpty {\n self.connectToServer(context: context)\n }\n self.pendingBytes.append(data)\n }\n\n func handlerAdded(context: ChannelHandlerContext) {\n // Add logger metadata.\n self.log?[metadataKey: \"proxy\"] = \"\\(context.channel.localAddress?.description ?? \"none\")\"\n self.log?[metadataKey: \"server\"] = \"\\(context.channel.remoteAddress?.description ?? \"none\")\"\n }\n}\n\nextension ConnectHandler: RemovableChannelHandler {\n func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) {\n var didRead = false\n\n // We are being removed, and need to deliver any pending bytes we may have if we're upgrading.\n while self.pendingBytes.count > 0 {\n let data = self.pendingBytes.removeFirst()\n context.fireChannelRead(data)\n didRead = true\n }\n\n if didRead {\n context.fireChannelReadComplete()\n }\n\n self.log?.trace(\"backend - removing connect handler from pipeline\")\n context.leavePipeline(removalToken: removalToken)\n }\n}\n\nextension ConnectHandler {\n private func connectToServer(context: ChannelHandlerContext) {\n self.log?.trace(\"backend - connecting\")\n\n ClientBootstrap(group: context.eventLoop)\n .connect(to: serverAddress)\n .assumeIsolatedUnsafeUnchecked()\n .whenComplete { result in\n switch result {\n case .success(let channel):\n self.log?.trace(\"backend - connected\")\n self.glue(channel, context: context)\n case .failure(let error):\n self.log?.error(\"backend - connect failed: \\(error)\")\n context.close(promise: nil)\n context.fireErrorCaught(error)\n }\n }\n }\n\n private func glue(_ peerChannel: Channel, context: ChannelHandlerContext) {\n self.log?.trace(\"backend - gluing channels\")\n\n // Now we need to glue our channel and the peer channel together.\n let (localGlue, peerGlue) = GlueHandler.matchedPair()\n do {\n try context.channel.pipeline.syncOperations.addHandler(localGlue)\n try peerChannel.pipeline.syncOperations.addHandler(peerGlue)\n context.pipeline.syncOperations.removeHandler(self, promise: nil)\n } catch {\n // Close connected peer channel before closing our channel.\n peerChannel.close(mode: .all, promise: nil)\n context.close(promise: nil)\n }\n }\n}\n"], ["/container/Sources/DNSServer/DNSServer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\nimport NIOCore\nimport NIOPosix\n\n/// Provides a DNS server.\n/// - Parameters:\n/// - host: The host address on which to listen.\n/// - port: The port for the server to listen.\npublic struct DNSServer {\n public var handler: DNSHandler\n let log: Logger?\n\n public init(\n handler: DNSHandler,\n log: Logger? = nil\n ) {\n self.handler = handler\n self.log = log\n }\n\n public func run(host: String, port: Int) async throws {\n // TODO: TCP server\n let srv = try await DatagramBootstrap(group: NIOSingletons.posixEventLoopGroup)\n .channelOption(.socketOption(.so_reuseaddr), value: 1)\n .bind(host: host, port: port)\n .flatMapThrowing { channel in\n try NIOAsyncChannel(\n wrappingChannelSynchronously: channel,\n configuration: NIOAsyncChannel.Configuration(\n inboundType: AddressedEnvelope.self,\n outboundType: AddressedEnvelope.self\n )\n )\n }\n .get()\n\n try await srv.executeThenClose { inbound, outbound in\n for try await var packet in inbound {\n try await self.handle(outbound: outbound, packet: &packet)\n }\n }\n }\n\n public func run(socketPath: String) async throws {\n // TODO: TCP server\n let srv = try await DatagramBootstrap(group: NIOSingletons.posixEventLoopGroup)\n .bind(unixDomainSocketPath: socketPath, cleanupExistingSocketFile: true)\n .flatMapThrowing { channel in\n try NIOAsyncChannel(\n wrappingChannelSynchronously: channel,\n configuration: NIOAsyncChannel.Configuration(\n inboundType: AddressedEnvelope.self,\n outboundType: AddressedEnvelope.self\n )\n )\n }\n .get()\n\n try await srv.executeThenClose { inbound, outbound in\n for try await var packet in inbound {\n log?.debug(\"received packet from \\(packet.remoteAddress)\")\n try await self.handle(outbound: outbound, packet: &packet)\n log?.debug(\"sent packet\")\n }\n }\n }\n\n public func stop() async throws {}\n}\n"], ["/container/Sources/ContainerClient/ProgressUpdateService.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport ContainerizationExtras\nimport Foundation\nimport TerminalProgress\n\n/// A service that sends progress updates to the client.\npublic actor ProgressUpdateService {\n private let endpointConnection: xpc_connection_t\n\n /// Creates a new instance for sending progress updates to the client.\n /// - Parameter message: The XPC message that contains the endpoint to connect to.\n public init?(message: XPCMessage) {\n guard let progressUpdateEndpoint = message.endpoint(key: .progressUpdateEndpoint) else {\n return nil\n }\n endpointConnection = xpc_connection_create_from_endpoint(progressUpdateEndpoint)\n xpc_connection_set_event_handler(endpointConnection) { _ in }\n // This connection will be closed by the client.\n xpc_connection_activate(endpointConnection)\n }\n\n /// Performs a progress update.\n /// - Parameter events: The events that represent the update.\n public func handler(_ events: [ProgressUpdateEvent]) async {\n let object = xpc_dictionary_create(nil, nil, 0)\n let replyMessage = XPCMessage(object: object)\n for event in events {\n switch event {\n case .setDescription(let description):\n replyMessage.set(key: .progressUpdateSetDescription, value: description)\n case .setSubDescription(let subDescription):\n replyMessage.set(key: .progressUpdateSetSubDescription, value: subDescription)\n case .setItemsName(let itemsName):\n replyMessage.set(key: .progressUpdateSetItemsName, value: itemsName)\n case .addTasks(let tasks):\n replyMessage.set(key: .progressUpdateAddTasks, value: tasks)\n case .setTasks(let tasks):\n replyMessage.set(key: .progressUpdateSetTasks, value: tasks)\n case .addTotalTasks(let totalTasks):\n replyMessage.set(key: .progressUpdateAddTotalTasks, value: totalTasks)\n case .setTotalTasks(let totalTasks):\n replyMessage.set(key: .progressUpdateSetTotalTasks, value: totalTasks)\n case .addSize(let size):\n replyMessage.set(key: .progressUpdateAddSize, value: size)\n case .setSize(let size):\n replyMessage.set(key: .progressUpdateSetSize, value: size)\n case .addTotalSize(let totalSize):\n replyMessage.set(key: .progressUpdateAddTotalSize, value: totalSize)\n case .setTotalSize(let totalSize):\n replyMessage.set(key: .progressUpdateSetTotalSize, value: totalSize)\n case .addItems(let items):\n replyMessage.set(key: .progressUpdateAddItems, value: items)\n case .setItems(let items):\n replyMessage.set(key: .progressUpdateSetItems, value: items)\n case .addTotalItems(let totalItems):\n replyMessage.set(key: .progressUpdateAddTotalItems, value: totalItems)\n case .setTotalItems(let totalItems):\n replyMessage.set(key: .progressUpdateSetTotalItems, value: totalItems)\n case .custom(_):\n // Unsupported progress update event in XPC communication.\n break\n }\n }\n xpc_connection_send_message(endpointConnection, replyMessage.underlying)\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport ContainerizationError\nimport Foundation\nimport TerminalProgress\n\nextension Application {\n struct NetworkCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a new network\")\n\n @Argument(help: \"Network name\")\n var name: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let config = NetworkConfiguration(id: self.name, mode: .nat)\n let state = try await ClientNetwork.create(configuration: config)\n print(state.id)\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerStart.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport TerminalProgress\n\nextension Application {\n struct ContainerStart: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"start\",\n abstract: \"Start a container\")\n\n @Flag(name: .shortAndLong, help: \"Attach STDOUT/STDERR\")\n var attach = false\n\n @Flag(name: .shortAndLong, help: \"Attach container's STDIN\")\n var interactive = false\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Container's ID\")\n var containerID: String\n\n func run() async throws {\n var exitCode: Int32 = 127\n\n let progressConfig = try ProgressConfig(\n description: \"Starting container\"\n )\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n\n let container = try await ClientContainer.get(id: containerID)\n let process = try await container.bootstrap()\n\n progress.set(description: \"Starting init process\")\n let detach = !self.attach && !self.interactive\n do {\n let io = try ProcessIO.create(\n tty: container.configuration.initProcess.terminal,\n interactive: self.interactive,\n detach: detach\n )\n progress.finish()\n if detach {\n try await process.start(io.stdio)\n defer {\n try? io.close()\n }\n try io.closeAfterStart()\n print(self.containerID)\n return\n }\n\n exitCode = try await Application.handleProcess(io: io, process: process)\n } catch {\n try? await container.stop()\n\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(.internalError, message: \"failed to start container: \\(error)\")\n }\n throw ArgumentParser.ExitCode(exitCode)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/String+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension String {\n public func fromISO8601DateString(to: String) -> String? {\n if let date = fromISO8601Date() {\n let dateformatTo = DateFormatter()\n dateformatTo.dateFormat = to\n return dateformatTo.string(from: date)\n }\n return nil\n }\n\n public func fromISO8601Date() -> Date? {\n let iso8601DateFormatter = ISO8601DateFormatter()\n iso8601DateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]\n return iso8601DateFormatter.date(from: self)\n }\n\n public func isAbsolutePath() -> Bool {\n self.starts(with: \"/\")\n }\n\n /// Trim all `char` characters from the left side of the string. Stops when encountering a character that\n /// doesn't match `char`.\n mutating public func trimLeft(char: Character) {\n if self.isEmpty {\n return\n }\n var trimTo = 0\n for c in self {\n if char != c {\n break\n }\n trimTo += 1\n }\n if trimTo != 0 {\n let index = self.index(self.startIndex, offsetBy: trimTo)\n self = String(self[index...])\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/Int+Formatted.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Int {\n func formattedTime() -> String {\n let secondsInMinute = 60\n let secondsInHour = secondsInMinute * 60\n let secondsInDay = secondsInHour * 24\n\n let days = self / secondsInDay\n let hours = (self % secondsInDay) / secondsInHour\n let minutes = (self % secondsInHour) / secondsInMinute\n let seconds = self % secondsInMinute\n\n var components = [String]()\n if days > 0 {\n components.append(\"\\(days)d\")\n }\n if hours > 0 || days > 0 {\n components.append(\"\\(hours)h\")\n }\n if minutes > 0 || hours > 0 || days > 0 {\n components.append(\"\\(minutes)m\")\n }\n components.append(\"\\(seconds)s\")\n return components.joined(separator: \" \")\n }\n\n func formattedNumber() -> String {\n let formatter = NumberFormatter()\n formatter.numberStyle = .decimal\n guard let formattedNumber = formatter.string(from: NSNumber(value: self)) else {\n return \"\"\n }\n return formattedNumber\n }\n}\n"], ["/container/Sources/CLI/Builder/BuilderStop.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct BuilderStop: AsyncParsableCommand {\n public static var configuration: CommandConfiguration {\n var config = CommandConfiguration()\n config.commandName = \"stop\"\n config._superCommandName = \"builder\"\n config.abstract = \"Stop builder\"\n config.usage = \"\\n\\t builder stop\"\n config.helpNames = NameSpecification(arrayLiteral: .customShort(\"h\"), .customLong(\"help\"))\n return config\n }\n\n func run() async throws {\n do {\n let container = try await ClientContainer.get(id: \"buildkit\")\n try await container.stop()\n } catch {\n if error is ContainerizationError {\n if (error as? ContainerizationError)?.code == .notFound {\n print(\"builder is not running\")\n return\n }\n }\n throw error\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/ContainerizationProgressAdapter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport TerminalProgress\n\npublic enum ContainerizationProgressAdapter: ProgressAdapter {\n public static func handler(from progressUpdate: ProgressUpdateHandler?) -> ProgressHandler? {\n guard let progressUpdate else {\n return nil\n }\n return { events in\n var updateEvents = [ProgressUpdateEvent]()\n for event in events {\n if event.event == \"add-items\" {\n if let items = event.value as? Int {\n updateEvents.append(.addItems(items))\n }\n } else if event.event == \"add-total-items\" {\n if let totalItems = event.value as? Int {\n updateEvents.append(.addTotalItems(totalItems))\n }\n } else if event.event == \"add-size\" {\n if let size = event.value as? Int64 {\n updateEvents.append(.addSize(size))\n }\n } else if event.event == \"add-total-size\" {\n if let totalSize = event.value as? Int64 {\n updateEvents.append(.addTotalSize(totalSize))\n }\n }\n }\n await progressUpdate(updateEvents)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/SignalThreshold.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\n\n// For a lot of programs, they don't install their own signal handlers for\n// SIGINT/SIGTERM which poses a somewhat fun problem for containers. Because\n// they're pid 1 (doesn't matter that it isn't in the \"root\" pid namespace)\n// the default actions for SIGINT and SIGTERM now are nops. So this type gives\n// us an opportunity to set a threshold for a certain number of signals received\n// so we can have an escape hatch for users to escape their horrific mistake\n// of cat'ing /dev/urandom by exit(1)'ing :)\npublic struct SignalThreshold {\n private let threshold: Int\n private let signals: [Int32]\n private var t: Task<(), Never>?\n\n public init(\n threshold: Int,\n signals: [Int32],\n ) {\n self.threshold = threshold\n self.signals = signals\n }\n\n // Start kicks off the signal watching. The passed in handler will\n // run only once upon passing the threshold number passed in the constructor.\n mutating public func start(handler: @Sendable @escaping () -> Void) {\n let signals = self.signals\n let threshold = self.threshold\n self.t = Task {\n var received = 0\n let signalHandler = AsyncSignalHandler.create(notify: signals)\n for await _ in signalHandler.signals {\n received += 1\n if received == threshold {\n handler()\n signalHandler.cancel()\n return\n }\n }\n }\n }\n\n public func stop() {\n self.t?.cancel()\n }\n}\n"], ["/container/Sources/SocketForwarder/GlueHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIOCore\n\nfinal class GlueHandler {\n\n private var partner: GlueHandler?\n\n private var context: ChannelHandlerContext?\n\n private var pendingRead: Bool = false\n\n private init() {}\n}\n\nextension GlueHandler {\n static func matchedPair() -> (GlueHandler, GlueHandler) {\n let first = GlueHandler()\n let second = GlueHandler()\n\n first.partner = second\n second.partner = first\n\n return (first, second)\n }\n}\n\nextension GlueHandler {\n private func partnerWrite(_ data: NIOAny) {\n self.context?.write(data, promise: nil)\n }\n\n private func partnerFlush() {\n self.context?.flush()\n }\n\n private func partnerWriteEOF() {\n self.context?.close(mode: .output, promise: nil)\n }\n\n private func partnerCloseFull() {\n self.context?.close(promise: nil)\n }\n\n private func partnerBecameWritable() {\n if self.pendingRead {\n self.pendingRead = false\n self.context?.read()\n }\n }\n\n private var partnerWritable: Bool {\n self.context?.channel.isWritable ?? false\n }\n}\n\nextension GlueHandler: ChannelDuplexHandler {\n typealias InboundIn = NIOAny\n typealias OutboundIn = NIOAny\n typealias OutboundOut = NIOAny\n\n func handlerAdded(context: ChannelHandlerContext) {\n self.context = context\n }\n\n func handlerRemoved(context: ChannelHandlerContext) {\n self.context = nil\n self.partner = nil\n }\n\n func channelRead(context: ChannelHandlerContext, data: NIOAny) {\n self.partner?.partnerWrite(data)\n }\n\n func channelReadComplete(context: ChannelHandlerContext) {\n self.partner?.partnerFlush()\n }\n\n func channelInactive(context: ChannelHandlerContext) {\n self.partner?.partnerCloseFull()\n }\n\n func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {\n if let event = event as? ChannelEvent, case .inputClosed = event {\n // We have read EOF.\n self.partner?.partnerWriteEOF()\n }\n }\n\n func errorCaught(context: ChannelHandlerContext, error: Error) {\n self.partner?.partnerCloseFull()\n }\n\n func channelWritabilityChanged(context: ChannelHandlerContext) {\n if context.channel.isWritable {\n self.partner?.partnerBecameWritable()\n }\n }\n\n func read(context: ChannelHandlerContext) {\n if let partner = self.partner, partner.partnerWritable {\n context.read()\n } else {\n self.pendingRead = true\n }\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerKill.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Darwin\n\nextension Application {\n struct ContainerKill: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kill\",\n abstract: \"Kill one or more running containers\")\n\n @Option(name: .shortAndLong, help: \"Signal to send the container(s)\")\n var signal: String = \"KILL\"\n\n @Flag(name: .shortAndLong, help: \"Kill all running containers\")\n var all = false\n\n @Argument(help: \"Container IDs\")\n var containerIDs: [String] = []\n\n @OptionGroup\n var global: Flags.Global\n\n func validate() throws {\n if containerIDs.count == 0 && !all {\n throw ContainerizationError(.invalidArgument, message: \"no containers specified and --all not supplied\")\n }\n if containerIDs.count > 0 && all {\n throw ContainerizationError(.invalidArgument, message: \"explicitly supplied container IDs conflicts with the --all flag\")\n }\n }\n\n mutating func run() async throws {\n let set = Set(containerIDs)\n\n var containers = try await ClientContainer.list().filter { c in\n c.status == .running\n }\n if !self.all {\n containers = containers.filter { c in\n set.contains(c.id)\n }\n }\n\n let signalNumber = try Signals.parseSignal(signal)\n\n var failed: [String] = []\n for container in containers {\n do {\n try await container.kill(signalNumber)\n print(container.id)\n } catch {\n log.error(\"failed to kill container \\(container.id): \\(error)\")\n failed.append(container.id)\n }\n }\n if failed.count > 0 {\n throw ContainerizationError(.internalError, message: \"kill failed for one or more containers\")\n }\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/Int64+Formatted.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Int64 {\n func formattedSize() -> String {\n let formattedSize = ByteCountFormatter.string(fromByteCount: self, countStyle: .binary)\n return formattedSize\n }\n\n func formattedSizeSpeed(from startTime: DispatchTime) -> String {\n let elapsedTimeNanoseconds = DispatchTime.now().uptimeNanoseconds - startTime.uptimeNanoseconds\n let elapsedTimeSeconds = Double(elapsedTimeNanoseconds) / 1_000_000_000\n guard elapsedTimeSeconds > 0 else {\n return \"0 B/s\"\n }\n\n let speed = Double(self) / elapsedTimeSeconds\n let formattedSpeed = ByteCountFormatter.string(fromByteCount: Int64(speed), countStyle: .binary)\n return \"\\(formattedSpeed)/s\"\n }\n}\n"], ["/container/Sources/CLI/Image/ImagePush.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\nimport TerminalProgress\n\nextension Application {\n struct ImagePush: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"push\",\n abstract: \"Push an image\"\n )\n\n @OptionGroup\n var global: Flags.Global\n\n @OptionGroup\n var registry: Flags.Registry\n\n @OptionGroup\n var progressFlags: Flags.Progress\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Argument var reference: String\n\n func run() async throws {\n var p: Platform?\n if let platform {\n p = try Platform(from: platform)\n }\n\n let scheme = try RequestScheme(registry.scheme)\n let image = try await ClientImage.get(reference: reference)\n\n var progressConfig: ProgressConfig\n if progressFlags.disableProgressUpdates {\n progressConfig = try ProgressConfig(disableProgressUpdates: progressFlags.disableProgressUpdates)\n } else {\n progressConfig = try ProgressConfig(\n description: \"Pushing image \\(image.reference)\",\n itemsName: \"blobs\",\n showItems: true,\n showSpeed: false,\n ignoreSmallSize: true\n )\n }\n let progress = ProgressBar(config: progressConfig)\n defer {\n progress.finish()\n }\n progress.start()\n _ = try await image.push(platform: p, scheme: scheme, progressUpdate: progress.handler)\n progress.finish()\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ImageDescription.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\n\n/// A type that represents an OCI image that can be used with sandboxes or containers.\npublic struct ImageDescription: Sendable, Codable {\n /// The public reference/name of the image.\n public let reference: String\n /// The descriptor of the image.\n public let descriptor: Descriptor\n\n public var digest: String { descriptor.digest }\n public var mediaType: String { descriptor.mediaType }\n\n public init(reference: String, descriptor: Descriptor) {\n self.reference = reference\n self.descriptor = descriptor\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkMode.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Networking mode that applies to client containers.\npublic enum NetworkMode: String, Codable, Sendable {\n /// NAT networking mode.\n /// Containers do not have routable IPs, and the host performs network\n /// address translation to allow containers to reach external services.\n case nat = \"nat\"\n}\n\nextension NetworkMode {\n public init() {\n self = .nat\n }\n\n public init?(_ value: String) {\n switch value.lowercased() {\n case \"nat\": self = .nat\n default: return nil\n }\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressTheme.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A theme for progress bar.\npublic protocol ProgressTheme: Sendable {\n /// The icons used to represent a spinner.\n var spinner: [String] { get }\n /// The icon used to represent a progress bar.\n var bar: String { get }\n /// The icon used to indicate that a progress bar finished.\n var done: String { get }\n}\n\npublic struct DefaultProgressTheme: ProgressTheme {\n public let spinner = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"]\n public let bar = \"█\"\n public let done = \"✔\"\n}\n\nextension ProgressTheme {\n func getSpinnerIcon(_ iteration: Int) -> String {\n spinner[iteration % spinner.count]\n }\n}\n"], ["/container/Sources/DNSServer/DNSServer+Handle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport NIOCore\nimport NIOPosix\n\nextension DNSServer {\n /// Handles the DNS request.\n /// - Parameters:\n /// - outbound: The NIOAsyncChannelOutboundWriter for which to respond.\n /// - packet: The request packet.\n func handle(\n outbound: NIOAsyncChannelOutboundWriter>,\n packet: inout AddressedEnvelope\n ) async throws {\n let chunkSize = 512\n var data = Data()\n\n self.log?.debug(\"reading data\")\n while packet.data.readableBytes > 0 {\n if let chunk = packet.data.readBytes(length: min(chunkSize, packet.data.readableBytes)) {\n data.append(contentsOf: chunk)\n }\n }\n\n self.log?.debug(\"deserializing message\")\n let query = try Message(deserialize: data)\n self.log?.debug(\"processing query: \\(query.questions)\")\n\n // always send response\n let responseData: Data\n do {\n self.log?.debug(\"awaiting processing\")\n var response =\n try await handler.answer(query: query)\n ?? Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n\n // no responses\n if response.answers.isEmpty {\n response.returnCode = .nonExistentDomain\n }\n\n self.log?.debug(\"serializing response\")\n responseData = try response.serialize()\n } catch {\n self.log?.error(\"error processing message from \\(query): \\(error)\")\n let response = Message(\n id: query.id,\n type: .response,\n returnCode: .notImplemented,\n questions: query.questions,\n answers: []\n )\n responseData = try response.serialize()\n }\n\n self.log?.debug(\"sending response for \\(query.id)\")\n let rData = ByteBuffer(bytes: responseData)\n try? await outbound.write(AddressedEnvelope(remoteAddress: packet.remoteAddress, data: rData))\n\n self.log?.debug(\"processing done\")\n\n }\n}\n"], ["/container/Sources/CLI/Image/ImageInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ImageInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more images\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Images to inspect\")\n var images: [String]\n\n func run() async throws {\n var printable = [any Codable]()\n let result = try await ClientImage.get(names: images)\n let notFound = result.error\n for image in result.images {\n guard !Utility.isInfraImage(name: image.reference) else {\n continue\n }\n printable.append(try await image.details())\n }\n if printable.count > 0 {\n print(try printable.jsonArray())\n }\n if notFound.count > 0 {\n throw ContainerizationError(.notFound, message: \"Images: \\(notFound.joined(separator: \"\\n\"))\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/PublishPort.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The network protocols available for port forwarding.\npublic enum PublishProtocol: String, Sendable, Codable {\n case tcp = \"tcp\"\n case udp = \"udp\"\n\n /// Initialize a protocol with to default value, `.tcp`.\n public init() {\n self = .tcp\n }\n\n /// Initialize a protocol value from the provided string.\n public init?(_ value: String) {\n switch value.lowercased() {\n case \"tcp\": self = .tcp\n case \"udp\": self = .udp\n default: return nil\n }\n }\n}\n\n/// Specifies internet port forwarding from host to container.\npublic struct PublishPort: Sendable, Codable {\n /// The IP address of the proxy listener on the host\n public let hostAddress: String\n\n /// The port number of the proxy listener on the host\n public let hostPort: Int\n\n /// The port number of the container listener\n public let containerPort: Int\n\n /// The network protocol for the proxy\n public let proto: PublishProtocol\n\n /// Creates a new port forwarding specification.\n public init(hostAddress: String, hostPort: Int, containerPort: Int, proto: PublishProtocol) {\n self.hostAddress = hostAddress\n self.hostPort = hostPort\n self.containerPort = containerPort\n self.proto = proto\n }\n}\n"], ["/container/Sources/DNSServer/Handlers/CompositeResolver.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Delegates a query sequentially to handlers until one provides a response.\npublic struct CompositeResolver: DNSHandler {\n private let handlers: [DNSHandler]\n\n public init(handlers: [DNSHandler]) {\n self.handlers = handlers\n }\n\n public func answer(query: Message) async throws -> Message? {\n for handler in self.handlers {\n if let response = try await handler.answer(query: query) {\n return response\n }\n }\n\n return nil\n }\n}\n"], ["/container/Sources/SocketForwarder/TCPForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\nimport NIO\nimport NIOFoundationCompat\n\npublic struct TCPForwarder: SocketForwarder {\n private let proxyAddress: SocketAddress\n\n private let serverAddress: SocketAddress\n\n private let eventLoopGroup: any EventLoopGroup\n\n private let log: Logger?\n\n public init(\n proxyAddress: SocketAddress,\n serverAddress: SocketAddress,\n eventLoopGroup: any EventLoopGroup,\n log: Logger? = nil\n ) throws {\n self.proxyAddress = proxyAddress\n self.serverAddress = serverAddress\n self.eventLoopGroup = eventLoopGroup\n self.log = log\n }\n\n public func run() throws -> EventLoopFuture {\n self.log?.trace(\"frontend - creating listener\")\n\n let bootstrap = ServerBootstrap(group: self.eventLoopGroup)\n .serverChannelOption(ChannelOptions.socket(.init(SOL_SOCKET), .init(SO_REUSEADDR)), value: 1)\n .childChannelOption(ChannelOptions.socket(.init(SOL_SOCKET), .init(SO_REUSEADDR)), value: 1)\n .childChannelInitializer { channel in\n channel.eventLoop.makeCompletedFuture {\n try channel.pipeline.syncOperations.addHandler(\n ConnectHandler(serverAddress: self.serverAddress, log: log)\n )\n }\n }\n\n return\n bootstrap\n .bind(to: self.proxyAddress)\n .flatMap { $0.eventLoop.makeSucceededFuture(SocketForwarderResult(channel: $0)) }\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerNetworkService\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct NetworkInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more networks\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Networks to inspect\")\n var networks: [String]\n\n func run() async throws {\n let objects: [any Codable] = try await ClientNetwork.list().filter {\n networks.contains($0.id)\n }.map {\n PrintableNetwork($0)\n }\n print(try objects.jsonArray())\n }\n }\n}\n"], ["/container/Sources/ContainerBuild/TerminalCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct TerminalCommand: Codable {\n let commandType: String\n let code: String\n let rows: UInt16\n let cols: UInt16\n\n enum CodingKeys: String, CodingKey {\n case commandType = \"command_type\"\n case code\n case rows\n case cols\n }\n\n init(rows: UInt16, cols: UInt16) {\n self.commandType = \"terminal\"\n self.code = \"winch\"\n self.rows = rows\n self.cols = cols\n }\n\n init() {\n self.commandType = \"terminal\"\n self.code = \"ack\"\n self.rows = 0\n self.cols = 0\n }\n\n func json() throws -> String? {\n let encoder = JSONEncoder()\n let data = try encoder.encode(self)\n return data.base64EncodedString().trimmingCharacters(in: CharacterSet(charactersIn: \"=\"))\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSCreate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\n\nextension Application {\n struct DNSCreate: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"create\",\n abstract: \"Create a local DNS domain for containers (must run as an administrator)\"\n )\n\n @Argument(help: \"the local domain name\")\n var domainName: String\n\n func run() async throws {\n let resolver: HostDNSResolver = HostDNSResolver()\n do {\n try resolver.createDomain(name: domainName)\n print(domainName)\n } catch let error as ContainerizationError {\n throw error\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot create domain (try sudo?)\")\n }\n\n do {\n try HostDNSResolver.reinitialize()\n } catch {\n throw ContainerizationError(.invalidState, message: \"mDNSResponder restart failed, run `sudo killall -HUP mDNSResponder` to deactivate domain\")\n }\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkState.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct NetworkStatus: Codable, Sendable {\n /// The address allocated for the network if no subnet was specified at\n /// creation time; otherwise, the subnet from the configuration.\n public let address: String\n /// The gateway IPv4 address.\n public let gateway: String\n\n public init(\n address: String,\n gateway: String\n ) {\n self.address = address\n self.gateway = gateway\n }\n\n}\n\n/// The configuration and runtime attributes for a network.\npublic enum NetworkState: Codable, Sendable {\n // The network has been configured.\n case created(NetworkConfiguration)\n // The network is running.\n case running(NetworkConfiguration, NetworkStatus)\n\n public var state: String {\n switch self {\n case .created: \"created\"\n case .running: \"running\"\n }\n }\n\n public var id: String {\n switch self {\n case .created(let configuration): configuration.id\n case .running(let configuration, _): configuration.id\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Configuration parameters for network creation.\npublic struct NetworkConfiguration: Codable, Sendable, Identifiable {\n /// A unique identifier for the network\n public let id: String\n\n /// The network type\n public let mode: NetworkMode\n\n /// The preferred CIDR address for the subnet, if specified\n public let subnet: String?\n\n /// Creates a network configuration\n public init(\n id: String,\n mode: NetworkMode,\n subnet: String? = nil\n ) {\n self.id = id\n self.mode = mode\n self.subnet = subnet\n }\n}\n"], ["/container/Sources/Helpers/RuntimeLinux/IsolatedInterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerSandboxService\nimport ContainerXPC\nimport Containerization\n\n/// Isolated container network interface strategy. This strategy prohibits\n/// container to container networking, but it is the only approach that\n/// works for macOS Sequoia.\nstruct IsolatedInterfaceStrategy: InterfaceStrategy {\n public func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) -> Interface {\n let gateway = interfaceIndex == 0 ? attachment.gateway : nil\n return NATInterface(address: attachment.address, gateway: gateway)\n }\n}\n"], ["/container/Sources/CLI/Codable+JSON.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport Foundation\n\nextension [any Codable] {\n func jsonArray() throws -> String {\n \"[\\(try self.map { String(data: try JSONEncoder().encode($0), encoding: .utf8)! }.joined(separator: \",\"))]\"\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerSnapshot.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\n\n/// A snapshot of a container along with its configuration\n/// and any runtime state information.\npublic struct ContainerSnapshot: Codable, Sendable {\n /// The configuration of the container.\n public let configuration: ContainerConfiguration\n /// The runtime status of the container.\n public let status: RuntimeStatus\n /// Network interfaces attached to the sandbox that are provided to the container.\n public let networks: [Attachment]\n\n public init(\n configuration: ContainerConfiguration,\n status: RuntimeStatus,\n networks: [Attachment]\n ) {\n self.configuration = configuration\n self.status = status\n self.networks = networks\n }\n}\n"], ["/container/Sources/CLI/Container/ContainerInspect.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\nimport SwiftProtobuf\n\nextension Application {\n struct ContainerInspect: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display information about one or more containers\")\n\n @OptionGroup\n var global: Flags.Global\n\n @Argument(help: \"Containers to inspect\")\n var containers: [String]\n\n func run() async throws {\n let objects: [any Codable] = try await ClientContainer.list().filter {\n containers.contains($0.id)\n }.map {\n PrintableContainer($0)\n }\n print(try objects.jsonArray())\n }\n }\n}\n"], ["/container/Sources/ContainerClient/SandboxSnapshot.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\n\n/// A snapshot of a sandbox and its resources.\npublic struct SandboxSnapshot: Codable, Sendable {\n /// The runtime status of the sandbox.\n public let status: RuntimeStatus\n /// Network attachments for the sandbox.\n public let networks: [Attachment]\n /// Containers placed in the sandbox.\n public let containers: [ContainerSnapshot]\n\n public init(\n status: RuntimeStatus,\n networks: [Attachment],\n containers: [ContainerSnapshot]\n ) {\n self.status = status\n self.networks = networks\n self.containers = containers\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSDelete.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct DNSDelete: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"delete\",\n abstract: \"Delete a local DNS domain (must run as an administrator)\",\n aliases: [\"rm\"]\n )\n\n @Argument(help: \"the local domain name\")\n var domainName: String\n\n func run() async throws {\n let resolver = HostDNSResolver()\n do {\n try resolver.deleteDomain(name: domainName)\n print(domainName)\n } catch {\n throw ContainerizationError(.invalidState, message: \"cannot create domain (try sudo?)\")\n }\n\n do {\n try HostDNSResolver.reinitialize()\n } catch {\n throw ContainerizationError(.invalidState, message: \"mDNSResponder restart failed, run `sudo killall -HUP mDNSResponder` to deactivate domain\")\n }\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/PublishSocket.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\n/// Represents a socket that should be published from container to host.\npublic struct PublishSocket: Sendable, Codable {\n /// The path to the socket in the container.\n public var containerPath: URL\n\n /// The path where the socket should appear on the host.\n public var hostPath: URL\n\n /// File permissions for the socket on the host.\n public var permissions: FilePermissions?\n\n public init(\n containerPath: URL,\n hostPath: URL,\n permissions: FilePermissions? = nil\n ) {\n self.containerPath = containerPath\n self.hostPath = hostPath\n self.permissions = permissions\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ClientHealthCheck.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\nimport Foundation\n\npublic enum ClientHealthCheck {\n static let serviceIdentifier = \"com.apple.container.apiserver\"\n}\n\nextension ClientHealthCheck {\n private static func newClient() -> XPCClient {\n XPCClient(service: serviceIdentifier)\n }\n\n public static func ping(timeout: Duration? = .seconds(5)) async throws {\n let client = Self.newClient()\n let request = XPCMessage(route: .ping)\n try await client.send(request, responseTimeout: timeout)\n }\n}\n"], ["/container/Sources/Services/ContainerImagesService/Client/ImageServiceXPCRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerXPC\n\npublic enum ImagesServiceXPCRoute: String {\n case imageList\n case imagePull\n case imagePush\n case imageTag\n case imageBuild\n case imageDelete\n case imageSave\n case imageLoad\n case imagePrune\n\n case contentGet\n case contentDelete\n case contentClean\n case contentIngestStart\n case contentIngestComplete\n case contentIngestCancel\n\n case imageUnpack\n case snapshotDelete\n case snapshotGet\n}\n\nextension XPCMessage {\n public init(route: ImagesServiceXPCRoute) {\n self.init(route: route.rawValue)\n }\n}\n\n#endif\n"], ["/container/Sources/ContainerClient/Array+Dedupe.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension Array where Element: Hashable {\n func dedupe() -> [Element] {\n var elems = Set()\n return filter { elems.insert($0).inserted }\n }\n}\n"], ["/container/Sources/SocketForwarder/SocketForwarderResult.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIO\n\npublic struct SocketForwarderResult: Sendable {\n private let channel: any Channel\n\n public init(channel: Channel) {\n self.channel = channel\n }\n\n public var proxyAddress: SocketAddress? { self.channel.localAddress }\n\n public func close() {\n self.channel.eventLoop.execute {\n _ = channel.close()\n }\n }\n\n public func wait() async throws {\n try await self.channel.closeFuture.get()\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/Attachment.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A snapshot of a network interface allocated to a sandbox.\npublic struct Attachment: Codable, Sendable {\n /// The network ID associated with the attachment.\n public let network: String\n /// The hostname associated with the attachment.\n public let hostname: String\n /// The subnet CIDR, where the address is the container interface IPv4 address.\n public let address: String\n /// The IPv4 gateway address.\n public let gateway: String\n\n public init(network: String, hostname: String, address: String, gateway: String) {\n self.network = network\n self.hostname = hostname\n self.address = address\n self.gateway = gateway\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSDefault.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\n\nextension Application {\n struct DNSDefault: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"default\",\n abstract: \"Set or unset the default local DNS domain\",\n subcommands: [\n DefaultSetCommand.self,\n DefaultUnsetCommand.self,\n DefaultInspectCommand.self,\n ]\n )\n\n struct DefaultSetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"set\",\n abstract: \"Set the default local DNS domain\"\n\n )\n\n @Argument(help: \"the default `--domain-name` to use for the `create` or `run` command\")\n var domainName: String\n\n func run() async throws {\n ClientDefaults.set(value: domainName, key: .defaultDNSDomain)\n print(domainName)\n }\n }\n\n struct DefaultUnsetCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"unset\",\n abstract: \"Unset the default local DNS domain\",\n aliases: [\"clear\"]\n )\n\n func run() async throws {\n ClientDefaults.unset(key: .defaultDNSDomain)\n print(\"Unset the default local DNS domain\")\n }\n }\n\n struct DefaultInspectCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"inspect\",\n abstract: \"Display the default local DNS domain\"\n )\n\n func run() async throws {\n print(ClientDefaults.getOptional(key: .defaultDNSDomain) ?? \"\")\n }\n }\n }\n}\n"], ["/container/Sources/CLI/Registry/Logout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Containerization\nimport ContainerizationOCI\n\nextension Application {\n struct Logout: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: \"Log out from a registry\")\n\n @Argument(help: \"Registry server name\")\n var registry: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let keychain = KeychainHelper(id: Constants.keychainID)\n let r = Reference.resolveDomain(domain: registry)\n try keychain.delete(domain: r)\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerCreateOptions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct ContainerCreateOptions: Codable, Sendable {\n public let autoRemove: Bool\n\n public init(autoRemove: Bool) {\n self.autoRemove = autoRemove\n }\n\n public static let `default` = ContainerCreateOptions(autoRemove: false)\n\n}\n"], ["/container/Sources/ContainerClient/Arch.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum Arch: String {\n case arm64, amd64\n\n public static func hostArchitecture() -> Arch {\n #if arch(arm64)\n return .arm64\n #elseif arch(x86_64)\n return .amd64\n #endif\n }\n}\n"], ["/container/Sources/Services/ContainerSandboxService/InterfaceStrategy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerNetworkService\nimport ContainerXPC\nimport Containerization\n\n/// A strategy for mapping network attachment information to a network interface.\npublic protocol InterfaceStrategy: Sendable {\n /// Map a client network attachment request to a network interface specification.\n ///\n /// - Parameters:\n /// - attachment: General attachment information that is common\n /// for all networks.\n /// - interfaceIndex: The zero-based index of the interface.\n /// - additionalData: If present, attachment information that is\n /// specific for the network to which the container will attach.\n ///\n /// - Returns: An XPC message with no parameters.\n func toInterface(attachment: Attachment, interfaceIndex: Int, additionalData: XPCMessage?) throws -> Interface\n}\n"], ["/container/Sources/CLI/Image/ImageTag.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\n\nextension Application {\n struct ImageTag: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"tag\",\n abstract: \"Tag an image\")\n\n @Argument(help: \"SOURCE_IMAGE[:TAG]\")\n var source: String\n\n @Argument(help: \"TARGET_IMAGE[:TAG]\")\n var target: String\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let existing = try await ClientImage.get(reference: source)\n let targetReference = try ClientImage.normalizeReference(target)\n try await existing.tag(new: targetReference)\n print(\"Image \\(source) tagged as \\(target)\")\n }\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/Network.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerXPC\n\n/// Defines common characteristics and operations for a network.\npublic protocol Network: Sendable {\n // Contains network attributes while the network is running\n var state: NetworkState { get async }\n\n // Use implementation-dependent network attributes\n nonisolated func withAdditionalData(_ handler: (XPCMessage?) throws -> Void) throws\n\n // Start the network\n func start() async throws\n}\n"], ["/container/Sources/CLI/Image/ImagePrune.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\n\nextension Application {\n struct ImagePrune: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"prune\",\n abstract: \"Remove unreferenced and dangling images\")\n\n @OptionGroup\n var global: Flags.Global\n\n func run() async throws {\n let (_, size) = try await ClientImage.pruneImages()\n let formatter = ByteCountFormatter()\n let freed = formatter.string(fromByteCount: Int64(size))\n print(\"Cleaned unreferenced images and snapshots\")\n print(\"Reclaimed \\(freed) in disk space\")\n }\n }\n}\n"], ["/container/Sources/ContainerClient/Core/ContainerStopOptions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct ContainerStopOptions: Sendable, Codable {\n public let timeoutInSeconds: Int32\n public let signal: Int32\n\n public static let `default` = ContainerStopOptions(\n timeoutInSeconds: 5,\n signal: SIGTERM\n )\n\n public init(timeoutInSeconds: Int32, signal: Int32) {\n self.timeoutInSeconds = timeoutInSeconds\n self.signal = signal\n }\n}\n"], ["/container/Sources/ContainerClient/SandboxRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum SandboxRoutes: String {\n /// Bootstrap the sandbox instance and create the init process.\n case bootstrap = \"com.apple.container.sandbox/bootstrap\"\n /// Create a process in the sandbox.\n case createProcess = \"com.apple.container.sandbox/createProcess\"\n /// Start a process in the sandbox.\n case start = \"com.apple.container.sandbox/start\"\n /// Stop the sandbox.\n case stop = \"com.apple.container.sandbox/stop\"\n /// Return the current state of the sandbox.\n case state = \"com.apple.container.sandbox/state\"\n /// Kill a process in the sandbox.\n case kill = \"com.apple.container.sandbox/kill\"\n /// Resize the pty of a process in the sandbox.\n case resize = \"com.apple.container.sandbox/resize\"\n /// Wait on a process in the sandbox.\n case wait = \"com.apple.container.sandbox/wait\"\n /// Execute a new process in the sandbox.\n case exec = \"com.apple.container.sandbox/exec\"\n /// Dial a vsock port in the sandbox.\n case dial = \"com.apple.container.sandbox/dial\"\n}\n"], ["/container/Sources/APIServer/HealthCheck/HealthCheckHarness.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerClient\nimport ContainerXPC\nimport Containerization\nimport Logging\n\nactor HealthCheckHarness {\n private let log: Logger\n\n public init(log: Logger) {\n self.log = log\n }\n\n @Sendable\n func ping(_ message: XPCMessage) async -> XPCMessage {\n message.reply()\n }\n}\n"], ["/container/Sources/CLI/Builder/Builder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct BuilderCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"builder\",\n abstract: \"Manage an image builder instance\",\n subcommands: [\n BuilderStart.self,\n BuilderStatus.self,\n BuilderStop.self,\n BuilderDelete.self,\n ])\n }\n}\n"], ["/container/Sources/CLI/System/DNS/DNSList.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerClient\nimport Foundation\n\nextension Application {\n struct DNSList: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"list\",\n abstract: \"List local DNS domains\",\n aliases: [\"ls\"]\n )\n\n func run() async throws {\n let resolver: HostDNSResolver = HostDNSResolver()\n let domains = resolver.listDomains()\n print(domains.joined(separator: \"\\n\"))\n }\n\n }\n}\n"], ["/container/Sources/TerminalProgress/ProgressUpdate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum ProgressUpdateEvent: Sendable {\n case setDescription(String)\n case setSubDescription(String)\n case setItemsName(String)\n case addTasks(Int)\n case setTasks(Int)\n case addTotalTasks(Int)\n case setTotalTasks(Int)\n case addItems(Int)\n case setItems(Int)\n case addTotalItems(Int)\n case setTotalItems(Int)\n case addSize(Int64)\n case setSize(Int64)\n case addTotalSize(Int64)\n case setTotalSize(Int64)\n case custom(String)\n}\n\npublic typealias ProgressUpdateHandler = @Sendable (_ events: [ProgressUpdateEvent]) async -> Void\n\npublic protocol ProgressAdapter {\n associatedtype T\n static func handler(from progressUpdate: ProgressUpdateHandler?) -> (@Sendable ([T]) async -> Void)?\n}\n"], ["/container/Sources/TerminalProgress/StandardError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct StandardError {\n func write(_ string: String) {\n if let data = string.data(using: .utf8) {\n FileHandle.standardError.write(data)\n }\n }\n}\n"], ["/container/Sources/CLI/System/SystemDNS.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationError\nimport Foundation\n\nextension Application {\n struct SystemDNS: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"dns\",\n abstract: \"Manage local DNS domains\",\n subcommands: [\n DNSCreate.self,\n DNSDelete.self,\n DNSList.self,\n DNSDefault.self,\n ]\n )\n }\n}\n"], ["/container/Sources/CLI/Container/ProcessUtils.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerClient\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n static func ensureRunning(container: ClientContainer) throws {\n if container.status != .running {\n throw ContainerizationError(.invalidState, message: \"container \\(container.id) is not running\")\n }\n }\n}\n"], ["/container/Sources/DNSServer/DNSHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Protocol for implementing custom DNS handlers.\npublic protocol DNSHandler {\n /// Attempt to answer a DNS query\n /// - Parameter query: the query message\n /// - Throws: a server failure occurred during the query\n /// - Returns: The response message for the query, or nil if the request\n /// is not within the scope of the handler.\n func answer(query: Message) async throws -> Message?\n}\n"], ["/container/Sources/CLI/Registry/RegistryCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct RegistryCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"registry\",\n abstract: \"Manage registry configurations\",\n subcommands: [\n Login.self,\n Logout.self,\n RegistryDefault.self,\n ],\n aliases: [\"r\"]\n )\n }\n}\n"], ["/container/Sources/CLI/Network/NetworkCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct NetworkCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"network\",\n abstract: \"Manage container networks\",\n subcommands: [\n NetworkCreate.self,\n NetworkDelete.self,\n NetworkList.self,\n NetworkInspect.self,\n ],\n aliases: [\"n\"]\n )\n }\n}\n"], ["/container/Sources/CLI/System/SystemCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct SystemCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"system\",\n abstract: \"Manage system components\",\n subcommands: [\n SystemDNS.self,\n SystemLogs.self,\n SystemStart.self,\n SystemStop.self,\n SystemStatus.self,\n SystemKernel.self,\n ],\n aliases: [\"s\"]\n )\n }\n}\n"], ["/container/Sources/CLI/System/SystemKernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct SystemKernel: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kernel\",\n abstract: \"Manage the default kernel configuration\",\n subcommands: [\n KernelSet.self\n ]\n )\n }\n}\n"], ["/container/Sources/CLI/Container/ContainersCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct ContainersCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"containers\",\n abstract: \"Manage containers\",\n subcommands: [\n ContainerCreate.self,\n ContainerDelete.self,\n ContainerExec.self,\n ContainerInspect.self,\n ContainerKill.self,\n ContainerList.self,\n ContainerLogs.self,\n ContainerStart.self,\n ContainerStop.self,\n ],\n aliases: [\"container\", \"c\"]\n )\n }\n}\n"], ["/container/Sources/CLI/Image/ImagesCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nextension Application {\n struct ImagesCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"images\",\n abstract: \"Manage images\",\n subcommands: [\n ImageInspect.self,\n ImageList.self,\n ImageLoad.self,\n ImagePrune.self,\n ImagePull.self,\n ImagePush.self,\n ImageRemove.self,\n ImageSave.self,\n ImageTag.self,\n ],\n aliases: [\"image\", \"i\"]\n )\n }\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkRoutes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum NetworkRoutes: String {\n /// Return the current state of the network.\n case state = \"com.apple.container.network/state\"\n /// Allocates parameters for attaching a sandbox to the network.\n case allocate = \"com.apple.container.network/allocate\"\n /// Deallocates parameters for attaching a sandbox to the network.\n case deallocate = \"com.apple.container.network/deallocate\"\n /// Disables the allocator if no sandboxes are attached.\n case disableAllocator = \"com.apple.container.network/disableAllocator\"\n /// Retrieves the allocation for a hostname.\n case lookup = \"com.apple.container.network/lookup\"\n}\n"], ["/container/Sources/Services/ContainerNetworkService/UserDefaults+Container.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension UserDefaults {\n public static let appSuiteName = \"com.apple.container.defaults\"\n}\n"], ["/container/Sources/ContainerClient/Core/Constants.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum Constants {\n public static let keychainID = \"com.apple.container\"\n}\n"], ["/container/Sources/ContainerClient/Core/RuntimeStatus.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Runtime status for a sandbox or container.\npublic enum RuntimeStatus: String, CaseIterable, Sendable, Codable {\n /// The object is in an unknown status.\n case unknown\n /// The object is currently stopped.\n case stopped\n /// The object is currently running.\n case running\n /// The object is currently stopping.\n case stopping\n}\n"], ["/container/Sources/ContainerClient/ContainerEvents.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\npublic enum ContainerEvent: Sendable, Codable {\n case containerStart(id: String)\n case containerExit(id: String, exitCode: Int64)\n}\n"], ["/container/Sources/SocketForwarder/SocketForwarder.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport NIO\n\npublic protocol SocketForwarder: Sendable {\n func run() throws -> EventLoopFuture\n}\n"], ["/container/Sources/Services/ContainerNetworkService/NetworkKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum NetworkKeys: String {\n case additionalData\n case allocatorDisabled\n case attachment\n case hostname\n case network\n case state\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:21:52", "created_task_model": "DeepSeek-R1", "function_skeleton": "public func getMachServices ( instanceId: String? = nil ) -> [String] { }", "code_description": "This code segment functions to: Generate a list of service identifiers by combining configured service types with hierarchical naming components, including optional instance differentiation, and assemble them into a structured collection."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\n public func getMachServices(instanceId: String? = nil) -> [String] {\n guard let services = config.servicesConfig?.services else {\n return []\n }\n \n let serviceTypes = Set(services.map { $0.type })\n return serviceTypes.compactMap { type in\n getMachService(instanceId: instanceId, type: type)\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 03-22-46"}, "editdistance_info": {"edit_distance": 33.8843, "calculate_time": "2025-08-21 03:22:46", "true_code_clean": "public func getMachServices(instanceId: String? = nil) -> [String] {\n guard let config = self.config.servicesConfig else {\n return []\n }\n var services = [String]()\n for service in config.services {\n let serviceName: String\n if let instanceId {\n serviceName = \"\\(Self.machServicePrefix)\\(service.type.rawValue).\\(name).\\(instanceId)\"\n } else {\n serviceName = \"\\(Self.machServicePrefix)\\(service.type.rawValue).\\(name)\"\n }\n services.append(serviceName)\n }\n return services\n }", "predict_code_clean": "public func getMachServices(instanceId: String? = nil) -> [String] {\n guard let services = config.servicesConfig?.services else {\n return []\n }\n let serviceTypes = Set(services.map { $0.type })\n return serviceTypes.compactMap { type in\n getMachService(instanceId: instanceId, type: type)\n }\n }"}}