Skip to content

backport: fix inappropriate connection reuse when using HTTP proxy if the initial CONNECT failed #2074

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.asynchttpclient.netty.channel.ChannelManager;
import org.asynchttpclient.netty.channel.Channels;
import org.asynchttpclient.netty.request.NettyRequestSender;
import org.asynchttpclient.util.HttpConstants.ResponseStatusCodes;

import java.io.IOException;
import java.net.InetSocketAddress;
Expand All @@ -39,9 +40,12 @@ public HttpHandler(AsyncHttpClientConfig config, ChannelManager channelManager,
super(config, channelManager, requestSender);
}

private boolean abortAfterHandlingStatus(AsyncHandler<?> handler,
private boolean abortAfterHandlingStatus(AsyncHandler<?> handler, HttpMethod httpMethod,
NettyResponseStatus status) throws Exception {
return handler.onStatusReceived(status) == State.ABORT;
// For non-200 response of a CONNECT request, it's still unconnected.
// We need to either close the connection or reuse it but send CONNECT request again.
// The former one is easier or we have to attach more state to Channel.
return handler.onStatusReceived(status) == State.ABORT || httpMethod == HttpMethod.CONNECT && status.getStatusCode() != ResponseStatusCodes.OK_200;
}

private boolean abortAfterHandlingHeaders(AsyncHandler<?> handler,
Expand Down Expand Up @@ -75,7 +79,7 @@ private void handleHttpResponse(final HttpResponse response, final Channel chann
HttpHeaders responseHeaders = response.headers();

if (!interceptors.exitAfterIntercept(channel, future, handler, response, status, responseHeaders)) {
boolean abort = abortAfterHandlingStatus(handler, status) || //
boolean abort = abortAfterHandlingStatus(handler, httpRequest.method(), status) || //
abortAfterHandlingHeaders(handler, responseHeaders) || //
abortAfterHandlingReactiveStreams(channel, future, handler);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ public NettyRequestSender(AsyncHttpClientConfig config,
this.clientState = clientState;
requestFactory = new NettyRequestFactory(config);
}

// needConnect returns true if the request is secure/websocket and a HTTP proxy is set
private boolean needConnect(final Request request, final ProxyServer proxyServer) {
return proxyServer != null
&& proxyServer.getProxyType().isHttp()
&& (request.getUri().isSecured() || request.getUri().isWebSocket());
}

public <T> ListenableFuture<T> sendRequest(final Request request,
final AsyncHandler<T> asyncHandler,
Expand All @@ -97,10 +104,7 @@ public <T> ListenableFuture<T> sendRequest(final Request request,
ProxyServer proxyServer = getProxyServer(config, request);

// WebSockets use connect tunneling to work with proxies
if (proxyServer != null
&& proxyServer.getProxyType().isHttp()
&& (request.getUri().isSecured() || request.getUri().isWebSocket())
&& !isConnectAlreadyDone(request, future)) {
if (needConnect(request, proxyServer) && !isConnectAlreadyDone(request, future)) {
// Proxy with HTTPS or WebSocket: CONNECT for sure
if (future != null && future.isConnectAllowed()) {
// Perform CONNECT
Expand All @@ -117,6 +121,8 @@ public <T> ListenableFuture<T> sendRequest(final Request request,

private boolean isConnectAlreadyDone(Request request, NettyResponseFuture<?> future) {
return future != null
// If the channel can't be reused or closed, a CONNECT is still required
&& future.isReuseChannel() && Channels.isChannelActive(future.channel())
&& future.getNettyRequest() != null
&& future.getNettyRequest().getHttpRequest().method() == HttpMethod.CONNECT
&& !request.getMethod().equals(CONNECT);
Expand All @@ -132,15 +138,19 @@ private <T> ListenableFuture<T> sendRequestWithCertainForceConnect(Request reque
NettyResponseFuture<T> future,
ProxyServer proxyServer,
boolean performConnectRequest) {

NettyResponseFuture<T> newFuture = newNettyRequestAndResponseFuture(request, asyncHandler, future, proxyServer,
performConnectRequest);

Channel channel = getOpenChannel(future, request, proxyServer, asyncHandler);

return Channels.isChannelActive(channel)
? sendRequestWithOpenChannel(newFuture, asyncHandler, channel)
: sendRequestWithNewChannel(request, proxyServer, newFuture, asyncHandler);
Channel channel = getOpenChannel(future, request, proxyServer, asyncHandler);
if (Channels.isChannelActive(channel)) {
NettyResponseFuture<T> newFuture = newNettyRequestAndResponseFuture(request, asyncHandler, future,
proxyServer, performConnectRequest);
return sendRequestWithOpenChannel(newFuture, asyncHandler, channel);
} else {
// A new channel is not expected when performConnectRequest is false. We need to
// revisit the condition of sending
// the CONNECT request to the new channel.
NettyResponseFuture<T> newFuture = newNettyRequestAndResponseFuture(request, asyncHandler, future,
proxyServer, needConnect(request, proxyServer));
return sendRequestWithNewChannel(request, proxyServer, newFuture, asyncHandler);
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
package org.asynchttpclient.proxy;

import org.asynchttpclient.*;
import org.asynchttpclient.proxy.ProxyServer.Builder;
import org.asynchttpclient.request.body.generator.ByteArrayBodyGenerator;
import org.asynchttpclient.test.EchoHandler;
import org.asynchttpclient.util.HttpConstants;
import org.eclipse.jetty.proxy.ConnectHandler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
Expand All @@ -23,11 +25,21 @@
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import io.netty.handler.codec.http.DefaultHttpHeaders;

import static org.asynchttpclient.Dsl.*;
import static org.asynchttpclient.test.TestUtils.LARGE_IMAGE_BYTES;
import static org.asynchttpclient.test.TestUtils.addHttpConnector;
import static org.asynchttpclient.test.TestUtils.addHttpsConnector;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertThrows;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Proxy usage tests.
Expand All @@ -37,7 +49,7 @@ public class HttpsProxyTest extends AbstractBasicTest {
private Server server2;

public AbstractHandler configureHandler() throws Exception {
return new ConnectHandler();
return new ProxyHandler();
}

@BeforeClass(alwaysRun = true)
Expand Down Expand Up @@ -129,4 +141,62 @@ public void testPooledConnectionsWithProxy() throws Exception {
assertEquals(r2.getStatusCode(), 200);
}
}

@Test
public void testFailedConnectWithProxy() throws Exception {
try (AsyncHttpClient asyncHttpClient = asyncHttpClient(config().setFollowRedirect(true).setUseInsecureTrustManager(true).setKeepAlive(true))) {
Builder proxyServer = proxyServer("localhost", port1);
proxyServer.setCustomHeaders(r -> new DefaultHttpHeaders().set(ProxyHandler.HEADER_FORBIDDEN, "1"));
RequestBuilder rb = get(getTargetUrl2()).setProxyServer(proxyServer);

Response response1 = asyncHttpClient.executeRequest(rb.build()).get();
assertEquals(403, response1.getStatusCode());

Response response2 = asyncHttpClient.executeRequest(rb.build()).get();
assertEquals(403, response2.getStatusCode());

Response response3 = asyncHttpClient.executeRequest(rb.build()).get();
assertEquals(403, response3.getStatusCode());
}
}

@Test
public void testClosedConnectionWithProxy() throws Exception {
try (AsyncHttpClient asyncHttpClient = asyncHttpClient(
config().setFollowRedirect(true).setUseInsecureTrustManager(true).setKeepAlive(true))) {
Builder proxyServer = proxyServer("localhost", port1);
proxyServer.setCustomHeaders(r -> new DefaultHttpHeaders().set(ProxyHandler.HEADER_FORBIDDEN, "2"));
RequestBuilder rb = get(getTargetUrl2()).setProxyServer(proxyServer);

assertThrows(ExecutionException.class, () -> asyncHttpClient.executeRequest(rb.build()).get());
assertThrows(ExecutionException.class, () -> asyncHttpClient.executeRequest(rb.build()).get());
assertThrows(ExecutionException.class, () -> asyncHttpClient.executeRequest(rb.build()).get());
}
}

public static class ProxyHandler extends ConnectHandler {
final static String HEADER_FORBIDDEN = "X-REJECT-REQUEST";

@Override
public void handle(String s, org.eclipse.jetty.server.Request r, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (HttpConstants.Methods.CONNECT.equalsIgnoreCase(request.getMethod())) {
String headerValue = request.getHeader(HEADER_FORBIDDEN);
if (headerValue == null) {
headerValue = "";
}
switch (headerValue) {
case "1":
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
r.setHandled(true);
return;
case "2":
r.getHttpChannel().getConnection().close();
r.setHandled(true);
return;
}
}
super.handle(s, r, request, response);
}
}
}