HttpProxyServerHandler.java
13.1 KB
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
package com.github.monkeywie.proxyee.handler;
import com.github.monkeywie.proxyee.crt.CertPool;
import com.github.monkeywie.proxyee.exception.HttpProxyExceptionHandle;
import com.github.monkeywie.proxyee.intercept.HttpProxyIntercept;
import com.github.monkeywie.proxyee.intercept.HttpProxyInterceptInitializer;
import com.github.monkeywie.proxyee.intercept.HttpProxyInterceptPipeline;
import com.github.monkeywie.proxyee.proxy.ProxyConfig;
import com.github.monkeywie.proxyee.proxy.ProxyHandleFactory;
import com.github.monkeywie.proxyee.server.HttpProxyServer;
import com.github.monkeywie.proxyee.server.HttpProxyServerConfig;
import com.github.monkeywie.proxyee.server.auth.HttpAuthContext;
import com.github.monkeywie.proxyee.server.auth.HttpProxyAuthenticationProvider;
import com.github.monkeywie.proxyee.server.auth.model.HttpToken;
import com.github.monkeywie.proxyee.util.ProtoUtil;
import com.github.monkeywie.proxyee.util.ProtoUtil.RequestProto;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.proxy.ProxyHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.resolver.NoopAddressResolverGroup;
import io.netty.util.ReferenceCountUtil;
import java.net.InetSocketAddress;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
public class HttpProxyServerHandler extends ChannelInboundHandlerAdapter {
private ChannelFuture cf;
private RequestProto requestProto;
private int status = 0;
private final HttpProxyServerConfig serverConfig;
private final ProxyConfig proxyConfig;
private final HttpProxyInterceptInitializer interceptInitializer;
private HttpProxyInterceptPipeline interceptPipeline;
private final HttpProxyExceptionHandle exceptionHandle;
private List requestList;
private boolean isConnect;
public HttpProxyServerConfig getServerConfig() {
return serverConfig;
}
public HttpProxyInterceptPipeline getInterceptPipeline() {
return interceptPipeline;
}
public HttpProxyExceptionHandle getExceptionHandle() {
return exceptionHandle;
}
public HttpProxyServerHandler(HttpProxyServerConfig serverConfig, HttpProxyInterceptInitializer interceptInitializer, ProxyConfig proxyConfig, HttpProxyExceptionHandle exceptionHandle) {
this.serverConfig = serverConfig;
this.proxyConfig = proxyConfig;
this.interceptInitializer = interceptInitializer;
this.exceptionHandle = exceptionHandle;
}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest request = (HttpRequest) msg;
// 第一次建立连接取host和端口号和处理代理握手
if (status == 0) {
requestProto = ProtoUtil.getRequestProto(request);
if (requestProto == null) { // bad request
ctx.channel().close();
return;
}
// 首次连接处理
if (serverConfig.getHttpProxyAcceptHandler() != null
&& !serverConfig.getHttpProxyAcceptHandler().onAccept(request, ctx.channel())) {
status = 2;
ctx.channel().close();
return;
}
// 代理身份验证
if (!authenticate(ctx, request)) {
status = 2;
ctx.channel().close();
return;
}
status = 1;
if ("CONNECT".equalsIgnoreCase(request.method().name())) {// 建立代理握手
status = 2;
HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpProxyServer.SUCCESS);
ctx.writeAndFlush(response);
ctx.channel().pipeline().remove("httpCodec");
// fix issue #42
ReferenceCountUtil.release(msg);
return;
}
}
interceptPipeline = buildPipeline();
interceptPipeline.setRequestProto(requestProto.copy());
// fix issue #27
if (request.uri().indexOf("/") != 0) {
URL url = new URL(request.uri());
request.setUri(url.getFile());
}
interceptPipeline.beforeRequest(ctx.channel(), request);
} else if (msg instanceof HttpContent) {
if (status != 2) {
interceptPipeline.beforeRequest(ctx.channel(), (HttpContent) msg);
} else {
ReferenceCountUtil.release(msg);
status = 1;
}
} else { // ssl和websocket的握手处理
if (serverConfig.isHandleSsl()) {
ByteBuf byteBuf = (ByteBuf) msg;
if (byteBuf.getByte(0) == 22) {// ssl握手
requestProto.setSsl(true);
int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
SslContext sslCtx = SslContextBuilder
.forServer(serverConfig.getServerPriKey(), CertPool.getCert(port, requestProto.getHost(), serverConfig)).build();
ctx.pipeline().addFirst("httpCodec", new HttpServerCodec());
ctx.pipeline().addFirst("sslHandle", sslCtx.newHandler(ctx.alloc()));
// 重新过一遍pipeline,拿到解密后的的http报文
ctx.pipeline().fireChannelRead(msg);
return;
}
}
handleProxyData(ctx.channel(), msg, false);
}
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
if (cf != null) {
cf.channel().close();
}
ctx.channel().close();
if (serverConfig.getHttpProxyAcceptHandler() != null) {
serverConfig.getHttpProxyAcceptHandler().onClose(ctx.channel());
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cf != null) {
cf.channel().close();
}
ctx.channel().close();
exceptionHandle.beforeCatch(ctx.channel(), cause);
}
private boolean authenticate(ChannelHandlerContext ctx, HttpRequest request) {
if (serverConfig.getAuthenticationProvider() != null) {
HttpProxyAuthenticationProvider authProvider = serverConfig.getAuthenticationProvider();
HttpToken httpToken = authProvider.authenticate(request.headers().get(HttpHeaderNames.PROXY_AUTHORIZATION));
if (httpToken == null) {
HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpProxyServer.UNAUTHORIZED);
response.headers().set(HttpHeaderNames.PROXY_AUTHENTICATE, authProvider.authType() + " realm=\"" + authProvider.authRealm() + "\"");
ctx.writeAndFlush(response);
return false;
}
HttpAuthContext.setToken(ctx.channel(), httpToken);
}
return true;
}
private void handleProxyData(Channel channel, Object msg, boolean isHttp) throws Exception {
if (cf == null) {
// connection异常 还有HttpContent进来,不转发
if (isHttp && !(msg instanceof HttpRequest)) {
return;
}
if (interceptPipeline == null) {
interceptPipeline = buildOnlyConnectPipeline();
interceptPipeline.setRequestProto(requestProto.copy());
}
interceptPipeline.beforeConnect(channel);
// by default we use the proxy config set in the pipeline
ProxyHandler proxyHandler = ProxyHandleFactory.build(interceptPipeline.getProxyConfig() == null ?
proxyConfig : interceptPipeline.getProxyConfig());
RequestProto requestProto = interceptPipeline.getRequestProto();
if (isHttp) {
HttpRequest httpRequest = (HttpRequest) msg;
// 检查requestProto是否有修改
RequestProto newRP = ProtoUtil.getRequestProto(httpRequest);
if (!newRP.equals(requestProto)) {
// 更新Host请求头
if ((requestProto.getSsl() && requestProto.getPort() == 443)
|| (!requestProto.getSsl() && requestProto.getPort() == 80)) {
httpRequest.headers().set(HttpHeaderNames.HOST, requestProto.getHost());
} else {
httpRequest.headers().set(HttpHeaderNames.HOST, requestProto.getHost() + ":" + requestProto.getPort());
}
}
}
/*
* 添加SSL client hello的Server Name Indication extension(SNI扩展) 有些服务器对于client
* hello不带SNI扩展时会直接返回Received fatal alert: handshake_failure(握手错误)
* 例如:https://cdn.mdn.mozilla.net/static/img/favicon32.7f3da72dcea1.png
*/
ChannelInitializer channelInitializer = isHttp ? new HttpProxyInitializer(channel, requestProto, proxyHandler)
: new TunnelProxyInitializer(channel, proxyHandler);
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(serverConfig.getProxyLoopGroup()) // 注册线程池
.channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
.handler(channelInitializer);
if (proxyHandler != null) {
// 代理服务器解析DNS和连接
bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
} else {
bootstrap.resolver(serverConfig.resolver());
}
requestList = new LinkedList();
cf = bootstrap.connect(requestProto.getHost(), requestProto.getPort());
cf.addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
future.channel().writeAndFlush(msg);
synchronized (requestList) {
requestList.forEach(obj -> future.channel().writeAndFlush(obj));
requestList.clear();
isConnect = true;
}
} else {
requestList.forEach(obj -> ReferenceCountUtil.release(obj));
requestList.clear();
getExceptionHandle().beforeCatch(channel, future.cause());
future.channel().close();
channel.close();
}
});
} else {
synchronized (requestList) {
if (isConnect) {
cf.channel().writeAndFlush(msg);
} else {
requestList.add(msg);
}
}
}
}
private HttpProxyInterceptPipeline buildPipeline() {
HttpProxyInterceptPipeline interceptPipeline = new HttpProxyInterceptPipeline(new HttpProxyIntercept() {
@Override
public void beforeRequest(Channel clientChannel, HttpRequest httpRequest, HttpProxyInterceptPipeline pipeline)
throws Exception {
handleProxyData(clientChannel, httpRequest, true);
}
@Override
public void beforeRequest(Channel clientChannel, HttpContent httpContent, HttpProxyInterceptPipeline pipeline)
throws Exception {
handleProxyData(clientChannel, httpContent, true);
}
@Override
public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse,
HttpProxyInterceptPipeline pipeline) throws Exception {
clientChannel.writeAndFlush(httpResponse);
if (HttpHeaderValues.WEBSOCKET.toString().equals(httpResponse.headers().get(HttpHeaderNames.UPGRADE))) {
// websocket转发原始报文
proxyChannel.pipeline().remove("httpCodec");
clientChannel.pipeline().remove("httpCodec");
}
}
@Override
public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpContent httpContent,
HttpProxyInterceptPipeline pipeline) throws Exception {
clientChannel.writeAndFlush(httpContent);
}
});
interceptInitializer.init(interceptPipeline);
return interceptPipeline;
}
// fix issue #186: 不拦截https报文时,暴露一个扩展点用于代理设置,并且保持一致的编程接口
private HttpProxyInterceptPipeline buildOnlyConnectPipeline() {
HttpProxyInterceptPipeline interceptPipeline = new HttpProxyInterceptPipeline(new HttpProxyIntercept());
interceptInitializer.init(interceptPipeline);
return interceptPipeline;
}
}