Search in sources :

Example 1 with HttpProxyHandler

use of io.netty.handler.proxy.HttpProxyHandler in project vert.x by eclipse.

the class ProxyChannelProvider method connect.

@Override
public void connect(VertxInternal vertx, Bootstrap bootstrap, ProxyOptions options, String host, int port, Handler<Channel> channelInitializer, Handler<AsyncResult<Channel>> channelHandler) {
    final String proxyHost = options.getHost();
    final int proxyPort = options.getPort();
    final String proxyUsername = options.getUsername();
    final String proxyPassword = options.getPassword();
    final ProxyType proxyType = options.getType();
    vertx.resolveAddress(proxyHost, dnsRes -> {
        if (dnsRes.succeeded()) {
            InetAddress address = dnsRes.result();
            InetSocketAddress proxyAddr = new InetSocketAddress(address, proxyPort);
            ProxyHandler proxy;
            switch(proxyType) {
                default:
                case HTTP:
                    proxy = proxyUsername != null && proxyPassword != null ? new HttpProxyHandler(proxyAddr, proxyUsername, proxyPassword) : new HttpProxyHandler(proxyAddr);
                    break;
                case SOCKS5:
                    proxy = proxyUsername != null && proxyPassword != null ? new Socks5ProxyHandler(proxyAddr, proxyUsername, proxyPassword) : new Socks5ProxyHandler(proxyAddr);
                    break;
                case SOCKS4:
                    proxy = proxyUsername != null ? new Socks4ProxyHandler(proxyAddr, proxyUsername) : new Socks4ProxyHandler(proxyAddr);
                    break;
            }
            bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
            InetSocketAddress targetAddress = InetSocketAddress.createUnresolved(host, port);
            bootstrap.handler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addFirst("proxy", proxy);
                    pipeline.addLast(new ChannelInboundHandlerAdapter() {

                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            if (evt instanceof ProxyConnectionEvent) {
                                pipeline.remove(proxy);
                                pipeline.remove(this);
                                channelInitializer.handle(ch);
                                channelHandler.handle(Future.succeededFuture(ch));
                            }
                            ctx.fireUserEventTriggered(evt);
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            channelHandler.handle(Future.failedFuture(cause));
                        }
                    });
                }
            });
            ChannelFuture future = bootstrap.connect(targetAddress);
            future.addListener(res -> {
                if (!res.isSuccess()) {
                    channelHandler.handle(Future.failedFuture(res.cause()));
                }
            });
        } else {
            channelHandler.handle(Future.failedFuture(dnsRes.cause()));
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ProxyHandler(io.netty.handler.proxy.ProxyHandler) HttpProxyHandler(io.netty.handler.proxy.HttpProxyHandler) Socks4ProxyHandler(io.netty.handler.proxy.Socks4ProxyHandler) Socks5ProxyHandler(io.netty.handler.proxy.Socks5ProxyHandler) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) ProxyConnectionEvent(io.netty.handler.proxy.ProxyConnectionEvent) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Socks4ProxyHandler(io.netty.handler.proxy.Socks4ProxyHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) Socks5ProxyHandler(io.netty.handler.proxy.Socks5ProxyHandler) HttpProxyHandler(io.netty.handler.proxy.HttpProxyHandler) ProxyType(io.vertx.core.net.ProxyType) InetAddress(java.net.InetAddress) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 2 with HttpProxyHandler

use of io.netty.handler.proxy.HttpProxyHandler in project jersey by jersey.

the class NettyConnector method apply.

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {
    final CompletableFuture<Object> settableFuture = new CompletableFuture<>();
    final URI requestUri = jerseyRequest.getUri();
    String host = requestUri.getHost();
    int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80;
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                // Enable HTTPS if necessary.
                if ("https".equals(requestUri.getScheme())) {
                    // making client authentication optional for now; it could be extracted to configurable property
                    JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true, ClientAuth.NONE);
                    p.addLast(jdkSslContext.newHandler(ch.alloc()));
                }
                // http proxy
                Configuration config = jerseyRequest.getConfiguration();
                final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
                if (proxyUri != null) {
                    final URI u = getProxyUri(proxyUri);
                    final String userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME, String.class);
                    final String password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class);
                    p.addLast(new HttpProxyHandler(new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()), userName, password));
                }
                p.addLast(new HttpClientCodec());
                p.addLast(new ChunkedWriteHandler());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback, settableFuture));
            }
        });
        // connect timeout
        Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(), ClientProperties.CONNECT_TIMEOUT, 0);
        if (connectTimeout > 0) {
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
        }
        // Make the connection attempt.
        final Channel ch = b.connect(host, port).sync().channel();
        // guard against prematurely closed channel
        final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
                if (!settableFuture.isDone()) {
                    settableFuture.completeExceptionally(new IOException("Channel closed."));
                }
            }
        };
        ch.closeFuture().addListener(closeListener);
        HttpRequest nettyRequest;
        if (jerseyRequest.hasEntity()) {
            nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        } else {
            nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        }
        // headers
        for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
            nettyRequest.headers().add(e.getKey(), e.getValue());
        }
        // host header - http 1.1
        nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());
        if (jerseyRequest.hasEntity()) {
            if (jerseyRequest.getLengthLong() == -1) {
                HttpUtil.setTransferEncodingChunked(nettyRequest, true);
            } else {
                nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
            }
        }
        if (jerseyRequest.hasEntity()) {
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
            final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
            jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {

                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return jerseyChunkedInput;
                }
            });
            if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
                ch.write(new HttpChunkedInput(jerseyChunkedInput));
            } else {
                ch.write(jerseyChunkedInput);
            }
            executorService.execute(new Runnable() {

                @Override
                public void run() {
                    // close listener is not needed any more.
                    ch.closeFuture().removeListener(closeListener);
                    try {
                        jerseyRequest.writeEntity();
                    } catch (IOException e) {
                        jerseyCallback.failure(e);
                        settableFuture.completeExceptionally(e);
                    }
                }
            });
            ch.flush();
        } else {
            // close listener is not needed any more.
            ch.closeFuture().removeListener(closeListener);
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
        }
    } catch (InterruptedException e) {
        settableFuture.completeExceptionally(e);
        return settableFuture;
    }
    return settableFuture;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Configuration(javax.ws.rs.core.Configuration) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) CompletableFuture(java.util.concurrent.CompletableFuture) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap) List(java.util.List) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) JerseyChunkedInput(org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) JdkSslContext(io.netty.handler.ssl.JdkSslContext) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProcessingException(javax.ws.rs.ProcessingException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) HttpProxyHandler(io.netty.handler.proxy.HttpProxyHandler) Map(java.util.Map)

Example 3 with HttpProxyHandler

use of io.netty.handler.proxy.HttpProxyHandler in project grpc-java by grpc.

the class ProtocolNegotiators method httpProxy.

/**
   * Returns a {@link ProtocolNegotiator} that does HTTP CONNECT proxy negotiation.
   */
public static ProtocolNegotiator httpProxy(final SocketAddress proxyAddress, @Nullable final String proxyUsername, @Nullable final String proxyPassword, final ProtocolNegotiator negotiator) {
    Preconditions.checkNotNull(proxyAddress, "proxyAddress");
    Preconditions.checkNotNull(negotiator, "negotiator");
    class ProxyNegotiator implements ProtocolNegotiator {

        @Override
        public Handler newHandler(GrpcHttp2ConnectionHandler http2Handler) {
            HttpProxyHandler proxyHandler;
            if (proxyUsername == null || proxyPassword == null) {
                proxyHandler = new HttpProxyHandler(proxyAddress);
            } else {
                proxyHandler = new HttpProxyHandler(proxyAddress, proxyUsername, proxyPassword);
            }
            return new BufferUntilProxyTunnelledHandler(proxyHandler, negotiator.newHandler(http2Handler));
        }
    }
    return new ProxyNegotiator();
}
Also used : HttpProxyHandler(io.netty.handler.proxy.HttpProxyHandler)

Aggregations

HttpProxyHandler (io.netty.handler.proxy.HttpProxyHandler)3 Channel (io.netty.channel.Channel)2 ChannelPipeline (io.netty.channel.ChannelPipeline)2 InetSocketAddress (java.net.InetSocketAddress)2 Bootstrap (io.netty.bootstrap.Bootstrap)1 ChannelFuture (io.netty.channel.ChannelFuture)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)1 SocketChannel (io.netty.channel.socket.SocketChannel)1 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)1 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)1 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)1 HttpChunkedInput (io.netty.handler.codec.http.HttpChunkedInput)1 HttpClientCodec (io.netty.handler.codec.http.HttpClientCodec)1 HttpContentDecompressor (io.netty.handler.codec.http.HttpContentDecompressor)1 HttpRequest (io.netty.handler.codec.http.HttpRequest)1 ProxyConnectionEvent (io.netty.handler.proxy.ProxyConnectionEvent)1 ProxyHandler (io.netty.handler.proxy.ProxyHandler)1 Socks4ProxyHandler (io.netty.handler.proxy.Socks4ProxyHandler)1 Socks5ProxyHandler (io.netty.handler.proxy.Socks5ProxyHandler)1