Search in sources :

Example 16 with SocketChannel

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

the class ProxyProtocolTest method test_PROXY_GET_v1.

@Test
public void test_PROXY_GET_v1() throws Exception {
    startServer(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            try {
                Assert.assertEquals("1.2.3.4", request.getRemoteAddr());
                Assert.assertEquals(1111, request.getRemotePort());
                Assert.assertEquals("5.6.7.8", request.getLocalAddr());
                Assert.assertEquals(2222, request.getLocalPort());
            } catch (Throwable th) {
                th.printStackTrace();
                response.setStatus(500);
            }
            baseRequest.setHandled(true);
        }
    });
    String request1 = "PROXY TCP4 1.2.3.4 5.6.7.8 1111 2222\r\n";
    SocketChannel channel = SocketChannel.open();
    channel.connect(new InetSocketAddress("localhost", connector.getLocalPort()));
    channel.write(ByteBuffer.wrap(request1.getBytes(StandardCharsets.UTF_8)));
    FuturePromise<Session> promise = new FuturePromise<>();
    client.accept(null, channel, new Session.Listener.Adapter(), promise);
    Session session = promise.get(5, TimeUnit.SECONDS);
    HttpFields fields = new HttpFields();
    String uri = "http://localhost:" + connector.getLocalPort() + "/";
    MetaData.Request metaData = new MetaData.Request("GET", new HttpURI(uri), HttpVersion.HTTP_2, fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, true);
    CountDownLatch latch = new CountDownLatch(1);
    session.newStream(frame, new Promise.Adapter<>(), new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            MetaData.Response response = (MetaData.Response) frame.getMetaData();
            Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
            if (frame.isEndStream())
                latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) FuturePromise(org.eclipse.jetty.util.FuturePromise) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) HttpURI(org.eclipse.jetty.http.HttpURI) HttpServletResponse(javax.servlet.http.HttpServletResponse) Promise(org.eclipse.jetty.util.Promise) FuturePromise(org.eclipse.jetty.util.FuturePromise) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 17 with SocketChannel

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

the class HTTP2Client method connect.

public void connect(SslContextFactory sslContextFactory, InetSocketAddress address, Session.Listener listener, Promise<Session> promise, Map<String, Object> context) {
    try {
        SocketChannel channel = SocketChannel.open();
        configure(channel);
        channel.configureBlocking(false);
        context = contextFrom(sslContextFactory, address, listener, promise, context);
        if (channel.connect(address))
            selector.accept(channel, context);
        else
            selector.connect(channel, context);
    } catch (Throwable x) {
        promise.failed(x);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel)

Example 18 with SocketChannel

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

the class ThreadStarvationTest method testDefaultServletSuccess.

@Test
@Slow
public void testDefaultServletSuccess() throws Exception {
    int maxThreads = 10;
    QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads, maxThreads);
    threadPool.setDetailedDump(true);
    _server = new Server(threadPool);
    // Prepare a big file to download.
    File directory = MavenTestingUtils.getTargetTestingDir();
    Files.createDirectories(directory.toPath());
    String resourceName = "resource.bin";
    Path resourcePath = Paths.get(directory.getPath(), resourceName);
    try (OutputStream output = Files.newOutputStream(resourcePath, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
        byte[] chunk = new byte[1024];
        Arrays.fill(chunk, (byte) 'X');
        chunk[chunk.length - 2] = '\r';
        chunk[chunk.length - 1] = '\n';
        for (int i = 0; i < 256 * 1024; ++i) output.write(chunk);
    }
    final CountDownLatch writePending = new CountDownLatch(1);
    ServerConnector connector = new ServerConnector(_server, 0, 1) {

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

                @Override
                protected void onIncompleteFlush() {
                    super.onIncompleteFlush();
                    writePending.countDown();
                }
            };
        }
    };
    connector.setIdleTimeout(Long.MAX_VALUE);
    _server.addConnector(connector);
    ServletContextHandler context = new ServletContextHandler(_server, "/");
    context.setResourceBase(directory.toURI().toString());
    context.addServlet(DefaultServlet.class, "/*").setAsyncSupported(false);
    _server.setHandler(context);
    _server.start();
    List<Socket> sockets = new ArrayList<>();
    for (int i = 0; i < maxThreads * 2; ++i) {
        Socket socket = new Socket("localhost", connector.getLocalPort());
        sockets.add(socket);
        OutputStream output = socket.getOutputStream();
        String request = "" + "GET /" + resourceName + " HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n";
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        Thread.sleep(100);
    }
    // Wait for a the servlet to block.
    Assert.assertTrue(writePending.await(5, TimeUnit.SECONDS));
    long expected = Files.size(resourcePath);
    byte[] buffer = new byte[48 * 1024];
    List<Exchanger<Long>> totals = new ArrayList<>();
    for (Socket socket : sockets) {
        final Exchanger<Long> x = new Exchanger<>();
        totals.add(x);
        final InputStream input = socket.getInputStream();
        new Thread() {

            @Override
            public void run() {
                long total = 0;
                try {
                    // look for CRLFCRLF
                    StringBuilder header = new StringBuilder();
                    int state = 0;
                    while (state < 4 && header.length() < 2048) {
                        int ch = input.read();
                        if (ch < 0)
                            break;
                        header.append((char) ch);
                        switch(state) {
                            case 0:
                                if (ch == '\r')
                                    state = 1;
                                break;
                            case 1:
                                if (ch == '\n')
                                    state = 2;
                                else
                                    state = 0;
                                break;
                            case 2:
                                if (ch == '\r')
                                    state = 3;
                                else
                                    state = 0;
                                break;
                            case 3:
                                if (ch == '\n')
                                    state = 4;
                                else
                                    state = 0;
                                break;
                        }
                    }
                    while (total < expected) {
                        int read = input.read(buffer);
                        if (read < 0)
                            break;
                        total += read;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        x.exchange(total);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
    for (Exchanger<Long> x : totals) {
        Long total = x.exchange(-1L, 10000, TimeUnit.SECONDS);
        Assert.assertEquals(expected, total.longValue());
    }
    // We could read everything, good.
    for (Socket socket : sockets) socket.close();
}
Also used : ManagedSelector(org.eclipse.jetty.io.ManagedSelector) SocketChannel(java.nio.channels.SocketChannel) Server(org.eclipse.jetty.server.Server) Exchanger(java.util.concurrent.Exchanger) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) ServerConnector(org.eclipse.jetty.server.ServerConnector) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) DefaultServlet(org.eclipse.jetty.servlet.DefaultServlet) Path(java.nio.file.Path) SelectionKey(java.nio.channels.SelectionKey) InputStream(java.io.InputStream) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelEndPoint(org.eclipse.jetty.io.ChannelEndPoint) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) File(java.io.File) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint) Socket(java.net.Socket) Test(org.junit.Test) Slow(org.eclipse.jetty.toolchain.test.annotation.Slow)

Example 19 with SocketChannel

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

the class Socks4ProxyTest method testSocks4Proxy.

@Test
public void testSocks4Proxy() throws Exception {
    int proxyPort = server.socket().getLocalPort();
    client.getProxyConfiguration().getProxies().add(new Socks4Proxy("localhost", proxyPort));
    final CountDownLatch latch = new CountDownLatch(1);
    byte ip1 = 127;
    byte ip2 = 0;
    byte ip3 = 0;
    byte ip4 = 13;
    String serverHost = ip1 + "." + ip2 + "." + ip3 + "." + ip4;
    // Any port will do
    int serverPort = proxyPort + 1;
    String method = "GET";
    String path = "/path";
    client.newRequest(serverHost, serverPort).method(method).path(path).timeout(5, TimeUnit.SECONDS).send(result -> {
        if (result.isSucceeded())
            latch.countDown();
    });
    SocketChannel channel = server.accept();
    int socks4MessageLength = 9;
    ByteBuffer buffer = ByteBuffer.allocate(socks4MessageLength);
    int read = channel.read(buffer);
    Assert.assertEquals(socks4MessageLength, read);
    Assert.assertEquals(4, buffer.get(0) & 0xFF);
    Assert.assertEquals(1, buffer.get(1) & 0xFF);
    Assert.assertEquals(serverPort, buffer.getShort(2) & 0xFFFF);
    Assert.assertEquals(ip1, buffer.get(4) & 0xFF);
    Assert.assertEquals(ip2, buffer.get(5) & 0xFF);
    Assert.assertEquals(ip3, buffer.get(6) & 0xFF);
    Assert.assertEquals(ip4, buffer.get(7) & 0xFF);
    Assert.assertEquals(0, buffer.get(8) & 0xFF);
    // Socks4 response.
    channel.write(ByteBuffer.wrap(new byte[] { 0, 0x5A, 0, 0, 0, 0, 0, 0 }));
    buffer = ByteBuffer.allocate(method.length() + 1 + path.length());
    read = channel.read(buffer);
    Assert.assertEquals(buffer.capacity(), read);
    buffer.flip();
    Assert.assertEquals(method + " " + path, StandardCharsets.UTF_8.decode(buffer).toString());
    // Response
    String response = "" + "HTTP/1.1 200 OK\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n";
    channel.write(ByteBuffer.wrap(response.getBytes("UTF-8")));
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    channel.close();
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 20 with SocketChannel

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

the class Socks4ProxyTest method testSocks4ProxyWithSplitResponse.

@Test
public void testSocks4ProxyWithSplitResponse() throws Exception {
    int proxyPort = server.socket().getLocalPort();
    client.getProxyConfiguration().getProxies().add(new Socks4Proxy("localhost", proxyPort));
    final CountDownLatch latch = new CountDownLatch(1);
    // Test expects an IP address.
    String serverHost = "127.0.0.13";
    // Any port will do
    int serverPort = proxyPort + 1;
    String method = "GET";
    client.newRequest(serverHost, serverPort).method(method).path("/path").timeout(5, TimeUnit.SECONDS).send(result -> {
        if (result.isSucceeded())
            latch.countDown();
        else
            result.getFailure().printStackTrace();
    });
    SocketChannel channel = server.accept();
    int socks4MessageLength = 9;
    ByteBuffer buffer = ByteBuffer.allocate(socks4MessageLength);
    int read = channel.read(buffer);
    Assert.assertEquals(socks4MessageLength, read);
    // Socks4 response, with split bytes.
    byte[] chunk1 = new byte[] { 0, 0x5A, 0 };
    byte[] chunk2 = new byte[] { 0, 0, 0, 0, 0 };
    channel.write(ByteBuffer.wrap(chunk1));
    // Wait before sending the second chunk.
    Thread.sleep(1000);
    channel.write(ByteBuffer.wrap(chunk2));
    buffer = ByteBuffer.allocate(method.length());
    read = channel.read(buffer);
    Assert.assertEquals(buffer.capacity(), read);
    buffer.flip();
    Assert.assertEquals(method, StandardCharsets.UTF_8.decode(buffer).toString());
    // Response
    String response = "" + "HTTP/1.1 200 OK\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n";
    channel.write(ByteBuffer.wrap(response.getBytes("UTF-8")));
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    channel.close();
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) 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