List of usage examples for io.netty.handler.codec.http HttpMethod CONNECT
HttpMethod CONNECT
To view the source code for io.netty.handler.codec.http HttpMethod CONNECT.
Click Source Link
From source file:com.chenyang.proxy.http.HttpSchemaHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) msg; String originalHost = HostNamePortUtil.getHostName(httpRequest); int originalPort = HostNamePortUtil.getPort(httpRequest); HttpRemote apnProxyRemote = new HttpRemote(originalHost, originalPort); if (!HostAuthenticationUtil.isValidAddress(apnProxyRemote.getInetSocketAddress())) { HttpErrorUtil.writeAndFlush(uaChannelCtx.channel(), HttpResponseStatus.FORBIDDEN); return; }/*from ww w . jav a 2s . com*/ Channel uaChannel = uaChannelCtx.channel(); HttpConnectionAttribute apnProxyConnectionAttribute = HttpConnectionAttribute.build( uaChannel.remoteAddress().toString(), httpRequest.getMethod().name(), httpRequest.getUri(), httpRequest.getProtocolVersion().text(), httpRequest.headers().get(HttpHeaders.Names.USER_AGENT), apnProxyRemote); uaChannelCtx.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute); uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute); if (httpRequest.getMethod().equals(HttpMethod.CONNECT)) { if (uaChannelCtx.pipeline().get(HttpUserAgentForwardHandler.HANDLER_NAME) != null) { uaChannelCtx.pipeline().remove(HttpUserAgentForwardHandler.HANDLER_NAME); } if (uaChannelCtx.pipeline().get(HttpUserAgentTunnelHandler.HANDLER_NAME) == null) { uaChannelCtx.pipeline().addLast(HttpUserAgentTunnelHandler.HANDLER_NAME, new HttpUserAgentTunnelHandler()); } } else { if (uaChannelCtx.pipeline().get(HttpUserAgentForwardHandler.HANDLER_NAME) == null) { uaChannelCtx.pipeline().addLast(HttpUserAgentForwardHandler.HANDLER_NAME, new HttpUserAgentForwardHandler()); } } } uaChannelCtx.fireChannelRead(msg); }
From source file:com.github.jonbonazza.puni.core.mux.DefaultMuxer.java
License:Apache License
public DefaultMuxer() { methodMap.put(HttpMethod.CONNECT, new HashMap<>()); methodMap.put(HttpMethod.DELETE, new HashMap<>()); methodMap.put(HttpMethod.GET, new HashMap<>()); methodMap.put(HttpMethod.HEAD, new HashMap<>()); methodMap.put(HttpMethod.OPTIONS, new HashMap<>()); methodMap.put(HttpMethod.PATCH, new HashMap<>()); methodMap.put(HttpMethod.POST, new HashMap<>()); methodMap.put(HttpMethod.PUT, new HashMap<>()); methodMap.put(HttpMethod.TRACE, new HashMap<>()); }
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 va 2 s.c o 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; }
From source file:com.hazelcast.openshift.TunnelServerConnector.java
License:Open Source License
@Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { Promise promise = new Promise(); Bootstrap bootstrap = createBootstrap(ctx.channel(), promise); ChannelFuture future = bootstrap.connect(httpHost, httpPort); Channel forward = future.sync().channel(); forward.closeFuture().addListener(f -> ctx.close()); ctx.channel().closeFuture().addListener(f -> forward.close()); HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, "/"); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); forward.writeAndFlush(request);// w ww. jav a2 s . com // Wait for the initial http response (ssl established) promise.sync(10, TimeUnit.SECONDS); // Exchange the HazelcastClient -> TunnelClient handler to proxy ChannelPipeline pipeline = ctx.pipeline(); pipeline.addLast(new ProxyForwardHandler(forward)); pipeline.remove(this); ctx.fireChannelRegistered(); }
From source file:com.linkedin.mitm.proxy.factory.HandlerDelegateFactory.java
License:Open Source License
public static ChannelHandlerDelegate create(HttpRequest httpRequest, ChannelMediator channelMediator, Map<Protocol, List<ConnectionFlowStep>> connectionFlowRegistry) { if (HttpMethod.CONNECT.equals(httpRequest.getMethod())) { List<ConnectionFlowStep> connectionFlow = connectionFlowRegistry.get(Protocol.HTTPS); ConnectionFlowProcessor httpsConnectionFlowProcessor = new ConnectionFlowProcessor(channelMediator, httpRequest, connectionFlow); channelMediator.initializeProxyModeController(httpRequest); return new HttpsChannelHandlerDelegate(channelMediator, httpsConnectionFlowProcessor); } else {/*from w w w . j av a 2 s . c om*/ List<ConnectionFlowStep> connectionFlow = connectionFlowRegistry.get(Protocol.HTTP); ConnectionFlowProcessor httpConnectionFlowProcessor = new ConnectionFlowProcessor(channelMediator, httpRequest, connectionFlow); channelMediator.initializeProxyModeController(httpRequest); return new HttpChannelHandlerDelegate(channelMediator, httpConnectionFlowProcessor); } }
From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java
License:Apache License
protected final <T> void writeRequest(final Channel channel, final AsyncHttpClientConfig config, final NettyResponseFuture<T> future, final HttpRequest nettyRequest) { try {/*from ww w . j ava2 s .co m*/ /** * If the channel is dead because it was pooled and the remote server decided to close it, * we just let it go and the closeChannel do it's work. */ if (!channel.isOpen() || !channel.isActive()) { return; } Body body = null; if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) { BodyGenerator bg = future.getRequest().getBodyGenerator(); if (bg != null) { // Netty issue with chunking. if (InputStreamBodyGenerator.class.isAssignableFrom(bg.getClass())) { InputStreamBodyGenerator.class.cast(bg).patchNettyChunkingIssue(true); } try { body = bg.createBody(); } catch (IOException ex) { throw new IllegalStateException(ex); } long length = body.getContentLength(); if (length >= 0) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, length); } else { nettyRequest.headers().set(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); } } else { body = null; } } if (TransferCompletionHandler.class.isAssignableFrom(future.getAsyncHandler().getClass())) { FluentCaseInsensitiveStringsMap h = new FluentCaseInsensitiveStringsMap(); for (String s : future.getNettyRequest().headers().names()) { for (String header : future.getNettyRequest().headers().getAll(s)) { h.add(s, header); } } TransferCompletionHandler.class.cast(future.getAsyncHandler()).transferAdapter( new NettyTransferAdapter(h, nettyRequest.getContent(), future.getRequest().getFile())); } // Leave it to true. if (future.getAndSetWriteHeaders(true)) { try { channel.write(nettyRequest) .addListener(new ProgressListener(true, future.getAsyncHandler(), future)); } catch (Throwable cause) { log.debug(cause.getMessage(), cause); try { channel.close(); } catch (RuntimeException ex) { log.debug(ex.getMessage(), ex); } return; } } if (future.getAndSetWriteBody(true)) { if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) { if (future.getRequest().getFile() != null) { final File file = future.getRequest().getFile(); long fileLength = 0; final RandomAccessFile raf = new RandomAccessFile(file, "r"); try { fileLength = raf.length(); ChannelFuture writeFuture; if (channel.pipeline().get(SslHandler.class) != null) { writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192)); } else { final FileRegion region = new OptimizedFileRegion(raf, 0, fileLength); writeFuture = channel.write(region); } writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future)); } catch (IOException ex) { if (raf != null) { try { raf.close(); } catch (IOException e) { } } throw ex; } } else if (body != null || future.getRequest().getParts() != null) { /** * TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements. */ if (future.getRequest().getParts() != null) { String boundary = future.getNettyRequest().headers().get("Content-Type"); String length = future.getNettyRequest().headers().get("Content-Length"); body = new MultipartBody(future.getRequest().getParts(), boundary, length); } ChannelFuture writeFuture; if (channel.pipeline().get(SslHandler.class) == null && (body instanceof RandomAccessBody)) { BodyFileRegion bodyFileRegion = new BodyFileRegion((RandomAccessBody) body); writeFuture = channel.write(bodyFileRegion); } else { BodyChunkedInput bodyChunkedInput = new BodyChunkedInput(body); BodyGenerator bg = future.getRequest().getBodyGenerator(); if (bg instanceof FeedableBodyGenerator) { ((FeedableBodyGenerator) bg).setListener(new FeedListener() { @Override public void onContentAdded() { channel.pipeline().get(ChunkedWriteHandler.class).resumeTransfer(); } }); } writeFuture = channel.write(bodyChunkedInput); } final Body b = body; writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future) { public void operationComplete(ChannelFuture cf) { try { b.close(); } catch (IOException e) { log.warn("Failed to close request body: {}", e.getMessage(), e); } super.operationComplete(cf); } }); } } } } catch (Throwable ioe) { try { channel.close(); } catch (RuntimeException ex) { log.debug(ex.getMessage(), ex); } } try { future.touch(); int requestTimeout = AsyncHttpProviderUtils.requestTimeout(config, future.getRequest()); if (requestTimeout != -1 && !future.isDone() && !future.isCancelled()) { ReaperFuture reaperFuture = new ReaperFuture(future); Future<?> scheduledFuture = config.reaper().scheduleAtFixedRate(reaperFuture, 0, requestTimeout, TimeUnit.MILLISECONDS); reaperFuture.setScheduledFuture(scheduledFuture); future.setReaperFuture(reaperFuture); } } catch (RejectedExecutionException ex) { abort(future, ex); } }
From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java
License:Apache License
protected final static HttpRequest buildRequest(AsyncHttpClientConfig config, Request request, URI uri, boolean allowConnect, ByteBuf buffer, ProxyServer proxyServer) throws IOException { String method = request.getMethod(); if (allowConnect && proxyServer != null && isSecure(uri)) { method = HttpMethod.CONNECT.toString(); }/*from w w w.ja va 2 s.c om*/ return construct(config, request, new HttpMethod(method), uri, buffer, proxyServer); }
From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java
License:Apache License
private static HttpRequest construct(AsyncHttpClientConfig config, Request request, HttpMethod m, URI uri, ByteBuf buffer, ProxyServer proxyServer) throws IOException { String host = AsyncHttpProviderUtils.getHost(uri); boolean webSocket = isWebSocket(uri); if (request.getVirtualHost() != null) { host = request.getVirtualHost(); }/*www.j a v a2 s .c o m*/ FullHttpRequest nettyRequest; if (m.equals(HttpMethod.CONNECT)) { nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri)); } else { String path = null; if (proxyServer != null && !(isSecure(uri) && config.isUseRelativeURIsWithSSLProxies())) path = uri.toString(); else if (uri.getRawQuery() != null) path = uri.getRawPath() + "?" + uri.getRawQuery(); else path = uri.getRawPath(); nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, m, path); } if (webSocket) { nettyRequest.headers().add(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET); nettyRequest.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE); nettyRequest.headers().add("Origin", "http://" + uri.getHost() + ":" + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort())); nettyRequest.headers().add(WEBSOCKET_KEY, WebSocketUtil.getKey()); nettyRequest.headers().add("Sec-WebSocket-Version", "13"); } if (host != null) { if (uri.getPort() == -1) { nettyRequest.headers().set(HttpHeaders.Names.HOST, host); } else if (request.getVirtualHost() != null) { nettyRequest.headers().set(HttpHeaders.Names.HOST, host); } else { nettyRequest.headers().set(HttpHeaders.Names.HOST, host + ":" + uri.getPort()); } } else { host = "127.0.0.1"; } if (!m.equals(HttpMethod.CONNECT)) { FluentCaseInsensitiveStringsMap h = request.getHeaders(); if (h != null) { for (String name : h.keySet()) { if (!"host".equalsIgnoreCase(name)) { for (String value : h.get(name)) { nettyRequest.headers().add(name, value); } } } } if (config.isCompressionEnabled()) { nettyRequest.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); } } else { List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION); if (isNonEmpty(auth) && auth.get(0).startsWith("NTLM")) { nettyRequest.headers().add(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0)); } } Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm(); if (realm != null && realm.getUsePreemptiveAuth()) { String domain = realm.getNtlmDomain(); if (proxyServer != null && proxyServer.getNtlmDomain() != null) { domain = proxyServer.getNtlmDomain(); } String authHost = realm.getNtlmHost(); if (proxyServer != null && proxyServer.getHost() != null) { host = proxyServer.getHost(); } switch (realm.getAuthScheme()) { case BASIC: nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(realm)); break; case DIGEST: if (isNonEmpty(realm.getNonce())) { try { nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeDigestAuthentication(realm)); } catch (NoSuchAlgorithmException e) { throw new SecurityException(e); } } break; case NTLM: try { String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost); nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg); } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } break; case KERBEROS: case SPNEGO: String challengeHeader = null; String server = proxyServer == null ? host : proxyServer.getHost(); try { challengeHeader = getSpnegoEngine().generateToken(server); } catch (Throwable e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader); break; case NONE: break; default: throw new IllegalStateException("Invalid Authentication " + realm); } } if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) { nettyRequest.headers().set(HttpHeaders.Names.CONNECTION, AsyncHttpProviderUtils.keepAliveHeaderValue(config)); } if (proxyServer != null) { if (!request.getHeaders().containsKey("Proxy-Connection")) { nettyRequest.headers().set("Proxy-Connection", AsyncHttpProviderUtils.keepAliveHeaderValue(config)); } if (proxyServer.getPrincipal() != null) { if (isNonEmpty(proxyServer.getNtlmDomain())) { List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION); if (!(isNonEmpty(auth) && auth.get(0).startsWith("NTLM"))) { try { String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(), proxyServer.getHost()); nettyRequest.headers().set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg); } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } } } else { nettyRequest.headers().set(HttpHeaders.Names.PROXY_AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(proxyServer)); } } } // Add default accept headers. if (request.getHeaders().getFirstValue("Accept") == null) { nettyRequest.headers().set(HttpHeaders.Names.ACCEPT, "*/*"); } if (request.getHeaders().getFirstValue("User-Agent") != null) { nettyRequest.headers().set("User-Agent", request.getHeaders().getFirstValue("User-Agent")); } else if (config.getUserAgent() != null) { nettyRequest.headers().set("User-Agent", config.getUserAgent()); } else { nettyRequest.headers().set("User-Agent", AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config)); } if (!m.equals(HttpMethod.CONNECT)) { if (isNonEmpty(request.getCookies())) { CookieEncoder httpCookieEncoder = new CookieEncoder(false); Iterator<Cookie> ic = request.getCookies().iterator(); Cookie c; org.jboss.netty.handler.codec.http.Cookie cookie; while (ic.hasNext()) { c = ic.next(); cookie = new DefaultCookie(c.getName(), c.getValue()); cookie.setPath(c.getPath()); cookie.setMaxAge(c.getMaxAge()); cookie.setDomain(c.getDomain()); httpCookieEncoder.addCookie(cookie); } nettyRequest.headers().set(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode()); } String reqType = request.getMethod(); if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) { String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding(); // We already have processed the body. if (buffer != null && buffer.writerIndex() != 0) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex()); nettyRequest.setContent(buffer); } else if (request.getByteData() != null) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length)); nettyRequest.setContent(Unpooled.wrappedBuffer(request.getByteData())); } else if (request.getStringData() != null) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length)); nettyRequest.setContent(Unpooled.wrappedBuffer(request.getStringData().getBytes(bodyCharset))); } else if (request.getStreamData() != null) { int[] lengthWrapper = new int[1]; byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper); int length = lengthWrapper[0]; nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length)); nettyRequest.setContent(Unpooled.wrappedBuffer(bytes, 0, length)); } else if (isNonEmpty(request.getParams())) { StringBuilder sb = new StringBuilder(); for (final Entry<String, List<String>> paramEntry : request.getParams()) { final String key = paramEntry.getKey(); for (final String value : paramEntry.getValue()) { if (sb.length() > 0) { sb.append("&"); } UTF8UrlEncoder.appendEncoded(sb, key); sb.append("="); UTF8UrlEncoder.appendEncoded(sb, value); } } nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length())); nettyRequest.setContent(Unpooled.wrappedBuffer(sb.toString().getBytes(bodyCharset))); if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); } } else if (request.getParts() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } MultipartRequestEntity mre = AsyncHttpProviderUtils .createMultipartRequestEntity(request.getParts(), request.getParams()); nettyRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType()); nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength())); /** * TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements. */ if (isSecure(uri)) { ByteBuf b = Unpooled.buffer(lenght); mre.writeRequest(new ByteBufOutputStream(b)); nettyRequest.setContent(b); } } else if (request.getEntityWriter() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } ByteBuf b = Unpooled.buffer(lenght); request.getEntityWriter().writeEntity(new ByteBufOutputStream(b)); nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex()); nettyRequest.setContent(b); } else if (request.getFile() != null) { File file = request.getFile(); if (!file.isFile()) { throw new IOException( String.format("File %s is not a file or doesn't exist", file.getAbsolutePath())); } nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length()); } } } return nettyRequest; }
From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java
License:Apache License
private <T> ListenableFuture<T> doConnect(final Request request, final AsyncHandler<T> asyncHandler, NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException { if (isClose.get()) { throw new IOException("Closed"); }//from www .ja v a 2 s .co m if (request.getUrl().startsWith(WEBSOCKET) && !validateWebSocketRequest(request, asyncHandler)) { throw new IOException("WebSocket method must be a GET"); } ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request); boolean useProxy = proxyServer != null; URI uri; if (useRawUrl) { uri = request.getRawURI(); } else { uri = request.getURI(); } Channel channel = null; if (useCache) { if (f != null && f.reuseChannel() && f.channel() != null) { channel = f.channel(); } else { URI connectionKeyUri = useProxy ? proxyServer.getURI() : uri; channel = lookupInCache(connectionKeyUri, request.getConnectionPoolKeyStrategy()); } } ByteBuf bufferedBytes = null; if (f != null && f.getRequest().getFile() == null && !f.getNettyRequest().getMethod().name().equals(HttpMethod.CONNECT.name())) { bufferedBytes = f.getNettyRequest().data(); } boolean useSSl = isSecure(uri) && !useProxy; if (channel != null && channel.isOpen() && channel.isActive()) { HttpRequest nettyRequest = buildRequest(config, request, uri, f == null ? false : f.isConnectAllowed(), bufferedBytes, proxyServer); if (f == null) { f = newFuture(uri, request, asyncHandler, nettyRequest, config, this, proxyServer); } else { nettyRequest = buildRequest(config, request, uri, f.isConnectAllowed(), bufferedBytes, proxyServer); f.setNettyRequest(nettyRequest); } f.setState(NettyResponseFuture.STATE.POOLED); f.attachChannel(channel, false); log.debug("\nUsing cached Channel {}\n for request \n{}\n", channel, nettyRequest); channel.pipeline().context(NettyAsyncHttpProvider.class).attr(DEFAULT_ATTRIBUTE).set(f); try { writeRequest(channel, config, f, nettyRequest); } catch (Exception ex) { log.debug("writeRequest failure", ex); if (useSSl && ex.getMessage() != null && ex.getMessage().contains("SSLEngine")) { log.debug("SSLEngine failure", ex); f = null; } else { try { asyncHandler.onThrowable(ex); } catch (Throwable t) { log.warn("doConnect.writeRequest()", t); } IOException ioe = new IOException(ex.getMessage()); ioe.initCause(ex); throw ioe; } } return f; } // Do not throw an exception when we need an extra connection for a redirect. if (!reclaimCache && !connectionsPool.canCacheConnection()) { IOException ex = new IOException("Too many connections " + config.getMaxTotalConnections()); try { asyncHandler.onThrowable(ex); } catch (Throwable t) { log.warn("!connectionsPool.canCacheConnection()", t); } throw ex; } boolean acquiredConnection = false; if (trackConnections) { if (!reclaimCache) { if (!freeConnections.tryAcquire()) { IOException ex = new IOException("Too many connections " + config.getMaxTotalConnections()); try { asyncHandler.onThrowable(ex); } catch (Throwable t) { log.warn("!connectionsPool.canCacheConnection()", t); } throw ex; } else { acquiredConnection = true; } } } NettyConnectListener<T> c = new NettyConnectListener.Builder<T>(config, request, asyncHandler, f, this, bufferedBytes).build(uri); boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, uri.getHost()); if (useSSl) { constructSSLPipeline(c); } ChannelFuture channelFuture; Bootstrap bootstrap = request.getUrl().startsWith(WEBSOCKET) ? (useSSl ? secureWebSocketBootstrap : webSocketBootstrap) : (useSSl ? secureBootstrap : plainBootstrap); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectionTimeoutInMs()); try { InetSocketAddress remoteAddress; if (request.getInetAddress() != null) { remoteAddress = new InetSocketAddress(request.getInetAddress(), AsyncHttpProviderUtils.getPort(uri)); } else if (proxyServer == null || avoidProxy) { remoteAddress = new InetSocketAddress(AsyncHttpProviderUtils.getHost(uri), AsyncHttpProviderUtils.getPort(uri)); } else { remoteAddress = new InetSocketAddress(proxyServer.getHost(), proxyServer.getPort()); } if (request.getLocalAddress() != null) { channelFuture = bootstrap.connect(remoteAddress, new InetSocketAddress(request.getLocalAddress(), 0)); } else { channelFuture = bootstrap.connect(remoteAddress); } } catch (Throwable t) { if (acquiredConnection) { freeConnections.release(); } abort(c.future(), t.getCause() == null ? t : t.getCause()); return c.future(); } boolean directInvokation = true; if (IN_IO_THREAD.get() && DefaultChannelFuture.isUseDeadLockChecker()) { directInvokation = false; } if (directInvokation && !asyncConnect && request.getFile() == null) { int timeOut = config.getConnectionTimeoutInMs() > 0 ? config.getConnectionTimeoutInMs() : Integer.MAX_VALUE; if (!channelFuture.awaitUninterruptibly(timeOut, TimeUnit.MILLISECONDS)) { if (acquiredConnection) { freeConnections.release(); } channelFuture.cancel(); abort(c.future(), new ConnectException(String.format("Connect operation to %s timeout %s", uri, timeOut))); } try { c.operationComplete(channelFuture); } catch (Exception e) { if (acquiredConnection) { freeConnections.release(); } IOException ioe = new IOException(e.getMessage()); ioe.initCause(e); try { asyncHandler.onThrowable(ioe); } catch (Throwable t) { log.warn("c.operationComplete()", t); } throw ioe; } } else { channelFuture.addListener(c); } log.debug("\nNon cached request \n{}\n\nusing Channel \n{}\n", c.future().getNettyRequest(), channelFuture.getChannel()); if (!c.future().isCancelled() || !c.future().isDone()) { openChannels.add(channelFuture.channel()); c.future().attachChannel(channelFuture.channel(), false); } return c.future(); }
From source file:com.otcdlink.chiron.downend.Http11ProxyHandler.java
License:Apache License
@Override protected Object newInitialMessage(ChannelHandlerContext ctx) throws Exception { InetSocketAddress raddr = destinationAddress(); String rhost;//ww w .j av a 2 s . c om if (raddr.isUnresolved()) { rhost = raddr.getHostString(); } else { rhost = raddr.getAddress().getHostAddress(); } FullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, rhost + ':' + raddr.getPort(), Unpooled.EMPTY_BUFFER, new DefaultHttpHeaders().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE).add( HttpHeaderNames.PROXY_CONNECTION, HttpHeaderValues.KEEP_ALIVE), EmptyHttpHeaders.INSTANCE); SocketAddress proxyAddress = proxyAddress(); if (proxyAddress instanceof InetSocketAddress) { InetSocketAddress hostAddr = (InetSocketAddress) proxyAddress; // req.headers().set(HttpHeaderNames.HOST, hostAddr.getHostString() + ':' + hostAddr.getPort()); req.headers().set(HttpHeaderNames.HOST, rhost + ':' + raddr.getPort()); } if (authorization != null) { req.headers().set(HttpHeaderNames.PROXY_AUTHORIZATION, authorization); } return req; }