-
-
Notifications
You must be signed in to change notification settings - Fork 15.8k
/
HttpProxyHandler.java
341 lines (286 loc) · 11.7 KB
/
HttpProxyHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.proxy;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.base64.Base64;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.ObjectUtil;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
/**
* Handler that establishes a blind forwarding proxy tunnel using
* <a href="https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.6">HTTP/1.1 CONNECT</a> request. It can be used to
* establish plaintext or secure tunnels.
* <p>
* HTTP users who need to connect to a
* <a href="https://datatracker.ietf.org/doc/html/rfc7230#page-10">message-forwarding HTTP proxy agent</a> instead of a
* tunneling proxy should not use this handler.
*/
public final class HttpProxyHandler extends ProxyHandler {
private static final String PROTOCOL = "http";
private static final String AUTH_BASIC = "basic";
// Wrapper for the HttpClientCodec to prevent it to be removed by other handlers by mistake (for example the
// WebSocket*Handshaker.
//
// See:
// - https://github.com/netty/netty/issues/5201
// - https://github.com/netty/netty/issues/5070
private final HttpClientCodecWrapper codecWrapper = new HttpClientCodecWrapper();
private final String username;
private final String password;
private final CharSequence authorization;
private final HttpHeaders outboundHeaders;
private final boolean ignoreDefaultPortsInConnectHostHeader;
private HttpResponseStatus status;
private HttpHeaders inboundHeaders;
public HttpProxyHandler(SocketAddress proxyAddress) {
this(proxyAddress, null);
}
public HttpProxyHandler(SocketAddress proxyAddress, HttpHeaders headers) {
this(proxyAddress, headers, false);
}
public HttpProxyHandler(SocketAddress proxyAddress,
HttpHeaders headers,
boolean ignoreDefaultPortsInConnectHostHeader) {
super(proxyAddress);
username = null;
password = null;
authorization = null;
this.outboundHeaders = headers;
this.ignoreDefaultPortsInConnectHostHeader = ignoreDefaultPortsInConnectHostHeader;
}
public HttpProxyHandler(SocketAddress proxyAddress, String username, String password) {
this(proxyAddress, username, password, null);
}
public HttpProxyHandler(SocketAddress proxyAddress, String username, String password,
HttpHeaders headers) {
this(proxyAddress, username, password, headers, false);
}
public HttpProxyHandler(SocketAddress proxyAddress,
String username,
String password,
HttpHeaders headers,
boolean ignoreDefaultPortsInConnectHostHeader) {
super(proxyAddress);
this.username = ObjectUtil.checkNotNull(username, "username");
this.password = ObjectUtil.checkNotNull(password, "password");
ByteBuf authz = Unpooled.copiedBuffer(username + ':' + password, CharsetUtil.UTF_8);
ByteBuf authzBase64;
try {
authzBase64 = Base64.encode(authz, false);
} finally {
authz.release();
}
try {
authorization = new AsciiString("Basic " + authzBase64.toString(CharsetUtil.US_ASCII));
} finally {
authzBase64.release();
}
this.outboundHeaders = headers;
this.ignoreDefaultPortsInConnectHostHeader = ignoreDefaultPortsInConnectHostHeader;
}
@Override
public String protocol() {
return PROTOCOL;
}
@Override
public String authScheme() {
return authorization != null? AUTH_BASIC : AUTH_NONE;
}
public String username() {
return username;
}
public String password() {
return password;
}
@Override
protected void addCodec(ChannelHandlerContext ctx) throws Exception {
ChannelPipeline p = ctx.pipeline();
String name = ctx.name();
p.addBefore(name, null, codecWrapper);
}
@Override
protected void removeEncoder(ChannelHandlerContext ctx) throws Exception {
codecWrapper.codec.removeOutboundHandler();
}
@Override
protected void removeDecoder(ChannelHandlerContext ctx) throws Exception {
codecWrapper.codec.removeInboundHandler();
}
@Override
protected Object newInitialMessage(ChannelHandlerContext ctx) throws Exception {
InetSocketAddress raddr = destinationAddress();
String hostString = HttpUtil.formatHostnameForHttp(raddr);
int port = raddr.getPort();
String url = hostString + ":" + port;
String hostHeader = (ignoreDefaultPortsInConnectHostHeader && (port == 80 || port == 443)) ?
hostString :
url;
FullHttpRequest req = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.CONNECT,
url,
Unpooled.EMPTY_BUFFER, false);
req.headers().set(HttpHeaderNames.HOST, hostHeader);
if (authorization != null) {
req.headers().set(HttpHeaderNames.PROXY_AUTHORIZATION, authorization);
}
if (outboundHeaders != null) {
req.headers().add(outboundHeaders);
}
return req;
}
@Override
protected boolean handleResponse(ChannelHandlerContext ctx, Object response) throws Exception {
if (response instanceof HttpResponse) {
if (status != null) {
throw new HttpProxyConnectException(exceptionMessage("too many responses"), /*headers=*/ null);
}
HttpResponse res = (HttpResponse) response;
status = res.status();
inboundHeaders = res.headers();
}
boolean finished = response instanceof LastHttpContent;
if (finished) {
if (status == null) {
throw new HttpProxyConnectException(exceptionMessage("missing response"), inboundHeaders);
}
if (status.code() != 200) {
throw new HttpProxyConnectException(exceptionMessage("status: " + status), inboundHeaders);
}
}
return finished;
}
/**
* Specific case of a connection failure, which may include headers from the proxy.
*/
public static final class HttpProxyConnectException extends ProxyConnectException {
private static final long serialVersionUID = -8824334609292146066L;
private final HttpHeaders headers;
/**
* @param message The failure message.
* @param headers Header associated with the connection failure. May be {@code null}.
*/
public HttpProxyConnectException(String message, HttpHeaders headers) {
super(message);
this.headers = headers;
}
/**
* Returns headers, if any. May be {@code null}.
*/
public HttpHeaders headers() {
return headers;
}
}
private static final class HttpClientCodecWrapper implements ChannelInboundHandler, ChannelOutboundHandler {
final HttpClientCodec codec = new HttpClientCodec();
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
codec.handlerAdded(ctx);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
codec.handlerRemoved(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
codec.exceptionCaught(ctx, cause);
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
codec.channelRegistered(ctx);
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
codec.channelUnregistered(ctx);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
codec.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
codec.channelInactive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
codec.channelRead(ctx, msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
codec.channelReadComplete(ctx);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
codec.userEventTriggered(ctx, evt);
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
codec.channelWritabilityChanged(ctx);
}
@Override
public void bind(ChannelHandlerContext ctx, SocketAddress localAddress,
ChannelPromise promise) throws Exception {
codec.bind(ctx, localAddress, promise);
}
@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
ChannelPromise promise) throws Exception {
codec.connect(ctx, remoteAddress, localAddress, promise);
}
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
codec.disconnect(ctx, promise);
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
codec.close(ctx, promise);
}
@Override
public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
codec.deregister(ctx, promise);
}
@Override
public void read(ChannelHandlerContext ctx) throws Exception {
codec.read(ctx);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
codec.write(ctx, msg, promise);
}
@Override
public void flush(ChannelHandlerContext ctx) throws Exception {
codec.flush(ctx);
}
}
}