Example usage for io.netty.handler.codec.socks SocksCmdStatus FAILURE

List of usage examples for io.netty.handler.codec.socks SocksCmdStatus FAILURE

Introduction

In this page you can find the example usage for io.netty.handler.codec.socks SocksCmdStatus FAILURE.

Prototype

SocksCmdStatus FAILURE

To view the source code for io.netty.handler.codec.socks SocksCmdStatus FAILURE.

Click Source Link

Usage

From source file:cc.agentx.client.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    boolean proxyMode = isAgentXNeeded(request.host());
    log.info("\tClient -> Proxy           \tTarget {}:{} [{}]", request.host(), request.port(),
            proxyMode ? "AGENTX" : "DIRECT");
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new FutureListener<Channel>() {
        @Override/*from w ww .  ja  v  a  2  s.  c o  m*/
        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(channelFuture -> {
                            ByteBuf byteBuf = Unpooled.buffer();
                            request.encodeAsByteBuf(byteBuf);
                            if (byteBuf.hasArray()) {
                                byte[] xRequestBytes = new byte[byteBuf.readableBytes()];
                                byteBuf.getBytes(0, xRequestBytes);

                                if (proxyMode) {
                                    // handshaking to remote proxy
                                    xRequestBytes = requestWrapper.wrap(xRequestBytes);
                                    outboundChannel.writeAndFlush(Unpooled.wrappedBuffer(
                                            exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes)));
                                }

                                // task handover
                                ReferenceCountUtil.retain(request); // auto-release? a trap?
                                ctx.pipeline().remove(XConnectHandler.this);
                                outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(),
                                        proxyMode ? wrapper : rawWrapper, false));
                                ctx.pipeline().addLast(new XRelayHandler(outboundChannel,
                                        proxyMode ? wrapper : rawWrapper, true));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));

                if (ctx.channel().isActive()) {
                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
        }
    });

    String host = request.host();
    int port = request.port();
    if (host.equals(config.getConsoleDomain())) {
        host = "localhost";
        port = config.getConsolePort();
    } else if (proxyMode) {
        host = config.getServerHost();
        port = config.getServerPort();
    }

    // ping target
    bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.channel().writeAndFlush(
                                new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                        if (ctx.channel().isActive()) {
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        }
                    }
                }
            });
}

From source file:cn.david.socks.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override//from w  w w .j  a va  2 s  .  co  m
        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(SocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                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.host(), request.port()).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 SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

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

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    final Channel inboundChannel = ctx.channel();
    final Promise<Channel> outboundPromise = newOutboundPromise(ctx, request);
    final int maxProxies = AppProps.PROPS.getInteger("upstream.socks5.count", 1);
    final AtomicBoolean isFinalSuccess = new AtomicBoolean(false);
    final AtomicBoolean isRetryOccured = new AtomicBoolean(false);
    for (int i = 1; i <= maxProxies; i++) {
        final boolean isFirstOne = (i == 1);
        final boolean isFinalOne = (i == maxProxies);
        if (!isFirstOne) {
            isRetryOccured.set(true);//from w w  w .j a v a  2s.co  m
        }
        try {
            final ProxyHandler upstreamProxyHandler = newUpstreamProxyHandler(i);
            final Bootstrap b = newConnectionBootstrap(inboundChannel, outboundPromise, upstreamProxyHandler);
            logger.info(String.format("Connecting backend %s:%s via %s", request.host(), request.port(),
                    upstreamProxyHandler != null ? upstreamProxyHandler.proxyAddress() : "direct"));
            ChannelFuture connFuture = b.connect(request.host(), request.port());
            connFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        // Connection established use handler provided results
                        if (upstreamProxyHandler == null) {
                            logger.info("Backend connected directly");
                        } else {
                            logger.info("Backend connected via: " + upstreamProxyHandler.proxyAddress());
                        }
                    } else {
                        // Close the connection if the connection attempt has failed.
                        if (isFinalOne) {
                            logger.error("Backend connection failed: " + future.cause(), future.cause());
                            ctx.channel().writeAndFlush(
                                    new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                            NettyChannelUtils.closeOnFlush(ctx.channel());
                        } else {
                            logger.warn("Backend connection failed: {}", future.cause().toString());
                        }
                    }
                }
            });
            connFuture.await(getConnectTimeoutMillis(), TimeUnit.MILLISECONDS);
            if (connFuture.isSuccess()) {
                isFinalSuccess.set(true);
                break;
            }
        } catch (Exception e) {
            logger.error("Connecting exception {} caught:", e);
        }
    }
    if (isFinalSuccess.get() && isRetryOccured.get()) {
        logger.warn("Protected from Error-Neko: {} times", nekoKilled.incrementAndGet());
    }
}

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

License:Apache License

/**
 * Create new promised callback on outbound channel operation complete.
 * //from   w  w w. j a  va 2 s  . c  om
 * @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.gxkj.demo.netty.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*from ww  w . j av  a 2 s  . c  o  m*/
        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) throws Exception {
                                ctx.pipeline().remove(getName());
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.channel().pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                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 DirectClientInitializer(promise));

    b.connect(request.host(), request.port()).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 SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:com.xx_dev.apn.socks.remote.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*w  ww .  j a  v  a 2s.  com*/
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                restLogger.info(request.host() + ":" + request.port() + "," + "T");
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .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 {
                restLogger.info(request.host() + ":" + request.port() + "," + "F");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                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.host(), request.port()).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.
                restLogger.info(request.host() + ":" + request.port() + "," + "F");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:org.kobeyoung81.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*from   ww  w . j a v a2  s .c o  m*/
        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(SocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
                //System.out.println(request.toString());
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                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));
    //System.out.println(request.host() +":"+ request.port());
    //SocksCmdRequest re = new SocksCmdRequest(request.cmdType(), request.addressType(), "192.168.87.103", 8080);
    b.connect(request.host(), request.port()).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 SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:org.wyb.sows.client.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    if (request.host().equals("127.0.0.1") || request.host().equals("localhost")) {
        System.err.println("Not able to establish bridge. Inform proxy client.");
        ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
        SocksServerUtils.closeOnFlush(ctx.channel());
    }//from   w  ww.ja v a  2s.  c om

    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()) {
                if (SocksServer.isDebug) {
                    System.out.println("Bridge is established. Inform proxy client.");
                }
                SocksCmdResponse resp = new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType());
                resp.setProtocolVersion(request.protocolVersion());
                ctx.channel().writeAndFlush(resp).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) {
                        ChannelPipeline pipeline = ctx.pipeline();
                        pipeline.remove(SocksServerConnectHandler.this);
                        // ctx.pipeline().addLast(new StringByteCodec());
                        pipeline.addLast(new WebSocketRelayHandler(outboundChannel));
                    }
                });
            } else {
                System.err.println("Not able to establish bridge. Inform proxy client.");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
    final Channel inboundChannel = ctx.channel();

    // Add authentication headers
    HttpHeaders authHeader = new DefaultHttpHeaders();
    authHeader.add(SowsAuthHelper.HEADER_SOWS_USER, this.userName);
    byte[] nonce = SowsAuthHelper.randomBytes(16);
    String seed = SowsAuthHelper.base64(nonce);
    authHeader.add(SowsAuthHelper.HEADER_SOWS_SEED, seed);
    byte[] sha1 = SowsAuthHelper.sha1((this.passcode + seed).getBytes(CharsetUtil.US_ASCII));
    String token = SowsAuthHelper.base64(sha1);
    authHeader.add(SowsAuthHelper.HEADER_SOWS_TOKEN, token);

    // initiating websocket client handler
    final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
            .newHandshaker(bridgeServiceUri, WebSocketVersion.V13, null, false, authHeader), promise,
            request.host(), request.port(), inboundChannel);
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
                }
            });
    if (SocksServer.isDebug) {
        System.out.println("Try to connect to bridge service.");
    }
    b.connect(bridgeServiceUri.getHost(), bridgeServiceUri.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
                if (SocksServer.isDebug) {
                    System.out.printf("Brige service connection is established. host=%s,port=%d \r\n",
                            bridgeServiceUri.getHost(), bridgeServiceUri.getPort());
                }
            } else {
                // Close the connection if the connection attempt has
                // failed.
                System.err.printf("Not able to connect bridge service! host=%s,port=%d \r\n",
                        bridgeServiceUri.getHost(), bridgeServiceUri.getPort());
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

}

From source file:pers.zlf.sslocal.handler.shadowsocks.ShadowsocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    final Option option = ShadowsocksClient.getShadowsocksOption(ctx.channel());
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*from  ww w  . j  a va2s  .c  om*/
        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(ShadowsocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(
                                        new ShadowsocksMessageCodec(CryptoFactory
                                                .createCrypto(option.getMethod(), option.getPassword())),
                                        new RelayHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayHandler(outboundChannel));

                                outboundChannel.writeAndFlush(request);
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                ChannelUtils.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(option.getRemoteHost(), option.getRemotePort()).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.
                if (logger.isErrorEnabled()) {
                    logger.error("Failed to connect shadowsocks server", future.cause());
                }

                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                ChannelUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}