Skip to content
Open
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 @@ -2,7 +2,6 @@

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;

import com.sun.jna.*;
import com.sun.jna.platform.win32.WinError;
Expand Down Expand Up @@ -126,6 +125,9 @@ public int read(
boolean requireStrictLength,
int timeoutMillis)
throws IOException {
if (len == 0) {
return 0;
}
HANDLE readerWaitable = getHandle(waitable);
HANDLE handle = getHandle(hFile);
Memory readBuffer = new Memory(len);
Expand All @@ -134,60 +136,86 @@ public int read(
olap.hEvent = readerWaitable;
olap.write();

boolean immediate = delegate.ReadFile(handle, readBuffer, len, null, olap.getPointer());
if (!immediate) {
int lastError = delegate.GetLastError();
if (lastError != WinError.ERROR_IO_PENDING) {
throw new IOException("ReadFile() failed: " + lastError);
boolean timedOut = false;
int actualLen;
try {
boolean immediate = delegate.ReadFile(handle, readBuffer, len, null, olap.getPointer());
if (!immediate) {
int lastError = delegate.GetLastError();
if (lastError != WinError.ERROR_IO_PENDING) {
throw new IOException("ReadFile() failed: " + lastError);
}
if (timeoutMillis > 0) {
int res = delegate.WaitForSingleObject(olap.hEvent, timeoutMillis);
if (res == WinError.WAIT_TIMEOUT) {
// Cancel only this read: another thread may be writing to the pipe. The kernel still
// owns olap and readBuffer, so wait below until the cancel completes.
delegate.CancelIoEx(handle, olap.getPointer());
timedOut = true;
}
}
}
if (timeoutMillis > 0) {
int res = delegate.WaitForSingleObject(olap.hEvent, timeoutMillis);
if (res == WinError.WAIT_TIMEOUT) {
throw new SocketTimeoutException("ReadFile() timed out " + res);
IntByReference r = new IntByReference();
if (!delegate.GetOverlappedResult(handle, olap.getPointer(), r, true)) {
int lastError = delegate.GetLastError();
if (timedOut && lastError == WinError.ERROR_OPERATION_ABORTED) {
throw new SocketTimeoutException("ReadFile() timed out after " + timeoutMillis + " ms");
}
throw new IOException("GetOverlappedResult() failed for read operation: " + lastError);
}
// If data arrived before the cancel took effect, the read succeeded after all
actualLen = r.getValue();
if (requireStrictLength && (actualLen != len)) {
throw new IOException(
"ReadFile() read less bytes than requested: expected "
+ len
+ " bytes, but read "
+ actualLen
+ " bytes");
}
readBuffer.read(0, buffer, offset, actualLen);
} finally {
// The kernel is done with readBuffer: GetOverlappedResult has returned, or ReadFile failed
// without starting a read
readBuffer.close();
}
IntByReference r = new IntByReference();
if (!delegate.GetOverlappedResult(handle, olap.getPointer(), r, true)) {
int lastError = delegate.GetLastError();
throw new IOException("GetOverlappedResult() failed for read operation: " + lastError);
}
int actualLen = r.getValue();
if (requireStrictLength && (actualLen != len)) {
throw new IOException(
"ReadFile() read less bytes than requested: expected "
+ len
+ " bytes, but read "
+ actualLen
+ " bytes");
}
byte[] byteArray = readBuffer.getByteArray(0, actualLen);
System.arraycopy(byteArray, 0, buffer, offset, actualLen);
return actualLen;
}

@Override
public void write(Handle waitable, Handle hHandle, byte[] b, int off, int len)
throws IOException {
if (len == 0) {
return;
}
HANDLE writerWaitable = getHandle(waitable);
HANDLE handle = getHandle(hHandle);
ByteBuffer data = ByteBuffer.wrap(b, off, len);
// Not a heap ByteBuffer: JNA would copy it to memory that it frees when
// WriteFile returns, while a pending write may still read from it.
Memory data = new Memory(len);
data.write(0, b, off, len);

OVERLAPPED olap = new OVERLAPPED();
olap.hEvent = writerWaitable;
olap.write();

boolean immediate = delegate.WriteFile(handle, data, len, null, olap.getPointer());
if (!immediate) {
int lastError = delegate.GetLastError();
if (lastError != WinError.ERROR_IO_PENDING) {
throw new IOException("WriteFile() failed: " + lastError);
}
}
IntByReference written = new IntByReference();
if (!delegate.GetOverlappedResult(handle, olap.getPointer(), written, true)) {
int lastError = delegate.GetLastError();
throw new IOException("GetOverlappedResult() failed for write operation: " + lastError);
try {
boolean immediate = delegate.WriteFile(handle, data, len, null, olap.getPointer());
if (!immediate) {
int lastError = delegate.GetLastError();
if (lastError != WinError.ERROR_IO_PENDING) {
throw new IOException("WriteFile() failed: " + lastError);
}
}
if (!delegate.GetOverlappedResult(handle, olap.getPointer(), written, true)) {
int lastError = delegate.GetLastError();
throw new IOException("GetOverlappedResult() failed for write operation: " + lastError);
}
} finally {
// Keeps data reachable until the write has completed, which it has once
// GetOverlappedResult returns
data.close();
}
if (written.getValue() != len) {
throw new IOException("WriteFile() wrote less bytes than requested");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.io.IOException;
import java.nio.ByteBuffer;

import com.sun.jna.*;
import com.sun.jna.platform.win32.WinNT;
Expand Down Expand Up @@ -77,7 +76,7 @@ boolean ReadFile(

boolean WriteFile(
HANDLE hFile,
ByteBuffer lpBuffer,
Memory lpBuffer,
int nNumberOfBytesToWrite,
IntByReference lpNumberOfBytesWritten,
Pointer lpOverlapped);
Expand Down
41 changes: 41 additions & 0 deletions src/test/java/org/scalasbt/ipcsocket/ReadTimeoutTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package org.scalasbt.ipcsocket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import org.junit.Test;
import static org.junit.Assert.*;

/** A read that times out must not consume or lose data that arrives later. */
public class ReadTimeoutTest extends BaseSocketSetup {
@Test(timeout = 20000)
public void readAfterTimeoutGetsData() throws IOException, InterruptedException {
// only named pipes implement SO_TIMEOUT
if (!isWin) return;
withSocket(
sock -> {
ServerSocket serverSocket = newServerSocket(sock);
SocketPair pair = SocketPair.connect(this, serverSocket, sock);
try (Socket client = pair.client;
Socket peer = pair.peer) {
client.setSoTimeout(100);
for (int i = 0; i < 20; i++) {
try {
client.getInputStream().read(new byte[16]);
fail("read returned without data");
} catch (SocketTimeoutException e) {
}
System.gc();
}
peer.getOutputStream().write(new byte[] {1, 2, 3});
client.setSoTimeout(5000);
byte[] buf = new byte[16];
assertEquals(3, client.getInputStream().read(buf));
assertArrayEquals(new byte[] {1, 2, 3}, java.util.Arrays.copyOf(buf, 3));
} finally {
serverSocket.close();
}
});
}
}
56 changes: 56 additions & 0 deletions src/test/java/org/scalasbt/ipcsocket/SocketPair.java
Original file line number Diff line number Diff line change
@@ -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<Socket> 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);
}
}
}
99 changes: 99 additions & 0 deletions src/test/java/org/scalasbt/ipcsocket/TimeoutWhileWritingTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package org.scalasbt.ipcsocket;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import static org.junit.Assert.*;

/**
* Like sbt's server: one thread reads with a short timeout while another writes. A timed-out read
* must not fail the writes, and must not lose data that arrives afterwards. The writes must send
* the data they were given.
*/
public class TimeoutWhileWritingTest extends BaseSocketSetup {
@Test(timeout = 60000)
public void writesSurviveReadTimeouts() throws Exception {
// only named pipes implement SO_TIMEOUT
if (!isWin) return;
withSocket(
sock -> {
ServerSocket serverSocket = newServerSocket(sock);
SocketPair pair = SocketPair.connect(this, serverSocket, sock);
try (Socket server = pair.peer;
Socket client = pair.client) {
server.setSoTimeout(50);
final int n = 2000;
CompletableFuture<Void> reader =
CompletableFuture.runAsync(
() -> {
try {
InputStream in = server.getInputStream();
int expected = 0;
while (expected < 20) {
try {
int b = in.read();
assertEquals("message lost after a read timeout", expected, b);
expected++;
} catch (SocketTimeoutException e) {
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
});
CompletableFuture<Void> clientWriter =
CompletableFuture.runAsync(
() -> {
try {
OutputStream out = client.getOutputStream();
for (int i = 0; i < 20; i++) {
Thread.sleep(120);
out.write(i);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
});
CompletableFuture<byte[]> clientReader =
CompletableFuture.supplyAsync(
() -> {
try {
byte[] buf = new byte[n * 100];
new DataInputStream(client.getInputStream()).readFully(buf);
return buf;
} catch (IOException e) {
throw new RuntimeException(e);
}
});
// The writes fill the pipe, so some complete later, after WriteFile has returned
OutputStream out = server.getOutputStream();
byte[] chunk = new byte[100];
for (int i = 0; i < n; i++) {
Arrays.fill(chunk, (byte) i);
out.write(chunk);
if (i % 100 == 0) Thread.sleep(10);
}
byte[] received = clientReader.get(30, TimeUnit.SECONDS);
for (int i = 0; i < n * 100; i++) {
if (received[i] != (byte) (i / 100)) {
fail("wrong data received at byte " + i);
}
}
clientWriter.get(30, TimeUnit.SECONDS);
reader.get(30, TimeUnit.SECONDS);
} catch (Exception e) {
throw new IOException(e);
} finally {
serverSocket.close();
}
});
}
}
Loading