Search in sources :

Example 1 with StreamConnection

use of org.xnio.StreamConnection in project undertow by undertow-io.

the class AjpReadListener method handleCPing.

private void handleCPing() {
    state = new AjpRequestParseState();
    final StreamConnection underlyingChannel = connection.getChannel();
    underlyingChannel.getSourceChannel().suspendReads();
    final ByteBuffer buffer = ByteBuffer.wrap(CPONG);
    int res;
    try {
        do {
            res = underlyingChannel.getSinkChannel().write(buffer);
            if (res == 0) {
                underlyingChannel.getSinkChannel().setWriteListener(new ChannelListener<ConduitStreamSinkChannel>() {

                    @Override
                    public void handleEvent(ConduitStreamSinkChannel channel) {
                        int res;
                        do {
                            try {
                                res = channel.write(buffer);
                                if (res == 0) {
                                    return;
                                }
                            } catch (IOException e) {
                                UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                                safeClose(connection);
                            }
                        } while (buffer.hasRemaining());
                        channel.suspendWrites();
                        AjpReadListener.this.handleEvent(underlyingChannel.getSourceChannel());
                    }
                });
                underlyingChannel.getSinkChannel().resumeWrites();
                return;
            }
        } while (buffer.hasRemaining());
        AjpReadListener.this.handleEvent(underlyingChannel.getSourceChannel());
    } catch (IOException e) {
        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
        safeClose(connection);
    }
}
Also used : IOException(java.io.IOException) StreamConnection(org.xnio.StreamConnection) ByteBuffer(java.nio.ByteBuffer) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) ConduitStreamSinkChannel(org.xnio.conduits.ConduitStreamSinkChannel)

Example 2 with StreamConnection

use of org.xnio.StreamConnection in project indy by Commonjava.

the class ProxyAcceptHandler method handleEvent.

@Override
public void handleEvent(AcceptingChannel<StreamConnection> channel) {
    long start = System.nanoTime();
    RequestContextHelper.setContext(RequestContextHelper.ACCESS_CHANNEL, AccessChannel.GENERIC_PROXY.toString());
    setContext(PACKAGE_TYPE, PKG_TYPE_GENERIC_HTTP);
    final Logger logger = LoggerFactory.getLogger(getClass());
    StreamConnection accepted;
    try {
        accepted = channel.accept();
    } catch (IOException e) {
        logger.error("Failed to accept httprox connection: " + e.getMessage(), e);
        accepted = null;
    }
    // to remove the return in the catch clause, which is bad form...
    if (accepted == null) {
        return;
    }
    RequestContextHelper.setContext(REQUEST_PHASE, REQUEST_PHASE_START);
    LoggerFactory.getLogger(PROXY_METRIC_LOGGER).info("START HTTProx request (from: {})", accepted.getPeerAddress());
    RequestContextHelper.clearContext(REQUEST_PHASE);
    logger.debug("accepted {}", accepted.getPeerAddress());
    final ConduitStreamSourceChannel source = accepted.getSourceChannel();
    final ConduitStreamSinkChannel sink = accepted.getSinkChannel();
    final ProxyRepositoryCreator creator = createRepoCreator();
    final ProxyResponseWriter writer = new ProxyResponseWriter(config, storeManager, contentController, proxyAuthenticator, cacheProvider, mdcManager, creator, accepted, metricsConfig, metricsManager, sliMetricSet, cacheProducer, start, proxyExecutor.getExecutor());
    logger.debug("Setting writer: {}", writer);
    sink.getWriteSetter().set(writer);
    final ProxyRequestReader reader = new ProxyRequestReader(writer, sink, traceManager == null ? Optional.empty() : Optional.of(traceManager));
    writer.setProxyRequestReader(reader);
    logger.debug("Setting reader: {}", reader);
    source.getReadSetter().set(reader);
    source.resumeReads();
}
Also used : IOException(java.io.IOException) Logger(org.slf4j.Logger) StreamConnection(org.xnio.StreamConnection) ConduitStreamSourceChannel(org.xnio.conduits.ConduitStreamSourceChannel) ConduitStreamSinkChannel(org.xnio.conduits.ConduitStreamSinkChannel)

Example 3 with StreamConnection

use of org.xnio.StreamConnection in project undertow by undertow-io.

the class UndertowAcceptingSslChannel method accept.

public UndertowSslConnection accept() throws IOException {
    final StreamConnection tcpConnection = tcpServer.accept();
    if (tcpConnection == null) {
        return null;
    }
    try {
        final InetSocketAddress peerAddress = tcpConnection.getPeerAddress(InetSocketAddress.class);
        final SSLEngine engine = ssl.getSslContext().createSSLEngine(getHostNameNoResolve(peerAddress), peerAddress.getPort());
        if (useCipherSuitesOrder) {
            SSLParameters sslParameters = engine.getSSLParameters();
            sslParameters.setUseCipherSuitesOrder(true);
            engine.setSSLParameters(sslParameters);
        }
        final boolean clientMode = useClientMode != 0;
        engine.setUseClientMode(clientMode);
        if (!clientMode) {
            final SslClientAuthMode clientAuthMode = UndertowAcceptingSslChannel.this.clientAuthMode;
            if (clientAuthMode != null)
                switch(clientAuthMode) {
                    case NOT_REQUESTED:
                        engine.setNeedClientAuth(false);
                        engine.setWantClientAuth(false);
                        break;
                    case REQUESTED:
                        engine.setWantClientAuth(true);
                        break;
                    case REQUIRED:
                        engine.setNeedClientAuth(true);
                        break;
                    default:
                        throw new IllegalStateException();
                }
        }
        engine.setEnableSessionCreation(enableSessionCreation != 0);
        final String[] cipherSuites = UndertowAcceptingSslChannel.this.cipherSuites;
        if (cipherSuites != null) {
            final Set<String> supported = new HashSet<>(Arrays.asList(engine.getSupportedCipherSuites()));
            if (supported.isEmpty()) {
                engine.setEnabledCipherSuites(cipherSuites);
            } else {
                final List<String> finalList = new ArrayList<>();
                for (String name : cipherSuites) {
                    if (supported.contains(name)) {
                        finalList.add(name);
                    }
                }
                engine.setEnabledCipherSuites(finalList.toArray(new String[finalList.size()]));
            }
        }
        final String[] protocols = UndertowAcceptingSslChannel.this.protocols;
        if (protocols != null) {
            final Set<String> supported = new HashSet<>(Arrays.asList(engine.getSupportedProtocols()));
            if (supported.isEmpty()) {
                engine.setEnabledProtocols(protocols);
            } else {
                final List<String> finalList = new ArrayList<>();
                for (String name : protocols) {
                    if (supported.contains(name)) {
                        finalList.add(name);
                    }
                }
                engine.setEnabledProtocols(finalList.toArray(new String[finalList.size()]));
            }
        }
        return accept(tcpConnection, engine);
    } catch (IOException | RuntimeException e) {
        IoUtils.safeClose(tcpConnection);
        UndertowLogger.REQUEST_LOGGER.failedToAcceptSSLRequest(e);
        return null;
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SSLEngine(javax.net.ssl.SSLEngine) ArrayList(java.util.ArrayList) IOException(java.io.IOException) StreamConnection(org.xnio.StreamConnection) SSLParameters(javax.net.ssl.SSLParameters) SslClientAuthMode(org.xnio.SslClientAuthMode) HashSet(java.util.HashSet)

Example 4 with StreamConnection

use of org.xnio.StreamConnection in project undertow by undertow-io.

the class WebSocketServlet method doGet.

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    final ServletWebSocketHttpExchange facade = new ServletWebSocketHttpExchange(req, resp, peerConnections);
    Handshake handshaker = null;
    for (Handshake method : handshakes) {
        if (method.matches(facade)) {
            handshaker = method;
            break;
        }
    }
    if (handshaker == null) {
        UndertowLogger.REQUEST_LOGGER.debug("Could not find hand shaker for web socket request");
        resp.sendError(StatusCodes.BAD_REQUEST);
        return;
    }
    final Handshake selected = handshaker;
    facade.upgradeChannel(new HttpUpgradeListener() {

        @Override
        public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) {
            WebSocketChannel channel = selected.createChannel(facade, streamConnection, facade.getBufferPool());
            peerConnections.add(channel);
            callback.onConnect(facade, channel);
        }
    });
    handshaker.handshake(facade);
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) HttpUpgradeListener(io.undertow.server.HttpUpgradeListener) StreamConnection(org.xnio.StreamConnection) Hybi07Handshake(io.undertow.websockets.core.protocol.version07.Hybi07Handshake) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) Handshake(io.undertow.websockets.core.protocol.Handshake) Hybi08Handshake(io.undertow.websockets.core.protocol.version08.Hybi08Handshake)

Example 5 with StreamConnection

use of org.xnio.StreamConnection in project undertow by undertow-io.

the class HttpReadListener method exchangeComplete.

public void exchangeComplete(final HttpServerExchange exchange) {
    connection.clearChannel();
    connection.setCurrentExchange(null);
    final HttpServerConnection connection = this.connection;
    if (exchange.isPersistent() && !isUpgradeOrConnect(exchange)) {
        final StreamConnection channel = connection.getChannel();
        if (connection.getExtraBytes() == null) {
            // we have to resume from with the io thread
            if (exchange.isInIoThread()) {
                // no need for CAS, we are in the IO thread
                newRequest();
                channel.getSourceChannel().setReadListener(HttpReadListener.this);
                channel.getSourceChannel().resumeReads();
                requestStateUpdater.set(this, 0);
            } else {
                while (true) {
                    if (connection.getOriginalSourceConduit().isReadShutdown() || connection.getOriginalSinkConduit().isWriteShutdown()) {
                        channel.getSourceChannel().suspendReads();
                        channel.getSinkChannel().suspendWrites();
                        IoUtils.safeClose(connection);
                        return;
                    } else {
                        if (requestStateUpdater.compareAndSet(this, 1, 2)) {
                            try {
                                newRequest();
                                channel.getSourceChannel().setReadListener(HttpReadListener.this);
                                channel.getSourceChannel().resumeReads();
                            } finally {
                                requestStateUpdater.set(this, 0);
                            }
                            break;
                        }
                    }
                }
            }
        } else {
            if (exchange.isInIoThread()) {
                // no need to CAS, as we don't actually resume
                requestStateUpdater.set(this, 0);
                newRequest();
                // no need to suspend reads here, the task will always run before the read listener anyway
                channel.getIoThread().execute(this);
            } else {
                while (true) {
                    if (connection.getOriginalSinkConduit().isWriteShutdown()) {
                        channel.getSourceChannel().suspendReads();
                        channel.getSinkChannel().suspendWrites();
                        IoUtils.safeClose(connection);
                        return;
                    } else if (requestStateUpdater.compareAndSet(this, 1, 2)) {
                        try {
                            newRequest();
                            channel.getSourceChannel().suspendReads();
                        } finally {
                            requestStateUpdater.set(this, 0);
                        }
                        break;
                    }
                }
                Executor executor = exchange.getDispatchExecutor();
                if (executor == null) {
                    executor = exchange.getConnection().getWorker();
                }
                executor.execute(this);
            }
        }
    } else if (!exchange.isPersistent()) {
        if (connection.getExtraBytes() != null) {
            connection.getExtraBytes().close();
            connection.setExtraBytes(null);
        }
        ConnectionUtils.cleanClose(connection.getChannel(), connection);
    } else {
        // upgrade or connect handling
        if (connection.getExtraBytes() != null) {
            connection.getChannel().getSourceChannel().setConduit(new ReadDataStreamSourceConduit(connection.getChannel().getSourceChannel().getConduit(), connection));
        }
        try {
            if (!connection.getChannel().getSinkChannel().flush()) {
                connection.getChannel().getSinkChannel().setWriteListener(ChannelListeners.flushingChannelListener(new ChannelListener<ConduitStreamSinkChannel>() {

                    @Override
                    public void handleEvent(ConduitStreamSinkChannel conduitStreamSinkChannel) {
                        connection.getUpgradeListener().handleUpgrade(connection.getChannel(), exchange);
                    }
                }, new ClosingChannelExceptionHandler<ConduitStreamSinkChannel>(connection)));
                connection.getChannel().getSinkChannel().resumeWrites();
                return;
            }
            connection.getUpgradeListener().handleUpgrade(connection.getChannel(), exchange);
        } catch (IOException e) {
            UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
            IoUtils.safeClose(connection);
        } catch (Throwable t) {
            UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t);
            IoUtils.safeClose(connection);
        }
    }
}
Also used : Executor(java.util.concurrent.Executor) ReadDataStreamSourceConduit(io.undertow.conduits.ReadDataStreamSourceConduit) IOException(java.io.IOException) StreamConnection(org.xnio.StreamConnection) ConduitStreamSinkChannel(org.xnio.conduits.ConduitStreamSinkChannel)

Aggregations

StreamConnection (org.xnio.StreamConnection)26 IOException (java.io.IOException)11 HttpServerExchange (io.undertow.server.HttpServerExchange)10 HttpUpgradeListener (io.undertow.server.HttpUpgradeListener)8 InetSocketAddress (java.net.InetSocketAddress)7 ChannelListener (org.xnio.ChannelListener)7 ConduitStreamSinkChannel (org.xnio.conduits.ConduitStreamSinkChannel)7 OptionMap (org.xnio.OptionMap)6 HttpHandler (io.undertow.server.HttpHandler)4 WebSocketChannel (io.undertow.websockets.core.WebSocketChannel)4 Handshake (io.undertow.websockets.core.protocol.Handshake)4 ConduitStreamSourceChannel (org.xnio.conduits.ConduitStreamSourceChannel)4 ByteBufferPool (io.undertow.connector.ByteBufferPool)3 DefaultByteBufferPool (io.undertow.server.DefaultByteBufferPool)3 HttpOpenListener (io.undertow.server.protocol.http.HttpOpenListener)3 HttpServerConnection (io.undertow.server.protocol.http.HttpServerConnection)3 ByteBuffer (java.nio.ByteBuffer)3 PooledByteBuffer (io.undertow.connector.PooledByteBuffer)2 Http2Channel (io.undertow.protocols.http2.Http2Channel)2 SessionConfig (io.undertow.server.session.SessionConfig)2