From 030fa535a98c5a83cf91194467a48ca54a9ff6ce Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Thu, 3 Dec 2026 21:52:35 +0100 Subject: [PATCH 1/4] Stabilize named pipe sockets: honor soTimeout, use IOExceptions, fix EOF handling - NamedPipeSocket: timeout-aware streams on top of the async channel, honor connect timeout, report isConnected/isBound, no-op half-close - NamedPipeJniSocket: mutable soTimeout shared with source/sink, pass connect timeout through - NamedPipeUtils: throw IOException/SocketTimeoutException instead of RuntimeException, classify read/write errors at the call site, drain cancelled overlapped I/O before returning Co-Authored-By: Claude Opus 5.5 --- .../client/filesocket/NamedPipeJniSocket.java | 34 +++- .../client/filesocket/NamedPipeSink.java | 24 +-- .../client/filesocket/NamedPipeSocket.java | 170 +++++++++++++++- .../client/filesocket/NamedPipeSource.java | 31 +-- .../client/filesocket/NamedPipeUtils.java | 192 ++++++++++-------- .../filesocket/NamedPipeSocketTest.java | 22 ++ 6 files changed, 329 insertions(+), 144 deletions(-) diff --git a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocket.java b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocket.java index cee0fb6..7eace65 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocket.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocket.java @@ -8,6 +8,7 @@ import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; +import java.net.SocketException; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; @@ -31,7 +32,10 @@ public class NamedPipeJniSocket extends FileSocket { private BufferedSource source; private BufferedSink sink; - private final Timeout ioTimeout = new Timeout().timeout(1000, TimeUnit.MILLISECONDS); + // shared and mutable: setSoTimeout() updates this instance, which NamedPipeSource/NamedPipeSink + // read from on every call, so a timeout change takes effect immediately without recreating the streams. + // 0 means no timeout (blocks indefinitely), matching java.net.Socket's default SO_TIMEOUT. + private final Timeout ioTimeout = new Timeout(); @Override public void connect(SocketAddress endpoint, int timeout) throws IOException { @@ -42,20 +46,42 @@ public void connect(SocketAddress endpoint, int timeout) throws IOException { InetSocketAddress inetSocketAddress = (InetSocketAddress) endpoint; InetAddress address = inetSocketAddress.getAddress(); String socketPath = decodeHostname(address); - connect(socketPath); + connect(socketPath, timeout); } - void connect(String socketPath) { + void connect(String socketPath) throws IOException { + connect(socketPath, 10_000); + } + + void connect(String socketPath, int timeoutMs) throws IOException { socketPath = socketPath.replace("/", "\\"); log.debug("connect via '{}'...", socketPath); - handle = NamedPipeUtils.connect(socketPath, 10_000, 500, 50); + handle = NamedPipeUtils.connect(socketPath, timeoutMs, 500, 50); connected = true; source = Okio.buffer(new NamedPipeSource(handle, ioTimeout)); sink = Okio.buffer(new NamedPipeSink(handle, ioTimeout)); } + @Override + public void setSoTimeout(int timeout) throws SocketException { + if (timeout < 0) { + throw new IllegalArgumentException("timeout can't be negative"); + } + if (timeout == 0) { + ioTimeout.clearTimeout(); + } + else { + ioTimeout.timeout(timeout, TimeUnit.MILLISECONDS); + } + } + + @Override + public int getSoTimeout() throws SocketException { + return (int) (ioTimeout.timeoutNanos() / 1_000_000); + } + @Override public InputStream getInputStream() throws IOException { ensureOpen(); diff --git a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSink.java b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSink.java index 5d2a4c5..d43ab18 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSink.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSink.java @@ -4,10 +4,7 @@ import org.jetbrains.annotations.NotNull; -import com.sun.jna.platform.win32.Kernel32; -import com.sun.jna.platform.win32.WinError; import com.sun.jna.platform.win32.WinNT; -import com.sun.jna.ptr.IntByReference; import okio.Buffer; import okio.Sink; @@ -16,11 +13,11 @@ public class NamedPipeSink implements Sink { private final WinNT.HANDLE handle; - private final int timeoutMillis; + private final Timeout timeout; public NamedPipeSink(WinNT.HANDLE handle, Timeout timeout) { this.handle = handle; - this.timeoutMillis = (int) timeout.timeoutNanos() / 1000; + this.timeout = timeout; } @Override @@ -37,21 +34,8 @@ public void write(@NotNull Buffer source, long byteCount) throws IOException { } byte[] data = source.readByteArray(byteCount); - IntByReference bytesWritten = new IntByReference(); - //boolean ok = NamedPipeUtils.writeFromBuffer(handle, data, data.length, bytesWritten); - boolean ok = NamedPipeUtils.writeOverlapped(handle, data, data.length, bytesWritten, timeoutMillis); - if (!ok) { - int err = Kernel32.INSTANCE.GetLastError(); - if (err == WinError.ERROR_OPERATION_ABORTED) { - // Expected when CancelIoEx() is called during close() - return; - } - throw new IOException("Failed to write to Named Pipe. WinError=" + err); - } - - if (bytesWritten.getValue() <= 0) { - throw new IOException("No bytes written to Named Pipe"); - } + int timeoutMillis = (int) (timeout.timeoutNanos() / 1_000_000); + NamedPipeUtils.writeOverlapped(handle, data, data.length, timeoutMillis); } @Override diff --git a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSocket.java b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSocket.java index 75cf847..801bfa1 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSocket.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSocket.java @@ -5,15 +5,22 @@ import java.io.IOException; import java.io.InputStream; +import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; -import java.nio.channels.Channels; import java.nio.file.FileSystemException; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; public class NamedPipeSocket extends FileSocket { @@ -22,14 +29,19 @@ public class NamedPipeSocket extends FileSocket { private AsynchronousFileByteChannel channel; private final AtomicBoolean closed = new AtomicBoolean(false); + private final AtomicBoolean connected = new AtomicBoolean(false); private InputStream inputStream; private OutputStream outputStream; + private volatile int soTimeout = 0; @Override public void connect(SocketAddress endpoint, int timeout) throws IOException { if (!(endpoint instanceof InetSocketAddress)) { throw new IllegalArgumentException("Expected endpoint to be a InetSocketAddress"); } + if (timeout < 0) { + throw new IllegalArgumentException("timeout can't be negative"); + } InetSocketAddress inetSocketAddress = (InetSocketAddress) endpoint; InetAddress address = inetSocketAddress.getAddress(); @@ -38,8 +50,8 @@ public void connect(SocketAddress endpoint, int timeout) throws IOException { socketPath = socketPath.replace("/", "\\\\"); - long startedAt = System.currentTimeMillis(); - timeout = Math.max(timeout, 10_000); + // timeout == 0 means "wait indefinitely", matching java.net.Socket#connect + long deadline = timeout == 0 ? Long.MAX_VALUE : System.currentTimeMillis() + timeout; while (true) { try { channel = new AsynchronousFileByteChannel( @@ -49,11 +61,12 @@ public void connect(SocketAddress endpoint, int timeout) throws IOException { StandardOpenOption.WRITE ) ); + connected.set(true); break; } catch (FileSystemException e) { - if (System.currentTimeMillis() - startedAt >= timeout) { - throw new RuntimeException(e); + if (System.currentTimeMillis() >= deadline) { + throw new SocketTimeoutException("Connect timed out after " + timeout + "ms: " + e.getMessage()); } else { // requires a bit more code and the net.java.dev.jna:jna dependency @@ -62,16 +75,62 @@ public void connect(SocketAddress endpoint, int timeout) throws IOException { Thread.sleep(100); } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + throw new InterruptedIOException("Connect interrupted"); } } } } } + @Override + public synchronized void setSoTimeout(int timeout) throws SocketException { + if (timeout < 0) { + throw new IllegalArgumentException("timeout can't be negative"); + } + this.soTimeout = timeout; + } + + @Override + public synchronized int getSoTimeout() throws SocketException { + return soTimeout; + } + + @Override + public boolean isConnected() { + // The base Socket implementation tracks this via its own SocketImpl, which our connect() override + // never touches -- so the inherited isConnected() would always report false. That in turn breaks + // shutdownOutput()/shutdownInput() (their default Socket implementation requires isConnected()), + // which e.g. OkHttp calls when finishing writing to a hijacked attach/exec stream. + return connected.get(); + } + + @Override + public boolean isBound() { + return connected.get(); + } + + @Override + public void shutdownOutput() throws SocketException { + // Named pipes have no OS-level half-close (unlike a TCP socket's SO_SHUTDOWN_WR), so there's nothing + // to actually shut down here; treat it as a no-op rather than delegating to the (nonexistent) SocketImpl. + // The read side stays open, matching the intent of a half-close. + if (!connected.get()) { + throw new SocketException("Socket is not connected"); + } + } + + @Override + public void shutdownInput() throws SocketException { + if (!connected.get()) { + throw new SocketException("Socket is not connected"); + } + } + @Override public InputStream getInputStream() { if (inputStream == null) { - this.inputStream = Channels.newInputStream(channel); + this.inputStream = new TimeoutAwareInputStream(); } return inputStream; } @@ -79,7 +138,7 @@ public InputStream getInputStream() { @Override public OutputStream getOutputStream() { if (outputStream == null) { - this.outputStream = Channels.newOutputStream(channel); + this.outputStream = new TimeoutAwareOutputStream(); } return outputStream; } @@ -98,11 +157,100 @@ public void close() throws IOException { if (channel != null) { channel.close(); } - if (inputStream != null) { - inputStream.close(); + } + + /** + * {@link java.nio.channels.Channels#newInputStream(java.nio.channels.AsynchronousByteChannel)} blocks on + * {@link Future#get()} with no timeout at all, so {@link #setSoTimeout(int)} (and e.g. OkHttp's readTimeout, + * which relies on it) would silently have no effect and a stalled/idle hijacked stream would block forever. + * This reimplements the stream on top of {@link Future#get(long, TimeUnit)} instead, honoring soTimeout. + */ + private class TimeoutAwareInputStream extends InputStream { + + @Override + public int read() throws IOException { + byte[] b = new byte[1]; + int n = read(b, 0, 1); + return n == -1 ? -1 : (b[0] & 0xff); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + if (len == 0) { + return 0; + } + ByteBuffer buffer = ByteBuffer.wrap(b, off, len); + Future future = channel.read(buffer); + int timeout = soTimeout; + try { + return timeout > 0 + ? future.get(timeout, TimeUnit.MILLISECONDS) + : future.get(); + } + catch (TimeoutException e) { + // best effort: the underlying ReadFile may already be past the point of no return and could still + // complete (consuming pipe bytes) after we've given up waiting for it. Treat the connection as + // unusable afterwards, like other transports do on a read timeout. + future.cancel(true); + throw new SocketTimeoutException("Read timed out after " + timeout + "ms"); + } + catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof IOException) { + throw (IOException) cause; + } + throw new IOException(cause); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new InterruptedIOException("Read interrupted"); + } + } + + @Override + public void close() throws IOException { + NamedPipeSocket.this.close(); } - if (outputStream != null) { - outputStream.close(); + } + + private class TimeoutAwareOutputStream extends OutputStream { + + @Override + public void write(int b) throws IOException { + write(new byte[]{(byte) b}, 0, 1); + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + if (len == 0) { + return; + } + ByteBuffer buffer = ByteBuffer.wrap(b, off, len); + while (buffer.hasRemaining()) { + Future future = channel.write(buffer); + try { + int written = future.get(); + if (written <= 0) { + throw new IOException("No bytes written to Named Pipe"); + } + } + catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof IOException) { + throw (IOException) cause; + } + throw new IOException(cause); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new InterruptedIOException("Write interrupted"); + } + } + } + + @Override + public void close() throws IOException { + NamedPipeSocket.this.close(); } } } diff --git a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSource.java b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSource.java index de55372..80ade36 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSource.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSource.java @@ -1,11 +1,10 @@ package de.gesellix.docker.client.filesocket; +import java.io.IOException; + import org.jetbrains.annotations.NotNull; -import com.sun.jna.platform.win32.Kernel32; -import com.sun.jna.platform.win32.WinError; import com.sun.jna.platform.win32.WinNT; -import com.sun.jna.ptr.IntByReference; import okio.Buffer; import okio.Source; @@ -14,15 +13,15 @@ public class NamedPipeSource implements Source { private final WinNT.HANDLE handle; - private final int timeoutMillis; + private final Timeout timeout; public NamedPipeSource(WinNT.HANDLE handle, Timeout timeout) { this.handle = handle; - this.timeoutMillis = (int) (timeout.timeoutNanos() / 1_000_000); + this.timeout = timeout; } @Override - public long read(@NotNull Buffer sink, long byteCount) { + public long read(@NotNull Buffer sink, long byteCount) throws IOException { if (byteCount < 0) { throw new IllegalArgumentException("Invalid buffer size: " + byteCount); } @@ -35,25 +34,15 @@ public long read(@NotNull Buffer sink, long byteCount) { } byte[] data = new byte[(int) byteCount]; - IntByReference bytesRead = new IntByReference(); - //boolean ok = NamedPipeUtils.readToBuffer(handle, data, bytesRead); - boolean ok = NamedPipeUtils.readOverlapped(handle, data, bytesRead, timeoutMillis); - if (!ok) { - int err = Kernel32.INSTANCE.GetLastError(); - if (err == WinError.ERROR_OPERATION_ABORTED) { - // Expected when CancelIoEx() is called during close() - return -1; - } - return err == 0 ? 0 : -1; // Other read error - } - - if (bytesRead.getValue() <= 0) { + int timeoutMillis = (int) (timeout.timeoutNanos() / 1_000_000); + int bytesRead = NamedPipeUtils.readOverlapped(handle, data, timeoutMillis); + if (bytesRead < 0) { return -1; // EOF } - sink.write(data, 0, bytesRead.getValue()); + sink.write(data, 0, bytesRead); sink.flush(); - return bytesRead.getValue(); + return bytesRead; } @NotNull diff --git a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java index f728a51..d8dafb0 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java @@ -2,6 +2,10 @@ import static com.sun.jna.platform.win32.WinBase.INVALID_HANDLE_VALUE; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.net.SocketTimeoutException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,13 +23,20 @@ public final class NamedPipeUtils { private NamedPipeUtils() { } + /** + * @param totalTimeoutMs overall deadline for the connect attempt, e.g. 15000. 0 means wait indefinitely. + * @param busyWaitCapMs cap for a single WaitNamedPipe call, e.g. 2000 + * @param notFoundBaseSleepMs initial backoff while the pipe doesn't exist yet, e.g. 50 + */ public static WinNT.HANDLE connect( String path, - int totalTimeoutMs, // z.B. 15000 - int busyWaitCapMs, // z.B. 2000 (max für einzelne WaitNamedPipe) - int notFoundBaseSleepMs // z.B. 50 - ) { - final long deadline = System.nanoTime() + (long) totalTimeoutMs * 1_000_000L; + int totalTimeoutMs, + int busyWaitCapMs, + int notFoundBaseSleepMs + ) throws IOException { + final long deadline = totalTimeoutMs == 0 + ? Long.MAX_VALUE + : System.nanoTime() + (long) totalTimeoutMs * 1_000_000L; int notFoundBackoff = notFoundBaseSleepMs; WinNT.HANDLE h; @@ -41,140 +52,148 @@ public static WinNT.HANDLE connect( ); if (!WinBase.INVALID_HANDLE_VALUE.equals(h)) { - // Verbunden – Handle ist sofort nutzbar (für Overlapped-I/O) + // connected, handle can be used for overlapped I/O right away log.debug("connected"); return h; } int err = Kernel32.INSTANCE.GetLastError(); - long remainingMs = Math.max(0, (deadline - System.nanoTime()) / 1_000_000L); + long remainingMs = deadline == Long.MAX_VALUE ? Long.MAX_VALUE : Math.max(0, (deadline - System.nanoTime()) / 1_000_000L); if (remainingMs == 0) { - log.debug("Connect timed out; last error=" + err); - throw new RuntimeException("Connect timed out; last error=" + err); + throw new SocketTimeoutException("Connect timed out after " + totalTimeoutMs + "ms; last error=" + err); } if (err == WinError.ERROR_PIPE_BUSY) { - log.debug("Pipe busy; last error=" + err); - // Warte, aber maximal busyWaitCapMs und nie länger als verbleibende Zeit + log.debug("Pipe busy; last error={}", err); + // wait, but at most busyWaitCapMs and never longer than the remaining time int to = (int) Math.min(remainingMs, busyWaitCapMs); boolean ok = Kernel32.INSTANCE.WaitNamedPipe(path, to); if (!ok) { - int e2 = Kernel32.INSTANCE.GetLastError(); // z.B. ERROR_SEM_TIMEOUT - if (e2 == WinError.ERROR_SEM_TIMEOUT && (deadline - System.nanoTime()) > 0) { - log.debug("Retry wait; last error=" + err); - continue; // Restzeit vorhanden → nochmal versuchen + int e2 = Kernel32.INSTANCE.GetLastError(); + if (e2 == WinError.ERROR_SEM_TIMEOUT && (deadline == Long.MAX_VALUE || (deadline - System.nanoTime()) > 0)) { + log.debug("Retry wait; last error={}", err); + continue; // time remaining -> retry } - throw new RuntimeException("WaitNamedPipe failed: " + e2); + throw new IOException("WaitNamedPipe failed: " + e2); } - // danach erneut versuchen + // try again afterward continue; } if (err == WinError.ERROR_FILE_NOT_FOUND) { - log.debug("File not found; last error=" + err); - // Server hat Pipe noch nicht erstellt → kurzer, exponentieller Backoff - int sleepMs = Math.min(notFoundBackoff, (int) remainingMs); + log.debug("File not found; last error={}", err); + // server hasn't created the pipe yet -> short, exponential backoff + long sleepMs = remainingMs == Long.MAX_VALUE ? notFoundBackoff : Math.min(notFoundBackoff, remainingMs); try { Thread.sleep(sleepMs); - } catch (InterruptedException ie) { + } + catch (InterruptedException ie) { Thread.currentThread().interrupt(); - throw new RuntimeException("Interrupted while waiting for pipe", ie); + throw new InterruptedIOException("Interrupted while waiting for pipe"); } - notFoundBackoff = Math.min(notFoundBackoff * 2, 250); // Deckel bei 250ms + notFoundBackoff = Math.min(notFoundBackoff * 2, 250); // cap at 250ms continue; } - // Andere Fehler → sofort abbrechen - throw new RuntimeException("CreateFile failed: " + err); + // any other error -> fail immediately + throw new IOException("CreateFile failed: " + err); } } - public static boolean readOverlapped(WinNT.HANDLE handle, byte[] buf, IntByReference bytesRead, int timeoutMillis) { + /** + * Overlapped read. Returns the number of bytes read (>= 1), or -1 on EOF (peer closed the pipe). + * Throws {@link SocketTimeoutException} if no data arrived within {@code timeoutMillis}, or {@link IOException} + * on any other I/O failure. + *

+ * The failure is classified right here, at the point where it happens, rather than leaving the caller to + * re-inspect {@code GetLastError()} afterward -- by then, other successful native calls (e.g. closing the + * event handle) may already have overwritten it. + */ + public static int readOverlapped(WinNT.HANDLE handle, byte[] buf, int timeoutMillis) throws IOException { WinNT.HANDLE evt = Kernel32.INSTANCE.CreateEvent(null, false, false, null); if (evt == null || WinBase.INVALID_HANDLE_VALUE.equals(evt)) { - throw new RuntimeException("CreateEvent failed: " + Kernel32.INSTANCE.GetLastError()); + throw new IOException("CreateEvent failed: " + Kernel32.INSTANCE.GetLastError()); } WinBase.OVERLAPPED overlapped = new WinBase.OVERLAPPED(); overlapped.hEvent = evt; -// overlapped.hEvent = evt; - overlapped.write(); // wichtig: Struktur in nativen Speicher schreiben - -// try { -// Thread.sleep(500); -// } catch (InterruptedException ie) { -// Thread.currentThread().interrupt(); -// throw new RuntimeException("Interrupted while waiting for pipe", ie); -// } + overlapped.write(); // write the struct to native memory try { + IntByReference bytesRead = new IntByReference(); boolean ok = Kernel32.INSTANCE.ReadFile(handle, buf, buf.length, null, overlapped); if (!ok) { int err = Kernel32.INSTANCE.GetLastError(); if (err != WinError.ERROR_IO_PENDING) { - log.debug("IO pending; last error=" + err); - return false; + if (err == WinError.ERROR_BROKEN_PIPE || err == WinError.ERROR_PIPE_NOT_CONNECTED || err == WinError.ERROR_NO_DATA) { + return -1; // EOF: pipe closed by peer + } + throw new IOException("ReadFile failed: " + err); } int wait = Kernel32.INSTANCE.WaitForSingleObject(evt, timeoutMillis); if (wait != WinBase.WAIT_OBJECT_0) { - log.debug("File not found; last error=" + err); + // Give up waiting and cancel the still-pending read. CancelIoEx only *requests* cancellation -- + // the kernel may still be about to write into `overlapped`/signal `evt` after it returns. We must + // block until that's truly settled (GetOverlappedResult with bWait=true) before this method + // returns and evt/overlapped become eligible for cleanup/GC; otherwise the OS can end up writing + // into freed native memory once the JNA-backed structures are gone, corrupting the heap. The + // drain call's own result/error is irrelevant here, we only need it to have happened. ExtendedKernel32.INSTANCE.CancelIoEx(handle, overlapped.getPointer()); - return false; + ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, overlapped, new IntByReference(), true); + throw new SocketTimeoutException("Named pipe read timed out after " + timeoutMillis + "ms"); } } - - // Ergebnis (auch bei synchroner Completion) abholen – ohne zusätzlich zu warten - if (!ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, overlapped, bytesRead, false)) { + // Pick up the result. bWait=true here: we already know the op is done (synchronous ReadFile) or its + // event is signaled (async path above), so this never actually blocks -- but bWait=false raced with + // the OS occasionally still settling the completion state right after a synchronous ReadFile, causing + // spurious ERROR_IO_INCOMPLETE (996). + if (!ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, overlapped, bytesRead, true)) { int err = Kernel32.INSTANCE.GetLastError(); - log.debug("Failed to get overlapped result; last error=" + err); - return false; + if (err == WinError.ERROR_OPERATION_ABORTED) { + return -1; // EOF: read was cancelled, e.g. via CancelIoEx() during close() + } + if (err == WinError.ERROR_BROKEN_PIPE || err == WinError.ERROR_PIPE_NOT_CONNECTED || err == WinError.ERROR_NO_DATA) { + return -1; // EOF: pipe closed by peer + } + throw new IOException("GetOverlappedResult(read) failed: " + err); } int n = bytesRead.getValue(); - log.debug("Bytes read: {}", bytesRead.getValue()); - // n == 0: EOF - return n >= 0; - } finally { + log.debug("Bytes read: {}", n); + return n == 0 ? -1 : n; // 0 bytes on a message-mode pipe read signals EOF + } + finally { closeHandle(evt); } } /** - * Overlapped-Write: schreibt buffer[0..len) vollständig oder wirft bei Timeout/Fehler. - * Beachtet Teil-Schreibungen und verwendet eine Gesamt-Deadline (timeoutMs). + * Overlapped write: writes buf[0..len) in full, or throws on timeout/error. Honors partial writes and + * uses an overall deadline (timeoutMs). timeoutMs == 0 means wait indefinitely. */ - public static boolean writeOverlapped( - WinNT.HANDLE handle, byte[] buf, int len, IntByReference bytesWritten, int timeoutMs) { + public static void writeOverlapped(WinNT.HANDLE handle, byte[] buf, int len, int timeoutMs) throws IOException { if (len < 0 || len > buf.length) { throw new IllegalArgumentException("len out of range"); } if (len == 0) { - return true; + return; } -// try { -// Thread.sleep(500); -// } catch (InterruptedException ie) { -// Thread.currentThread().interrupt(); -// throw new RuntimeException("Interrupted while waiting for pipe", ie); -// } - - final long deadline = System.nanoTime() + (long) timeoutMs * 1_000_000L; + final long deadline = timeoutMs == 0 ? Long.MAX_VALUE : System.nanoTime() + (long) timeoutMs * 1_000_000L; int totalWritten = 0; while (totalWritten < len) { - long remainingMs = (deadline - System.nanoTime()) / 1_000_000L; + long remainingMs = deadline == Long.MAX_VALUE ? Integer.MAX_VALUE : (deadline - System.nanoTime()) / 1_000_000L; if (remainingMs <= 0) { - throw new RuntimeException("writeOverlapped: overall timeout; written=" + totalWritten + "/" + len); + throw new SocketTimeoutException("writeOverlapped: overall timeout after " + timeoutMs + "ms; written=" + totalWritten + "/" + len); } - // Frisches auto-reset Event pro Operation WinNT.HANDLE evt = Kernel32.INSTANCE.CreateEvent(null, false, false, null); if (evt == null || WinBase.INVALID_HANDLE_VALUE.equals(evt)) { - throw new RuntimeException("CreateEvent failed: " + Kernel32.INSTANCE.GetLastError()); + throw new IOException("CreateEvent failed: " + Kernel32.INSTANCE.GetLastError()); } WinBase.OVERLAPPED ol = new WinBase.OVERLAPPED(); @@ -182,53 +201,50 @@ public static boolean writeOverlapped( ol.write(); try { + IntByReference bytesWritten = new IntByReference(); boolean ok = Kernel32.INSTANCE.WriteFile(handle, buf, len, null, ol); if (!ok) { int err = Kernel32.INSTANCE.GetLastError(); - // Sofortige Fehler if (err != WinError.ERROR_IO_PENDING) { if (err == WinError.ERROR_NO_DATA || err == WinError.ERROR_BROKEN_PIPE) { - throw new RuntimeException("writeOverlapped: pipe closed by peer"); + throw new IOException("writeOverlapped: pipe closed by peer"); } - throw new RuntimeException("WriteFile failed: " + err); + throw new IOException("WriteFile failed: " + err); } - // Asynchron → warten bis fertig oder Timeout int wait = Kernel32.INSTANCE.WaitForSingleObject(evt, (int) Math.min(Integer.MAX_VALUE, remainingMs)); if (wait != WinBase.WAIT_OBJECT_0) { - // Timeout/Fehler → I/O abbrechen + // see the matching comment in readOverlapped: must drain via GetOverlappedResult(bWait=true) + // before returning, or the kernel can still write into ol/evt after they're freed/GC'd. ExtendedKernel32.INSTANCE.CancelIoEx(handle, ol.getPointer()); - // Optional: warten, bis Cancel durch ist (nicht zwingend) - throw new RuntimeException("writeOverlapped: wait failed/timeout (Wait=" + wait + ")"); + ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, ol, new IntByReference(), true); + throw new SocketTimeoutException("writeOverlapped: wait timed out (wait=" + wait + ")"); } } - // Ergebnis abholen (blockiert nicht, weil Event signalisiert) - if (!ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, ol, bytesWritten, false)) { - int e2 = Kernel32.INSTANCE.GetLastError(); - if (e2 == WinError.ERROR_OPERATION_ABORTED) { - throw new RuntimeException("writeOverlapped: operation aborted"); + // bWait=true: same rationale as in readOverlapped -- avoids racing a synchronous WriteFile + // completion, which could otherwise surface a spurious ERROR_IO_INCOMPLETE (996). + if (!ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, ol, bytesWritten, true)) { + int err = Kernel32.INSTANCE.GetLastError(); + if (err == WinError.ERROR_OPERATION_ABORTED) { + throw new IOException("writeOverlapped: operation aborted"); } - throw new RuntimeException("GetOverlappedResult(write) failed: " + e2); + throw new IOException("GetOverlappedResult(write) failed: " + err); } int n = bytesWritten.getValue(); - if (n < 0) { - throw new RuntimeException("writeOverlapped: negative bytesWritten? " + n); - } - if (n == 0) { - // Möglich, wenn Gegenstelle zu ist → als Fehler behandeln - throw new RuntimeException("writeOverlapped: wrote 0 bytes, likely peer closed"); + if (n <= 0) { + // possible when the peer has closed its end + throw new IOException("writeOverlapped: wrote 0 bytes, likely peer closed"); } totalWritten += n; - } finally { + } + finally { closeHandle(evt); } } -// return totalWritten >= 0; - return true; } public static boolean readToBuffer(HANDLE handle, byte[] buf, IntByReference bytesRead) { diff --git a/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeSocketTest.java b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeSocketTest.java index 921a3b7..c270c88 100644 --- a/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeSocketTest.java +++ b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeSocketTest.java @@ -11,6 +11,7 @@ import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; +import java.net.SocketTimeoutException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Date; @@ -21,6 +22,8 @@ import java.util.function.Consumer; import static java.net.InetAddress.getByAddress; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class NamedPipeSocketTest { @@ -32,6 +35,25 @@ void canConnect() throws IOException { } } + @Test + @EnabledOnOs(OS.WINDOWS) + void readRespectsSoTimeout() throws IOException { + // Regression test: getInputStream() used to be backed by Channels.newInputStream(AsynchronousByteChannel), + // which blocks on Future#get() with no timeout at all, so setSoTimeout() was silently ignored and a read + // on an idle pipe hung forever. It must now throw SocketTimeoutException within roughly soTimeout millis. + try (NamedPipeSocket namedPipeSocket = new NamedPipeSocket()) { + namedPipeSocket.connect(new InetSocketAddress(getByAddress(namedPipeSocket.encodeHostname("//./pipe/docker_engine"), new byte[] {0, 0, 0, 0}), 0)); + namedPipeSocket.setSoTimeout(500); + InputStream is = namedPipeSocket.getInputStream(); + + long start = System.currentTimeMillis(); + // never send a request, so the pipe stays idle and the read has nothing to complete with + assertThrows(SocketTimeoutException.class, () -> is.read(new byte[1024])); + long duration = System.currentTimeMillis() - start; + assertTrue(duration < 5000, "timeout took way longer than the configured soTimeout: " + duration + "ms"); + } + } + @Test @EnabledOnOs(OS.WINDOWS) void testPlainHijacked() throws Exception { From 6de5c426438b6b8f728e04b0d4b9488c240064e8 Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Thu, 3 Dec 2026 22:00:17 +0100 Subject: [PATCH 2/4] Fix overlapped named pipe I/O: native buffers, stale OVERLAPPED, zero timeout - pass a JNA Memory buffer instead of byte[] to overlapped ReadFile/WriteFile: JNA only keeps a byte[] valid during the call, so pending I/O read from or wrote into released memory - pass the OVERLAPPED as raw pointer: passing the Structure made JNA write its stale fields (Internal=STATUS_PENDING) back before GetOverlappedResult, causing ERROR_IO_INCOMPLETE (bWait=false) or a hang (bWait=true) - map soTimeout 0 to INFINITE for WaitForSingleObject instead of "don't wait" - resume partial writes at the current offset instead of resending from 0 - keep data of a read that completed right before a timeout cancellation - add in-process pipe tests forcing pending reads/writes and soTimeout Co-Authored-By: Claude Opus 5.5 --- .../client/filesocket/ExtendedKernel32.java | 36 +++++ .../client/filesocket/NamedPipeUtils.java | 131 +++++++++++++----- .../filesocket/NamedPipeJniSocketTest.java | 124 +++++++++++++++++ 3 files changed, 254 insertions(+), 37 deletions(-) diff --git a/src/main/java/de/gesellix/docker/client/filesocket/ExtendedKernel32.java b/src/main/java/de/gesellix/docker/client/filesocket/ExtendedKernel32.java index 0505b32..120726c 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/ExtendedKernel32.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/ExtendedKernel32.java @@ -19,6 +19,42 @@ boolean GetOverlappedResult( boolean bWait ); + /** + * Variant taking the raw OVERLAPPED pointer. Prefer this one for overlapped I/O: passing a + * {@link WinBase.OVERLAPPED} Structure lets JNA auto-write its Java-side fields into native memory + * before the call, overwriting the completion status set by the kernel. + */ + boolean GetOverlappedResult( + WinNT.HANDLE hFile, + Pointer lpOverlapped, + IntByReference lpNumberOfBytesTransferred, + boolean bWait + ); + + /** + * ReadFile with a native buffer and raw OVERLAPPED pointer, both of which must stay valid + * until the (possibly asynchronous) operation has completed. + */ + boolean ReadFile( + WinNT.HANDLE hFile, + Pointer lpBuffer, + int nNumberOfBytesToRead, + IntByReference lpNumberOfBytesRead, + Pointer lpOverlapped + ); + + /** + * WriteFile with a native buffer and raw OVERLAPPED pointer, both of which must stay valid + * until the (possibly asynchronous) operation has completed. + */ + boolean WriteFile( + WinNT.HANDLE hFile, + Pointer lpBuffer, + int nNumberOfBytesToWrite, + IntByReference lpNumberOfBytesWritten, + Pointer lpOverlapped + ); + /** * Cancels all pending I/O operations on the specified file handle. * diff --git a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java index d8dafb0..9541bcd 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java @@ -3,12 +3,15 @@ import static com.sun.jna.platform.win32.WinBase.INVALID_HANDLE_VALUE; import java.io.IOException; +import java.lang.ref.Reference; import java.io.InterruptedIOException; import java.net.SocketTimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; import com.sun.jna.platform.win32.Kernel32; import com.sun.jna.platform.win32.WinBase; import com.sun.jna.platform.win32.WinError; @@ -110,51 +113,60 @@ public static WinNT.HANDLE connect( * event handle) may already have overwritten it. */ public static int readOverlapped(WinNT.HANDLE handle, byte[] buf, int timeoutMillis) throws IOException { + if (buf.length == 0) { + return 0; + } WinNT.HANDLE evt = Kernel32.INSTANCE.CreateEvent(null, false, false, null); if (evt == null || WinBase.INVALID_HANDLE_VALUE.equals(evt)) { throw new IOException("CreateEvent failed: " + Kernel32.INSTANCE.GetLastError()); } - WinBase.OVERLAPPED overlapped = new WinBase.OVERLAPPED(); - overlapped.hEvent = evt; - overlapped.write(); // write the struct to native memory + // Both the data buffer and the OVERLAPPED struct must stay at a stable native address until the I/O has + // completed, because the kernel writes into them asynchronously. A plain byte[] doesn't qualify: JNA only + // copies/pins it for the duration of the ReadFile() call itself, so a pending read would land in memory + // that has already been released (and the data would never reach buf). + Memory nativeBuf = new Memory(buf.length); + WinBase.OVERLAPPED overlapped = newOverlapped(evt); + // Only ever pass the raw pointer to native calls: passing the Structure makes JNA auto-write its (stale) + // Java-side fields back into native memory before each call, which would clobber the completion status + // the kernel has written in the meantime -- e.g. resetting Internal to STATUS_PENDING, which makes + // GetOverlappedResult report ERROR_IO_INCOMPLETE (bWait=false) or wait forever on the auto-reset event + // that has already been consumed (bWait=true). + Pointer ol = overlapped.getPointer(); try { IntByReference bytesRead = new IntByReference(); - boolean ok = Kernel32.INSTANCE.ReadFile(handle, buf, buf.length, null, overlapped); + boolean ok = ExtendedKernel32.INSTANCE.ReadFile(handle, nativeBuf, buf.length, null, ol); if (!ok) { int err = Kernel32.INSTANCE.GetLastError(); if (err != WinError.ERROR_IO_PENDING) { - if (err == WinError.ERROR_BROKEN_PIPE || err == WinError.ERROR_PIPE_NOT_CONNECTED || err == WinError.ERROR_NO_DATA) { + if (isPeerClosed(err)) { return -1; // EOF: pipe closed by peer } throw new IOException("ReadFile failed: " + err); } - int wait = Kernel32.INSTANCE.WaitForSingleObject(evt, timeoutMillis); + int wait = Kernel32.INSTANCE.WaitForSingleObject(evt, toWaitMillis(timeoutMillis)); if (wait != WinBase.WAIT_OBJECT_0) { - // Give up waiting and cancel the still-pending read. CancelIoEx only *requests* cancellation -- - // the kernel may still be about to write into `overlapped`/signal `evt` after it returns. We must - // block until that's truly settled (GetOverlappedResult with bWait=true) before this method - // returns and evt/overlapped become eligible for cleanup/GC; otherwise the OS can end up writing - // into freed native memory once the JNA-backed structures are gone, corrupting the heap. The - // drain call's own result/error is irrelevant here, we only need it to have happened. - ExtendedKernel32.INSTANCE.CancelIoEx(handle, overlapped.getPointer()); - ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, overlapped, new IntByReference(), true); + // Give up waiting and cancel the still-pending read. CancelIoEx only *requests* cancellation, so we + // must block until the operation has truly settled (GetOverlappedResult with bWait=true) before the + // native memory becomes eligible for GC. + ExtendedKernel32.INSTANCE.CancelIoEx(handle, ol); + if (ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, ol, bytesRead, true) && bytesRead.getValue() > 0) { + // the read completed just before the cancellation took effect: don't drop the data + return copyRead(nativeBuf, buf, bytesRead.getValue()); + } throw new SocketTimeoutException("Named pipe read timed out after " + timeoutMillis + "ms"); } } - // Pick up the result. bWait=true here: we already know the op is done (synchronous ReadFile) or its - // event is signaled (async path above), so this never actually blocks -- but bWait=false raced with - // the OS occasionally still settling the completion state right after a synchronous ReadFile, causing - // spurious ERROR_IO_INCOMPLETE (996). - if (!ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, overlapped, bytesRead, true)) { + // The operation is done (synchronous ReadFile) or its event is signaled, so this doesn't block. + if (!ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, ol, bytesRead, true)) { int err = Kernel32.INSTANCE.GetLastError(); if (err == WinError.ERROR_OPERATION_ABORTED) { return -1; // EOF: read was cancelled, e.g. via CancelIoEx() during close() } - if (err == WinError.ERROR_BROKEN_PIPE || err == WinError.ERROR_PIPE_NOT_CONNECTED || err == WinError.ERROR_NO_DATA) { + if (isPeerClosed(err)) { return -1; // EOF: pipe closed by peer } throw new IOException("GetOverlappedResult(read) failed: " + err); @@ -162,10 +174,12 @@ public static int readOverlapped(WinNT.HANDLE handle, byte[] buf, int timeoutMil int n = bytesRead.getValue(); log.debug("Bytes read: {}", n); - return n == 0 ? -1 : n; // 0 bytes on a message-mode pipe read signals EOF + return n == 0 ? -1 : copyRead(nativeBuf, buf, n); // 0 bytes on a message-mode pipe read signals EOF } finally { closeHandle(evt); + Reference.reachabilityFence(overlapped); + Reference.reachabilityFence(nativeBuf); } } @@ -183,12 +197,23 @@ public static void writeOverlapped(WinNT.HANDLE handle, byte[] buf, int len, int final long deadline = timeoutMs == 0 ? Long.MAX_VALUE : System.nanoTime() + (long) timeoutMs * 1_000_000L; + // see readOverlapped() on why the data has to live in native memory for overlapped I/O + Memory nativeBuf = new Memory(len); + nativeBuf.write(0, buf, 0, len); + int totalWritten = 0; while (totalWritten < len) { - long remainingMs = deadline == Long.MAX_VALUE ? Integer.MAX_VALUE : (deadline - System.nanoTime()) / 1_000_000L; - if (remainingMs <= 0) { - throw new SocketTimeoutException("writeOverlapped: overall timeout after " + timeoutMs + "ms; written=" + totalWritten + "/" + len); + int waitMillis; + if (deadline == Long.MAX_VALUE) { + waitMillis = WinBase.INFINITE; + } + else { + long remainingMs = (deadline - System.nanoTime()) / 1_000_000L; + if (remainingMs <= 0) { + throw new SocketTimeoutException("writeOverlapped: overall timeout after " + timeoutMs + "ms; written=" + totalWritten + "/" + len); + } + waitMillis = (int) Math.min(Integer.MAX_VALUE - 1, remainingMs); } WinNT.HANDLE evt = Kernel32.INSTANCE.CreateEvent(null, false, false, null); @@ -196,40 +221,45 @@ public static void writeOverlapped(WinNT.HANDLE handle, byte[] buf, int len, int throw new IOException("CreateEvent failed: " + Kernel32.INSTANCE.GetLastError()); } - WinBase.OVERLAPPED ol = new WinBase.OVERLAPPED(); - ol.hEvent = evt; - ol.write(); + // see readOverlapped() on why only the raw pointer is passed to native calls + WinBase.OVERLAPPED overlapped = newOverlapped(evt); + Pointer ol = overlapped.getPointer(); try { IntByReference bytesWritten = new IntByReference(); - boolean ok = Kernel32.INSTANCE.WriteFile(handle, buf, len, null, ol); + // continue after what has already been written, a partial write must not resend the beginning + boolean ok = ExtendedKernel32.INSTANCE.WriteFile(handle, nativeBuf.share(totalWritten), len - totalWritten, null, ol); if (!ok) { int err = Kernel32.INSTANCE.GetLastError(); if (err != WinError.ERROR_IO_PENDING) { - if (err == WinError.ERROR_NO_DATA || err == WinError.ERROR_BROKEN_PIPE) { - throw new IOException("writeOverlapped: pipe closed by peer"); + if (isPeerClosed(err)) { + throw new IOException("writeOverlapped: pipe closed by peer (" + err + ")"); } throw new IOException("WriteFile failed: " + err); } - int wait = Kernel32.INSTANCE.WaitForSingleObject(evt, (int) Math.min(Integer.MAX_VALUE, remainingMs)); + int wait = Kernel32.INSTANCE.WaitForSingleObject(evt, waitMillis); if (wait != WinBase.WAIT_OBJECT_0) { // see the matching comment in readOverlapped: must drain via GetOverlappedResult(bWait=true) - // before returning, or the kernel can still write into ol/evt after they're freed/GC'd. - ExtendedKernel32.INSTANCE.CancelIoEx(handle, ol.getPointer()); - ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, ol, new IntByReference(), true); - throw new SocketTimeoutException("writeOverlapped: wait timed out (wait=" + wait + ")"); + // before the native memory becomes eligible for GC. + ExtendedKernel32.INSTANCE.CancelIoEx(handle, ol); + IntByReference drained = new IntByReference(); + ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, ol, drained, true); + throw new SocketTimeoutException("writeOverlapped: wait timed out (wait=" + wait + "); written=" + + (totalWritten + Math.max(0, drained.getValue())) + "/" + len); } } - // bWait=true: same rationale as in readOverlapped -- avoids racing a synchronous WriteFile - // completion, which could otherwise surface a spurious ERROR_IO_INCOMPLETE (996). + // The operation is done (synchronous WriteFile) or its event is signaled, so this doesn't block. if (!ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, ol, bytesWritten, true)) { int err = Kernel32.INSTANCE.GetLastError(); if (err == WinError.ERROR_OPERATION_ABORTED) { throw new IOException("writeOverlapped: operation aborted"); } + if (isPeerClosed(err)) { + throw new IOException("writeOverlapped: pipe closed by peer (" + err + ")"); + } throw new IOException("GetOverlappedResult(write) failed: " + err); } @@ -243,8 +273,35 @@ public static void writeOverlapped(WinNT.HANDLE handle, byte[] buf, int len, int } finally { closeHandle(evt); + Reference.reachabilityFence(overlapped); } } + Reference.reachabilityFence(nativeBuf); + } + + private static WinBase.OVERLAPPED newOverlapped(WinNT.HANDLE evt) { + WinBase.OVERLAPPED overlapped = new WinBase.OVERLAPPED(); + overlapped.hEvent = evt; + overlapped.write(); // write the struct to native memory once, the kernel owns it from now on + overlapped.setAutoSynch(false); + return overlapped; + } + + private static int copyRead(Memory nativeBuf, byte[] buf, int n) { + nativeBuf.read(0, buf, 0, n); + return n; + } + + /** + * Maps a Java-style timeout (0 = wait indefinitely) to a WaitForSingleObject timeout, + * where 0 would mean "don't wait at all". + */ + private static int toWaitMillis(int timeoutMillis) { + return timeoutMillis <= 0 ? WinBase.INFINITE : timeoutMillis; + } + + private static boolean isPeerClosed(int err) { + return err == WinError.ERROR_BROKEN_PIPE || err == WinError.ERROR_PIPE_NOT_CONNECTED || err == WinError.ERROR_NO_DATA; } public static boolean readToBuffer(HANDLE handle, byte[] buf, IntByReference bytesRead) { diff --git a/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocketTest.java b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocketTest.java index 3ebe008..d54851b 100644 --- a/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocketTest.java +++ b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocketTest.java @@ -7,16 +7,20 @@ import static com.sun.jna.platform.win32.WinBase.PIPE_WAIT; import static com.sun.jna.platform.win32.WinError.ERROR_PIPE_CONNECTED; import static java.net.InetAddress.getByAddress; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; +import java.net.SocketTimeoutException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; @@ -26,6 +30,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import org.junit.jupiter.api.Disabled; @@ -222,6 +227,125 @@ public void testInProcessServerClient() throws Exception { serverThread.join(); } + @Test + @EnabledOnOs(OS.WINDOWS) + public void pendingOverlappedReadAndWriteTransferCorrectData() throws Exception { + // Regression test for the overlapped I/O path, where the operation doesn't complete synchronously: + // - the payload exceeds the pipe buffer, so the client's WriteFile goes pending until the server reads + // - the server delays its response, so the client's ReadFile goes pending as well + // Both used to break: JNA only kept the byte[] valid during the native call itself, and a default + // soTimeout of 0 was passed to WaitForSingleObject as "don't wait at all". + String pipePath = "\\\\.\\pipe\\filesocket_test_pending_io"; + byte[] payload = new byte[64 * 1024]; + for (int i = 0; i < payload.length; i++) { + payload[i] = (byte) (i % 251); + } + byte[] response = "delayed response".getBytes(StandardCharsets.UTF_8); + + CountDownLatch pipeCreated = new CountDownLatch(1); + AtomicReference serverError = new AtomicReference<>(); + Thread serverThread = new Thread(() -> { + WinNT.HANDLE pipeHandle = Kernel32.INSTANCE.CreateNamedPipe( + pipePath, + PIPE_ACCESS_DUPLEX, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, + 1, 4096, 4096, 0, null + ); + try { + assertNotEquals(INVALID_HANDLE_VALUE, pipeHandle, "Invalid pipe handle"); + pipeCreated.countDown(); + assertTrue(Kernel32.INSTANCE.ConnectNamedPipe(pipeHandle, null) + || Kernel32.INSTANCE.GetLastError() == ERROR_PIPE_CONNECTED, "Client failed to connect"); + + // let the client's write go pending before reading anything + Thread.sleep(300); + ByteArrayOutputStream received = new ByteArrayOutputStream(); + byte[] readBuffer = new byte[4096]; + IntByReference bytesRead = new IntByReference(); + while (received.size() < payload.length) { + assertTrue(NamedPipeUtils.readToBuffer(pipeHandle, readBuffer, bytesRead), "Server read failed"); + received.write(readBuffer, 0, bytesRead.getValue()); + } + assertArrayEquals(payload, received.toByteArray(), "Server received corrupted payload"); + + // let the client's read go pending before responding + Thread.sleep(300); + IntByReference written = new IntByReference(); + assertTrue(NamedPipeUtils.writeFromBuffer(pipeHandle, response, response.length, written), "Server write failed"); + Kernel32.INSTANCE.FlushFileBuffers(pipeHandle); + } + catch (Throwable t) { + serverError.set(t); + pipeCreated.countDown(); + } + finally { + Kernel32.INSTANCE.DisconnectNamedPipe(pipeHandle); + NamedPipeUtils.closeHandle(pipeHandle); + } + }); + serverThread.start(); + assertTrue(pipeCreated.await(2, TimeUnit.SECONDS), "Server did not create pipe in time"); + + try (NamedPipeJniSocket client = new NamedPipeJniSocket()) { + client.connect(pipePath); + assertEquals(0, client.getSoTimeout()); + + OutputStream os = client.getOutputStream(); + os.write(payload); + os.flush(); + + InputStream is = client.getInputStream(); + byte[] buf = new byte[1024]; + int read = is.read(buf); + assertEquals(new String(response, StandardCharsets.UTF_8), new String(buf, 0, read, StandardCharsets.UTF_8)); + } + finally { + serverThread.join(5000); + } + if (serverError.get() != null) { + throw new AssertionError("Server failed", serverError.get()); + } + } + + @Test + @EnabledOnOs(OS.WINDOWS) + public void readRespectsSoTimeout() throws Exception { + String pipePath = "\\\\.\\pipe\\filesocket_test_so_timeout"; + CountDownLatch pipeCreated = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(1); + Thread serverThread = new Thread(() -> { + WinNT.HANDLE pipeHandle = Kernel32.INSTANCE.CreateNamedPipe( + pipePath, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 4096, 4096, 0, null); + pipeCreated.countDown(); + Kernel32.INSTANCE.ConnectNamedPipe(pipeHandle, null); + try { + done.await(10, TimeUnit.SECONDS); // stay idle, never send anything + } + catch (InterruptedException ignored) { + } + Kernel32.INSTANCE.DisconnectNamedPipe(pipeHandle); + NamedPipeUtils.closeHandle(pipeHandle); + }); + serverThread.start(); + assertTrue(pipeCreated.await(2, TimeUnit.SECONDS), "Server did not create pipe in time"); + + try (NamedPipeJniSocket client = new NamedPipeJniSocket()) { + client.connect(pipePath); + client.setSoTimeout(300); + assertEquals(300, client.getSoTimeout()); + + InputStream is = client.getInputStream(); + long start = System.currentTimeMillis(); + assertThrows(SocketTimeoutException.class, () -> is.read(new byte[16])); + long duration = System.currentTimeMillis() - start; + assertTrue(duration >= 250 && duration < 5000, "unexpected timeout duration: " + duration + "ms"); + } + finally { + done.countDown(); + serverThread.join(5000); + } + } + @Test @EnabledOnOs(OS.WINDOWS) public void testCloseDuringPendingRead_DoesNotHang() throws Exception { From 9f14272e9bfd793e1be95fcebb238cba3fa4cedf Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Thu, 3 Dec 2026 22:10:05 +0100 Subject: [PATCH 3/4] Allow selecting the named pipe implementation, keep pending reads across timeouts - NamedPipeSocketFactory: choose NamedPipeSocket (CHANNEL, default) or NamedPipeJniSocket (JNI) via constructor, system property de.gesellix.docker.client.filesocket.namedpipe.impl or env var DOCKER_FILESOCKET_NAMEDPIPE_IMPL - NamedPipeSocket: read into an internal buffer and keep a timed-out read pending for the next read() instead of losing its data, writing into the caller's array later, or running two reads concurrently; fail cleanly when not connected or closed - NamedPipeJniSocket: isBound/shutdownOutput/shutdownInput like NamedPipeSocket - NamedPipeImplementationsTest: the same in-process pipe scenarios for both implementations, replacing the JNI-only tests Co-Authored-By: Claude Opus 5.5 --- .../client/filesocket/NamedPipeJniSocket.java | 25 +- .../client/filesocket/NamedPipeSocket.java | 72 ++++- .../filesocket/NamedPipeSocketFactory.java | 72 ++++- .../NamedPipeImplementationsTest.java | 261 ++++++++++++++++++ .../filesocket/NamedPipeJniSocketTest.java | 124 --------- .../NamedPipeSocketFactoryTest.java | 46 ++- 6 files changed, 459 insertions(+), 141 deletions(-) create mode 100644 src/test/java/de/gesellix/docker/client/filesocket/NamedPipeImplementationsTest.java diff --git a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocket.java b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocket.java index 7eace65..76450e7 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocket.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocket.java @@ -26,8 +26,8 @@ public class NamedPipeJniSocket extends FileSocket { private static final Logger log = LoggerFactory.getLogger(NamedPipeJniSocket.class); private WinNT.HANDLE handle; - private boolean connected = false; - private boolean closed = false; + private volatile boolean connected = false; + private volatile boolean closed = false; private BufferedSource source; private BufferedSink sink; @@ -133,6 +133,27 @@ public boolean isClosed() { return closed; } + @Override + public boolean isBound() { + return connected; + } + + @Override + public void shutdownOutput() throws SocketException { + // Named pipes have no half-close, see NamedPipeSocket#shutdownOutput(). Without this override, the + // inherited implementation would fail, because it relies on a SocketImpl that is never connected. + if (!connected) { + throw new SocketException("Socket is not connected"); + } + } + + @Override + public void shutdownInput() throws SocketException { + if (!connected) { + throw new SocketException("Socket is not connected"); + } + } + private void ensureOpen() throws IOException { if (closed) { throw new IOException("NamedPipeSocket is closed"); diff --git a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSocket.java b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSocket.java index 801bfa1..03f288e 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSocket.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSocket.java @@ -128,7 +128,7 @@ public void shutdownInput() throws SocketException { } @Override - public InputStream getInputStream() { + public synchronized InputStream getInputStream() { if (inputStream == null) { this.inputStream = new TimeoutAwareInputStream(); } @@ -136,7 +136,7 @@ public InputStream getInputStream() { } @Override - public OutputStream getOutputStream() { + public synchronized OutputStream getOutputStream() { if (outputStream == null) { this.outputStream = new TimeoutAwareOutputStream(); } @@ -159,14 +159,31 @@ public void close() throws IOException { } } + private void ensureOpen() throws SocketException { + if (closed.get()) { + throw new SocketException("Socket is closed"); + } + if (!connected.get()) { + throw new SocketException("Socket is not connected"); + } + } + /** * {@link java.nio.channels.Channels#newInputStream(java.nio.channels.AsynchronousByteChannel)} blocks on * {@link Future#get()} with no timeout at all, so {@link #setSoTimeout(int)} (and e.g. OkHttp's readTimeout, * which relies on it) would silently have no effect and a stalled/idle hijacked stream would block forever. * This reimplements the stream on top of {@link Future#get(long, TimeUnit)} instead, honoring soTimeout. + *

+ * Reads go into an internal buffer owned by this stream. When a read times out, the underlying channel read + * can't be cancelled and stays pending; it's kept and awaited again by the next {@link #read(byte[], int, int)}. + * That way no bytes get lost, the caller's array is never written to after read() has returned, and there is + * never more than one outstanding read on the pipe. */ private class TimeoutAwareInputStream extends InputStream { + private final ByteBuffer readBuffer = (ByteBuffer) ByteBuffer.allocate(8192).limit(0); + private Future pendingRead; + @Override public int read() throws IOException { byte[] b = new byte[1]; @@ -175,26 +192,36 @@ public int read() throws IOException { } @Override - public int read(byte[] b, int off, int len) throws IOException { + public synchronized int read(byte[] b, int off, int len) throws IOException { + if (off < 0 || len < 0 || len > b.length - off) { + throw new IndexOutOfBoundsException(); + } if (len == 0) { return 0; } - ByteBuffer buffer = ByteBuffer.wrap(b, off, len); - Future future = channel.read(buffer); + if (pendingRead == null && readBuffer.hasRemaining()) { + return drainTo(b, off, len); + } + + if (pendingRead == null) { + ensureOpen(); + readBuffer.clear(); + pendingRead = channel.read(readBuffer); + } int timeout = soTimeout; + int n; try { - return timeout > 0 - ? future.get(timeout, TimeUnit.MILLISECONDS) - : future.get(); + n = timeout > 0 + ? pendingRead.get(timeout, TimeUnit.MILLISECONDS) + : pendingRead.get(); } catch (TimeoutException e) { - // best effort: the underlying ReadFile may already be past the point of no return and could still - // complete (consuming pipe bytes) after we've given up waiting for it. Treat the connection as - // unusable afterwards, like other transports do on a read timeout. - future.cancel(true); + // keep pendingRead, the next read() continues waiting for it throw new SocketTimeoutException("Read timed out after " + timeout + "ms"); } catch (ExecutionException e) { + pendingRead = null; + readBuffer.limit(0); Throwable cause = e.getCause(); if (cause instanceof IOException) { throw (IOException) cause; @@ -202,9 +229,29 @@ public int read(byte[] b, int off, int len) throws IOException { throw new IOException(cause); } catch (InterruptedException e) { + // keep pendingRead, it's still owned by the channel Thread.currentThread().interrupt(); throw new InterruptedIOException("Read interrupted"); } + + pendingRead = null; + if (n < 0) { + readBuffer.limit(0); + return -1; + } + readBuffer.flip(); + return drainTo(b, off, len); + } + + private int drainTo(byte[] b, int off, int len) { + int count = Math.min(len, readBuffer.remaining()); + readBuffer.get(b, off, count); + return count; + } + + @Override + public synchronized int available() { + return pendingRead == null ? readBuffer.remaining() : 0; } @Override @@ -225,6 +272,7 @@ public void write(byte[] b, int off, int len) throws IOException { if (len == 0) { return; } + ensureOpen(); ByteBuffer buffer = ByteBuffer.wrap(b, off, len); while (buffer.hasRemaining()) { Future future = channel.write(buffer); diff --git a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSocketFactory.java b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSocketFactory.java index 1e3bd0c..478b0fa 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSocketFactory.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeSocketFactory.java @@ -1,11 +1,81 @@ package de.gesellix.docker.client.filesocket; import java.net.Socket; +import java.util.Locale; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Creates sockets for Windows named pipes. + *

+ * Two implementations are available, see {@link Implementation}. Without explicit configuration, + * the implementation is chosen via the system property {@value #IMPLEMENTATION_PROPERTY} + * or the environment variable {@value #IMPLEMENTATION_ENV}, e.g. {@code -Dde.gesellix.docker.client.filesocket.namedpipe.impl=jni}. + * The default is {@link Implementation#CHANNEL}. + */ public class NamedPipeSocketFactory extends FileSocketFactory { + private static final Logger log = LoggerFactory.getLogger(NamedPipeSocketFactory.class); + + public static final String IMPLEMENTATION_PROPERTY = "de.gesellix.docker.client.filesocket.namedpipe.impl"; + public static final String IMPLEMENTATION_ENV = "DOCKER_FILESOCKET_NAMEDPIPE_IMPL"; + + public enum Implementation { + /** + * {@link NamedPipeSocket}: based on {@link java.nio.channels.AsynchronousFileChannel}. + */ + CHANNEL, + /** + * {@link NamedPipeJniSocket}: based on overlapped I/O via JNA. + */ + JNI; + + public static Implementation parse(String value) { + if (value == null || value.trim().isEmpty()) { + return CHANNEL; + } + try { + return valueOf(value.trim().toUpperCase(Locale.ROOT)); + } + catch (IllegalArgumentException e) { + log.warn("Unknown named pipe implementation '{}', falling back to {}", value, CHANNEL); + return CHANNEL; + } + } + } + + private final Implementation implementation; + + public NamedPipeSocketFactory() { + this(configuredImplementation()); + } + + public NamedPipeSocketFactory(Implementation implementation) { + this.implementation = implementation == null ? Implementation.CHANNEL : implementation; + log.debug("using named pipe implementation {}", this.implementation); + } + + public Implementation getImplementation() { + return implementation; + } + + static Implementation configuredImplementation() { + String value = System.getProperty(IMPLEMENTATION_PROPERTY); + if (value == null || value.trim().isEmpty()) { + value = System.getenv(IMPLEMENTATION_ENV); + } + return Implementation.parse(value); + } + @Override public Socket createSocket() { - return new NamedPipeSocket(); + switch (implementation) { + case JNI: + return new NamedPipeJniSocket(); + case CHANNEL: + default: + return new NamedPipeSocket(); + } } } diff --git a/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeImplementationsTest.java b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeImplementationsTest.java new file mode 100644 index 0000000..4435ca3 --- /dev/null +++ b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeImplementationsTest.java @@ -0,0 +1,261 @@ +package de.gesellix.docker.client.filesocket; + +import static com.sun.jna.platform.win32.WinBase.INVALID_HANDLE_VALUE; +import static com.sun.jna.platform.win32.WinBase.PIPE_ACCESS_DUPLEX; +import static com.sun.jna.platform.win32.WinBase.PIPE_READMODE_BYTE; +import static com.sun.jna.platform.win32.WinBase.PIPE_TYPE_BYTE; +import static com.sun.jna.platform.win32.WinBase.PIPE_WAIT; +import static com.sun.jna.platform.win32.WinError.ERROR_PIPE_CONNECTED; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketTimeoutException; +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; + +import com.sun.jna.platform.win32.Kernel32; +import com.sun.jna.platform.win32.WinNT; +import com.sun.jna.ptr.IntByReference; + +import de.gesellix.docker.client.filesocket.NamedPipeSocketFactory.Implementation; + +/** + * Runs the same scenarios against both named pipe implementations, using an in-process pipe server + * (no Docker engine required). + */ +@EnabledOnOs(OS.WINDOWS) +class NamedPipeImplementationsTest { + + @Nested + class Channel extends Contract { + + @Override + Implementation implementation() { + return Implementation.CHANNEL; + } + } + + @Nested + class Jni extends Contract { + + @Override + Implementation implementation() { + return Implementation.JNI; + } + } + + abstract static class Contract { + + abstract Implementation implementation(); + + @Test + void createsExpectedSocketType() { + Socket socket = new NamedPipeSocketFactory(implementation()).createSocket(); + assertEquals(implementation() == Implementation.JNI ? NamedPipeJniSocket.class : NamedPipeSocket.class, socket.getClass()); + } + + @Test + void pendingReadAndWriteTransferCorrectData() throws Exception { + // The payload exceeds the pipe buffer, so the client's write can't complete before the server reads, + // and the server delays its response, so the client's read has to wait as well. + byte[] payload = new byte[64 * 1024]; + for (int i = 0; i < payload.length; i++) { + payload[i] = (byte) (i % 251); + } + byte[] response = "delayed response".getBytes(StandardCharsets.UTF_8); + + try (PipeServer server = new PipeServer(pipeHandle -> { + Thread.sleep(300); + assertArrayEquals(payload, PipeServer.readFully(pipeHandle, payload.length), "Server received corrupted payload"); + Thread.sleep(300); + PipeServer.write(pipeHandle, response); + }); + Socket client = connect(server)) { + assertEquals(0, client.getSoTimeout()); + + OutputStream os = client.getOutputStream(); + os.write(payload); + os.flush(); + + byte[] buf = new byte[1024]; + int read = client.getInputStream().read(buf); + assertEquals("delayed response", new String(buf, 0, read, StandardCharsets.UTF_8)); + server.awaitAndRethrow(); + } + } + + @Test + void readTimeoutKeepsSocketUsableWithoutLosingData() throws Exception { + CountDownLatch timedOut = new CountDownLatch(1); + byte[] lateData = "late data".getBytes(StandardCharsets.UTF_8); + + try (PipeServer server = new PipeServer(pipeHandle -> { + assertTrue(timedOut.await(10, TimeUnit.SECONDS)); + PipeServer.write(pipeHandle, lateData); + }); + Socket client = connect(server)) { + client.setSoTimeout(300); + assertEquals(300, client.getSoTimeout()); + InputStream is = client.getInputStream(); + + long start = System.currentTimeMillis(); + assertThrows(SocketTimeoutException.class, () -> is.read(new byte[16])); + long duration = System.currentTimeMillis() - start; + assertTrue(duration >= 250 && duration < 5000, "unexpected timeout duration: " + duration + "ms"); + + timedOut.countDown(); + client.setSoTimeout(5000); + byte[] buf = new byte[16]; + int read = is.read(buf); + assertEquals("late data", new String(buf, 0, read, StandardCharsets.UTF_8)); + server.awaitAndRethrow(); + } + } + + @Test + void halfCloseIsSupported() throws Exception { + // OkHttp calls shutdownOutput() when it finishes writing to a hijacked (attach/exec) stream + try (PipeServer server = new PipeServer(pipeHandle -> PipeServer.write(pipeHandle, "bye".getBytes(StandardCharsets.UTF_8))); + Socket client = connect(server)) { + assertTrue(client.isConnected()); + assertTrue(client.isBound()); + assertDoesNotThrow(client::shutdownOutput); + + byte[] buf = new byte[16]; + int read = client.getInputStream().read(buf); + assertEquals("bye", new String(buf, 0, read, StandardCharsets.UTF_8)); + server.awaitAndRethrow(); + } + } + + @Test + void closeUnblocksPendingRead() throws Exception { + CountDownLatch done = new CountDownLatch(1); + try (PipeServer server = new PipeServer(pipeHandle -> done.await(10, TimeUnit.SECONDS))) { + Socket client = connect(server); + InputStream is = client.getInputStream(); + AtomicReference result = new AtomicReference<>(); + Thread reader = new Thread(() -> { + try { + result.set(is.read(new byte[16])); + } + catch (IOException e) { + result.set(e); + } + }); + reader.start(); + Thread.sleep(300); + + long start = System.currentTimeMillis(); + client.close(); + reader.join(5000); + assertTrue(System.currentTimeMillis() - start < 5000, "close() didn't unblock the reader"); + assertTrue(client.isClosed()); + // either EOF or an IOException is fine, but the reader must not hang + assertTrue(result.get() != null, "reader still blocked"); + done.countDown(); + } + } + + Socket connect(PipeServer server) throws IOException { + Socket socket = new NamedPipeSocketFactory(implementation()).createSocket(); + FileSocket fileSocket = (FileSocket) socket; + InetAddress address = InetAddress.getByAddress(fileSocket.encodeHostname(server.path), new byte[]{0, 0, 0, 0}); + socket.connect(new InetSocketAddress(address, 0), 5000); + return socket; + } + } + + /** + * Minimal single-connection named pipe server, using plain blocking I/O on its end. + */ + static class PipeServer implements AutoCloseable { + + interface Script { + + void run(WinNT.HANDLE pipeHandle) throws Exception; + } + + final String path = "//./pipe/filesocket_test_" + UUID.randomUUID(); + private final Thread thread; + private final AtomicReference error = new AtomicReference<>(); + + PipeServer(Script script) throws InterruptedException { + CountDownLatch created = new CountDownLatch(1); + thread = new Thread(() -> { + WinNT.HANDLE pipeHandle = Kernel32.INSTANCE.CreateNamedPipe( + path.replace("/", "\\"), + PIPE_ACCESS_DUPLEX, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, + 1, 4096, 4096, 0, null); + created.countDown(); + try { + if (INVALID_HANDLE_VALUE.equals(pipeHandle)) { + throw new IllegalStateException("CreateNamedPipe failed: " + Kernel32.INSTANCE.GetLastError()); + } + if (!Kernel32.INSTANCE.ConnectNamedPipe(pipeHandle, null) && Kernel32.INSTANCE.GetLastError() != ERROR_PIPE_CONNECTED) { + throw new IllegalStateException("ConnectNamedPipe failed: " + Kernel32.INSTANCE.GetLastError()); + } + script.run(pipeHandle); + Kernel32.INSTANCE.FlushFileBuffers(pipeHandle); + } + catch (Throwable t) { + error.set(t); + } + finally { + Kernel32.INSTANCE.DisconnectNamedPipe(pipeHandle); + NamedPipeUtils.closeHandle(pipeHandle); + } + }, "pipe-server"); + thread.setDaemon(true); + thread.start(); + assertTrue(created.await(5, TimeUnit.SECONDS), "Server did not create pipe in time"); + } + + static byte[] readFully(WinNT.HANDLE pipeHandle, int length) { + ByteArrayOutputStream received = new ByteArrayOutputStream(); + byte[] readBuffer = new byte[4096]; + IntByReference bytesRead = new IntByReference(); + while (received.size() < length) { + assertTrue(NamedPipeUtils.readToBuffer(pipeHandle, readBuffer, bytesRead), "Server read failed"); + received.write(readBuffer, 0, bytesRead.getValue()); + } + return received.toByteArray(); + } + + static void write(WinNT.HANDLE pipeHandle, byte[] data) { + IntByReference written = new IntByReference(); + assertTrue(NamedPipeUtils.writeFromBuffer(pipeHandle, data, data.length, written), "Server write failed"); + } + + void awaitAndRethrow() throws InterruptedException { + thread.join(10_000); + if (error.get() != null) { + throw new AssertionError("Server failed", error.get()); + } + } + + @Override + public void close() throws InterruptedException { + thread.join(10_000); + } + } +} diff --git a/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocketTest.java b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocketTest.java index d54851b..3ebe008 100644 --- a/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocketTest.java +++ b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocketTest.java @@ -7,20 +7,16 @@ import static com.sun.jna.platform.win32.WinBase.PIPE_WAIT; import static com.sun.jna.platform.win32.WinError.ERROR_PIPE_CONNECTED; import static java.net.InetAddress.getByAddress; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; -import java.net.SocketTimeoutException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; @@ -30,7 +26,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import org.junit.jupiter.api.Disabled; @@ -227,125 +222,6 @@ public void testInProcessServerClient() throws Exception { serverThread.join(); } - @Test - @EnabledOnOs(OS.WINDOWS) - public void pendingOverlappedReadAndWriteTransferCorrectData() throws Exception { - // Regression test for the overlapped I/O path, where the operation doesn't complete synchronously: - // - the payload exceeds the pipe buffer, so the client's WriteFile goes pending until the server reads - // - the server delays its response, so the client's ReadFile goes pending as well - // Both used to break: JNA only kept the byte[] valid during the native call itself, and a default - // soTimeout of 0 was passed to WaitForSingleObject as "don't wait at all". - String pipePath = "\\\\.\\pipe\\filesocket_test_pending_io"; - byte[] payload = new byte[64 * 1024]; - for (int i = 0; i < payload.length; i++) { - payload[i] = (byte) (i % 251); - } - byte[] response = "delayed response".getBytes(StandardCharsets.UTF_8); - - CountDownLatch pipeCreated = new CountDownLatch(1); - AtomicReference serverError = new AtomicReference<>(); - Thread serverThread = new Thread(() -> { - WinNT.HANDLE pipeHandle = Kernel32.INSTANCE.CreateNamedPipe( - pipePath, - PIPE_ACCESS_DUPLEX, - PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, - 1, 4096, 4096, 0, null - ); - try { - assertNotEquals(INVALID_HANDLE_VALUE, pipeHandle, "Invalid pipe handle"); - pipeCreated.countDown(); - assertTrue(Kernel32.INSTANCE.ConnectNamedPipe(pipeHandle, null) - || Kernel32.INSTANCE.GetLastError() == ERROR_PIPE_CONNECTED, "Client failed to connect"); - - // let the client's write go pending before reading anything - Thread.sleep(300); - ByteArrayOutputStream received = new ByteArrayOutputStream(); - byte[] readBuffer = new byte[4096]; - IntByReference bytesRead = new IntByReference(); - while (received.size() < payload.length) { - assertTrue(NamedPipeUtils.readToBuffer(pipeHandle, readBuffer, bytesRead), "Server read failed"); - received.write(readBuffer, 0, bytesRead.getValue()); - } - assertArrayEquals(payload, received.toByteArray(), "Server received corrupted payload"); - - // let the client's read go pending before responding - Thread.sleep(300); - IntByReference written = new IntByReference(); - assertTrue(NamedPipeUtils.writeFromBuffer(pipeHandle, response, response.length, written), "Server write failed"); - Kernel32.INSTANCE.FlushFileBuffers(pipeHandle); - } - catch (Throwable t) { - serverError.set(t); - pipeCreated.countDown(); - } - finally { - Kernel32.INSTANCE.DisconnectNamedPipe(pipeHandle); - NamedPipeUtils.closeHandle(pipeHandle); - } - }); - serverThread.start(); - assertTrue(pipeCreated.await(2, TimeUnit.SECONDS), "Server did not create pipe in time"); - - try (NamedPipeJniSocket client = new NamedPipeJniSocket()) { - client.connect(pipePath); - assertEquals(0, client.getSoTimeout()); - - OutputStream os = client.getOutputStream(); - os.write(payload); - os.flush(); - - InputStream is = client.getInputStream(); - byte[] buf = new byte[1024]; - int read = is.read(buf); - assertEquals(new String(response, StandardCharsets.UTF_8), new String(buf, 0, read, StandardCharsets.UTF_8)); - } - finally { - serverThread.join(5000); - } - if (serverError.get() != null) { - throw new AssertionError("Server failed", serverError.get()); - } - } - - @Test - @EnabledOnOs(OS.WINDOWS) - public void readRespectsSoTimeout() throws Exception { - String pipePath = "\\\\.\\pipe\\filesocket_test_so_timeout"; - CountDownLatch pipeCreated = new CountDownLatch(1); - CountDownLatch done = new CountDownLatch(1); - Thread serverThread = new Thread(() -> { - WinNT.HANDLE pipeHandle = Kernel32.INSTANCE.CreateNamedPipe( - pipePath, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 4096, 4096, 0, null); - pipeCreated.countDown(); - Kernel32.INSTANCE.ConnectNamedPipe(pipeHandle, null); - try { - done.await(10, TimeUnit.SECONDS); // stay idle, never send anything - } - catch (InterruptedException ignored) { - } - Kernel32.INSTANCE.DisconnectNamedPipe(pipeHandle); - NamedPipeUtils.closeHandle(pipeHandle); - }); - serverThread.start(); - assertTrue(pipeCreated.await(2, TimeUnit.SECONDS), "Server did not create pipe in time"); - - try (NamedPipeJniSocket client = new NamedPipeJniSocket()) { - client.connect(pipePath); - client.setSoTimeout(300); - assertEquals(300, client.getSoTimeout()); - - InputStream is = client.getInputStream(); - long start = System.currentTimeMillis(); - assertThrows(SocketTimeoutException.class, () -> is.read(new byte[16])); - long duration = System.currentTimeMillis() - start; - assertTrue(duration >= 250 && duration < 5000, "unexpected timeout duration: " + duration + "ms"); - } - finally { - done.countDown(); - serverThread.join(5000); - } - } - @Test @EnabledOnOs(OS.WINDOWS) public void testCloseDuringPendingRead_DoesNotHang() throws Exception { diff --git a/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeSocketFactoryTest.java b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeSocketFactoryTest.java index fbc1ad7..62ff2f8 100644 --- a/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeSocketFactoryTest.java +++ b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeSocketFactoryTest.java @@ -1,13 +1,55 @@ package de.gesellix.docker.client.filesocket; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; +import de.gesellix.docker.client.filesocket.NamedPipeSocketFactory.Implementation; class NamedPipeSocketFactoryTest { + private final String originalValue = System.getProperty(NamedPipeSocketFactory.IMPLEMENTATION_PROPERTY); + + @AfterEach + void restoreProperty() { + if (originalValue == null) { + System.clearProperty(NamedPipeSocketFactory.IMPLEMENTATION_PROPERTY); + } + else { + System.setProperty(NamedPipeSocketFactory.IMPLEMENTATION_PROPERTY, originalValue); + } + } + + @Test + void createsNamedPipeSocketByDefault() { + System.clearProperty(NamedPipeSocketFactory.IMPLEMENTATION_PROPERTY); + if (System.getenv(NamedPipeSocketFactory.IMPLEMENTATION_ENV) == null) { + assertTrue(new NamedPipeSocketFactory().createSocket() instanceof NamedPipeSocket); + } + } + @Test - void createsNamedPipeSocket() { + void selectsImplementationViaSystemProperty() { + System.setProperty(NamedPipeSocketFactory.IMPLEMENTATION_PROPERTY, "jni"); + assertEquals(Implementation.JNI, new NamedPipeSocketFactory().getImplementation()); + assertTrue(new NamedPipeSocketFactory().createSocket() instanceof NamedPipeJniSocket); + + System.setProperty(NamedPipeSocketFactory.IMPLEMENTATION_PROPERTY, " Channel "); assertTrue(new NamedPipeSocketFactory().createSocket() instanceof NamedPipeSocket); } + + @Test + void selectsImplementationExplicitly() { + System.setProperty(NamedPipeSocketFactory.IMPLEMENTATION_PROPERTY, "jni"); + assertTrue(new NamedPipeSocketFactory(Implementation.CHANNEL).createSocket() instanceof NamedPipeSocket); + } + + @Test + void fallsBackToDefaultForUnknownValues() { + assertEquals(Implementation.CHANNEL, Implementation.parse("unknown")); + assertEquals(Implementation.CHANNEL, Implementation.parse(null)); + assertEquals(Implementation.CHANNEL, Implementation.parse("")); + } } From 40cda2cd7fdab882383a7dc6d73bed835e041c29 Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Thu, 3 Dec 2026 22:30:00 +0100 Subject: [PATCH 4/4] Make overlapped named pipe waits interruptible WaitForSingleObject can't be interrupted from Java, so a read without soTimeout ignored Thread.interrupt(). docker-remote-api-client relies on interrupts (runInterruptible) to cancel blocking attach/exec frame reads, which made attach (interactive) hang with the JNI implementation on WCOW. Wait in 100ms slices, and cancel and drain the I/O when interrupted. Co-Authored-By: Claude Opus 5.5 --- .../client/filesocket/NamedPipeUtils.java | 73 ++++++++++++++++--- .../NamedPipeImplementationsTest.java | 29 ++++++++ 2 files changed, 90 insertions(+), 12 deletions(-) diff --git a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java index 9541bcd..5764827 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java @@ -146,8 +146,8 @@ public static int readOverlapped(WinNT.HANDLE handle, byte[] buf, int timeoutMil throw new IOException("ReadFile failed: " + err); } - int wait = Kernel32.INSTANCE.WaitForSingleObject(evt, toWaitMillis(timeoutMillis)); - if (wait != WinBase.WAIT_OBJECT_0) { + WaitResult wait = awaitEvent(evt, timeoutMillis); + if (wait != WaitResult.SIGNALED) { // Give up waiting and cancel the still-pending read. CancelIoEx only *requests* cancellation, so we // must block until the operation has truly settled (GetOverlappedResult with bWait=true) before the // native memory becomes eligible for GC. @@ -156,7 +156,7 @@ public static int readOverlapped(WinNT.HANDLE handle, byte[] buf, int timeoutMil // the read completed just before the cancellation took effect: don't drop the data return copyRead(nativeBuf, buf, bytesRead.getValue()); } - throw new SocketTimeoutException("Named pipe read timed out after " + timeoutMillis + "ms"); + throw waitFailure(wait, "Named pipe read", timeoutMillis); } } @@ -206,7 +206,7 @@ public static void writeOverlapped(WinNT.HANDLE handle, byte[] buf, int len, int while (totalWritten < len) { int waitMillis; if (deadline == Long.MAX_VALUE) { - waitMillis = WinBase.INFINITE; + waitMillis = 0; // wait indefinitely } else { long remainingMs = (deadline - System.nanoTime()) / 1_000_000L; @@ -239,15 +239,19 @@ public static void writeOverlapped(WinNT.HANDLE handle, byte[] buf, int len, int throw new IOException("WriteFile failed: " + err); } - int wait = Kernel32.INSTANCE.WaitForSingleObject(evt, waitMillis); - if (wait != WinBase.WAIT_OBJECT_0) { + WaitResult wait = awaitEvent(evt, waitMillis); + if (wait != WaitResult.SIGNALED) { // see the matching comment in readOverlapped: must drain via GetOverlappedResult(bWait=true) // before the native memory becomes eligible for GC. ExtendedKernel32.INSTANCE.CancelIoEx(handle, ol); IntByReference drained = new IntByReference(); ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, ol, drained, true); - throw new SocketTimeoutException("writeOverlapped: wait timed out (wait=" + wait + "); written=" - + (totalWritten + Math.max(0, drained.getValue())) + "/" + len); + IOException failure = waitFailure(wait, "writeOverlapped", waitMillis); + if (failure instanceof InterruptedIOException) { + ((InterruptedIOException) failure).bytesTransferred = totalWritten + Math.max(0, drained.getValue()); + } + log.debug("writeOverlapped gave up: {}; written={}/{}", wait, totalWritten + Math.max(0, drained.getValue()), len); + throw failure; } } @@ -292,12 +296,57 @@ private static int copyRead(Memory nativeBuf, byte[] buf, int n) { return n; } + private enum WaitResult { + SIGNALED, TIMED_OUT, INTERRUPTED, FAILED + } + /** - * Maps a Java-style timeout (0 = wait indefinitely) to a WaitForSingleObject timeout, - * where 0 would mean "don't wait at all". + * Upper bound for a single native wait, so that a pending operation notices {@link Thread#interrupt()}. + * A native WaitForSingleObject call can't be interrupted from Java, but callers rely on interrupts to + * cancel blocking reads, e.g. the docker-remote-api-client via kotlinx.coroutines' runInterruptible. */ - private static int toWaitMillis(int timeoutMillis) { - return timeoutMillis <= 0 ? WinBase.INFINITE : timeoutMillis; + private static final int WAIT_SLICE_MS = 100; + + /** + * Waits for the event to become signaled. + * + * @param timeoutMillis Java-style timeout, 0 waits indefinitely (WaitForSingleObject would treat 0 as "don't wait at all") + */ + private static WaitResult awaitEvent(WinNT.HANDLE evt, int timeoutMillis) { + final long deadline = timeoutMillis <= 0 ? Long.MAX_VALUE : System.nanoTime() + timeoutMillis * 1_000_000L; + while (true) { + if (Thread.currentThread().isInterrupted()) { + return WaitResult.INTERRUPTED; + } + long sliceMs = WAIT_SLICE_MS; + if (deadline != Long.MAX_VALUE) { + long remainingMs = (deadline - System.nanoTime() + 999_999L) / 1_000_000L; + if (remainingMs <= 0) { + return WaitResult.TIMED_OUT; + } + sliceMs = Math.min(sliceMs, remainingMs); + } + int wait = Kernel32.INSTANCE.WaitForSingleObject(evt, (int) sliceMs); + if (wait == WinBase.WAIT_OBJECT_0) { + return WaitResult.SIGNALED; + } + if (wait != WinError.WAIT_TIMEOUT) { + log.debug("WaitForSingleObject returned {}, last error={}", wait, Kernel32.INSTANCE.GetLastError()); + return WaitResult.FAILED; + } + } + } + + private static IOException waitFailure(WaitResult wait, String operation, int timeoutMillis) { + switch (wait) { + case TIMED_OUT: + return new SocketTimeoutException(operation + " timed out after " + timeoutMillis + "ms"); + case INTERRUPTED: + // the thread's interrupt status stays set + return new InterruptedIOException(operation + " interrupted"); + default: + return new IOException(operation + " failed: WaitForSingleObject failed"); + } } private static boolean isPeerClosed(int err) { diff --git a/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeImplementationsTest.java b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeImplementationsTest.java index 4435ca3..a21aa51 100644 --- a/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeImplementationsTest.java +++ b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeImplementationsTest.java @@ -15,6 +15,7 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -146,6 +147,34 @@ void halfCloseIsSupported() throws Exception { } } + @Test + void interruptUnblocksPendingRead() throws Exception { + // docker-remote-api-client cancels blocking frame reads (attach/exec) via Thread.interrupt(), see + // kotlinx.coroutines' runInterruptible. A read without soTimeout must not ignore that. + CountDownLatch done = new CountDownLatch(1); + try (PipeServer server = new PipeServer(pipeHandle -> done.await(10, TimeUnit.SECONDS)); + Socket client = connect(server)) { + InputStream is = client.getInputStream(); + AtomicReference result = new AtomicReference<>(); + Thread reader = new Thread(() -> { + try { + result.set(is.read(new byte[16])); + } + catch (IOException e) { + result.set(e); + } + }); + reader.start(); + Thread.sleep(300); + + reader.interrupt(); + reader.join(5000); + assertTrue(!reader.isAlive(), "interrupt didn't unblock the reader"); + assertTrue(result.get() instanceof InterruptedIOException, "expected InterruptedIOException, got " + result.get()); + done.countDown(); + } + } + @Test void closeUnblocksPendingRead() throws Exception { CountDownLatch done = new CountDownLatch(1);