Search in sources :

Example 96 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext 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 97 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project drill by apache.

the class UserServer method getHandshakeHandler.

@Override
protected ServerHandshakeHandler<UserToBitHandshake> getHandshakeHandler(final BitToUserConnection connection) {
    return new ServerHandshakeHandler<UserToBitHandshake>(RpcType.HANDSHAKE, UserToBitHandshake.PARSER) {

        @Override
        protected void consumeHandshake(ChannelHandlerContext ctx, UserToBitHandshake inbound) throws Exception {
            BitToUserHandshake handshakeResp = getHandshakeResponse(inbound);
            OutboundRpcMessage msg = new OutboundRpcMessage(RpcMode.RESPONSE, this.handshakeType, coordinationId, handshakeResp);
            ctx.writeAndFlush(msg);
            if (handshakeResp.getStatus() != HandshakeStatus.SUCCESS && handshakeResp.getStatus() != HandshakeStatus.AUTH_REQUIRED) {
                // If handling handshake results in an error, throw an exception to terminate the connection.
                throw new RpcException("Handshake request failed: " + handshakeResp.getErrorMessage());
            }
        }

        @Override
        public BitToUserHandshake getHandshakeResponse(UserToBitHandshake inbound) throws Exception {
            if (logger.isTraceEnabled()) {
                logger.trace("Handling handshake from user to bit. {}", serializeUserToBitHandshakeWithoutPassword(inbound));
            }
            // if timeout is unsupported or is set to false, disable timeout.
            if (!inbound.hasSupportTimeout() || !inbound.getSupportTimeout()) {
                connection.disableReadTimeout();
                logger.warn("Timeout Disabled as client {} doesn't support it.", connection.getName());
            }
            BitToUserHandshake.Builder respBuilder = BitToUserHandshake.newBuilder().setRpcVersion(UserRpcConfig.RPC_VERSION).setServerInfos(UserRpcUtils.getRpcEndpointInfos(SERVER_NAME)).addAllSupportedMethods(UserRpcConfig.SUPPORTED_SERVER_METHODS);
            try {
                if (inbound.getRpcVersion() != UserRpcConfig.RPC_VERSION) {
                    final String errMsg = String.format("Invalid rpc version. Expected %d, actual %d.", UserRpcConfig.RPC_VERSION, inbound.getRpcVersion());
                    return handleFailure(respBuilder, HandshakeStatus.RPC_VERSION_MISMATCH, errMsg, null);
                }
                connection.setHandshake(inbound);
                if (!config.isAuthEnabled()) {
                    connection.finalizeSession(inbound.getCredentials().getUserName());
                    respBuilder.setStatus(HandshakeStatus.SUCCESS);
                    return respBuilder.build();
                }
                // If sasl_support field is absent in handshake message then treat the client as < 1.10 client
                final boolean clientSupportsSasl = inbound.hasSaslSupport();
                // saslSupportOrdinal will be set to UNKNOWN_SASL_SUPPORT, if sasl_support field in handshake is set to a
                // value which is unknown to this server. We will treat those clients as one which knows SASL protocol.
                final int saslSupportOrdinal = (clientSupportsSasl) ? inbound.getSaslSupport().ordinal() : SaslSupport.UNKNOWN_SASL_SUPPORT.ordinal();
                // Check if client doesn't support SASL or only supports SASL_AUTH and server has encryption enabled
                if ((!clientSupportsSasl || saslSupportOrdinal == SaslSupport.SASL_AUTH.ordinal()) && config.isEncryptionEnabled()) {
                    throw new UserAuthenticationException("The server doesn't allow client without encryption support." + " Please upgrade your client or talk to your system administrator.");
                }
                if (!clientSupportsSasl) {
                    // for backward compatibility < 1.10
                    final String userName = inbound.getCredentials().getUserName();
                    if (logger.isTraceEnabled()) {
                        logger.trace("User {} on connection {} is likely using an older client.", userName, connection.getRemoteAddress());
                    }
                    try {
                        String password = "";
                        final UserProperties props = inbound.getProperties();
                        for (int i = 0; i < props.getPropertiesCount(); i++) {
                            Property prop = props.getProperties(i);
                            if (DrillProperties.PASSWORD.equalsIgnoreCase(prop.getKey())) {
                                password = prop.getValue();
                                break;
                            }
                        }
                        final PlainFactory plainFactory;
                        try {
                            plainFactory = (PlainFactory) config.getAuthProvider().getAuthenticatorFactory(PlainFactory.SIMPLE_NAME);
                        } catch (final SaslException e) {
                            throw new UserAuthenticationException("The server no longer supports username/password" + " based authentication. Please talk to your system administrator.");
                        }
                        plainFactory.getAuthenticator().authenticate(userName, password);
                        connection.changeHandlerTo(config.getMessageHandler());
                        connection.finalizeSession(userName);
                        respBuilder.setStatus(HandshakeStatus.SUCCESS);
                        logger.info("Authenticated {} from {} successfully using PLAIN", userName, connection.getRemoteAddress());
                        return respBuilder.build();
                    } catch (UserAuthenticationException ex) {
                        return handleFailure(respBuilder, HandshakeStatus.AUTH_FAILED, ex.getMessage(), ex);
                    }
                }
                // Offer all the configured mechanisms to client. If certain mechanism doesn't support encryption
                // like PLAIN, those should fail during the SASL handshake negotiation.
                respBuilder.addAllAuthenticationMechanisms(config.getAuthProvider().getAllFactoryNames());
                // set the encrypted flag in handshake message. For older clients this field is optional so will be ignored
                respBuilder.setEncrypted(connection.isEncryptionEnabled());
                respBuilder.setMaxWrappedSize(connection.getMaxWrappedSize());
                // for now, this means PLAIN credentials will be sent over twice
                // (during handshake and during sasl exchange)
                respBuilder.setStatus(HandshakeStatus.AUTH_REQUIRED);
                return respBuilder.build();
            } catch (Exception e) {
                return handleFailure(respBuilder, HandshakeStatus.UNKNOWN_FAILURE, e.getMessage(), e);
            }
        }
    };
}
Also used : PlainFactory(org.apache.drill.exec.rpc.security.plain.PlainFactory) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SaslException(javax.security.sasl.SaslException) RpcException(org.apache.drill.exec.rpc.RpcException) SaslException(javax.security.sasl.SaslException) UserAuthenticationException(org.apache.drill.exec.rpc.user.security.UserAuthenticationException) DrillbitStartupException(org.apache.drill.exec.exception.DrillbitStartupException) IOException(java.io.IOException) DrillException(org.apache.drill.common.exceptions.DrillException) UserToBitHandshake(org.apache.drill.exec.proto.UserProtos.UserToBitHandshake) UserAuthenticationException(org.apache.drill.exec.rpc.user.security.UserAuthenticationException) UserProperties(org.apache.drill.exec.proto.UserProtos.UserProperties) BitToUserHandshake(org.apache.drill.exec.proto.UserProtos.BitToUserHandshake) OutboundRpcMessage(org.apache.drill.exec.rpc.OutboundRpcMessage) RpcException(org.apache.drill.exec.rpc.RpcException) Property(org.apache.drill.exec.proto.UserProtos.Property)

Example 98 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project component-runtime by Talend.

the class ServingProxyHandler method channelRead0.

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;
    }
    api.getExecutor().execute(() -> {
        final Map<String, String> headers = StreamSupport.stream(Spliterators.spliteratorUnknownSize(request.headers().iteratorAsString(), Spliterator.IMMUTABLE), false).collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
        final Attribute<String> baseAttr = ctx.channel().attr(Handlers.BASE);
        Optional<Response> matching = api.getResponseLocator().findMatching(new RequestImpl((baseAttr == null || baseAttr.get() == null ? "" : baseAttr.get()) + request.uri(), request.method().name(), headers), api.getHeaderFilter());
        if (!matching.isPresent()) {
            if (HttpMethod.CONNECT.name().equalsIgnoreCase(request.method().name())) {
                final Map<String, String> responseHeaders = new HashMap<>();
                responseHeaders.put(HttpHeaderNames.CONNECTION.toString(), HttpHeaderValues.KEEP_ALIVE.toString());
                responseHeaders.put(HttpHeaderNames.CONTENT_LENGTH.toString(), "0");
                matching = of(new ResponseImpl(responseHeaders, HttpResponseStatus.OK.code(), Unpooled.EMPTY_BUFFER.array()));
                if (api.getSslContext() != null) {
                    final SSLEngine sslEngine = api.getSslContext().createSSLEngine();
                    sslEngine.setUseClientMode(false);
                    ctx.channel().pipeline().addFirst("ssl", new SslHandler(sslEngine, true));
                    final String uri = request.uri();
                    final String[] parts = uri.split(":");
                    ctx.channel().attr(Handlers.BASE).set("https://" + parts[0] + (parts.length > 1 && !"443".equals(parts[1]) ? ":" + parts[1] : ""));
                }
            } else {
                sendError(ctx, new HttpResponseStatus(HttpURLConnection.HTTP_BAD_REQUEST, "You are in proxy mode. No response was found for the simulated request. Please ensure to capture it for next executions. " + request.method().name() + " " + request.uri()));
                return;
            }
        }
        final Response resp = matching.get();
        final ByteBuf bytes = ofNullable(resp.payload()).map(Unpooled::copiedBuffer).orElse(Unpooled.EMPTY_BUFFER);
        final HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(resp.status()), bytes);
        HttpUtil.setContentLength(response, bytes.array().length);
        if (!api.isSkipProxyHeaders()) {
            response.headers().set("X-Talend-Proxy-JUnit", "true");
        }
        ofNullable(resp.headers()).ifPresent(h -> h.forEach((k, v) -> response.headers().set(k, v)));
        ctx.writeAndFlush(response);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) HttpVersion(io.netty.handler.codec.http.HttpVersion) Handlers.sendError(org.talend.sdk.component.junit.http.internal.impl.Handlers.sendError) Handlers.closeOnFlush(org.talend.sdk.component.junit.http.internal.impl.Handlers.closeOnFlush) Spliterators(java.util.Spliterators) Optional.of(java.util.Optional.of) Response(org.talend.sdk.component.junit.http.api.Response) HashMap(java.util.HashMap) SSLEngine(javax.net.ssl.SSLEngine) HttpApiHandler(org.talend.sdk.component.junit.http.api.HttpApiHandler) Unpooled(io.netty.buffer.Unpooled) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Collectors.toMap(java.util.stream.Collectors.toMap) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) StreamSupport(java.util.stream.StreamSupport) Attribute(io.netty.util.Attribute) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) Optional.ofNullable(java.util.Optional.ofNullable) HttpMethod(io.netty.handler.codec.http.HttpMethod) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Slf4j(lombok.extern.slf4j.Slf4j) SslHandler(io.netty.handler.ssl.SslHandler) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Optional(java.util.Optional) ChannelHandler(io.netty.channel.ChannelHandler) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AllArgsConstructor(lombok.AllArgsConstructor) Spliterator(java.util.Spliterator) HttpUtil(io.netty.handler.codec.http.HttpUtil) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HashMap(java.util.HashMap) SSLEngine(javax.net.ssl.SSLEngine) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ByteBuf(io.netty.buffer.ByteBuf) SslHandler(io.netty.handler.ssl.SslHandler) Response(org.talend.sdk.component.junit.http.api.Response) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HashMap(java.util.HashMap) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map)

Example 99 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project redisson by redisson.

the class RedisChannelInitializer method initSsl.

private void initSsl(final RedisClientConfig config, Channel ch) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, SSLException, UnrecoverableKeyException {
    if (!config.getAddress().isSsl()) {
        return;
    }
    io.netty.handler.ssl.SslProvider provided = io.netty.handler.ssl.SslProvider.JDK;
    if (config.getSslProvider() == SslProvider.OPENSSL) {
        provided = io.netty.handler.ssl.SslProvider.OPENSSL;
    }
    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(provided);
    sslContextBuilder.protocols(config.getSslProtocols());
    if (config.getSslTruststore() != null) {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream stream = config.getSslTruststore().openStream();
        try {
            char[] password = null;
            if (config.getSslTruststorePassword() != null) {
                password = config.getSslTruststorePassword().toCharArray();
            }
            keyStore.load(stream, password);
        } finally {
            stream.close();
        }
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContextBuilder.trustManager(trustManagerFactory);
    }
    if (config.getSslKeystore() != null) {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream stream = config.getSslKeystore().openStream();
        char[] password = null;
        if (config.getSslKeystorePassword() != null) {
            password = config.getSslKeystorePassword().toCharArray();
        }
        try {
            keyStore.load(stream, password);
        } finally {
            stream.close();
        }
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);
        sslContextBuilder.keyManager(keyManagerFactory);
    }
    SSLParameters sslParams = new SSLParameters();
    if (config.isSslEnableEndpointIdentification()) {
        sslParams.setEndpointIdentificationAlgorithm("HTTPS");
    } else {
        if (config.getSslTruststore() == null) {
            sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        }
    }
    SslContext sslContext = sslContextBuilder.build();
    String hostname = config.getSslHostname();
    if (hostname == null || NetUtil.createByteArrayFromIpAddressString(hostname) != null) {
        hostname = config.getAddress().getHost();
    }
    SSLEngine sslEngine = sslContext.newEngine(ch.alloc(), hostname, config.getAddress().getPort());
    sslEngine.setSSLParameters(sslParams);
    SslHandler sslHandler = new SslHandler(sslEngine);
    ch.pipeline().addLast(sslHandler);
    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

        volatile boolean sslInitDone;

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            if (sslInitDone) {
                super.channelActive(ctx);
            }
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (!sslInitDone && (evt instanceof SslHandshakeCompletionEvent)) {
                SslHandshakeCompletionEvent e = (SslHandshakeCompletionEvent) evt;
                if (e.isSuccess()) {
                    sslInitDone = true;
                    ctx.fireChannelActive();
                } else {
                    RedisConnection connection = RedisConnection.getFrom(ctx.channel());
                    connection.closeAsync();
                    connection.getConnectionPromise().completeExceptionally(e.cause());
                }
            }
            super.userEventTriggered(ctx, evt);
        }
    });
}
Also used : SslHandshakeCompletionEvent(io.netty.handler.ssl.SslHandshakeCompletionEvent) InputStream(java.io.InputStream) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) javax.net.ssl(javax.net.ssl) KeyStore(java.security.KeyStore) SslHandler(io.netty.handler.ssl.SslHandler) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) SslContext(io.netty.handler.ssl.SslContext) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) RedisConnection(org.redisson.client.RedisConnection)

Example 100 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project motan by weibocom.

the class NettyHttpRequestHandlerTest method testChannelRead0.

@Test
public void testChannelRead0() throws Exception {
    final MessageHandler messageHandler = mockery.mock(MessageHandler.class);
    final ChannelHandlerContext ctx = mockery.mock(ChannelHandlerContext.class);
    final FullHttpResponse response = mockery.mock(FullHttpResponse.class);
    mockery.checking(new Expectations() {

        {
            allowing(ctx).write(with(any(FullHttpResponse.class)));
            will(new CustomAction("verify") {

                @Override
                public Object invoke(Invocation invocation) throws Throwable {
                    FullHttpResponse actualResponse = (FullHttpResponse) invocation.getParameter(0);
                    assertNotNull(actualResponse);
                    assertEquals(response, actualResponse);
                    return null;
                }
            });
            allowing(ctx).flush();
            will(returnValue(null));
            allowing(ctx).close();
            will(returnValue(null));
            atLeast(1).of(messageHandler).handle(with(any(Channel.class)), with(any(Object.class)));
            will(returnValue(response));
            allowing(response).headers();
            will(returnValue(new DefaultHttpHeaders()));
        }
    });
    FullHttpRequest httpRequest = buildHttpRequest("anyPath");
    NettyHttpRequestHandler handler = new NettyHttpRequestHandler(null, messageHandler);
    handler.channelRead0(ctx, httpRequest);
}
Also used : Expectations(org.jmock.Expectations) MessageHandler(com.weibo.api.motan.transport.MessageHandler) Invocation(org.jmock.api.Invocation) CustomAction(org.jmock.lib.action.CustomAction) Channel(com.weibo.api.motan.transport.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Test(org.junit.Test)

Aggregations

ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)661 Channel (io.netty.channel.Channel)274 ByteBuf (io.netty.buffer.ByteBuf)234 ChannelFuture (io.netty.channel.ChannelFuture)210 Test (org.junit.Test)208 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)201 Bootstrap (io.netty.bootstrap.Bootstrap)177 InetSocketAddress (java.net.InetSocketAddress)160 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)156 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)154 Test (org.junit.jupiter.api.Test)153 ChannelPipeline (io.netty.channel.ChannelPipeline)151 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)141 AtomicReference (java.util.concurrent.atomic.AtomicReference)140 IOException (java.io.IOException)137 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)120 ClosedChannelException (java.nio.channels.ClosedChannelException)119 CountDownLatch (java.util.concurrent.CountDownLatch)115 ArrayList (java.util.ArrayList)113 List (java.util.List)111