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/NamedPipeJniSocket.java b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeJniSocket.java index cee0fb6..76450e7 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; @@ -25,13 +26,16 @@ 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; - 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(); @@ -107,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/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..03f288e 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,6 +75,8 @@ public void connect(SocketAddress endpoint, int timeout) throws IOException { Thread.sleep(100); } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + throw new InterruptedIOException("Connect interrupted"); } } } @@ -69,17 +84,61 @@ public void connect(SocketAddress endpoint, int timeout) throws IOException { } @Override - public InputStream getInputStream() { + 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 synchronized InputStream getInputStream() { if (inputStream == null) { - this.inputStream = Channels.newInputStream(channel); + this.inputStream = new TimeoutAwareInputStream(); } return inputStream; } @Override - public OutputStream getOutputStream() { + public synchronized OutputStream getOutputStream() { if (outputStream == null) { - this.outputStream = Channels.newOutputStream(channel); + this.outputStream = new TimeoutAwareOutputStream(); } return outputStream; } @@ -98,11 +157,148 @@ public void close() throws IOException { if (channel != null) { channel.close(); } - if (inputStream != null) { - inputStream.close(); + } + + private void ensureOpen() throws SocketException { + if (closed.get()) { + throw new SocketException("Socket is closed"); + } + if (!connected.get()) { + throw new SocketException("Socket is not connected"); } - if (outputStream != null) { - outputStream.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. + *

+ * 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]; + int n = read(b, 0, 1); + return n == -1 ? -1 : (b[0] & 0xff); + } + + @Override + 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; + } + 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 { + n = timeout > 0 + ? pendingRead.get(timeout, TimeUnit.MILLISECONDS) + : pendingRead.get(); + } + catch (TimeoutException e) { + // 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; + } + 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 + public void close() throws IOException { + NamedPipeSocket.this.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; + } + ensureOpen(); + 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/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/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..5764827 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/NamedPipeUtils.java @@ -2,9 +2,16 @@ 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; @@ -19,13 +26,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,194 +55,302 @@ 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 { + 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 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); -// } + // 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 { - boolean ok = Kernel32.INSTANCE.ReadFile(handle, buf, buf.length, null, overlapped); + IntByReference bytesRead = new IntByReference(); + boolean ok = ExtendedKernel32.INSTANCE.ReadFile(handle, nativeBuf, buf.length, null, ol); if (!ok) { int err = Kernel32.INSTANCE.GetLastError(); if (err != WinError.ERROR_IO_PENDING) { - log.debug("IO pending; last error=" + err); - return false; + if (isPeerClosed(err)) { + 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); - ExtendedKernel32.INSTANCE.CancelIoEx(handle, overlapped.getPointer()); - return false; + 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. + 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 waitFailure(wait, "Named pipe read", timeoutMillis); } } - - // Ergebnis (auch bei synchroner Completion) abholen – ohne zusätzlich zu warten - if (!ExtendedKernel32.INSTANCE.GetOverlappedResult(handle, overlapped, bytesRead, false)) { + // 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(); - 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 (isPeerClosed(err)) { + 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 : copyRead(nativeBuf, buf, n); // 0 bytes on a message-mode pipe read signals EOF + } + finally { closeHandle(evt); + Reference.reachabilityFence(overlapped); + Reference.reachabilityFence(nativeBuf); } } /** - * 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 = timeoutMs == 0 ? Long.MAX_VALUE : System.nanoTime() + (long) timeoutMs * 1_000_000L; - final long deadline = 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 - System.nanoTime()) / 1_000_000L; - if (remainingMs <= 0) { - throw new RuntimeException("writeOverlapped: overall timeout; written=" + totalWritten + "/" + len); + int waitMillis; + if (deadline == Long.MAX_VALUE) { + waitMillis = 0; // wait indefinitely + } + 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); } - // 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(); - 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 { - boolean ok = Kernel32.INSTANCE.WriteFile(handle, buf, len, null, ol); + IntByReference bytesWritten = new IntByReference(); + // 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(); - // 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"); + if (isPeerClosed(err)) { + throw new IOException("writeOverlapped: pipe closed by peer (" + err + ")"); } - 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 - ExtendedKernel32.INSTANCE.CancelIoEx(handle, ol.getPointer()); - // Optional: warten, bis Cancel durch ist (nicht zwingend) - throw new RuntimeException("writeOverlapped: wait failed/timeout (Wait=" + wait + ")"); + 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); + 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; } } - // 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"); + // 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 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); + 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; + } + + private enum WaitResult { + SIGNALED, TIMED_OUT, INTERRUPTED, FAILED + } + + /** + * 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 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"); } -// return totalWritten >= 0; - return true; + } + + 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/NamedPipeImplementationsTest.java b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeImplementationsTest.java new file mode 100644 index 0000000..a21aa51 --- /dev/null +++ b/src/test/java/de/gesellix/docker/client/filesocket/NamedPipeImplementationsTest.java @@ -0,0 +1,290 @@ +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.InterruptedIOException; +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 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); + 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/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("")); + } } 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 {