/
HttpProxyServerHandle.java
240 lines (224 loc) · 9.15 KB
/
HttpProxyServerHandle.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
package lee.study.proxyee.handler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpVersion;
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.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import lee.study.proxyee.crt.CertPool;
import lee.study.proxyee.exception.HttpProxyExceptionHandle;
import lee.study.proxyee.intercept.HttpProxyIntercept;
import lee.study.proxyee.intercept.HttpProxyInterceptInitializer;
import lee.study.proxyee.intercept.HttpProxyInterceptPipeline;
import lee.study.proxyee.proxy.ProxyConfig;
import lee.study.proxyee.proxy.ProxyHandleFactory;
import lee.study.proxyee.server.HttpProxyServer;
import lee.study.proxyee.server.HttpProxyServerConfig;
import lee.study.proxyee.util.ProtoUtil;
import lee.study.proxyee.util.ProtoUtil.RequestProto;
public class HttpProxyServerHandle extends ChannelInboundHandlerAdapter {
private ChannelFuture cf;
private String host;
private int port;
private boolean isSsl = false;
private int status = 0;
private HttpProxyServerConfig serverConfig;
private ProxyConfig proxyConfig;
private HttpProxyInterceptInitializer interceptInitializer;
private HttpProxyInterceptPipeline interceptPipeline;
private HttpProxyExceptionHandle exceptionHandle;
private List requestList;
private boolean isConnect;
public HttpProxyServerConfig getServerConfig() {
return serverConfig;
}
public HttpProxyInterceptPipeline getInterceptPipeline() {
return interceptPipeline;
}
public HttpProxyExceptionHandle getExceptionHandle() {
return exceptionHandle;
}
public HttpProxyServerHandle(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 requestProto = ProtoUtil.getRequestProto(request);
if (requestProto == null) { //bad request
ctx.channel().close();
return;
}
status = 1;
this.host = requestProto.getHost();
this.port = requestProto.getPort();
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");
return;
}
}
interceptPipeline = buildPiepeline();
interceptPipeline.setRequestProto(new RequestProto(host, port, isSsl));
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的握手处理
ByteBuf byteBuf = (ByteBuf) msg;
if (byteBuf.getByte(0) == 22) {//ssl握手
isSsl = true;
SslContext sslCtx = SslContextBuilder
.forServer(serverConfig.getServerPriKey(), CertPool.getCert(this.host, 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();
}
@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 void handleProxyData(Channel channel, Object msg, boolean isHttp)
throws Exception {
if (cf == null) {
if (isHttp && !(msg instanceof HttpRequest)) { //connection异常 还有HttpContent进来,不转发
return;
}
ProxyHandler proxyHandler = ProxyHandleFactory.build(proxyConfig);
/*
添加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
*/
RequestProto requestProto = new RequestProto(host, port, isSsl);
ChannelInitializer channelInitializer =
isHttp ? new HttpProxyInitializer(channel, requestProto, proxyHandler)
: new TunnelProxyInitializer(channel, proxyHandler);
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(serverConfig.getLoopGroup()) // 注册线程池
.channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
.handler(channelInitializer);
if (proxyConfig != null) {
//代理服务器解析DNS和连接
bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
}
requestList = new LinkedList();
cf = bootstrap.connect(host, port);
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 {
future.channel().close();
channel.close();
}
});
} else {
synchronized (requestList) {
if (isConnect) {
cf.channel().writeAndFlush(msg);
} else {
requestList.add(msg);
}
}
}
}
private HttpProxyInterceptPipeline buildPiepeline() {
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;
}
}