mocker icon indicating copy to clipboard operation
mocker copied to clipboard

`cp` copies binary files as empty and cannot copy directories; `container cp` does both

Open PixCZ opened this issue 1 month ago • 1 comments

mocker version: 0.9.7 (Homebrew) — macOS 27, container 1.5.0, arm64; reproduced on 0.9.6 and again on 0.9.7. Code references are against main @ 4402015.

Summary

cp is emulated with exec cat / exec -i tee through a UTF-8 String (ContainerEngine.swift:567-600). A binary file therefore arrives as an empty file with exit code 0, a directory fails with "failed to read", and a dir/ destination cannot be used. container cp 1.5.0 handles all of these natively (directory trees, binary content, file -> dir/).

Reproduction

$ mocker run -d --name c alpine:3.20 sleep 120
$ mocker exec c dd if=/dev/urandom of=/tmp/blob.bin bs=1k count=50
$ mocker cp c:/tmp/blob.bin ./blob.bin; echo $?
0
$ wc -c < ./blob.bin
0                      # Docker: 51200
$ mocker exec c mkdir -p /data/sub
$ mocker cp c:/data ./out/
Error: Error response from daemon: failed to read /data from container c

compose cp goes through the same two functions (Compose.swift:1842-1849) and additionally does nothing at all when neither side is service:path.

Proposed behaviour (what the branch does)

cp and compose cp resolve the container name and hand the transfer to container cp; the two exec-based helpers go away. Copying between two containers is rejected with Docker's message.

After, against container 1.5.0: a directory tree comes back intact, a 100 kB random file keeps its md5 both ways, and cp c:/file ./dir/ lands in the directory.

$ mocker cp c:/data ./out/ && find ./out -type f
./out/data/a.txt
./out/data/blob.bin
./out/data/sub/b.txt
$ mocker cp c:/x c:/y
Error: Error response from daemon: copying between containers is not supported

A tested fix is on my fork, branch fix/cp-native (compare); the diff is below. Happy to open it as a PR if you want it, or you can take it from here — see the note in # about coordinating.

Proposed fix: git diff main...fix/cp-native
diff --git a/Sources/Mocker/Commands/Compose.swift b/Sources/Mocker/Commands/Compose.swift
index efff34b..fd15bde 100644
--- a/Sources/Mocker/Commands/Compose.swift
+++ b/Sources/Mocker/Commands/Compose.swift
@@ -1834,21 +1834,18 @@ struct ComposeCp: AsyncParsableCommand {
 
         let engine = try ContainerEngine(config: config)
 
-        // Parse service:path format
-        let parts = source.split(separator: ":", maxSplits: 1).map(String.init)
-        if parts.count == 2 && !parts[0].hasPrefix("/") && !parts[0].hasPrefix(".") {
-            // Copy from container
-            let containerName = "\(project)-\(parts[0])-\(index)"
-            let data = try await engine.copyFromContainer(containerName, path: parts[1])
-            try data.write(to: URL(fileURLWithPath: destination))
-        } else {
-            let dstParts = destination.split(separator: ":", maxSplits: 1).map(String.init)
-            if dstParts.count == 2 && !dstParts[0].hasPrefix("/") {
-                let containerName = "\(project)-\(dstParts[0])-\(index)"
-                let data = try Data(contentsOf: URL(fileURLWithPath: source))
-                try await engine.copyToContainer(containerName, path: dstParts[1], data: data)
-            }
+        // `service:path` on either side; the service maps to its `<index>` container.
+        let (srcService, srcPath) = Cp.parseCpArg(source)
+        let (dstService, dstPath) = Cp.parseCpArg(destination)
+        guard srcService != nil || dstService != nil else {
+            throw MockerError.operationFailed("copying requires one of source or destination to be a service")
+        }
+        func side(_ service: String?, _ path: String) async throws -> String {
+            guard let service else { return path }
+            let containerName = "\(project)-\(service)-\(index)"
+            return "\(try await engine.inspect(containerName).name):\(path)"
         }
+        try await engine.copy(from: try await side(srcService, srcPath), to: try await side(dstService, dstPath))
     }
 }
 
diff --git a/Sources/Mocker/Commands/Cp.swift b/Sources/Mocker/Commands/Cp.swift
index 93f5950..c536a5c 100644
--- a/Sources/Mocker/Commands/Cp.swift
+++ b/Sources/Mocker/Commands/Cp.swift
@@ -27,23 +27,32 @@ struct Cp: AsyncParsableCommand {
         let engine = try ContainerEngine(config: config)
 
         // Parse source and destination: "container:path" or just "path"
-        let (srcContainer, srcPath) = parseCpArg(source)
-        let (dstContainer, dstPath) = parseCpArg(destination)
-
-        if let containerName = srcContainer {
-            // Copy from container to host
-            let data = try await engine.copyFromContainer(containerName, path: srcPath)
-            try data.write(to: URL(fileURLWithPath: dstPath))
-        } else if let containerName = dstContainer {
-            // Copy from host to container
-            let data = try Data(contentsOf: URL(fileURLWithPath: srcPath))
-            try await engine.copyToContainer(containerName, path: dstPath, data: data)
-        } else {
+        let (srcContainer, srcPath) = Self.parseCpArg(source)
+        let (dstContainer, dstPath) = Self.parseCpArg(destination)
+
+        switch (srcContainer, dstContainer) {
+        case (nil, nil):
             throw MockerError.operationFailed("copying requires one of source or destination to be a container")
+        case (.some, .some):
+            throw MockerError.operationFailed("copying between containers is not supported")
+        default:
+            break
         }
+
+        // `container cp` wants the runtime's container name; resolve Docker names,
+        // IDs and prefixes to it the same way every other command does.
+        let src = try await resolved(srcContainer, srcPath, engine)
+        let dst = try await resolved(dstContainer, dstPath, engine)
+        try await engine.copy(from: src, to: dst)
+    }
+
+    private func resolved(_ container: String?, _ path: String, _ engine: ContainerEngine) async throws -> String {
+        guard let container else { return path }
+        return "\(try await engine.inspect(container).name):\(path)"
     }
 
-    private func parseCpArg(_ arg: String) -> (String?, String) {
+    /// Split `container:path` from a plain host path. Pure; safe to unit-test.
+    static func parseCpArg(_ arg: String) -> (String?, String) {
         // Format: "container:path" or just "path"
         let parts = arg.split(separator: ":", maxSplits: 1).map(String.init)
         if parts.count == 2 && !parts[0].hasPrefix("/") && !parts[0].hasPrefix(".") {
diff --git a/Sources/MockerKit/Container/ContainerEngine.swift b/Sources/MockerKit/Container/ContainerEngine.swift
index f4cc69d..0b4f054 100644
--- a/Sources/MockerKit/Container/ContainerEngine.swift
+++ b/Sources/MockerKit/Container/ContainerEngine.swift
@@ -564,38 +564,16 @@ public actor ContainerEngine {
 
     // MARK: - Copy
 
-    public func copyFromContainer(_ identifier: String, path: String) async throws -> Data {
-        let container = try await resolve(identifier)
-        let (output, exitCode) = try await runCLI(["exec", container.name, "cat", path])
-        guard exitCode == 0 else {
-            throw MockerError.operationFailed("failed to read \(path) from container \(identifier)")
-        }
-        return Data(output.utf8)
-    }
-
-    public func copyToContainer(_ identifier: String, path: String, data: Data) async throws {
-        let container = try await resolve(identifier)
-        // Write data via stdin pipe to tee — avoids shell interpolation (injection-safe)
-        let content = String(data: data, encoding: .utf8) ?? ""
-        let process = Process()
-        process.executableURL = URL(fileURLWithPath: Self.containerCLI)
-        process.arguments = ["exec", "-i", container.name, "tee", "--", path]
-        let inputPipe = Pipe()
-        process.standardInput = inputPipe
-        // Discard tee stdout (it echoes input) — use /dev/null to avoid pipe-buffer hang
-        process.standardOutput = FileHandle.nullDevice
-        process.standardError = FileHandle.nullDevice
-        try process.run()
-        inputPipe.fileHandleForWriting.write(Data(content.utf8))
-        inputPipe.fileHandleForWriting.closeFile()
-        // Use async-safe termination handler instead of blocking waitUntilExit
-        let exitCode = await withCheckedContinuation { (continuation: CheckedContinuation<Int32, Never>) in
-            process.terminationHandler = { p in
-                continuation.resume(returning: p.terminationStatus)
-            }
-        }
+    /// Copy between the host and a container through `container cp`, which handles
+    /// directories, binary content and `dir/` destinations natively. The container side
+    /// of `source`/`destination` is `<runtime name>:<path>`; the other side is a host path.
+    public func copy(from source: String, to destination: String) async throws {
+        let (output, exitCode) = try await runCLI(["cp", source, destination])
         guard exitCode == 0 else {
-            throw MockerError.operationFailed("failed to write to \(path) in container \(identifier)")
+            // The CLI's own "Error: " lead-in would otherwise be printed twice.
+            var message = output.trimmingCharacters(in: .whitespacesAndNewlines)
+            if message.hasPrefix("Error: ") { message.removeFirst("Error: ".count) }
+            throw MockerError.operationFailed(message)
         }
     }
 

PixCZ avatar Oct 21 '26 08:10 PixCZ

Shipped in 0.9.8 (ref #109), checked with the Homebrew build on container 1.5.0. Thanks @BluPix!

us avatar Oct 25 '26 12:10 us