From 0a1b5d401630b54022363de97b39aa246d81bd0b Mon Sep 17 00:00:00 2001 From: Lukas Rytz Date: Tue, 27 Oct 2026 18:46:59 +0100 Subject: [PATCH] Fix ByteBuffer handling in ForwardingSocketChannel ForwardingSocketChannel makes a socket usable as a SocketChannel. Windows always uses it, and Unix uses it on Java versions before 17. It ignored the position and limit of the ByteBuffers passed to it: - read threw IndexOutOfBoundsException at end of stream instead of returning -1, and could put the data at the wrong place in the buffer. - write sent the buffer's whole backing array and didn't advance its position, so a loop that writes until the buffer is empty never ended. - The read and write variants that take several buffers only used the first one. Now read and write respect the buffer's position and limit, and the variants with several buffers use all of them. Also, getRemoteAddress returned the local address instead of the remote one. Co-Authored-By: Claude Opus 5.5 --- .../scalasbt/ipcsocket/SocketChannels.java | 30 +++-- .../ForwardingSocketChannelTest.java | 109 ++++++++++++++++++ .../org/scalasbt/ipcsocket/SocketPair.java | 56 +++++++++ 3 files changed, 183 insertions(+), 12 deletions(-) create mode 100644 src/test/java/org/scalasbt/ipcsocket/ForwardingSocketChannelTest.java create mode 100644 src/test/java/org/scalasbt/ipcsocket/SocketPair.java diff --git a/src/main/java/org/scalasbt/ipcsocket/SocketChannels.java b/src/main/java/org/scalasbt/ipcsocket/SocketChannels.java index eefe738..5d4401b 100644 --- a/src/main/java/org/scalasbt/ipcsocket/SocketChannels.java +++ b/src/main/java/org/scalasbt/ipcsocket/SocketChannels.java @@ -226,41 +226,47 @@ public SocketAddress getLocalAddress() { @Override public SocketAddress getRemoteAddress() { - return this.socket.getLocalSocketAddress(); + return this.socket.getRemoteSocketAddress(); } @Override public final int write(ByteBuffer buffer) throws IOException { - byte[] bs = buffer.array(); + byte[] bs = new byte[buffer.remaining()]; + buffer.get(bs); this.socket.getOutputStream().write(bs); return bs.length; } @Override public final long write(ByteBuffer buffers[], int offset, int length) throws IOException { - if (length == 0 || buffers.length == 0) { - return 0; - } else { - - return write(buffers[offset]); + long total = 0; + for (int i = offset; i < offset + length; i++) { + total += write(buffers[i]); } + return total; } @Override public final int read(ByteBuffer buffer) throws IOException { + if (!buffer.hasRemaining()) { + return 0; + } byte[] bs = new byte[buffer.remaining()]; int size = this.socket.getInputStream().read(bs); - buffer.put(bs, buffer.position(), size); + if (size > 0) { + buffer.put(bs, 0, size); + } return size; } @Override public final long read(ByteBuffer buffers[], int offset, int length) throws IOException { - if (length == 0 || buffers.length == 0) { - return 0; - } else { - return read(buffers[offset]); + for (int i = offset; i < offset + length; i++) { + if (buffers[i].hasRemaining()) { + return read(buffers[i]); + } } + return 0; } @Override diff --git a/src/test/java/org/scalasbt/ipcsocket/ForwardingSocketChannelTest.java b/src/test/java/org/scalasbt/ipcsocket/ForwardingSocketChannelTest.java new file mode 100644 index 0000000..9439d36 --- /dev/null +++ b/src/test/java/org/scalasbt/ipcsocket/ForwardingSocketChannelTest.java @@ -0,0 +1,109 @@ +package org.scalasbt.ipcsocket; + +import java.io.DataInputStream; +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.nio.charset.StandardCharsets; +import org.junit.Test; +import static org.junit.Assert.*; + +/** The channel that wraps our sockets must honour the ByteBuffer contract. */ +public class ForwardingSocketChannelTest extends BaseSocketSetup { + interface ChannelTest { + void run(SocketChannel channel, Socket peer) throws IOException; + } + + private void withChannel(ChannelTest test) throws IOException, InterruptedException { + withSocket( + sock -> { + ServerSocket serverSocket = newServerSocket(sock); + try { + SocketPair pair = SocketPair.connect(this, serverSocket, sock); + SocketChannel channel = SocketChannels.fromSocket(pair.client); + Socket peer = pair.peer; + try { + test.run(channel, peer); + } finally { + channel.close(); + peer.close(); + } + } finally { + serverSocket.close(); + } + }); + } + + private static String readExactly(Socket peer, int n) throws IOException { + byte[] bs = new byte[n]; + new DataInputStream(peer.getInputStream()).readFully(bs); + return new String(bs, StandardCharsets.UTF_8); + } + + @Test(timeout = 10000) + public void readAtEndOfStreamReturnsMinusOne() throws IOException, InterruptedException { + // Windows named pipes report a closed peer as an IOException, not as end of stream + if (isWin) return; + withChannel( + (channel, peer) -> { + peer.close(); + assertEquals(-1, channel.read(ByteBuffer.allocate(16))); + }); + } + + @Test(timeout = 10000) + public void readStoresAtBufferPosition() throws IOException, InterruptedException { + withChannel( + (channel, peer) -> { + peer.getOutputStream().write("abc".getBytes(StandardCharsets.UTF_8)); + ByteBuffer buf = ByteBuffer.allocate(16); + buf.put((byte) 'x').put((byte) 'y'); + int n = 0; + while (n < 3) n += channel.read(buf); + assertEquals(5, buf.position()); + assertEquals("xyabc", new String(buf.array(), 0, 5, StandardCharsets.UTF_8)); + }); + } + + @Test(timeout = 10000) + public void writeSendsOnlyRemainingBytes() throws IOException, InterruptedException { + withChannel( + (channel, peer) -> { + ByteBuffer buf = ByteBuffer.allocate(16); + buf.put("hi".getBytes(StandardCharsets.UTF_8)).flip(); + while (buf.hasRemaining()) channel.write(buf); + ByteBuffer direct = ByteBuffer.allocateDirect(8); + direct.put((byte) '!').flip(); + assertEquals(1, channel.write(direct)); + assertFalse(direct.hasRemaining()); + assertEquals("hi!", readExactly(peer, 3)); + }); + } + + @Test(timeout = 10000) + public void gatheringWriteSendsAllBuffers() throws IOException, InterruptedException { + withChannel( + (channel, peer) -> { + ByteBuffer[] bufs = { + ByteBuffer.wrap("skip".getBytes(StandardCharsets.UTF_8)), + ByteBuffer.wrap("ab".getBytes(StandardCharsets.UTF_8)), + ByteBuffer.wrap("cd".getBytes(StandardCharsets.UTF_8)) + }; + assertEquals(4, channel.write(bufs, 1, 2)); + assertEquals("abcd", readExactly(peer, 4)); + }); + } + + @Test(timeout = 10000) + public void scatteringReadSkipsFullBuffers() throws IOException, InterruptedException { + withChannel( + (channel, peer) -> { + peer.getOutputStream().write("z".getBytes(StandardCharsets.UTF_8)); + ByteBuffer[] bufs = {ByteBuffer.allocate(0), ByteBuffer.allocate(4)}; + assertEquals(1, channel.read(bufs, 0, 2)); + assertEquals('z', bufs[1].get(0)); + }); + } +} diff --git a/src/test/java/org/scalasbt/ipcsocket/SocketPair.java b/src/test/java/org/scalasbt/ipcsocket/SocketPair.java new file mode 100644 index 0000000..b8b3ab1 --- /dev/null +++ b/src/test/java/org/scalasbt/ipcsocket/SocketPair.java @@ -0,0 +1,56 @@ +package org.scalasbt.ipcsocket; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +/** + * A connected client and the server's socket for it. A named pipe instance only exists while the + * server is in accept(), so the client connects after accept() has started. + */ +final class SocketPair { + final Socket client; + final Socket peer; + + private SocketPair(Socket client, Socket peer) { + this.client = client; + this.peer = peer; + } + + static SocketPair connect(BaseSocketSetup setup, ServerSocket server, String name) + throws IOException { + CompletableFuture accept = + CompletableFuture.supplyAsync( + () -> { + try { + return server.accept(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); + long deadline = System.currentTimeMillis() + 10000; + Socket client; + while (true) { + try { + client = setup.newClientSocket(name); + break; + } catch (IOException e) { + if (System.currentTimeMillis() > deadline) throw e; + try { + Thread.sleep(20); + } catch (InterruptedException ie) { + throw new IOException(ie); + } + } + } + try { + return new SocketPair(client, accept.get(10, TimeUnit.SECONDS)); + } catch (Exception e) { + client.close(); + throw new IOException(e); + } + } +}