Example usage for io.netty.channel ChannelHandlerContext pipeline

List of usage examples for io.netty.channel ChannelHandlerContext pipeline

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext pipeline.

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline

Usage

From source file:com.github.mrstampy.gameboot.otp.netty.client.ClientHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    SslHandler handler = ctx.pipeline().get(SslHandler.class);

    if (handler == null)
        return;/*from  ww  w .ja  v  a 2 s .  c  om*/

    handler.handshakeFuture().addListener(f -> validate(f, ctx));
}

From source file:com.github.mrstampy.gameboot.otp.netty.client.ClientHandler.java

License:Open Source License

private void unencrypted(ChannelHandlerContext ctx, byte[] msg) throws Exception {
    Response r = getResponse(msg);
    lastResponse = r;//from   w  ww . j av a  2 s . c  o  m

    boolean c = ctx.pipeline().get(SslHandler.class) != null;

    log.info("Unencrypted: on {} channel\n{}", (c ? "secured" : "unsecured"), mapper.writeValueAsString(r));

    if (!ok(r.getResponseCode()))
        return;

    if (ResponseCode.INFO == r.getResponseCode()) {
        Object[] payload = r.getPayload();
        if (payload == null || payload.length == 0 || !(payload[0] instanceof Map<?, ?>)) {
            throw new IllegalStateException("Expecting map of systemId:[value]");
        }

        systemId = (Long) ((Map<?, ?>) payload[0]).get("systemId");

        log.info("Setting system id {}", systemId);
        clearChannel = ctx.channel();
        return;
    }

    JsonNode node = mapper.readTree(msg);
    JsonNode response = node.get("payload");

    boolean hasKey = response != null && response.isArray() && response.size() == 1;

    if (hasKey) {
        log.info("Setting key");
        otpKey = response.get(0).binaryValue();
        return;
    }

    switch (r.getType()) {
    case OtpKeyRequest.TYPE:
        log.info("Deleting key");
        otpKey = null;
        break;
    default:
        break;
    }
}

From source file:com.github.mrstampy.gameboot.otp.netty.OtpEncryptedNettyHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    SslHandler handler = ctx.pipeline().get(SslHandler.class);

    if (handler == null) {
        log.error("Unencrypted channels cannot process OTP New Key requests.  Disconnecting {}", ctx.channel());
        ctx.close();/*from  w  ww.  j a v a  2s.  c  om*/
        return;
    }

    handler.handshakeFuture().addListener(f -> validate(f, ctx));
}

From source file:com.github.netfreer.shadowducks.client.handler.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override/*  w w w. j av  a2 s .c om*/
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS,
                                    request.dstAddrType(), request.dstAddr(), request.dstPort()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));
        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Attribute<Long> beginTimeAttr = ctx.channel().attr(AttrKeys.CHANNEL_BEGIN_TIME);
                final long parseTime = beginTimeAttr.get();
                long usedTime = System.currentTimeMillis() - parseTime;
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                    logger.info("connect {}:{} success, use time {} millis.", request.dstAddr(),
                            request.dstPort(), usedTime);
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                    logger.info("connect {}:{} failure, use time {} millis.", request.dstAddr(),
                            request.dstPort(), usedTime);
                }
                beginTimeAttr.set(null);
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.github.netfreer.shadowducks.client.handler.SocksServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, SocksMessage socksRequest) throws Exception {
    switch (socksRequest.version()) {
    case SOCKS4a:
        Socks4CommandRequest socksV4CmdRequest = (Socks4CommandRequest) socksRequest;
        if (socksV4CmdRequest.type() == Socks4CommandType.CONNECT) {
            ctx.pipeline().addLast(new SocksServerConnectHandler());
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(socksRequest);
        } else {/*w  w w  . ja v  a 2s.c  o  m*/
            ctx.close();
        }
        break;
    case SOCKS5:
        if (socksRequest instanceof Socks5InitialRequest) {
            // auth support example
            //ctx.pipeline().addFirst(new Socks5PasswordAuthRequestDecoder());
            //ctx.write(new DefaultSocks5AuthMethodResponse(Socks5AuthMethod.PASSWORD));
            ctx.pipeline().addFirst(new Socks5CommandRequestDecoder());
            ctx.write(new DefaultSocks5InitialResponse(Socks5AuthMethod.NO_AUTH));
        } else if (socksRequest instanceof Socks5PasswordAuthRequest) {
            ctx.pipeline().addFirst(new Socks5CommandRequestDecoder());
            ctx.write(new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.SUCCESS));
        } else if (socksRequest instanceof Socks5CommandRequest) {
            Socks5CommandRequest socks5CmdRequest = (Socks5CommandRequest) socksRequest;
            if (socks5CmdRequest.type() == Socks5CommandType.CONNECT) {
                ctx.pipeline().addLast(new SocksServerConnectHandler());
                ctx.pipeline().remove(this);
                ctx.fireChannelRead(socksRequest);
            } else {
                //TODO UDP Process
                ctx.close();
            }
        } else {
            ctx.close();
        }
        break;
    case UNKNOWN:
        ctx.close();
        break;
    }
}

From source file:com.github.pgasync.impl.netty.NettyPgProtocolStream.java

License:Apache License

ChannelInboundHandlerAdapter newStartupHandler(StartupMessage startup) {
    return new ChannelInboundHandlerAdapter() {
        @Override//from  ww  w .j a  va  2 s . com
        public void channelActive(ChannelHandlerContext context) {
            NettyPgProtocolStream.this.ctx = context;

            if (useSsl) {
                write(SSLHandshake.INSTANCE);
                return;
            }
            write(startup);
            context.pipeline().remove(this);
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext context, Object evt) throws Exception {
            if (evt instanceof SslHandshakeCompletionEvent && ((SslHandshakeCompletionEvent) evt).isSuccess()) {
                write(startup);
                context.pipeline().remove(this);
            }
        }
    };
}

From source file:com.github.pgasync.impl.netty.NettyPgProtocolStream.java

License:Apache License

ChannelHandler newSslInitiator() {
    return new ByteToMessageDecoder() {
        @Override//from  ww  w .  j  av a 2  s.c  o  m
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            if (in.readableBytes() < 1) {
                return;
            }
            if ('S' != in.readByte()) {
                ctx.fireExceptionCaught(
                        new IllegalStateException("SSL required but not supported by backend server"));
                return;
            }
            ctx.pipeline().remove(this);
            ctx.pipeline().addFirst(SslContextBuilder.forClient()
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build().newHandler(ctx.alloc()));
        }
    };
}

From source file:com.github.sinsinpub.pero.backend.ConnectBackendHandler.java

License:Apache License

/**
 * Create new promised callback on outbound channel operation complete.
 * //from w ww  . j av  a  2  s  .co m
 * @param ctx
 * @param request
 * @return Promise
 */
protected Promise<Channel> newOutboundPromise(final ChannelHandlerContext ctx, final SocksCmdRequest request) {
    final Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) {
                                ctx.pipeline().remove(ConnectBackendHandler.this);
                                outboundChannel.pipeline().addLast(new RelayTrafficHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayTrafficHandler(outboundChannel));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                NettyChannelUtils.closeOnFlush(ctx.channel());
            }
        }
    });
    return promise;
}

From source file:com.github.sinsinpub.pero.frontend.SocksServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, SocksRequest socksRequest) throws Exception {
    switch (socksRequest.requestType()) {
    case INIT: {//from  w  w  w . j  av a 2  s  .  c om
        ctx.pipeline().addFirst(new SocksCmdRequestDecoder());
        ctx.write(new SocksInitResponse(SocksAuthScheme.NO_AUTH));
        break;
    }
    case AUTH:
        ctx.pipeline().addFirst(new SocksCmdRequestDecoder());
        ctx.write(new SocksAuthResponse(SocksAuthStatus.SUCCESS));
        break;
    case CMD:
        SocksCmdRequest req = (SocksCmdRequest) socksRequest;
        if (req.cmdType() == SocksCmdType.CONNECT) {
            ctx.pipeline().addLast(oioExecutorGroup, getConnectBackendHandler());
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(socksRequest);
        } else {
            ctx.close();
        }
        break;
    case UNKNOWN:
        ctx.close();
        break;
    }
}

From source file:com.github.sinsinpub.pero.manual.proxyhandler.HttpProxyServer.java

License:Apache License

private boolean authenticate(ChannelHandlerContext ctx, FullHttpRequest req) {
    assertThat(req.method(), Matchers.is(HttpMethod.CONNECT));

    if (testMode != TestMode.INTERMEDIARY) {
        ctx.pipeline().addBefore(ctx.name(), "lineDecoder", new LineBasedFrameDecoder(64, false, true));
    }//from w  w w .j a v  a 2  s .co  m

    ctx.pipeline().remove(HttpObjectAggregator.class);
    ctx.pipeline().remove(HttpRequestDecoder.class);

    boolean authzSuccess = false;
    if (username != null) {
        CharSequence authz = req.headers().get(HttpHeaderNames.PROXY_AUTHORIZATION);
        if (authz != null) {
            String[] authzParts = StringUtil.split(authz.toString(), ' ', 2);
            ByteBuf authzBuf64 = Unpooled.copiedBuffer(authzParts[1], CharsetUtil.US_ASCII);
            ByteBuf authzBuf = Base64.decode(authzBuf64);

            String expectedAuthz = username + ':' + password;
            authzSuccess = "Basic".equals(authzParts[0])
                    && expectedAuthz.equals(authzBuf.toString(CharsetUtil.US_ASCII));

            authzBuf64.release();
            authzBuf.release();
        }
    } else {
        authzSuccess = true;
    }

    return authzSuccess;
}