GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Never speak h2c prior knowledge to an HTTP proxy · mkurz/async-http-client@0b4f999

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • client/src
    • main/java/org/asynchttpclient/netty/channel
      • NettyConnectListener.java
    • test/java/org/asynchttpclient/proxy
      • ProxyH2cTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎client/src/main/java/org/asynchttpclient/netty/channel/NettyConnectListener.java‎

Copy file name to clipboardExpand all lines: client/src/main/java/org/asynchttpclient/netty/channel/NettyConnectListener.java
+7-1Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,13 @@ protected void onFailure(Throwable cause) {
267267
} else {
268268
// h2c (cleartext HTTP/2 prior knowledge): upgrade to HTTP/2 without TLS. WebSocket (ws://) is
269269
// excluded for the same RFC 8441 reason as the TLS path above — it stays on HTTP/1.1.
270-
if (!uri.isSecured() && channelManager.isHttp2CleartextEnabled() && !uri.isWebSocket()) {
270+
// Prior knowledge is knowledge about the origin, so it may only be acted on when the origin is
271+
// the peer of this socket. With an HTTP proxy configured a cleartext target needs no CONNECT,
272+
// so the request goes to the proxy in absolute-URI form and the preface would be written at a
273+
// peer that never agreed to HTTP/2. A SOCKS proxy tunnels at the transport layer, so its peer
274+
// is still the origin.
275+
boolean peerIsOrigin = proxyServer == null || proxyServer.getProxyType().isSocks();
276+
if (peerIsOrigin && !uri.isSecured() && channelManager.isHttp2CleartextEnabled() && !uri.isWebSocket()) {
271277
channelManager.upgradePipelineToHttp2(channel.pipeline());
272278
registerHttp2AndManageSemaphore(channel, semaphore, permit);
273279
}
Collapse file

‎client/src/test/java/org/asynchttpclient/proxy/ProxyH2cTest.java‎

Copy file name to clipboard
+210Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
/*
2+
* Copyright (c) 2026 AsyncHttpClient Project. All rights reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.asynchttpclient.proxy;
17+
18+
import io.netty.bootstrap.ServerBootstrap;
19+
import io.netty.buffer.Unpooled;
20+
import io.netty.channel.Channel;
21+
import io.netty.channel.ChannelHandlerContext;
22+
import io.netty.channel.ChannelInitializer;
23+
import io.netty.channel.SimpleChannelInboundHandler;
24+
import io.netty.channel.nio.NioEventLoopGroup;
25+
import io.netty.channel.socket.nio.NioServerSocketChannel;
26+
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
27+
import io.netty.handler.codec.http2.DefaultHttp2Headers;
28+
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
29+
import io.netty.handler.codec.http2.Http2DataFrame;
30+
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
31+
import io.netty.handler.codec.http2.Http2HeadersFrame;
32+
import io.netty.handler.codec.http2.Http2MultiplexHandler;
33+
import io.netty.handler.codec.http2.Http2StreamChannel;
34+
import org.asynchttpclient.AsyncHttpClient;
35+
import org.asynchttpclient.HttpProtocol;
36+
import org.asynchttpclient.Response;
37+
import org.asynchttpclient.testserver.SocksProxy;
38+
import org.junit.jupiter.api.Test;
39+
40+
import java.io.IOException;
41+
import java.io.InputStream;
42+
import java.net.InetSocketAddress;
43+
import java.net.ServerSocket;
44+
import java.net.Socket;
45+
import java.nio.charset.StandardCharsets;
46+
import java.util.List;
47+
import java.util.concurrent.CopyOnWriteArrayList;
48+
import java.util.concurrent.CountDownLatch;
49+
import java.util.concurrent.ExecutorService;
50+
import java.util.concurrent.Executors;
51+
import java.util.concurrent.TimeUnit;
52+
53+
import static org.asynchttpclient.Dsl.asyncHttpClient;
54+
import static org.asynchttpclient.Dsl.config;
55+
import static org.asynchttpclient.Dsl.proxyServer;
56+
import static org.junit.jupiter.api.Assertions.assertEquals;
57+
import static org.junit.jupiter.api.Assertions.assertTrue;
58+
59+
/**
60+
* Cleartext HTTP/2 (prior knowledge) and proxies.
61+
* <p>
62+
* Prior knowledge is knowledge about the <em>origin</em>, so it may only be acted on when the origin is what
63+
* is on the other end of the socket. Behind an HTTP forward proxy it is not: a cleartext target needs no
64+
* {@code CONNECT}, so the request goes to the proxy in absolute-URI HTTP/1.1 form. Behind a SOCKS proxy it
65+
* is, because SOCKS tunnels at the transport layer — which is why the guard cannot simply be
66+
* {@code proxyServer == null}.
67+
*/
68+
public class ProxyH2cTest {
69+
70+
/** Echoes the method and {@code :authority} of whatever the client sent, over cleartext HTTP/2. */
71+
private static final class H2cHandler extends SimpleChannelInboundHandler<Object> {
72+
73+
private io.netty.handler.codec.http2.Http2Headers requestHeaders;
74+
75+
@Override
76+
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
77+
if (msg instanceof Http2HeadersFrame) {
78+
Http2HeadersFrame headersFrame = (Http2HeadersFrame) msg;
79+
requestHeaders = headersFrame.headers();
80+
if (headersFrame.isEndStream()) {
81+
respond(ctx);
82+
}
83+
} else if (msg instanceof Http2DataFrame && ((Http2DataFrame) msg).isEndStream()) {
84+
respond(ctx);
85+
}
86+
}
87+
88+
private void respond(ChannelHandlerContext ctx) {
89+
String method = requestHeaders.method() != null ? requestHeaders.method().toString() : "?";
90+
ctx.write(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers().status("200"), false));
91+
ctx.writeAndFlush(new DefaultHttp2DataFrame(
92+
Unpooled.copiedBuffer(method, StandardCharsets.UTF_8), true));
93+
}
94+
95+
@Override
96+
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
97+
ctx.close();
98+
}
99+
}
100+
101+
/**
102+
* An HTTP forward proxy stub that records the first line it is sent and hangs up. Enough to see whether
103+
* AsyncHttpClient opened with an HTTP/1.1 request or with the HTTP/2 connection preface.
104+
*/
105+
@Test
106+
public void h2cIsNotSpokenToAnHttpProxy() throws Exception {
107+
List<String> firstLines = new CopyOnWriteArrayList<>();
108+
CountDownLatch received = new CountDownLatch(1);
109+
ExecutorService pool = Executors.newCachedThreadPool(r -> {
110+
Thread t = new Thread(r, "h2c-probe-proxy");
111+
t.setDaemon(true);
112+
return t;
113+
});
114+
115+
try (ServerSocket serverSocket = new ServerSocket(0)) {
116+
pool.submit(() -> {
117+
try (Socket client = serverSocket.accept()) {
118+
InputStream in = client.getInputStream();
119+
StringBuilder sb = new StringBuilder();
120+
int c;
121+
while ((c = in.read()) != -1 && c != '\n') {
122+
if (c != '\r') {
123+
sb.append((char) c);
124+
}
125+
}
126+
firstLines.add(sb.toString());
127+
} catch (IOException ignored) {
128+
// the client hangs up as soon as we do
129+
} finally {
130+
received.countDown();
131+
}
132+
});
133+
134+
try (AsyncHttpClient client = asyncHttpClient(config()
135+
.setHttp2CleartextEnabled(true)
136+
.setProxyServer(proxyServer("localhost", serverSocket.getLocalPort())))) {
137+
try {
138+
client.prepareGet("http://example.invalid:8080/probe").execute().get(10, TimeUnit.SECONDS);
139+
} catch (Exception expected) {
140+
// the stub proxy answers nothing; only the request head matters
141+
}
142+
}
143+
144+
assertTrue(received.await(10, TimeUnit.SECONDS), "the proxy never saw a request");
145+
} finally {
146+
pool.shutdownNow();
147+
}
148+
149+
assertEquals(1, firstLines.size());
150+
assertEquals("GET http://example.invalid:8080/probe HTTP/1.1", firstLines.get(0),
151+
"AsyncHttpClient must open an HTTP/1.1 exchange with an HTTP proxy, not an HTTP/2 preface");
152+
}
153+
154+
/**
155+
* SOCKS tunnels at the transport layer, so the peer of everything written after the SOCKS handshake is
156+
* the origin: h2c prior knowledge still applies and must not be disabled along with the HTTP-proxy case.
157+
*/
158+
@Test
159+
public void h2cIsSpokenThroughASocksProxy() throws Exception {
160+
NioEventLoopGroup serverGroup = new NioEventLoopGroup(1);
161+
Channel serverChannel = null;
162+
SocksProxy socks = new SocksProxy(30_000);
163+
Thread socksThread = new Thread(() -> {
164+
try {
165+
socks.run();
166+
} catch (IOException ignored) {
167+
// shutting down
168+
}
169+
});
170+
socksThread.setDaemon(true);
171+
socksThread.start();
172+
173+
try {
174+
serverChannel = new ServerBootstrap()
175+
.group(serverGroup)
176+
.channel(NioServerSocketChannel.class)
177+
.childHandler(new ChannelInitializer<Channel>() {
178+
@Override
179+
protected void initChannel(Channel ch) {
180+
ch.pipeline()
181+
.addLast(Http2FrameCodecBuilder.forServer().build())
182+
.addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
183+
@Override
184+
protected void initChannel(Http2StreamChannel streamCh) {
185+
streamCh.pipeline().addLast(new H2cHandler());
186+
}
187+
}));
188+
}
189+
})
190+
.bind(0).sync().channel();
191+
int serverPort = ((InetSocketAddress) serverChannel.localAddress()).getPort();
192+
193+
try (AsyncHttpClient client = asyncHttpClient(config()
194+
.setHttp2CleartextEnabled(true)
195+
.setProxyServer(proxyServer("localhost", socks.getPort()).setProxyType(ProxyType.SOCKS_V4)))) {
196+
Response response = client.prepareGet("http://localhost:" + serverPort + "/probe")
197+
.execute().get(30, TimeUnit.SECONDS);
198+
assertEquals(200, response.getStatusCode());
199+
assertEquals(HttpProtocol.HTTP_2, response.getProtocol());
200+
assertEquals("GET", response.getResponseBody());
201+
}
202+
} finally {
203+
socks.stop();
204+
if (serverChannel != null) {
205+
serverChannel.close().sync();
206+
}
207+
serverGroup.shutdownGracefully(0, 100, TimeUnit.MILLISECONDS).sync();
208+
}
209+
}
210+
}

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.