From c986e9f5e2f7ee8bacdc4718818414c64b23b630 Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Thu, 3 Dec 2026 23:10:50 +0100 Subject: [PATCH] Delegate socket options and half-close in UnixSocket UnixSocket wraps an AFUNIXSocket, but the inherited java.net.Socket methods operated on the wrapper's own SocketImpl, which never gets connected: - setSoTimeout() was a no-op, so OkHttp's readTimeout never applied - shutdownOutput() failed with "SocketException: Not connected", e.g. when OkHttp closes the request body of a hijacked attach/exec stream Delegate SO_TIMEOUT (remembering a value set before connect), half-close and the related state queries to the actual socket. Co-Authored-By: Claude Opus 5.5 --- .../docker/client/filesocket/UnixSocket.java | 62 ++++++- .../client/filesocket/UnixSocketTest.java | 165 ++++++++++++++++++ 2 files changed, 226 insertions(+), 1 deletion(-) create mode 100644 src/test/java/de/gesellix/docker/client/filesocket/UnixSocketTest.java diff --git a/src/main/java/de/gesellix/docker/client/filesocket/UnixSocket.java b/src/main/java/de/gesellix/docker/client/filesocket/UnixSocket.java index d57f09c..f1eff8a 100644 --- a/src/main/java/de/gesellix/docker/client/filesocket/UnixSocket.java +++ b/src/main/java/de/gesellix/docker/client/filesocket/UnixSocket.java @@ -19,6 +19,8 @@ public class UnixSocket extends FileSocket { private static final Logger log = LoggerFactory.getLogger(UnixSocket.class); private AFUNIXSocket socket = null; + // SO_TIMEOUT set before connect(), applied to the actual socket once it exists + private Integer pendingSoTimeout = null; @Override public void connect(SocketAddress endpoint, int timeout) throws IOException { @@ -36,7 +38,65 @@ public void connect(SocketAddress endpoint, int timeout) throws IOException { socket = AFUNIXSocket.newInstance(); socket.connect(AFUNIXSocketAddress.of(socketFile), socketTimeout); - socket.setSoTimeout(socketTimeout); + // keeps the previous default (read timeout = connect timeout) unless a timeout has been set explicitly + socket.setSoTimeout(pendingSoTimeout != null ? pendingSoTimeout : socketTimeout); + } + + // All of the following must be delegated to the actual AFUNIXSocket: the inherited java.net.Socket + // implementations operate on this wrapper's own SocketImpl, which never gets connected. That made e.g. + // setSoTimeout() (OkHttp's readTimeout) a no-op, and shutdownOutput() (called by OkHttp when closing the + // request body of a hijacked attach/exec stream) fail with "SocketException: Not connected". + + @Override + public synchronized void setSoTimeout(int timeout) throws SocketException { + if (timeout < 0) { + throw new IllegalArgumentException("timeout can't be negative"); + } + if (socket == null) { + pendingSoTimeout = timeout; + } + else { + socket.setSoTimeout(timeout); + } + } + + @Override + public synchronized int getSoTimeout() throws SocketException { + if (socket == null) { + return pendingSoTimeout != null ? pendingSoTimeout : 0; + } + return socket.getSoTimeout(); + } + + @Override + public void shutdownInput() throws IOException { + if (socket == null) { + throw new SocketException("Socket is not connected"); + } + socket.shutdownInput(); + } + + @Override + public void shutdownOutput() throws IOException { + if (socket == null) { + throw new SocketException("Socket is not connected"); + } + socket.shutdownOutput(); + } + + @Override + public boolean isInputShutdown() { + return socket != null && socket.isInputShutdown(); + } + + @Override + public boolean isOutputShutdown() { + return socket != null && socket.isOutputShutdown(); + } + + @Override + public boolean isBound() { + return socket != null && socket.isBound(); } @Override diff --git a/src/test/java/de/gesellix/docker/client/filesocket/UnixSocketTest.java b/src/test/java/de/gesellix/docker/client/filesocket/UnixSocketTest.java new file mode 100644 index 0000000..d1f0ef8 --- /dev/null +++ b/src/test/java/de/gesellix/docker/client/filesocket/UnixSocketTest.java @@ -0,0 +1,165 @@ +package de.gesellix.docker.client.filesocket; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.File; +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.nio.file.Files; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIf; +import org.newsclub.net.unix.AFUNIXServerSocket; +import org.newsclub.net.unix.AFUNIXSocket; +import org.newsclub.net.unix.AFUNIXSocketAddress; + +/** + * Uses an in-process unix domain socket server, no Docker engine required. + */ +@EnabledIf("isSupported") +class UnixSocketTest { + + static boolean isSupported() { + return AFUNIXSocket.isSupported(); + } + + private File socketFile; + private AFUNIXServerSocket server; + + @BeforeEach + void startServer() throws IOException { + socketFile = new File(Files.createTempDirectory("filesocket").toFile(), "test.sock"); + server = AFUNIXServerSocket.newInstance(); + server.bind(AFUNIXSocketAddress.of(socketFile)); + } + + @AfterEach + void stopServer() throws IOException { + server.close(); + socketFile.delete(); + socketFile.getParentFile().delete(); + } + + private Socket connect() throws IOException { + UnixSocket socket = new UnixSocket(); + InetAddress address = InetAddress.getByAddress(socket.encodeHostname(socketFile.getAbsolutePath()), new byte[]{0, 0, 0, 0}); + socket.connect(new InetSocketAddress(address, 0), 5000); + return socket; + } + + @Test + void halfCloseSignalsEndOfInputToThePeer() throws Exception { + // OkHttp calls shutdownOutput() when it finishes writing to a hijacked (attach/exec) stream. + // The peer must see EOF on its input, while our input stays open for the response. + AtomicReference serverError = new AtomicReference<>(); + Thread serverThread = new Thread(() -> { + try (Socket peer = server.accept()) { + InputStream in = peer.getInputStream(); + ByteArrayOutputStream received = new ByteArrayOutputStream(); + byte[] buf = new byte[64]; + int n; + while ((n = in.read(buf)) != -1) { + received.write(buf, 0, n); + } + OutputStream out = peer.getOutputStream(); + out.write(("#" + received.toString("UTF-8") + "#").getBytes(StandardCharsets.UTF_8)); + out.flush(); + } + catch (Throwable t) { + serverError.set(t); + } + }); + serverThread.start(); + + try (Socket client = connect()) { + assertTrue(client.isConnected()); + assertTrue(client.isBound()); + + client.getOutputStream().write("hello".getBytes(StandardCharsets.UTF_8)); + client.getOutputStream().flush(); + assertDoesNotThrow(client::shutdownOutput); + assertTrue(client.isOutputShutdown()); + assertFalse(client.isInputShutdown()); + + ByteArrayOutputStream response = new ByteArrayOutputStream(); + byte[] buf = new byte[64]; + int n; + while ((n = client.getInputStream().read(buf)) != -1) { + response.write(buf, 0, n); + } + assertEquals("#hello#", response.toString("UTF-8")); + } + serverThread.join(5000); + if (serverError.get() != null) { + throw new AssertionError("Server failed", serverError.get()); + } + } + + @Test + void readRespectsSoTimeout() throws Exception { + CountDownLatch done = new CountDownLatch(1); + Thread serverThread = new Thread(() -> { + try (Socket ignored = server.accept()) { + done.await(10, TimeUnit.SECONDS); // stay idle + } + catch (Exception ignored) { + } + }); + serverThread.start(); + + try (Socket client = connect()) { + client.setSoTimeout(300); + assertEquals(300, client.getSoTimeout()); + + long start = System.currentTimeMillis(); + assertThrows(SocketTimeoutException.class, () -> client.getInputStream().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 + void soTimeoutSetBeforeConnectIsApplied() throws Exception { + Thread serverThread = new Thread(() -> { + try (Socket ignored = server.accept()) { + Thread.sleep(1000); + } + catch (Exception ignored) { + } + }); + serverThread.start(); + + UnixSocket socket = new UnixSocket(); + socket.setSoTimeout(1234); + assertEquals(1234, socket.getSoTimeout()); + InetAddress address = InetAddress.getByAddress(socket.encodeHostname(socketFile.getAbsolutePath()), new byte[]{0, 0, 0, 0}); + socket.connect(new InetSocketAddress(address, 0), 5000); + try { + assertEquals(1234, socket.getSoTimeout()); + } + finally { + socket.close(); + serverThread.join(5000); + } + } +}