Search in sources :

Example 76 with ChannelPipeline

use of io.netty.channel.ChannelPipeline in project runelite by runelite.

the class HandshakeResponseHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, HandshakeResponsePacket handshakeResponse) throws Exception {
    Channel channel = ctx.channel();
    ChannelPipeline p = ctx.pipeline();
    CompletableFuture<HandshakeResponseType> handshakeFuture = client.getHandshakeFuture();
    assert handshakeFuture != null;
    if (handshakeResponse.getResponse() != HandshakeResponseType.RESPONSE_OK) {
        logger.warn("Non-ok response from server {}", handshakeResponse.getResponse());
        ctx.close();
        return;
    }
    // Send encryption packet
    EncryptionPacket encryptionPacket = new EncryptionPacket();
    encryptionPacket.setKey((byte) 0);
    channel.writeAndFlush(encryptionPacket);
    client.setState(ClientState.CONNECTED);
    logger.info("Client is now connected!");
    p.replace("decoder", "decoder", new ArchiveResponseDecoder());
    handshakeFuture.complete(handshakeResponse.getResponse());
}
Also used : HandshakeResponseType(net.runelite.protocol.api.login.HandshakeResponseType) EncryptionPacket(net.runelite.protocol.api.update.EncryptionPacket) Channel(io.netty.channel.Channel) ChannelPipeline(io.netty.channel.ChannelPipeline) ArchiveResponseDecoder(net.runelite.protocol.update.decoders.ArchiveResponseDecoder)

Example 77 with ChannelPipeline

use of io.netty.channel.ChannelPipeline in project drill by axbaretto.

the class AbstractRemoteConnection method addSecurityHandlers.

/**
 * Helps to add all the required security handler's after negotiation for encryption is completed.
 * <p>Handler's before encryption is negotiated are:</p>
 * <ul>
 *    <li>  PROTOCOL_DECODER {@link ProtobufLengthDecoder} </li>
 *    <li>  MESSAGE_DECODER {@link RpcDecoder}  </li>
 *    <li>  PROTOCOL_ENCODER {@link RpcEncoder} </li>
 *    <li>  HANDSHAKE_HANDLER {@link org.apache.drill.exec.rpc.BasicClient.ClientHandshakeHandler} OR
 *                            {@link org.apache.drill.exec.rpc.BasicServer.ServerHandshakeHandler}  </li>
 *    <li>  optional - IDLE_STATE_HANDLER {@link org.apache.drill.exec.rpc.BasicClient.IdlePingHandler} OR
 *                   - TIMEOUT_HANDLER {@link org.apache.drill.exec.rpc.BasicServer.LoggingReadTimeoutHandler}  </li>
 *    <li>  MESSAGE_HANDLER {@link org.apache.drill.exec.rpc.RpcBus.InboundHandler} </li>
 *    <li>  EXCEPTION_HANDLER {@link RpcExceptionHandler} </li>
 * </ul>
 * <p>Handler's after encryption is negotiated are:</p>
 * <ul>
 *    <li>  LENGTH_DECODER_HANDLER {@link LengthFieldBasedFrameDecoder}
 *    <li>  SASL_DECRYPTION_HANDLER {@link SaslDecryptionHandler}
 *    <li>  PROTOCOL_DECODER {@link ProtobufLengthDecoder}
 *    <li>  MESSAGE_DECODER {@link RpcDecoder}
 *    <li>  SASL_ENCRYPTION_HANDLER {@link SaslEncryptionHandler}
 *    <li>  CHUNK_CREATION_HANDLER {@link ChunkCreationHandler}
 *    <li>  PROTOCOL_ENCODER {@link RpcEncoder}
 *    <li>  HANDSHAKE_HANDLER {@link org.apache.drill.exec.rpc.BasicClient.ClientHandshakeHandler} OR
 *                            {@link org.apache.drill.exec.rpc.BasicServer.ServerHandshakeHandler}
 *    <li>  optional - IDLE_STATE_HANDLER {@link org.apache.drill.exec.rpc.BasicClient.IdlePingHandler} OR
 *                   - TIMEOUT_HANDLER {@link org.apache.drill.exec.rpc.BasicServer.LoggingReadTimeoutHandler}
 *    <li>  MESSAGE_HANDLER {@link org.apache.drill.exec.rpc.RpcBus.InboundHandler}
 *    <li>  EXCEPTION_HANDLER {@link RpcExceptionHandler}
 * </ul>
 * <p>
 *  If encryption is enabled ChunkCreationHandler is always added to divide the Rpc message into chunks of
 *  negotiated {@link EncryptionContextImpl#wrapSizeLimit} bytes. This helps to make a generic encryption handler.
 * </p>
 */
@Override
public void addSecurityHandlers() {
    final ChannelPipeline channelPipeline = getChannel().pipeline();
    if (channelPipeline.names().contains(RpcConstants.SSL_HANDLER)) {
        channelPipeline.addAfter(RpcConstants.SSL_HANDLER, RpcConstants.SASL_DECRYPTION_HANDLER, new SaslDecryptionHandler(saslCodec, getMaxWrappedSize(), OutOfMemoryHandler.DEFAULT_INSTANCE));
        channelPipeline.addAfter(RpcConstants.SSL_HANDLER, RpcConstants.LENGTH_DECODER_HANDLER, new LengthFieldBasedFrameDecoder(ByteOrder.BIG_ENDIAN, Integer.MAX_VALUE, RpcConstants.LENGTH_FIELD_OFFSET, RpcConstants.LENGTH_FIELD_LENGTH, RpcConstants.LENGTH_ADJUSTMENT, RpcConstants.INITIAL_BYTES_TO_STRIP, true));
    } else {
        channelPipeline.addFirst(RpcConstants.SASL_DECRYPTION_HANDLER, new SaslDecryptionHandler(saslCodec, getMaxWrappedSize(), OutOfMemoryHandler.DEFAULT_INSTANCE));
        channelPipeline.addFirst(RpcConstants.LENGTH_DECODER_HANDLER, new LengthFieldBasedFrameDecoder(ByteOrder.BIG_ENDIAN, Integer.MAX_VALUE, RpcConstants.LENGTH_FIELD_OFFSET, RpcConstants.LENGTH_FIELD_LENGTH, RpcConstants.LENGTH_ADJUSTMENT, RpcConstants.INITIAL_BYTES_TO_STRIP, true));
    }
    channelPipeline.addAfter(RpcConstants.MESSAGE_DECODER, RpcConstants.SASL_ENCRYPTION_HANDLER, new SaslEncryptionHandler(saslCodec, getWrapSizeLimit(), OutOfMemoryHandler.DEFAULT_INSTANCE));
    channelPipeline.addAfter(RpcConstants.SASL_ENCRYPTION_HANDLER, RpcConstants.CHUNK_CREATION_HANDLER, new ChunkCreationHandler(getWrapSizeLimit()));
}
Also used : LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 78 with ChannelPipeline

use of io.netty.channel.ChannelPipeline in project apollo by apollo-rsps.

the class ServiceChannelInitializer method initChannel.

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("handshakeDecoder", new HandshakeDecoder());
    pipeline.addLast("timeout", new IdleStateHandler(NetworkConstants.IDLE_TIME, 0, 0));
    pipeline.addLast("handler", handler);
}
Also used : IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) HandshakeDecoder(org.apollo.net.codec.handshake.HandshakeDecoder) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 79 with ChannelPipeline

use of io.netty.channel.ChannelPipeline in project scalecube by scalecube.

the class NettyStreamChannelInitializer method initChannel.

@Override
protected void initChannel(Channel channel) {
    ChannelPipeline pipeline = channel.pipeline();
    // contexs contexts contexs
    channel.pipeline().addLast(channelContextHandler);
    // frame codecs
    pipeline.addLast(new LengthFieldPrepender(LENGTH_FIELD_LENGTH));
    pipeline.addLast(new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, 0, LENGTH_FIELD_LENGTH, 0, LENGTH_FIELD_LENGTH));
    // message acceptor
    pipeline.addLast(messageHandler);
    // at-least-something exception handler
    pipeline.addLast(new ChannelInboundHandlerAdapter() {

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
            // Hint: at this point one can look at throwable, make some exception translation, and via channelContext post
            // ChannelContextError event, and hence give business layer ability to react on low level system error events
            LOGGER.warn("Exception caught for channel {}, {}", ctx.channel(), throwable);
        }
    });
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) ChannelPipeline(io.netty.channel.ChannelPipeline) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 80 with ChannelPipeline

use of io.netty.channel.ChannelPipeline in project activemq-artemis by apache.

the class NettyConnector method createConnection.

@Override
public Connection createConnection() {
    if (channelClazz == null) {
        return null;
    }
    // HORNETQ-907 - strip off IPv6 scope-id (if necessary)
    SocketAddress remoteDestination = new InetSocketAddress(host, port);
    InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress();
    if (inetAddress instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) inetAddress;
        if (inet6Address.getScopeId() != 0) {
            try {
                remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()), ((InetSocketAddress) remoteDestination).getPort());
            } catch (UnknownHostException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
    }
    logger.debug("Remote destination: " + remoteDestination);
    ChannelFuture future;
    // port 0 does not work so only use local address if set
    if (localPort != 0) {
        SocketAddress localDestination;
        if (localAddress != null) {
            localDestination = new InetSocketAddress(localAddress, localPort);
        } else {
            localDestination = new InetSocketAddress(localPort);
        }
        future = bootstrap.connect(remoteDestination, localDestination);
    } else {
        future = bootstrap.connect(remoteDestination);
    }
    future.awaitUninterruptibly();
    if (future.isSuccess()) {
        final Channel ch = future.channel();
        SslHandler sslHandler = ch.pipeline().get(SslHandler.class);
        if (sslHandler != null) {
            Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
            if (handshakeFuture.awaitUninterruptibly(30000)) {
                if (handshakeFuture.isSuccess()) {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
                    channelHandler.active = true;
                } else {
                    ch.close().awaitUninterruptibly();
                    ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause());
                    return null;
                }
            } else {
                // handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds"));
                ch.close().awaitUninterruptibly();
                return null;
            }
        }
        if (httpUpgradeEnabled) {
            // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler.
            try {
                // get this first incase it removes itself
                HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade");
                String scheme = "http";
                if (sslEnabled) {
                    scheme = "https";
                }
                String ipv6Host = IPV6Util.encloseHost(host);
                URI uri = new URI(scheme, null, ipv6Host, port, null, null, null);
                HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
                request.headers().set(HttpHeaderNames.HOST, ipv6Host);
                request.headers().set(HttpHeaderNames.UPGRADE, ACTIVEMQ_REMOTING);
                request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderNames.UPGRADE);
                final String serverName = ConfigurationHelper.getStringProperty(TransportConstants.ACTIVEMQ_SERVER_NAME, null, configuration);
                if (serverName != null) {
                    request.headers().set(TransportConstants.ACTIVEMQ_SERVER_NAME, serverName);
                }
                final String endpoint = ConfigurationHelper.getStringProperty(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration);
                if (endpoint != null) {
                    request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
                }
                // Get 16 bit nonce and base 64 encode it
                byte[] nonce = randomBytes(16);
                String key = base64(nonce);
                request.headers().set(SEC_ACTIVEMQ_REMOTING_KEY, key);
                ch.attr(REMOTING_KEY).set(key);
                logger.debugf("Sending HTTP request %s", request);
                // Send the HTTP request.
                ch.writeAndFlush(request);
                if (!httpUpgradeHandler.awaitHandshake()) {
                    ch.close().awaitUninterruptibly();
                    return null;
                }
            } catch (URISyntaxException e) {
                ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(e);
                return null;
            }
        } else {
            ChannelPipeline channelPipeline = ch.pipeline();
            ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
            channelHandler.active = true;
        }
        // No acceptor on a client connection
        Listener connectionListener = new Listener();
        NettyConnection conn = new NettyConnection(configuration, ch, connectionListener, !httpEnabled && batchDelay > 0, false);
        connectionListener.connectionCreated(null, conn, protocolManager);
        return conn;
    } else {
        Throwable t = future.cause();
        if (t != null && !(t instanceof ConnectException)) {
            ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause());
        }
        return null;
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) HttpRequest(io.netty.handler.codec.http.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) BaseConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.BaseConnectionLifeCycleListener) ClientConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.ClientConnectionLifeCycleListener) UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) KQueueSocketChannel(io.netty.channel.kqueue.KQueueSocketChannel) Channel(io.netty.channel.Channel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Inet6Address(java.net.Inet6Address) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) SslHandler(io.netty.handler.ssl.SslHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress) ConnectException(java.net.ConnectException)

Aggregations

ChannelPipeline (io.netty.channel.ChannelPipeline)331 SocketChannel (io.netty.channel.socket.SocketChannel)95 Channel (io.netty.channel.Channel)86 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)84 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)77 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)74 Bootstrap (io.netty.bootstrap.Bootstrap)72 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)62 ChannelFuture (io.netty.channel.ChannelFuture)61 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)57 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)57 EventLoopGroup (io.netty.channel.EventLoopGroup)49 InetSocketAddress (java.net.InetSocketAddress)43 SslHandler (io.netty.handler.ssl.SslHandler)42 HttpServerCodec (io.netty.handler.codec.http.HttpServerCodec)37 IOException (java.io.IOException)35 LoggingHandler (io.netty.handler.logging.LoggingHandler)33 StringDecoder (io.netty.handler.codec.string.StringDecoder)32 IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)30 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)29