List of usage examples for io.netty.handler.proxy ProxyHandler proxyAddress
SocketAddress proxyAddress
To view the source code for io.netty.handler.proxy ProxyHandler proxyAddress.
Click Source Link
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 . ja va 2s . c om*/ } 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()); } }