Search in sources :

Example 1 with SocketChannel

use of java.nio.channels.SocketChannel in project jetty.project by eclipse.

the class ALPNNegotiationTest method testAbruptCloseDuringHandshake.

@Test
public void testAbruptCloseDuringHandshake() throws Exception {
    InetSocketAddress address = prepare();
    SslContextFactory sslContextFactory = newSslContextFactory();
    sslContextFactory.start();
    SSLEngine sslEngine = sslContextFactory.newSSLEngine(address);
    sslEngine.setUseClientMode(true);
    ALPN.put(sslEngine, new ALPN.ClientProvider() {

        @Override
        public void unsupported() {
        }

        @Override
        public List<String> protocols() {
            return Arrays.asList("h2");
        }

        @Override
        public void selected(String s) {
        }
    });
    sslEngine.beginHandshake();
    ByteBuffer encrypted = ByteBuffer.allocate(sslEngine.getSession().getPacketBufferSize());
    sslEngine.wrap(BufferUtil.EMPTY_BUFFER, encrypted);
    encrypted.flip();
    try (SocketChannel channel = SocketChannel.open(address)) {
        // Send ClientHello, immediately followed by FIN (no TLS Close Alert)
        channel.write(encrypted);
        channel.shutdownOutput();
        // Read ServerHello from server
        encrypted.clear();
        int read = channel.read(encrypted);
        encrypted.flip();
        Assert.assertTrue(read > 0);
        ByteBuffer decrypted = ByteBuffer.allocate(sslEngine.getSession().getApplicationBufferSize());
        sslEngine.unwrap(encrypted, decrypted);
        // It may happen that the read() above read both the ServerHello and the TLS Close Alert.
        if (!encrypted.hasRemaining()) {
            // Now if we can read more, we should read the TLS Close Alert and then the TCP FIN.
            encrypted.clear();
            read = channel.read(encrypted);
            Assert.assertTrue(read > 0);
            encrypted.flip();
        }
        Assert.assertEquals(21, encrypted.get());
        encrypted.clear();
        Assert.assertEquals(-1, channel.read(encrypted));
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) InetSocketAddress(java.net.InetSocketAddress) SSLEngine(javax.net.ssl.SSLEngine) ALPN(org.eclipse.jetty.alpn.ALPN) List(java.util.List) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 2 with SocketChannel

use of java.nio.channels.SocketChannel in project jetty.project by eclipse.

the class HTTP2ServerTest method testCommitFailure.

@Test
public void testCommitFailure() throws Exception {
    final long delay = 1000;
    final AtomicBoolean broken = new AtomicBoolean();
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            try {
                // Wait for the SETTINGS frames to be exchanged.
                Thread.sleep(delay);
                broken.set(true);
            } catch (InterruptedException x) {
                throw new InterruptedIOException();
            }
        }
    });
    server.stop();
    ServerConnector connector2 = new ServerConnector(server, new HTTP2ServerConnectionFactory(new HttpConfiguration())) {

        @Override
        protected ChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException {
            return new SocketChannelEndPoint(channel, selectSet, key, getScheduler()) {

                @Override
                public void write(Callback callback, ByteBuffer... buffers) throws IllegalStateException {
                    if (broken.get())
                        callback.failed(new IOException("explicitly_thrown_by_test"));
                    else
                        super.write(callback, buffers);
                }
            };
        }
    };
    server.addConnector(connector2);
    server.start();
    ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
    generator.control(lease, new PrefaceFrame());
    generator.control(lease, new SettingsFrame(new HashMap<>(), false));
    MetaData.Request metaData = newRequest("GET", new HttpFields());
    generator.control(lease, new HeadersFrame(1, metaData, null, true));
    try (Socket client = new Socket("localhost", connector2.getLocalPort())) {
        OutputStream output = client.getOutputStream();
        for (ByteBuffer buffer : lease.getByteBuffers()) output.write(BufferUtil.toArray(buffer));
        // The server will close the connection abruptly since it
        // cannot write and therefore cannot even send the GO_AWAY.
        Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter(), 4096, 8192);
        boolean closed = parseResponse(client, parser, 2 * delay);
        Assert.assertTrue(closed);
    }
}
Also used : ManagedSelector(org.eclipse.jetty.io.ManagedSelector) ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) InterruptedIOException(java.io.InterruptedIOException) SocketChannel(java.nio.channels.SocketChannel) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServerConnector(org.eclipse.jetty.server.ServerConnector) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) SelectionKey(java.nio.channels.SelectionKey) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Parser(org.eclipse.jetty.http2.parser.Parser) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callback(org.eclipse.jetty.util.Callback) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint) Socket(java.net.Socket) Test(org.junit.Test)

Example 3 with SocketChannel

use of java.nio.channels.SocketChannel in project jetty.project by eclipse.

the class SelectChannelEndPointTest method testShutdown.

@Test
public void testShutdown() throws Exception {
    Socket client = newClient();
    client.setSoTimeout(500);
    SocketChannel server = _connector.accept();
    server.configureBlocking(false);
    _manager.accept(server);
    // Write client to server
    client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
        int b = client.getInputStream().read();
        assertTrue(b > 0);
        assertEquals(c, (char) b);
    }
    // wait for read timeout
    long start = System.currentTimeMillis();
    try {
        client.getInputStream().read();
        Assert.fail();
    } catch (SocketTimeoutException e) {
        assertTrue(System.currentTimeMillis() - start >= 400);
    }
    // write then shutdown
    client.getOutputStream().write("Goodbye Cruel TLS".getBytes(StandardCharsets.UTF_8));
    client.shutdownOutput();
    // Verify echo server to client
    for (char c : "Goodbye Cruel TLS".toCharArray()) {
        int b = client.getInputStream().read();
        assertTrue(b > 0);
        assertEquals(c, (char) b);
    }
    // Read close
    assertEquals(-1, client.getInputStream().read());
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketTimeoutException(java.net.SocketTimeoutException) Socket(java.net.Socket) Test(org.junit.Test)

Example 4 with SocketChannel

use of java.nio.channels.SocketChannel in project jetty.project by eclipse.

the class SelectChannelEndPointTest method testRejectedExecution.

// TODO make this test reliable
@Test
@Ignore
public void testRejectedExecution() throws Exception {
    _manager.stop();
    _threadPool.stop();
    final CountDownLatch latch = new CountDownLatch(1);
    BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(4);
    _threadPool = new QueuedThreadPool(4, 4, 60000, q);
    _manager = new SelectorManager(_threadPool, _scheduler, 1) {

        @Override
        protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey selectionKey) throws IOException {
            SocketChannelEndPoint endp = new SocketChannelEndPoint(channel, selector, selectionKey, getScheduler());
            _lastEndPoint = endp;
            _lastEndPointLatch.countDown();
            return endp;
        }

        @Override
        public Connection newConnection(SelectableChannel channel, EndPoint endpoint, Object attachment) throws IOException {
            return new TestConnection(endpoint, latch);
        }
    };
    _threadPool.start();
    _manager.start();
    AtomicInteger timeout = new AtomicInteger();
    AtomicInteger rejections = new AtomicInteger();
    AtomicInteger echoed = new AtomicInteger();
    CountDownLatch closed = new CountDownLatch(20);
    for (int i = 0; i < 20; i++) {
        new Thread() {

            public void run() {
                try (Socket client = newClient()) {
                    client.setSoTimeout(5000);
                    SocketChannel server = _connector.accept();
                    server.configureBlocking(false);
                    _manager.accept(server);
                    // Write client to server
                    client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
                    client.getOutputStream().flush();
                    client.shutdownOutput();
                    // Verify echo server to client
                    for (char c : "HelloWorld".toCharArray()) {
                        int b = client.getInputStream().read();
                        assertTrue(b > 0);
                        assertEquals(c, (char) b);
                    }
                    assertEquals(-1, client.getInputStream().read());
                    echoed.incrementAndGet();
                } catch (SocketTimeoutException x) {
                    x.printStackTrace();
                    timeout.incrementAndGet();
                } catch (Throwable x) {
                    rejections.incrementAndGet();
                } finally {
                    closed.countDown();
                }
            }
        }.start();
    }
    // unblock the handling
    latch.countDown();
    // wait for all clients to complete or fail
    closed.await();
    // assert some clients must have been rejected
    Assert.assertThat(rejections.get(), Matchers.greaterThan(0));
    // but not all of them
    Assert.assertThat(rejections.get(), Matchers.lessThan(20));
    // none should have timed out
    Assert.assertThat(timeout.get(), Matchers.equalTo(0));
    // and the rest should have worked
    Assert.assertThat(echoed.get(), Matchers.equalTo(20 - rejections.get()));
    // and the selector is still working for new requests
    try (Socket client = newClient()) {
        client.setSoTimeout(5000);
        SocketChannel server = _connector.accept();
        server.configureBlocking(false);
        _manager.accept(server);
        // Write client to server
        client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
        client.getOutputStream().flush();
        client.shutdownOutput();
        // Verify echo server to client
        for (char c : "HelloWorld".toCharArray()) {
            int b = client.getInputStream().read();
            assertTrue(b > 0);
            assertEquals(c, (char) b);
        }
        assertEquals(-1, client.getInputStream().read());
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) SocketTimeoutException(java.net.SocketTimeoutException) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) SelectableChannel(java.nio.channels.SelectableChannel) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Socket(java.net.Socket) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 5 with SocketChannel

use of java.nio.channels.SocketChannel in project jetty.project by eclipse.

the class SelectChannelEndPointTest method testEcho.

@Test
public void testEcho() throws Exception {
    Socket client = newClient();
    client.setSoTimeout(60000);
    SocketChannel server = _connector.accept();
    server.configureBlocking(false);
    _manager.accept(server);
    // Write client to server
    client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
        int b = client.getInputStream().read();
        assertTrue(b > 0);
        assertEquals(c, (char) b);
    }
    // wait for read timeout
    client.setSoTimeout(500);
    long start = System.currentTimeMillis();
    try {
        client.getInputStream().read();
        Assert.fail();
    } catch (SocketTimeoutException e) {
        long duration = System.currentTimeMillis() - start;
        Assert.assertThat("timeout duration", duration, greaterThanOrEqualTo(400L));
    }
    // write then shutdown
    client.getOutputStream().write("Goodbye Cruel TLS".getBytes(StandardCharsets.UTF_8));
    // Verify echo server to client
    for (char c : "Goodbye Cruel TLS".toCharArray()) {
        int b = client.getInputStream().read();
        Assert.assertThat("expect valid char integer", b, greaterThan(0));
        assertEquals("expect characters to be same", c, (char) b);
    }
    client.close();
    for (int i = 0; i < 10; ++i) {
        if (server.isOpen())
            Thread.sleep(10);
        else
            break;
    }
    assertFalse(server.isOpen());
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketTimeoutException(java.net.SocketTimeoutException) Socket(java.net.Socket) Test(org.junit.Test)

Aggregations

SocketChannel (java.nio.channels.SocketChannel)759 ServerSocketChannel (java.nio.channels.ServerSocketChannel)337 IOException (java.io.IOException)321 InetSocketAddress (java.net.InetSocketAddress)228 ByteBuffer (java.nio.ByteBuffer)188 SelectionKey (java.nio.channels.SelectionKey)126 Socket (java.net.Socket)101 Test (org.junit.Test)87 ClosedChannelException (java.nio.channels.ClosedChannelException)63 ServerSocket (java.net.ServerSocket)49 Selector (java.nio.channels.Selector)48 SocketAddress (java.net.SocketAddress)36 ClosedSelectorException (java.nio.channels.ClosedSelectorException)33 ConnectException (java.net.ConnectException)27 CancelledKeyException (java.nio.channels.CancelledKeyException)27 ArrayList (java.util.ArrayList)27 SocketTimeoutException (java.net.SocketTimeoutException)25 SelectableChannel (java.nio.channels.SelectableChannel)23 HashMap (java.util.HashMap)23 OutputStream (java.io.OutputStream)22