Fixes #2547 - Review usages of ServerSocket[Channel].accept().

Signed-off-by: Simone Bordet <simone.bordet@gmail.com>
This commit is contained in:
Simone Bordet 2018-05-16 18:40:10 +02:00
parent 7a7aa0f1b1
commit 744f9054b3
11 changed files with 1347 additions and 1371 deletions

View File

@ -479,7 +479,8 @@ public class HttpClientTLSTest
latch.countDown();
});
Socket socket = server.accept();
try (Socket socket = server.accept())
{
SSLSocket sslSocket = (SSLSocket)serverTLSFactory.getSslContext().getSocketFactory().createSocket(socket, null, socket.getPort(), true);
sslSocket.setUseClientMode(false);
BufferedReader reader = new BufferedReader(new InputStreamReader(sslSocket.getInputStream(), StandardCharsets.UTF_8));
@ -509,8 +510,9 @@ public class HttpClientTLSTest
output.write(response.getBytes(StandardCharsets.UTF_8));
output.write(half);
output.flush();
// Simulate a truncation attack by raw closing.
socket.close();
// Simulate a truncation attack by raw closing
// the socket in the try-with-resources block end.
}
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}

View File

@ -98,7 +98,8 @@ public class ServerConnectionCloseTest
private void testServerSendsConnectionClose(boolean shutdownOutput, boolean chunked, String content) throws Exception
{
ServerSocket server = new ServerSocket(0);
try (ServerSocket server = new ServerSocket(0))
{
int port = server.getLocalPort();
startClient();
@ -107,8 +108,8 @@ public class ServerConnectionCloseTest
FutureResponseListener listener = new FutureResponseListener(request);
request.send(listener);
Socket socket = server.accept();
try (Socket socket = server.accept())
{
InputStream input = socket.getInputStream();
consumeRequest(input);
@ -156,6 +157,8 @@ public class ServerConnectionCloseTest
Assert.assertEquals(0, connectionPool.getIdleConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnectionCount());
}
}
}
private boolean consumeRequest(InputStream input) throws IOException
{

View File

@ -79,8 +79,8 @@ public class Socks4ProxyTest
latch.countDown();
});
SocketChannel channel = server.accept();
try (SocketChannel channel = server.accept())
{
int socks4MessageLength = 9;
ByteBuffer buffer = ByteBuffer.allocate(socks4MessageLength);
int read = channel.read(buffer);
@ -112,8 +112,7 @@ public class Socks4ProxyTest
channel.write(ByteBuffer.wrap(response.getBytes("UTF-8")));
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
channel.close();
}
}
@Test
@ -139,8 +138,8 @@ public class Socks4ProxyTest
result.getFailure().printStackTrace();
});
SocketChannel channel = server.accept();
try (SocketChannel channel = server.accept())
{
int socks4MessageLength = 9;
ByteBuffer buffer = ByteBuffer.allocate(socks4MessageLength);
int read = channel.read(buffer);
@ -171,7 +170,6 @@ public class Socks4ProxyTest
channel.write(ByteBuffer.wrap(response.getBytes("UTF-8")));
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
channel.close();
}
}
}

View File

@ -104,7 +104,8 @@ public class TLSServerConnectionCloseTest
private void testServerSendsConnectionClose(boolean chunked, String content) throws Exception
{
ServerSocket server = new ServerSocket(0);
try (ServerSocket server = new ServerSocket(0))
{
int port = server.getLocalPort();
startClient();
@ -113,7 +114,8 @@ public class TLSServerConnectionCloseTest
FutureResponseListener listener = new FutureResponseListener(request);
request.send(listener);
Socket socket = server.accept();
try (Socket socket = server.accept())
{
SSLContext sslContext = client.getSslContextFactory().getSslContext();
SSLSocket sslSocket = (SSLSocket)sslContext.getSocketFactory().createSocket(socket, "localhost", port, false);
sslSocket.setUseClientMode(false);
@ -186,6 +188,8 @@ public class TLSServerConnectionCloseTest
Assert.assertEquals(0, connectionPool.getIdleConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnectionCount());
}
}
}
private boolean consumeRequest(InputStream input) throws IOException
{

View File

@ -101,7 +101,8 @@ public class SslBytesClientTest extends SslBytesTest
Assert.assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS));
final SSLSocket server = (SSLSocket)acceptor.accept();
try (SSLSocket server = (SSLSocket)acceptor.accept())
{
server.setUseClientMode(false);
Future<Object> handshake = threadPool.submit(() ->
@ -165,8 +166,7 @@ public class SslBytesClientTest extends SslBytesTest
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
server.close();
}
}
@Test
@ -178,7 +178,8 @@ public class SslBytesClientTest extends SslBytesTest
Assert.assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS));
final SSLSocket server = (SSLSocket)acceptor.accept();
try (SSLSocket server = (SSLSocket)acceptor.accept())
{
server.setUseClientMode(false);
Future<Object> handshake = threadPool.submit(() ->
@ -279,8 +280,7 @@ public class SslBytesClientTest extends SslBytesTest
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
Assert.assertEquals(data1.length + data2.length, response.getContent().length);
server.close();
}
}
@Test
@ -294,7 +294,8 @@ public class SslBytesClientTest extends SslBytesTest
Assert.assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS));
final SSLSocket server = (SSLSocket)acceptor.accept();
try (SSLSocket server = (SSLSocket)acceptor.accept())
{
server.setUseClientMode(false);
Future<Object> handshake = threadPool.submit(() ->
@ -347,7 +348,6 @@ public class SslBytesClientTest extends SslBytesTest
Assert.assertEquals(TLSRecord.Type.ALERT, record.getType());
record = proxy.readFromClient();
Assert.assertNull(record);
server.close();
}
}
}

View File

@ -54,7 +54,8 @@ public class InvalidServerTest extends AbstractTest
}
}, promise);
Socket socket = server.accept();
try (Socket socket = server.accept())
{
OutputStream output = socket.getOutputStream();
output.write("enough_junk_bytes".getBytes(StandardCharsets.UTF_8));
@ -73,4 +74,5 @@ public class InvalidServerTest extends AbstractTest
}
}
}
}
}

View File

@ -18,14 +18,6 @@
package org.eclipse.jetty.io;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@ -52,10 +44,17 @@ import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.OS;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.IO;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class IOTest
{
@Test
@ -73,11 +72,10 @@ public class IOTest
@Test
public void testHalfClose() throws Exception
{
ServerSocket connector = new ServerSocket(0);
try (ServerSocket connector = new ServerSocket(0);
Socket client = new Socket("localhost", connector.getLocalPort());
Socket server = connector.accept();
Socket server = connector.accept())
{
// we can write both ways
client.getOutputStream().write(1);
assertEquals(1, server.getInputStream().read());
@ -100,7 +98,7 @@ public class IOTest
client.getOutputStream().write(1);
fail("exception expected");
}
catch (SocketException e)
catch (SocketException expected)
{
}
@ -117,7 +115,7 @@ public class IOTest
server.getInputStream().read();
fail("exception expected");
}
catch (SocketException e)
catch (SocketException expected)
{
}
@ -134,7 +132,7 @@ public class IOTest
client.getInputStream().read();
fail("exception expected");
}
catch (SocketException e)
catch (SocketException expected)
{
}
@ -153,7 +151,7 @@ public class IOTest
server.getOutputStream().write(1);
fail("exception expected");
}
catch (SocketException e)
catch (SocketException expected)
{
}
@ -174,17 +172,20 @@ public class IOTest
server.close();
assertTrue(server.isClosed());
}
}
@Test
public void testHalfCloseClientServer() throws Exception
{
ServerSocketChannel connector = ServerSocketChannel.open();
try (ServerSocketChannel connector = ServerSocketChannel.open())
{
connector.socket().bind(null);
Socket client = SocketChannel.open(connector.socket().getLocalSocketAddress()).socket();
try (Socket client = SocketChannel.open(connector.socket().getLocalSocketAddress()).socket())
{
client.setSoTimeout(1000);
client.setSoLinger(false, -1);
Socket server = connector.accept().socket();
try (Socket server = connector.accept().socket())
{
server.setSoTimeout(1000);
server.setSoLinger(false, -1);
@ -221,35 +222,32 @@ public class IOTest
assertFalse(server.isInputShutdown());
//System.err.println("ISHUT "+server);
try
{
server.shutdownInput();
}
catch (SocketException e)
{
// System.err.println(e);
}
//System.err.println("CLOSE "+server);
server.close();
}
catch (Exception e)
{
System.err.println(e);
e.printStackTrace();
assertTrue(OS.IS_OSX);
}
}
}
}
}
@Test
public void testHalfCloseBadClient() throws Exception
{
ServerSocketChannel connector = ServerSocketChannel.open();
try (ServerSocketChannel connector = ServerSocketChannel.open())
{
connector.socket().bind(null);
Socket client = SocketChannel.open(connector.socket().getLocalSocketAddress()).socket();
try (Socket client = SocketChannel.open(connector.socket().getLocalSocketAddress()).socket())
{
client.setSoTimeout(1000);
client.setSoLinger(false, -1);
Socket server = connector.accept().socket();
try (Socket server = connector.accept().socket())
{
server.setSoTimeout(1000);
server.setSoLinger(false, -1);
@ -264,8 +262,6 @@ public class IOTest
//System.err.println("OSHUT "+server);
server.shutdownOutput();
try
{
// Client reads response
assertEquals(1, client.getInputStream().read());
@ -296,38 +292,33 @@ public class IOTest
client.getOutputStream().write(1);
// Client eventually sees Broken Pipe
int i = 0;
try
{
for (i = 0; i < 100000; i++)
for (int i = 0; i < 100000; i++)
client.getOutputStream().write(1);
Assert.fail();
}
catch (IOException e)
catch (IOException expected)
{
}
client.close();
}
catch (Exception e)
{
System.err.println("PLEASE INVESTIGATE:");
e.printStackTrace();
}
}
}
@Test
public void testServerChannelInterrupt() throws Exception
{
final ServerSocketChannel connector = ServerSocketChannel.open();
try (ServerSocketChannel connector = ServerSocketChannel.open())
{
connector.configureBlocking(true);
connector.socket().bind(null);
Socket client = SocketChannel.open(connector.socket().getLocalSocketAddress()).socket();
try (Socket client = SocketChannel.open(connector.socket().getLocalSocketAddress()).socket())
{
client.setSoTimeout(2000);
client.setSoLinger(false, -1);
Socket server = connector.accept().socket();
try (Socket server = connector.accept().socket())
{
server.setSoTimeout(2000);
server.setSoLinger(false, -1);
@ -341,37 +332,32 @@ public class IOTest
// Client reads
assertEquals(1, client.getInputStream().read());
// block a thread in accept
final CountDownLatch alatch=new CountDownLatch(2);
Thread acceptor = new Thread()
{
@Override
public void run()
final CountDownLatch latch = new CountDownLatch(2);
Thread acceptor = new Thread(() ->
{
try
{
alatch.countDown();
latch.countDown();
connector.accept();
}
catch (Throwable e)
catch (Throwable ignored)
{
}
finally
{
alatch.countDown();
latch.countDown();
}
}
};
});
acceptor.start();
while (alatch.getCount()==2)
while (latch.getCount() == 2)
Thread.sleep(10);
// interrupt the acceptor
acceptor.interrupt();
// wait for acceptor to exit
assertTrue(alatch.await(10,TimeUnit.SECONDS));
assertTrue(latch.await(10, TimeUnit.SECONDS));
// connector is closed
assertFalse(connector.isOpen());
@ -389,9 +375,9 @@ public class IOTest
server.getOutputStream().write(43);
// Client reads
assertEquals(43, client.getInputStream().read());
client.close();
}
}
}
}
@ -401,7 +387,7 @@ public class IOTest
{
try (ServerSocket connector = new ServerSocket(0);
Socket client = new Socket("127.0.0.1", connector.getLocalPort());
Socket server = connector.accept();)
Socket server = connector.accept())
{
client.setTcpNoDelay(true);
client.setSoLinger(true, 0);
@ -430,8 +416,8 @@ public class IOTest
assertEquals(-1, server.getInputStream().read());
server.shutdownInput();
// Since output was already shutdown, server closes
server.close();
// Since output was already shutdown, server
// closes in the try-with-resources block end.
}
}
@ -490,28 +476,27 @@ public class IOTest
assertEquals(expected,wrote);
for (int i=0;i<buffers.length;i++)
assertEquals(0,buffers[i].remaining());
for (ByteBuffer buffer : buffers)
assertEquals(0, buffer.remaining());
}
@Test
public void testSelectorWakeup() throws Exception
{
ServerSocketChannel connector = ServerSocketChannel.open();
try (ServerSocketChannel connector = ServerSocketChannel.open())
{
connector.bind(null);
InetSocketAddress addr=(InetSocketAddress)connector.getLocalAddress();
SocketChannel client = SocketChannel.open();
client.connect(new InetSocketAddress("127.0.0.1",addr.getPort()));
SocketChannel server = connector.accept();
InetSocketAddress addr = (InetSocketAddress)connector.getLocalAddress();
try (SocketChannel client = SocketChannel.open(new InetSocketAddress("127.0.0.1", addr.getPort()));
SocketChannel server = connector.accept())
{
server.configureBlocking(false);
Selector selector = Selector.open();
SelectionKey key = server.register(selector,SelectionKey.OP_READ);
SelectionKey key = server.register(selector, SelectionKey.OP_READ);
assertThat(key,notNullValue());
assertThat(key, notNullValue());
assertThat(selector.selectNow(), is(0));
// Test wakeup before select
@ -519,23 +504,20 @@ public class IOTest
assertThat(selector.select(), is(0));
// Test wakeup after select
new Thread()
{
@Override
public void run()
new Thread(() ->
{
try
{
Thread.sleep(100);
selector.wakeup();
}
catch(Exception e)
catch (Exception e)
{
e.printStackTrace();
}
}
}.start();
}).start();
assertThat(selector.select(), is(0));
}
}
}
}

View File

@ -18,10 +18,6 @@
package org.eclipse.jetty.io;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
@ -31,39 +27,38 @@ import java.nio.channels.SocketChannel;
import org.junit.Test;
/**
*
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class NIOTest
{
@Test
public void testSelector() throws Exception
{
ServerSocket acceptor = new ServerSocket(0);
try (ServerSocket acceptor = new ServerSocket(0);
Selector selector = Selector.open();
// Create client server socket pair
SocketChannel client = SocketChannel.open(acceptor.getLocalSocketAddress());
Socket server = acceptor.accept();
Socket server = acceptor.accept())
{
server.setTcpNoDelay(true);
// Make the client non blocking and register it with selector for reads
client.configureBlocking(false);
SelectionKey key = client.register(selector,SelectionKey.OP_READ);
SelectionKey key = client.register(selector, SelectionKey.OP_READ);
// assert it is not selected
assertTrue(key.isValid());
assertFalse(key.isReadable());
assertEquals(0,key.readyOps());
assertEquals(0, key.readyOps());
// try selecting and assert nothing selected
int selected = selector.selectNow();
assertEquals(0,selected);
assertEquals(0,selector.selectedKeys().size());
assertEquals(0, selected);
assertEquals(0, selector.selectedKeys().size());
assertTrue(key.isValid());
assertFalse(key.isReadable());
assertEquals(0,key.readyOps());
assertEquals(0, key.readyOps());
// Write a byte from server to client
server.getOutputStream().write(42);
@ -71,66 +66,66 @@ public class NIOTest
// select again and assert selection found for read
selected = selector.select(1000);
assertEquals(1,selected);
assertEquals(1,selector.selectedKeys().size());
assertEquals(1, selected);
assertEquals(1, selector.selectedKeys().size());
assertTrue(key.isValid());
assertTrue(key.isReadable());
assertEquals(1,key.readyOps());
assertEquals(1, key.readyOps());
// select again and see that it is not reselect, but stays selected
selected = selector.select(100);
assertEquals(0,selected);
assertEquals(1,selector.selectedKeys().size());
assertEquals(0, selected);
assertEquals(1, selector.selectedKeys().size());
assertTrue(key.isValid());
assertTrue(key.isReadable());
assertEquals(1,key.readyOps());
assertEquals(1, key.readyOps());
// read the byte
ByteBuffer buf = ByteBuffer.allocate(1024);
int len=client.read(buf);
assertEquals(1,len);
int len = client.read(buf);
assertEquals(1, len);
buf.flip();
assertEquals(42,buf.get());
assertEquals(42, buf.get());
buf.clear();
// But this does not change the key
assertTrue(key.isValid());
assertTrue(key.isReadable());
assertEquals(1,key.readyOps());
assertEquals(1, key.readyOps());
// Even if we select again ?
selected = selector.select(100);
assertEquals(0,selected);
assertEquals(1,selector.selectedKeys().size());
assertEquals(0, selected);
assertEquals(1, selector.selectedKeys().size());
assertTrue(key.isValid());
assertTrue(key.isReadable());
assertEquals(1,key.readyOps());
assertEquals(1, key.readyOps());
// Unless we remove the key from the select set
// and then it is still flagged as isReadable()
selector.selectedKeys().clear();
assertEquals(0,selector.selectedKeys().size());
assertEquals(0, selector.selectedKeys().size());
assertTrue(key.isValid());
assertTrue(key.isReadable());
assertEquals(1,key.readyOps());
assertEquals(1, key.readyOps());
// Now if we select again - it is still flagged as readable!!!
selected = selector.select(100);
assertEquals(0,selected);
assertEquals(0,selector.selectedKeys().size());
assertEquals(0, selected);
assertEquals(0, selector.selectedKeys().size());
assertTrue(key.isValid());
assertTrue(key.isReadable());
assertEquals(1,key.readyOps());
assertEquals(1, key.readyOps());
// Only when it is selected for something else does that state change.
key.interestOps(SelectionKey.OP_READ|SelectionKey.OP_WRITE);
key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
selected = selector.select(1000);
assertEquals(1,selected);
assertEquals(1,selector.selectedKeys().size());
assertEquals(1, selected);
assertEquals(1, selector.selectedKeys().size());
assertTrue(key.isValid());
assertTrue(key.isWritable());
assertFalse(key.isReadable());
assertEquals(SelectionKey.OP_WRITE,key.readyOps());
assertEquals(SelectionKey.OP_WRITE, key.readyOps());
}
}
}

View File

@ -65,7 +65,7 @@ public class SocketChannelEndPointInterestsTest
{
@Override
protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey key) throws IOException
protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey key)
{
SocketChannelEndPoint endp = new SocketChannelEndPoint(channel, selector, key, getScheduler())
{
@ -176,11 +176,12 @@ public class SocketChannelEndPointInterestsTest
}
});
Socket client = new Socket();
try (Socket client = new Socket())
{
client.connect(connector.getLocalAddress());
client.setSoTimeout(5000);
SocketChannel server = connector.accept();
try (SocketChannel server = connector.accept())
{
server.configureBlocking(false);
selectorManager.accept(server);
@ -203,10 +204,10 @@ public class SocketChannelEndPointInterestsTest
while (size.getAndDecrement() > 0)
clientInput.read();
client.close();
Assert.assertNull(failure.get());
}
}
}
private interface Interested
{
@ -214,5 +215,4 @@ public class SocketChannelEndPointInterestsTest
void onIncompleteFlush();
}
}

View File

@ -18,13 +18,6 @@
package org.eclipse.jetty.io;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
@ -73,6 +66,13 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
@SuppressWarnings("Duplicates")
@RunWith(Parameterized.class)
public class SocketChannelEndPointTest
@ -143,13 +143,12 @@ public class SocketChannelEndPointTest
@Test
public void testEcho() throws Exception
{
Socket client = _scenario.newClient(_connector);
try (Socket client = _scenario.newClient(_connector))
{
client.setSoTimeout(60000);
SocketChannel server = _connector.accept();
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
// Write client to server
@ -160,7 +159,7 @@ public class SocketChannelEndPointTest
{
int b = client.getInputStream().read();
assertTrue(b > 0);
assertEquals(c, (char) b);
assertEquals(c, (char)b);
}
// wait for read timeout
@ -185,7 +184,7 @@ public class SocketChannelEndPointTest
{
int b = client.getInputStream().read();
Assert.assertThat("expect valid char integer", b, greaterThan(0));
assertEquals("expect characters to be same", c, (char) b);
assertEquals("expect characters to be same", c, (char)b);
}
client.close();
@ -198,19 +197,20 @@ public class SocketChannelEndPointTest
}
assertFalse(server.isOpen());
}
}
}
@Test
public void testShutdown() throws Exception
{
assumeTrue("Scenario supports half-close", _scenario.supportsHalfCloses());
Socket client = _scenario.newClient(_connector);
try (Socket client = _scenario.newClient(_connector))
{
client.setSoTimeout(500);
SocketChannel server = _connector.accept();
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
// Write client to server
@ -221,7 +221,7 @@ public class SocketChannelEndPointTest
{
int b = client.getInputStream().read();
assertTrue(b > 0);
assertEquals(c, (char) b);
assertEquals(c, (char)b);
}
// wait for read timeout
@ -245,21 +245,22 @@ public class SocketChannelEndPointTest
{
int b = client.getInputStream().read();
assertTrue(b > 0);
assertEquals(c, (char) b);
assertEquals(c, (char)b);
}
// Read close
assertEquals(-1, client.getInputStream().read());
}
}
}
@Test
public void testReadBlocked() throws Exception
{
Socket client = _scenario.newClient(_connector);
SocketChannel server = _connector.accept();
try (Socket client = _scenario.newClient(_connector);
SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
OutputStream clientOutputStream = client.getOutputStream();
@ -298,19 +299,20 @@ public class SocketChannelEndPointTest
{
int b = clientInputStream.read();
assertTrue(b > 0);
assertEquals(c, (char) b);
assertEquals(c, (char)b);
}
}
}
@Test
public void testStress() throws Exception
{
Socket client = _scenario.newClient(_connector);
try (Socket client = _scenario.newClient(_connector))
{
client.setSoTimeout(30000);
SocketChannel server = _connector.accept();
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
final int writes = 200000;
@ -327,14 +329,11 @@ public class SocketChannelEndPointTest
Assert.assertTrue(_lastEndPointLatch.await(1, TimeUnit.SECONDS));
_lastEndPoint.setIdleTimeout(5000);
new Thread()
new Thread(() ->
{
@Override
public void run()
{
Thread.currentThread().setPriority(MAX_PRIORITY);
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
long last = -1;
int count = -1;
int count1 = -1;
try
{
while (latch.getCount() > 0)
@ -347,11 +346,11 @@ public class SocketChannelEndPointTest
assertEquals(0xff & b0, b);
}
count = 0;
count1 = 0;
int b = in.read();
while (b > 0 && b != '\n')
{
count = count * 10 + (b - '0');
count1 = count1 * 10 + (b - '0');
b = in.read();
}
last = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
@ -366,7 +365,7 @@ public class SocketChannelEndPointTest
{
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
System.err.println("count=" + count);
System.err.println("count=" + count1);
System.err.println("latch=" + latch.getCount());
System.err.println("time=" + (now - start));
System.err.println("last=" + (now - last));
@ -375,8 +374,7 @@ public class SocketChannelEndPointTest
e.printStackTrace();
}
}
}.start();
}).start();
// Write client to server
for (int i = 1; i < writes; i++)
@ -404,17 +402,18 @@ public class SocketChannelEndPointTest
assertEquals(0, latch.getCount());
}
}
}
@Test
public void testWriteBlocked() throws Exception
{
Socket client = _scenario.newClient(_connector);
try (Socket client = _scenario.newClient(_connector))
{
client.setSoTimeout(10000);
SocketChannel server = _connector.accept();
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
// Write client to server
@ -438,7 +437,7 @@ public class SocketChannelEndPointTest
int b = in.read();
byteNum++;
assertTrue(b > 0);
assertEquals("test-" + i + "/" + j, c, (char) b);
assertEquals("test-" + i + "/" + j, c, (char)b);
}
if (i == 0)
@ -464,6 +463,8 @@ public class SocketChannelEndPointTest
}
assertFalse(server.isOpen());
}
}
}
// TODO make this test reliable
@ -482,7 +483,7 @@ public class SocketChannelEndPointTest
{
@Override
protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey selectionKey) throws IOException
protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey selectionKey)
{
SocketChannelEndPoint endp = new SocketChannelEndPoint(channel, selector, selectionKey, getScheduler());
_lastEndPoint = endp;
@ -491,7 +492,7 @@ public class SocketChannelEndPointTest
}
@Override
public Connection newConnection(SelectableChannel channel, EndPoint endpoint, Object attachment) throws IOException
public Connection newConnection(SelectableChannel channel, EndPoint endpoint, Object attachment)
{
return new TestConnection(endpoint, latch, getExecutor(), _blockAt, _writeCount);
}
@ -507,18 +508,14 @@ public class SocketChannelEndPointTest
CountDownLatch closed = new CountDownLatch(20);
for (int i = 0; i < 20; i++)
{
new Thread()
new Thread(() ->
{
@Override
public void run()
{
try (Socket client = _scenario.newClient(_connector);)
try (Socket client = _scenario.newClient(_connector))
{
client.setSoTimeout(5000);
SocketChannel server = _connector.accept();
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
// Write client to server
@ -531,11 +528,12 @@ public class SocketChannelEndPointTest
{
int b = client.getInputStream().read();
assertTrue(b > 0);
assertEquals(c, (char) b);
assertEquals(c, (char)b);
}
assertEquals(-1, client.getInputStream().read());
echoed.incrementAndGet();
}
}
catch (SocketTimeoutException x)
{
x.printStackTrace();
@ -549,8 +547,7 @@ public class SocketChannelEndPointTest
{
closed.countDown();
}
}
}.start();
}).start();
}
// unblock the handling
@ -572,10 +569,9 @@ public class SocketChannelEndPointTest
try (Socket client = _scenario.newClient(_connector))
{
client.setSoTimeout(5000);
SocketChannel server = _connector.accept();
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
// Write client to server
@ -588,11 +584,12 @@ public class SocketChannelEndPointTest
{
int b = client.getInputStream().read();
assertTrue(b > 0);
assertEquals(c, (char) b);
assertEquals(c, (char)b);
}
assertEquals(-1, client.getInputStream().read());
}
}
}
public class ScenarioSelectorManager extends SelectorManager
{
@ -601,7 +598,7 @@ public class SocketChannelEndPointTest
super(executor, scheduler);
}
protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey key) throws IOException
protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey key)
{
SocketChannelEndPoint endp = new SocketChannelEndPoint(channel, selector, key, getScheduler());
endp.setIdleTimeout(60000);
@ -611,7 +608,7 @@ public class SocketChannelEndPointTest
}
@Override
public Connection newConnection(SelectableChannel channel, EndPoint endpoint, Object attachment) throws IOException
public Connection newConnection(SelectableChannel channel, EndPoint endpoint, Object attachment)
{
return _scenario.newConnection(channel, endpoint, getExecutor(), _blockAt, _writeCount);
}

View File

@ -91,7 +91,7 @@ public class SslConnectionTest
@Override
protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey selectionKey) throws IOException
protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey selectionKey)
{
SocketChannelEndPoint endp = new TestEP(channel, selector, selectionKey, getScheduler());
endp.setIdleTimeout(60000);
@ -126,8 +126,7 @@ public class SslConnectionTest
return false;
}
}
boolean flushed=super.flush(buffers);
return flushed;
return super.flush(buffers);
}
}
@ -186,15 +185,7 @@ public class SslConnectionTest
fillInterested();
else
{
getExecutor().execute(new Runnable()
{
@Override
public void run()
{
getEndPoint().write(_writeCallback,BufferUtil.toBuffer("Hello Client"));
}
});
getExecutor().execute(() -> getEndPoint().write(_writeCallback,BufferUtil.toBuffer("Hello Client")));
}
}
@ -264,52 +255,54 @@ public class SslConnectionTest
@Test
public void testHelloWorld() throws Exception
{
Socket client = newClient();
try (Socket client = newClient())
{
client.setSoTimeout(60000);
SocketChannel server = _connector.accept();
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
client.getOutputStream().write("Hello".getBytes(StandardCharsets.UTF_8));
byte[] buffer = new byte[1024];
int len=client.getInputStream().read(buffer);
int len = client.getInputStream().read(buffer);
Assert.assertEquals(5, len);
Assert.assertEquals("Hello",new String(buffer,0,len,StandardCharsets.UTF_8));
Assert.assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8));
_dispatches.set(0);
client.getOutputStream().write("World".getBytes(StandardCharsets.UTF_8));
len=5;
while(len>0)
len-=client.getInputStream().read(buffer);
client.close();
len = 5;
while (len > 0)
len -= client.getInputStream().read(buffer);
}
}
}
@Test
public void testRenegotiate() throws Exception
{
SSLSocket client = newClient();
try (SSLSocket client = newClient())
{
client.setSoTimeout(60000);
SocketChannel server = _connector.accept();
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
client.getOutputStream().write("Hello".getBytes(StandardCharsets.UTF_8));
byte[] buffer = new byte[1024];
int len=client.getInputStream().read(buffer);
int len = client.getInputStream().read(buffer);
Assert.assertEquals(5, len);
Assert.assertEquals("Hello",new String(buffer,0,len,StandardCharsets.UTF_8));
Assert.assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8));
client.startHandshake();
client.getOutputStream().write("World".getBytes(StandardCharsets.UTF_8));
len=client.getInputStream().read(buffer);
len = client.getInputStream().read(buffer);
Assert.assertEquals(5, len);
Assert.assertEquals("World",new String(buffer,0,len,StandardCharsets.UTF_8));
client.close();
Assert.assertEquals("World", new String(buffer, 0, len, StandardCharsets.UTF_8));
}
}
}
@Test
@ -317,18 +310,19 @@ public class SslConnectionTest
{
__sslCtxFactory.setRenegotiationAllowed(false);
SSLSocket client = newClient();
try (SSLSocket client = newClient())
{
client.setSoTimeout(60000);
SocketChannel server = _connector.accept();
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
client.getOutputStream().write("Hello".getBytes(StandardCharsets.UTF_8));
byte[] buffer = new byte[1024];
int len=client.getInputStream().read(buffer);
int len = client.getInputStream().read(buffer);
Assert.assertEquals(5, len);
Assert.assertEquals("Hello",new String(buffer,0,len,StandardCharsets.UTF_8));
Assert.assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8));
client.startHandshake();
@ -338,11 +332,13 @@ public class SslConnectionTest
client.getInputStream().read(buffer);
Assert.fail();
}
catch(SSLException e)
catch (SSLException e)
{
// expected
}
}
}
}
@Test
public void testRenegotiateLimit() throws Exception
@ -350,32 +346,33 @@ public class SslConnectionTest
__sslCtxFactory.setRenegotiationAllowed(true);
__sslCtxFactory.setRenegotiationLimit(2);
SSLSocket client = newClient();
try (SSLSocket client = newClient())
{
client.setSoTimeout(60000);
SocketChannel server = _connector.accept();
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
client.getOutputStream().write("Good".getBytes(StandardCharsets.UTF_8));
byte[] buffer = new byte[1024];
int len=client.getInputStream().read(buffer);
int len = client.getInputStream().read(buffer);
Assert.assertEquals(4, len);
Assert.assertEquals("Good",new String(buffer,0,len,StandardCharsets.UTF_8));
Assert.assertEquals("Good", new String(buffer, 0, len, StandardCharsets.UTF_8));
client.startHandshake();
client.getOutputStream().write("Bye".getBytes(StandardCharsets.UTF_8));
len=client.getInputStream().read(buffer);
len = client.getInputStream().read(buffer);
Assert.assertEquals(3, len);
Assert.assertEquals("Bye",new String(buffer,0,len,StandardCharsets.UTF_8));
Assert.assertEquals("Bye", new String(buffer, 0, len, StandardCharsets.UTF_8));
client.startHandshake();
client.getOutputStream().write("Cruel".getBytes(StandardCharsets.UTF_8));
len=client.getInputStream().read(buffer);
len = client.getInputStream().read(buffer);
Assert.assertEquals(5, len);
Assert.assertEquals("Cruel",new String(buffer,0,len,StandardCharsets.UTF_8));
Assert.assertEquals("Cruel", new String(buffer, 0, len, StandardCharsets.UTF_8));
client.startHandshake();
@ -385,43 +382,44 @@ public class SslConnectionTest
client.getInputStream().read(buffer);
Assert.fail();
}
catch(SSLException e)
catch (SSLException e)
{
// expected
}
}
}
}
@Test
public void testWriteOnConnect() throws Exception
{
_testFill=false;
_writeCallback = new FutureCallback();
Socket client = newClient();
client.setSoTimeout(10000);
SocketChannel server = _connector.accept();
try (Socket client = newClient())
{
client.setSoTimeout(10000);
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
byte[] buffer = new byte[1024];
int len=client.getInputStream().read(buffer);
Assert.assertEquals("Hello Client",new String(buffer,0,len,StandardCharsets.UTF_8));
Assert.assertEquals(null,_writeCallback.get(100,TimeUnit.MILLISECONDS));
client.close();
int len = client.getInputStream().read(buffer);
Assert.assertEquals("Hello Client", new String(buffer, 0, len, StandardCharsets.UTF_8));
Assert.assertNull(_writeCallback.get(100, TimeUnit.MILLISECONDS));
}
}
}
@Test
public void testBlockedWrite() throws Exception
{
Socket client = newClient();
try (Socket client = newClient())
{
client.setSoTimeout(5000);
SocketChannel server = _connector.accept();
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
@ -430,72 +428,67 @@ public class SslConnectionTest
client.getOutputStream().write("Hello".getBytes(StandardCharsets.UTF_8));
byte[] buffer = new byte[1024];
int len=client.getInputStream().read(buffer);
int len = client.getInputStream().read(buffer);
Assert.assertEquals(5, len);
Assert.assertEquals("Hello",new String(buffer,0,len,StandardCharsets.UTF_8));
Assert.assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8));
_dispatches.set(0);
client.getOutputStream().write("World".getBytes(StandardCharsets.UTF_8));
len=5;
while(len>0)
len-=client.getInputStream().read(buffer);
len = 5;
while (len > 0)
len -= client.getInputStream().read(buffer);
Assert.assertEquals(0, len);
client.close();
}
}
}
@Test
public void testManyLines() throws Exception
{
final Socket client = newClient();
try (Socket client = newClient())
{
client.setSoTimeout(10000);
SocketChannel server = _connector.accept();
try (SocketChannel server = _connector.accept())
{
server.configureBlocking(false);
_manager.accept(server);
final int LINES=20;
final CountDownLatch count=new CountDownLatch(LINES);
final int LINES = 20;
final CountDownLatch count = new CountDownLatch(LINES);
new Thread()
{
@Override
public void run()
new Thread(() ->
{
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(),StandardCharsets.UTF_8));
while(count.getCount()>0)
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
while (count.getCount() > 0)
{
String line=in.readLine();
if (line==null)
String line = in.readLine();
if (line == null)
break;
// System.err.println(line);
count.countDown();
}
}
catch(IOException e)
catch (IOException e)
{
e.printStackTrace();
}
}
}.start();
}).start();
for (int i=0;i<LINES;i++)
for (int i = 0; i < LINES; i++)
{
client.getOutputStream().write(("HelloWorld "+i+"\n").getBytes(StandardCharsets.UTF_8));
client.getOutputStream().write(("HelloWorld " + i + "\n").getBytes(StandardCharsets.UTF_8));
// System.err.println("wrote");
if (i%1000==0)
if (i % 1000 == 0)
{
client.getOutputStream().flush();
Thread.sleep(10);
}
}
Assert.assertTrue(count.await(20,TimeUnit.SECONDS));
client.close();
Assert.assertTrue(count.await(20, TimeUnit.SECONDS));
}
}
}
}