io.netty.handler.proxy.ProxyHandler Java Examples

The following examples show how to use io.netty.handler.proxy.ProxyHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProxyIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private Connection establishConnecton(TestAmqpPeer testPeer, Supplier<ProxyHandler> proxyHandlerSupplier, boolean ssl, String optionsString) throws JMSException {
    testPeer.expectSaslPlain("guest", "guest");
    testPeer.expectOpen();

    // Each connection creates a session for managing temporary destinations etc
    testPeer.expectBegin();

    String remoteURI = buildURI(testPeer, ssl, optionsString);
    LOG.debug("connect to {}", remoteURI);
    JmsConnectionFactory factory = new JmsConnectionFactory(remoteURI);
    factory.setExtension(JmsConnectionExtensions.PROXY_HANDLER_SUPPLIER.toString(), (connection1, remote) -> {
        return proxyHandlerSupplier;
    });
    Connection connection = factory.createConnection("guest", "guest");

    // Set a clientId to provoke the actual AMQP connection process to occur.
    connection.setClientID("clientName");

    assertNull(testPeer.getThrowable());

    return connection;
}
 
Example #2
Source File: ProxyIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testCreateConnectionViaSocksProxy() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();
         TestProxy testProxy = new TestProxy(ProxyType.SOCKS5)) {
        testProxy.start();

        AtomicInteger supplierUsageCount = new AtomicInteger();
        Supplier<ProxyHandler> proxyHandlerSupplier = () -> {
            supplierUsageCount.incrementAndGet();
            return new Socks5ProxyHandler(new InetSocketAddress("localhost", testProxy.getPort()));
        };

        Connection connection = establishConnecton(testPeer, proxyHandlerSupplier, false, null);

        testPeer.expectClose();
        connection.close();

        assertEquals(1, testProxy.getSuccessCount());
        assertEquals("Unexpected handler supplier usage count", 1, supplierUsageCount.get());
    }
}
 
Example #3
Source File: ProxyHandlerSupplier.java    From cute-proxy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public ProxyHandler newProxyHandler() {
    switch (proxySetting.type()) {
        case ProxySetting.TYPE_HTTP:
            if (proxySetting.user().isEmpty()) {
                return new HttpProxyHandler(address);
            } else {
                return new HttpProxyHandler(address, proxySetting.user(), proxySetting.password());
            }

        case ProxySetting.TYPE_SOCKS5:
            if (proxySetting.user().isEmpty()) {
                return new Socks5ProxyHandler(address);
            } else {
                return new Socks5ProxyHandler(address, proxySetting.user(), proxySetting.password());
            }
        case ProxySetting.TYPE_SOCKS4:
            if (proxySetting.user().isEmpty()) {
                return new Socks4ProxyHandler(address);
            } else {
                return new Socks4ProxyHandler(address, proxySetting.user());
            }
        default:
            throw new RuntimeException("unknown proxy type: " + proxySetting.type());
    }
}
 
Example #4
Source File: TunnelProxyHandler.java    From cute-proxy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected Bootstrap initBootStrap(Promise<Channel> promise, EventLoopGroup eventLoopGroup) {
    return new Bootstrap()
            .group(eventLoopGroup)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, NettySettings.CONNECT_TIMEOUT)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ProxyHandler proxyHandler = proxyHandlerSupplier.get();
                    if (proxyHandler != null) {
                        ch.pipeline().addLast(proxyHandler);
                    }
                    ch.pipeline().addLast(new ChannelActiveAwareHandler(promise));
                }
            });
}
 
Example #5
Source File: ProxyIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testCreateSecureConnectionViaSocksProxy() throws Exception {
    TransportOptions sslOptions = new TransportOptions();
    sslOptions.setKeyStoreLocation(BROKER_JKS_KEYSTORE);
    sslOptions.setKeyStorePassword(PASSWORD);
    sslOptions.setVerifyHost(false);

    SSLContext context = TransportSupport.createJdkSslContext(sslOptions);
    try (TestAmqpPeer testPeer = new TestAmqpPeer(context, false);
         TestProxy testProxy = new TestProxy(ProxyType.SOCKS5)) {
        testProxy.start();

        String connOptions = "?transport.trustStoreLocation=" + CLIENT_JKS_TRUSTSTORE + "&" + "transport.trustStorePassword=" + PASSWORD
                + "&" + "transport.useOpenSSL=" + false;
        AtomicInteger supplierUsageCount = new AtomicInteger();
        Supplier<ProxyHandler> proxyHandlerSupplier = () -> {
            supplierUsageCount.incrementAndGet();
            return new Socks5ProxyHandler(new InetSocketAddress("localhost", testProxy.getPort()));
        };

        Connection connection = establishConnecton(testPeer, proxyHandlerSupplier, true, connOptions);

        Socket socket = testPeer.getClientSocket();
        assertTrue(socket instanceof SSLSocket);

        testPeer.expectClose();
        connection.close();

        assertEquals(1, testProxy.getSuccessCount());
        assertEquals("Unexpected handler supplier usage count", 1, supplierUsageCount.get());
    }
}
 
Example #6
Source File: NettyTcpTransport.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
private void configureChannel(final Channel channel) throws Exception {
    if (options.getProxyHandlerSupplier() != null) {
        Supplier<ProxyHandler> proxyHandlerSupplier = options.getProxyHandlerSupplier();

        ProxyHandler proxyHandler = proxyHandlerSupplier.get();
        Objects.requireNonNull(proxyHandler, "No proxy handler was returned by the supplier");

        channel.pipeline().addFirst(proxyHandler);
    }
    if (isSecure()) {
        final SslHandler sslHandler;
        try {
            sslHandler = TransportSupport.createSslHandler(channel.alloc(), getRemoteLocation(), getTransportOptions());
        } catch (Exception ex) {
            throw IOExceptionSupport.create(ex);
        }

        channel.pipeline().addLast("ssl", sslHandler);
    }

    if (getTransportOptions().isTraceBytes()) {
        channel.pipeline().addLast("logger", new LoggingHandler(getClass()));
    }

    addAdditionalHandlers(channel.pipeline());

    channel.pipeline().addLast(createChannelHandler());
}
 
Example #7
Source File: ProxyProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
public void addProxyHandler(Channel channel) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.addFirst(NettyPipeline.ProxyHandler, newProxyHandler());

	if (pipeline.get(NettyPipeline.LoggingHandler) != null) {
		pipeline.addBefore(NettyPipeline.ProxyHandler,
				NettyPipeline.ProxyLoggingHandler,
				new LoggingHandler("reactor.netty.proxy"));
	}
}
 
Example #8
Source File: HttpConnectProxyMatcher.java    From cute-proxy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public HttpConnectProxyMatcher(MessageListener messageListener,
                               ServerSSLContextManager sslContextManager,
                               Supplier<ProxyHandler> proxyHandlerSupplier) {
    this.messageListener = messageListener;
    this.sslContextManager = sslContextManager;
    this.proxyHandlerSupplier = proxyHandlerSupplier;
}
 
Example #9
Source File: ProxyProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
/**
 * Return a new eventual {@link ProxyHandler}
 *
 * @return a new eventual {@link ProxyHandler}
 */
public final ProxyHandler newProxyHandler() {
	InetSocketAddress proxyAddr = this.address.get();
	String username = this.username;
	String password = Objects.nonNull(username) && Objects.nonNull(this.password) ?
			this.password.apply(username) : null;

	final boolean b = Objects.nonNull(username) && Objects.nonNull(password);
	final ProxyHandler proxyHandler;
	switch (this.type) {
		case HTTP:
			proxyHandler = b ?
					new HttpProxyHandler(proxyAddr, username, password, this.httpHeaders.get()) :
					new HttpProxyHandler(proxyAddr, this.httpHeaders.get());
			break;
		case SOCKS4:
			proxyHandler = Objects.nonNull(username) ? new Socks4ProxyHandler(proxyAddr, username) :
					new Socks4ProxyHandler(proxyAddr);
			break;
		case SOCKS5:
			proxyHandler = b ?
					new Socks5ProxyHandler(proxyAddr, username, password) :
					new Socks5ProxyHandler(proxyAddr);
			break;
		default:
			throw new IllegalArgumentException("Proxy type unsupported : " + this.type);
	}
	proxyHandler.setConnectTimeoutMillis(connectTimeoutMillis);
	return proxyHandler;
}
 
Example #10
Source File: ProxyHandlerSupplier.java    From cute-proxy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public ProxyHandler get() {
    if (!proxySetting.use()) {
        return null;
    }
    ProxyHandler proxyHandler = newProxyHandler();
    proxyHandler.setConnectTimeoutMillis(NettySettings.CONNECT_TIMEOUT);
    return proxyHandler;
}
 
Example #11
Source File: Socks4ProxyHandler.java    From cute-proxy with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Socks4ProxyHandler(MessageListener messageListener, ServerSSLContextManager sslContextManager,
                          Supplier<ProxyHandler> proxyHandlerSupplier) {
    super(messageListener, sslContextManager, proxyHandlerSupplier);
}
 
Example #12
Source File: HttpProxyHandler.java    From cute-proxy with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public HttpProxyHandler(MessageListener messageListener, Supplier<ProxyHandler> proxyHandlerSupplier) {
    this.messageListener = messageListener;
    this.proxyHandlerSupplier = proxyHandlerSupplier;
}
 
Example #13
Source File: Socks5ProxyHandler.java    From cute-proxy with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Socks5ProxyHandler(MessageListener messageListener, ServerSSLContextManager sslContextManager,
                          Supplier<ProxyHandler> proxyHandlerSupplier) {
    super(messageListener, sslContextManager, proxyHandlerSupplier);
}
 
Example #14
Source File: ProtocolNegotiators.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
public BufferUntilProxyTunnelledHandler(
    ProxyHandler proxyHandler, ProtocolNegotiator.Handler handler) {
  super(proxyHandler, handler);
  this.originalHandler = handler;
}
 
Example #15
Source File: TunnelProxyHandler.java    From cute-proxy with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public TunnelProxyHandler(MessageListener messageListener, ServerSSLContextManager sslContextManager,
                          Supplier<ProxyHandler> proxyHandlerSupplier) {
    this.messageListener = messageListener;
    this.sslContextManager = sslContextManager;
    this.proxyHandlerSupplier = proxyHandlerSupplier;
}
 
Example #16
Source File: HttpConnectProxyInitializer.java    From cute-proxy with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public HttpConnectProxyInitializer(MessageListener messageListener, ServerSSLContextManager sslContextManager,
                                   Supplier<ProxyHandler> proxyHandlerSupplier) {
    super(messageListener, sslContextManager, proxyHandlerSupplier);
}
 
Example #17
Source File: HttpProxyMatcher.java    From cute-proxy with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public HttpProxyMatcher(MessageListener messageListener, Supplier<ProxyHandler> proxyHandlerSupplier) {
    this.messageListener = messageListener;
    this.proxyHandlerSupplier = proxyHandlerSupplier;
}
 
Example #18
Source File: Socks4ProxyMatcher.java    From cute-proxy with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Socks4ProxyMatcher(MessageListener messageListener, ServerSSLContextManager sslContextManager,
                          Supplier<ProxyHandler> proxyHandlerSupplier) {
    this.messageListener = messageListener;
    this.sslContextManager = sslContextManager;
    this.proxyHandlerSupplier = proxyHandlerSupplier;
}
 
Example #19
Source File: Socks5ProxyMatcher.java    From cute-proxy with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Socks5ProxyMatcher(MessageListener messageListener, ServerSSLContextManager sslContextManager,
                          Supplier<ProxyHandler> proxyHandlerSupplier) {
    this.messageListener = messageListener;
    this.sslContextManager = sslContextManager;
    this.proxyHandlerSupplier = proxyHandlerSupplier;
}
 
Example #20
Source File: TunnelProxyInitializer.java    From proxyee with MIT License 4 votes vote down vote up
public TunnelProxyInitializer(Channel clientChannel,
                              ProxyHandler proxyHandler) {
    this.clientChannel = clientChannel;
    this.proxyHandler = proxyHandler;
}
 
Example #21
Source File: HttpProxyInitializer.java    From proxyee with MIT License 4 votes vote down vote up
public HttpProxyInitializer(Channel clientChannel, RequestProto requestProto,
                            ProxyHandler proxyHandler) {
    this.clientChannel = clientChannel;
    this.requestProto = requestProto;
    this.proxyHandler = proxyHandler;
}
 
Example #22
Source File: HttpProxyServerHandle.java    From proxyee with MIT License 4 votes vote down vote up
private void handleProxyData(Channel channel, Object msg, boolean isHttp) throws Exception {
    if (cf == null) {
        // connection异常 还有HttpContent进来,不转发
        if (isHttp && !(msg instanceof HttpRequest)) {
            return;
        }
        ProxyHandler proxyHandler = ProxyHandleFactory.build(proxyConfig);
        /*
         * 添加SSL client hello的Server Name Indication extension(SNI扩展) 有些服务器对于client
         * hello不带SNI扩展时会直接返回Received fatal alert: handshake_failure(握手错误)
         * 例如:https://cdn.mdn.mozilla.net/static/img/favicon32.7f3da72dcea1.png
         */
        RequestProto requestProto;
        if (!isHttp) {
            requestProto = new RequestProto(host, port, isSsl);
            if (this.tunnelIntercept != null) {
                this.tunnelIntercept.handle(requestProto);
            }
        } else {
            requestProto = interceptPipeline.getRequestProto();
            HttpRequest httpRequest = (HttpRequest) msg;
            // 检查requestProto是否有修改
            RequestProto newRP = ProtoUtil.getRequestProto(httpRequest);
            if (!newRP.equals(requestProto)) {
                // 更新Host请求头
                if ((requestProto.getSsl() && requestProto.getPort() == 443)
                        || (!requestProto.getSsl() && requestProto.getPort() == 80)) {
                    httpRequest.headers().set(HttpHeaderNames.HOST, requestProto.getHost());
                } else {
                    httpRequest.headers().set(HttpHeaderNames.HOST, requestProto.getHost() + ":" + requestProto.getPort());
                }
            }
        }
        ChannelInitializer channelInitializer = isHttp ? new HttpProxyInitializer(channel, requestProto, proxyHandler)
                : new TunnelProxyInitializer(channel, proxyHandler);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(serverConfig.getProxyLoopGroup()) // 注册线程池
                .channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
                .handler(channelInitializer);
        if (proxyConfig != null) {
            // 代理服务器解析DNS和连接
            bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
        }
        requestList = new LinkedList();
        cf = bootstrap.connect(requestProto.getHost(), requestProto.getPort());
        cf.addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                future.channel().writeAndFlush(msg);
                synchronized (requestList) {
                    requestList.forEach(obj -> future.channel().writeAndFlush(obj));
                    requestList.clear();
                    isConnect = true;
                }
            } else {
                requestList.forEach(obj -> ReferenceCountUtil.release(obj));
                requestList.clear();
                getExceptionHandle().beforeCatch(channel, future.cause());
                future.channel().close();
                channel.close();
            }
        });
    } else {
        synchronized (requestList) {
            if (isConnect) {
                cf.channel().writeAndFlush(msg);
            } else {
                requestList.add(msg);
            }
        }
    }
}