Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down
165 changes: 165 additions & 0 deletions src/test/java/de/gesellix/docker/client/filesocket/UnixSocketTest.java
Original file line number Diff line number Diff line change
@@ -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<Throwable> 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);
}
}
}
Loading