HttpProxyServer.java
8.3 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
package com.github.monkeywie.proxyee.server;
import com.github.monkeywie.proxyee.crt.CertPool;
import com.github.monkeywie.proxyee.crt.CertUtil;
import com.github.monkeywie.proxyee.exception.HttpProxyExceptionHandle;
import com.github.monkeywie.proxyee.handler.HttpProxyServerHandler;
import com.github.monkeywie.proxyee.intercept.HttpProxyInterceptInitializer;
import com.github.monkeywie.proxyee.proxy.ProxyConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
public class HttpProxyServer {
private final static InternalLogger log = InternalLoggerFactory.getInstance(HttpProxyServer.class);
//http代理隧道握手成功
public final static HttpResponseStatus SUCCESS = new HttpResponseStatus(200,
"Connection established");
public final static HttpResponseStatus UNAUTHORIZED = new HttpResponseStatus(407,
"Unauthorized");
private HttpProxyCACertFactory caCertFactory;
private HttpProxyServerConfig serverConfig;
private HttpProxyInterceptInitializer proxyInterceptInitializer;
private HttpProxyExceptionHandle httpProxyExceptionHandle;
private ProxyConfig proxyConfig;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private void init() {
if (serverConfig == null) {
serverConfig = new HttpProxyServerConfig();
}
serverConfig.setProxyLoopGroup(new NioEventLoopGroup(serverConfig.getProxyGroupThreads()));
if (serverConfig.isHandleSsl()) {
try {
serverConfig.setClientSslCtx(
SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
.build());
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
X509Certificate caCert;
PrivateKey caPriKey;
if (caCertFactory == null) {
caCert = CertUtil.loadCert(classLoader.getResourceAsStream("ca.crt"));
caPriKey = CertUtil.loadPriKey(classLoader.getResourceAsStream("ca_private.der"));
} else {
caCert = caCertFactory.getCACert();
caPriKey = caCertFactory.getCAPriKey();
}
//读取CA证书使用者信息
serverConfig.setIssuer(CertUtil.getSubject(caCert));
//读取CA证书有效时段(server证书有效期超出CA证书的,在手机上会提示证书不安全)
serverConfig.setCaNotBefore(caCert.getNotBefore());
serverConfig.setCaNotAfter(caCert.getNotAfter());
//CA私钥用于给动态生成的网站SSL证书签证
serverConfig.setCaPriKey(caPriKey);
//生产一对随机公私钥用于网站SSL证书动态创建
KeyPair keyPair = CertUtil.genKeyPair();
serverConfig.setServerPriKey(keyPair.getPrivate());
serverConfig.setServerPubKey(keyPair.getPublic());
} catch (Exception e) {
serverConfig.setHandleSsl(false);
log.warn("SSL init fail,cause:" + e.getMessage());
}
}
if (proxyInterceptInitializer == null) {
proxyInterceptInitializer = new HttpProxyInterceptInitializer();
}
if (httpProxyExceptionHandle == null) {
httpProxyExceptionHandle = new HttpProxyExceptionHandle();
}
}
public HttpProxyServer serverConfig(HttpProxyServerConfig serverConfig) {
this.serverConfig = serverConfig;
return this;
}
public HttpProxyServer proxyInterceptInitializer(
HttpProxyInterceptInitializer proxyInterceptInitializer) {
this.proxyInterceptInitializer = proxyInterceptInitializer;
return this;
}
public HttpProxyServer httpProxyExceptionHandle(
HttpProxyExceptionHandle httpProxyExceptionHandle) {
this.httpProxyExceptionHandle = httpProxyExceptionHandle;
return this;
}
public HttpProxyServer proxyConfig(ProxyConfig proxyConfig) {
this.proxyConfig = proxyConfig;
return this;
}
public HttpProxyServer caCertFactory(HttpProxyCACertFactory caCertFactory) {
this.caCertFactory = caCertFactory;
return this;
}
public void start(int port) {
start(null, port);
}
public void start(String ip, int port) {
try {
ChannelFuture channelFuture = doBind(ip, port);
CountDownLatch latch = new CountDownLatch(1);
channelFuture.addListener(future -> {
if (future.cause() != null) {
httpProxyExceptionHandle.startCatch(future.cause());
}
latch.countDown();
});
latch.await();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
httpProxyExceptionHandle.startCatch(e);
} finally {
close();
}
}
public CompletionStage<Void> startAsync(int port) {
return startAsync(null, port);
}
public CompletionStage<Void> startAsync(String ip, int port) {
ChannelFuture channelFuture = doBind(ip, port);
CompletableFuture<Void> future = new CompletableFuture<>();
channelFuture.addListener(start -> {
if (start.isSuccess()) {
future.complete(null);
shutdownHook();
} else {
future.completeExceptionally(start.cause());
close();
}
});
return future;
}
private ChannelFuture doBind(String ip, int port) {
init();
bossGroup = new NioEventLoopGroup(serverConfig.getBossGroupThreads());
workerGroup = new NioEventLoopGroup(serverConfig.getWorkerGroupThreads());
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
// .option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.DEBUG))
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast("httpCodec", new HttpServerCodec());
ch.pipeline().addLast("serverHandle",
new HttpProxyServerHandler(serverConfig, proxyInterceptInitializer, proxyConfig,
httpProxyExceptionHandle));
}
});
return ip == null ? bootstrap.bind(port) : bootstrap.bind(ip, port);
}
/**
* 释放资源
*/
public void close() {
EventLoopGroup eventLoopGroup = serverConfig.getProxyLoopGroup();
if (!(eventLoopGroup.isShutdown() || eventLoopGroup.isShuttingDown())) {
eventLoopGroup.shutdownGracefully();
}
if (!(bossGroup.isShutdown() || bossGroup.isShuttingDown())) {
bossGroup.shutdownGracefully();
}
if (!(workerGroup.isShutdown() || workerGroup.isShuttingDown())) {
workerGroup.shutdownGracefully();
}
CertPool.clear();
}
/**
* 注册JVM关闭的钩子以释放资源
*/
public void shutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(this::close, "Server Shutdown Thread"));
}
}