Search in sources :

Example 16 with EndPoint

use of org.eclipse.jetty.io.EndPoint in project jetty.project by eclipse.

the class ClientCloseTest method testWriteException.

@Test
public void testWriteException() throws Exception {
    // Set client timeout
    final int timeout = 1000;
    client.setMaxIdleTimeout(timeout);
    // Client connects
    CloseTrackingSocket clientSocket = new CloseTrackingSocket();
    Future<Session> clientConnectFuture = client.connect(clientSocket, server.getWsUri());
    // Server accepts connect
    IBlockheadServerConnection serverConn = server.accept();
    serverConn.upgrade();
    // client confirms connection via echo
    confirmConnection(clientSocket, clientConnectFuture, serverConn);
    // setup client endpoint for write failure (test only)
    EndPoint endp = clientSocket.getEndPoint();
    endp.shutdownOutput();
    // client enqueue close frame
    // client write failure
    final String origCloseReason = "Normal Close";
    clientSocket.getSession().close(StatusCode.NORMAL, origCloseReason);
    assertThat("OnError Latch", clientSocket.errorLatch.await(2, TimeUnit.SECONDS), is(true));
    assertThat("OnError", clientSocket.error.get(), instanceOf(EofException.class));
    // client triggers close event on client ws-endpoint
    // assert - close code==1006 (abnormal)
    // assert - close reason message contains (write failure)
    clientSocket.assertReceivedCloseEvent(timeout, is(StatusCode.ABNORMAL), containsString("EOF"));
}
Also used : EofException(org.eclipse.jetty.io.EofException) IBlockheadServerConnection(org.eclipse.jetty.websocket.common.test.IBlockheadServerConnection) EndPoint(org.eclipse.jetty.io.EndPoint) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint) Matchers.containsString(org.hamcrest.Matchers.containsString) EndPoint(org.eclipse.jetty.io.EndPoint) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint) Session(org.eclipse.jetty.websocket.api.Session) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) Test(org.junit.Test)

Example 17 with EndPoint

use of org.eclipse.jetty.io.EndPoint in project jetty.project by eclipse.

the class ClientCloseTest method testNetworkCongestion.

@Ignore("Need sbordet's help here")
@Test
public void testNetworkCongestion() throws Exception {
    // Set client timeout
    final int timeout = 1000;
    client.setMaxIdleTimeout(timeout);
    // Client connects
    CloseTrackingSocket clientSocket = new CloseTrackingSocket();
    Future<Session> clientConnectFuture = client.connect(clientSocket, server.getWsUri());
    // Server accepts connect
    IBlockheadServerConnection serverConn = server.accept();
    serverConn.upgrade();
    // client confirms connection via echo
    confirmConnection(clientSocket, clientConnectFuture, serverConn);
    // client sends BIG frames (until it cannot write anymore)
    // server must not read (for test purpose, in order to congest connection)
    // when write is congested, client enqueue close frame
    // client initiate write, but write never completes
    EndPoint endp = clientSocket.getEndPoint();
    assertThat("EndPoint is testable", endp, instanceOf(TestEndPoint.class));
    TestEndPoint testendp = (TestEndPoint) endp;
    char[] msg = new char[10240];
    int writeCount = 0;
    long writeSize = 0;
    int i = 0;
    while (!testendp.congestedFlush.get()) {
        int z = i - ((i / 26) * 26);
        char c = (char) ('a' + z);
        Arrays.fill(msg, c);
        clientSocket.getRemote().sendStringByFuture(String.valueOf(msg));
        writeCount++;
        writeSize += msg.length;
    }
    LOG.info("Wrote {} frames totalling {} bytes of payload before congestion kicked in", writeCount, writeSize);
    // Verify timeout error
    assertThat("OnError Latch", clientSocket.errorLatch.await(2, TimeUnit.SECONDS), is(true));
    assertThat("OnError", clientSocket.error.get(), instanceOf(SocketTimeoutException.class));
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) IBlockheadServerConnection(org.eclipse.jetty.websocket.common.test.IBlockheadServerConnection) EndPoint(org.eclipse.jetty.io.EndPoint) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint) EndPoint(org.eclipse.jetty.io.EndPoint) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint) Session(org.eclipse.jetty.websocket.api.Session) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 18 with EndPoint

use of org.eclipse.jetty.io.EndPoint in project jetty.project by eclipse.

the class ClientCloseTest method testProtocolException.

@Test
public void testProtocolException() throws Exception {
    // Set client timeout
    final int timeout = 1000;
    client.setMaxIdleTimeout(timeout);
    // Client connects
    CloseTrackingSocket clientSocket = new CloseTrackingSocket();
    Future<Session> clientConnectFuture = client.connect(clientSocket, server.getWsUri());
    // Server accepts connect
    IBlockheadServerConnection serverConn = server.accept();
    serverConn.upgrade();
    // client confirms connection via echo
    confirmConnection(clientSocket, clientConnectFuture, serverConn);
    // client should not have received close message (yet)
    clientSocket.assertNoCloseEvent();
    // server sends bad close frame (too big of a reason message)
    byte[] msg = new byte[400];
    Arrays.fill(msg, (byte) 'x');
    ByteBuffer bad = ByteBuffer.allocate(500);
    RawFrameBuilder.putOpFin(bad, OpCode.CLOSE, true);
    RawFrameBuilder.putLength(bad, msg.length + 2, false);
    bad.putShort((short) StatusCode.NORMAL);
    bad.put(msg);
    BufferUtil.flipToFlush(bad, 0);
    try (StacklessLogging quiet = new StacklessLogging(Parser.class)) {
        serverConn.write(bad);
        // client should have noticed the error
        assertThat("OnError Latch", clientSocket.errorLatch.await(2, TimeUnit.SECONDS), is(true));
        assertThat("OnError", clientSocket.error.get(), instanceOf(ProtocolException.class));
        assertThat("OnError", clientSocket.error.get().getMessage(), containsString("Invalid control frame"));
        // client parse invalid frame, notifies server of close (protocol error)
        confirmServerReceivedCloseFrame(serverConn, StatusCode.PROTOCOL, allOf(containsString("Invalid control frame"), containsString("length")));
    }
    // server disconnects
    serverConn.disconnect();
    // client triggers close event on client ws-endpoint
    clientSocket.assertReceivedCloseEvent(timeout, is(StatusCode.PROTOCOL), allOf(containsString("Invalid control frame"), containsString("length")));
}
Also used : ProtocolException(org.eclipse.jetty.websocket.api.ProtocolException) IBlockheadServerConnection(org.eclipse.jetty.websocket.common.test.IBlockheadServerConnection) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) ByteBuffer(java.nio.ByteBuffer) EndPoint(org.eclipse.jetty.io.EndPoint) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint) Session(org.eclipse.jetty.websocket.api.Session) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) Test(org.junit.Test)

Example 19 with EndPoint

use of org.eclipse.jetty.io.EndPoint in project jetty.project by eclipse.

the class WebSocketUpgradeRequest method upgrade.

@Override
public void upgrade(HttpResponse response, HttpConnectionOverHTTP oldConn) {
    if (!this.getHeaders().get(HttpHeader.UPGRADE).equalsIgnoreCase("websocket")) {
        // Not my upgrade
        throw new HttpResponseException("Not WebSocket Upgrade", response);
    }
    // Check the Accept hash
    String reqKey = this.getHeaders().get(HttpHeader.SEC_WEBSOCKET_KEY);
    String expectedHash = AcceptHash.hashKey(reqKey);
    String respHash = response.getHeaders().get(HttpHeader.SEC_WEBSOCKET_ACCEPT);
    if (expectedHash.equalsIgnoreCase(respHash) == false) {
        throw new HttpResponseException("Invalid Sec-WebSocket-Accept hash", response);
    }
    // We can upgrade
    EndPoint endp = oldConn.getEndPoint();
    WebSocketClientConnection connection = new WebSocketClientConnection(endp, wsClient.getExecutor(), wsClient.getScheduler(), localEndpoint.getPolicy(), wsClient.getBufferPool());
    URI requestURI = this.getURI();
    WebSocketSession session = getSessionFactory().createSession(requestURI, localEndpoint, connection);
    session.setUpgradeRequest(new ClientUpgradeRequest(this));
    session.setUpgradeResponse(new ClientUpgradeResponse(response));
    connection.addListener(session);
    ExtensionStack extensionStack = new ExtensionStack(getExtensionFactory());
    List<ExtensionConfig> extensions = new ArrayList<>();
    HttpField extField = response.getHeaders().getField(HttpHeader.SEC_WEBSOCKET_EXTENSIONS);
    if (extField != null) {
        String[] extValues = extField.getValues();
        if (extValues != null) {
            for (String extVal : extValues) {
                QuotedStringTokenizer tok = new QuotedStringTokenizer(extVal, ",");
                while (tok.hasMoreTokens()) {
                    extensions.add(ExtensionConfig.parse(tok.nextToken()));
                }
            }
        }
    }
    extensionStack.negotiate(extensions);
    extensionStack.configure(connection.getParser());
    extensionStack.configure(connection.getGenerator());
    // Setup Incoming Routing
    connection.setNextIncomingFrames(extensionStack);
    extensionStack.setNextIncoming(session);
    // Setup Outgoing Routing
    session.setOutgoingHandler(extensionStack);
    extensionStack.setNextOutgoing(connection);
    session.addManaged(extensionStack);
    session.setFuture(fut);
    wsClient.addManaged(session);
    if (upgradeListener != null) {
        upgradeListener.onHandshakeResponse(new ClientUpgradeResponse(response));
    }
    // Now swap out the connection
    endp.upgrade(connection);
}
Also used : ArrayList(java.util.ArrayList) WebSocketClientConnection(org.eclipse.jetty.websocket.client.io.WebSocketClientConnection) HttpResponseException(org.eclipse.jetty.client.HttpResponseException) EndPoint(org.eclipse.jetty.io.EndPoint) URI(java.net.URI) ExtensionStack(org.eclipse.jetty.websocket.common.extensions.ExtensionStack) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) QuotedStringTokenizer(org.eclipse.jetty.util.QuotedStringTokenizer) ExtensionConfig(org.eclipse.jetty.websocket.api.extensions.ExtensionConfig) HttpField(org.eclipse.jetty.http.HttpField)

Example 20 with EndPoint

use of org.eclipse.jetty.io.EndPoint in project jetty.project by eclipse.

the class SslBytesServerTest method init.

@Before
public void init() throws Exception {
    threadPool = Executors.newCachedThreadPool();
    server = new Server();
    File keyStore = MavenTestingUtils.getTestResourceFile("keystore.jks");
    sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(keyStore.getAbsolutePath());
    sslContextFactory.setKeyStorePassword("storepwd");
    HttpConnectionFactory httpFactory = new HttpConnectionFactory() {

        @Override
        public Connection newConnection(Connector connector, EndPoint endPoint) {
            return configure(new HttpConnection(getHttpConfiguration(), connector, endPoint, getHttpCompliance(), isRecordHttpComplianceViolations()) {

                @Override
                protected HttpParser newHttpParser(HttpCompliance compliance) {
                    return new HttpParser(newRequestHandler(), getHttpConfiguration().getRequestHeaderSize(), compliance) {

                        @Override
                        public boolean parseNext(ByteBuffer buffer) {
                            httpParses.incrementAndGet();
                            return super.parseNext(buffer);
                        }
                    };
                }

                @Override
                protected boolean onReadTimeout() {
                    final Runnable idleHook = SslBytesServerTest.this.idleHook;
                    if (idleHook != null)
                        idleHook.run();
                    return super.onReadTimeout();
                }
            }, connector, endPoint);
        }
    };
    httpFactory.getHttpConfiguration().addCustomizer(new SecureRequestCustomizer());
    SslConnectionFactory sslFactory = new SslConnectionFactory(sslContextFactory, httpFactory.getProtocol()) {

        @Override
        protected SslConnection newSslConnection(Connector connector, EndPoint endPoint, SSLEngine engine) {
            return new SslConnection(connector.getByteBufferPool(), connector.getExecutor(), endPoint, engine) {

                @Override
                protected DecryptedEndPoint newDecryptedEndPoint() {
                    return new DecryptedEndPoint() {

                        @Override
                        public int fill(ByteBuffer buffer) throws IOException {
                            sslFills.incrementAndGet();
                            return super.fill(buffer);
                        }

                        @Override
                        public boolean flush(ByteBuffer... appOuts) throws IOException {
                            sslFlushes.incrementAndGet();
                            return super.flush(appOuts);
                        }
                    };
                }
            };
        }
    };
    ServerConnector connector = new ServerConnector(server, null, null, null, 1, 1, sslFactory, httpFactory) {

        @Override
        protected ChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException {
            ChannelEndPoint endp = super.newEndPoint(channel, selectSet, key);
            serverEndPoint.set(endp);
            return endp;
        }
    };
    connector.setIdleTimeout(idleTimeout);
    connector.setPort(0);
    server.addConnector(connector);
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException {
            try {
                request.setHandled(true);
                String contentLength = request.getHeader("Content-Length");
                if (contentLength != null) {
                    int length = Integer.parseInt(contentLength);
                    ServletInputStream input = httpRequest.getInputStream();
                    ServletOutputStream output = httpResponse.getOutputStream();
                    byte[] buffer = new byte[32 * 1024];
                    while (length > 0) {
                        int read = input.read(buffer);
                        if (read < 0)
                            throw new EOFException();
                        length -= read;
                        if (target.startsWith("/echo"))
                            output.write(buffer, 0, read);
                    }
                }
            } catch (IOException x) {
                if (!(target.endsWith("suppress_exception")))
                    throw x;
            }
        }
    });
    server.start();
    serverPort = connector.getLocalPort();
    sslContext = sslContextFactory.getSslContext();
    proxy = new SimpleProxy(threadPool, "localhost", serverPort);
    proxy.start();
    logger.info("proxy:{} <==> server:{}", proxy.getPort(), serverPort);
}
Also used : ManagedSelector(org.eclipse.jetty.io.ManagedSelector) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) SocketChannel(java.nio.channels.SocketChannel) Server(org.eclipse.jetty.server.Server) HttpConnection(org.eclipse.jetty.server.HttpConnection) ChannelEndPoint(org.eclipse.jetty.io.ChannelEndPoint) ServletOutputStream(javax.servlet.ServletOutputStream) SSLEngine(javax.net.ssl.SSLEngine) EndPoint(org.eclipse.jetty.io.EndPoint) ChannelEndPoint(org.eclipse.jetty.io.ChannelEndPoint) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) ServletInputStream(javax.servlet.ServletInputStream) EOFException(java.io.EOFException) HttpParser(org.eclipse.jetty.http.HttpParser) SelectionKey(java.nio.channels.SelectionKey) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) HttpCompliance(org.eclipse.jetty.http.HttpCompliance) SslConnection(org.eclipse.jetty.io.ssl.SslConnection) File(java.io.File) Before(org.junit.Before)

Aggregations

EndPoint (org.eclipse.jetty.io.EndPoint)42 Test (org.junit.Test)19 IOException (java.io.IOException)11 ByteBuffer (java.nio.ByteBuffer)10 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 HttpServletResponse (javax.servlet.http.HttpServletResponse)9 SSLEngine (javax.net.ssl.SSLEngine)8 ServletException (javax.servlet.ServletException)8 WebSocketSession (org.eclipse.jetty.websocket.common.WebSocketSession)8 InputStream (java.io.InputStream)7 Socket (java.net.Socket)7 ByteBufferPool (org.eclipse.jetty.io.ByteBufferPool)7 SocketChannelEndPoint (org.eclipse.jetty.io.SocketChannelEndPoint)7 OutputStream (java.io.OutputStream)6 SslConnection (org.eclipse.jetty.io.ssl.SslConnection)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 HttpClientTransportOverHTTP (org.eclipse.jetty.client.http.HttpClientTransportOverHTTP)5 Connector (org.eclipse.jetty.server.Connector)5 ServerConnector (org.eclipse.jetty.server.ServerConnector)5