forked from alibaba/anyproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.js
387 lines (343 loc) · 12 KB
/
proxy.js
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
'use strict';
const http = require('http'),
https = require('https'),
async = require('async'),
color = require('colorful'),
certMgr = require('./lib/certMgr'),
Recorder = require('./lib/recorder'),
logUtil = require('./lib/log'),
util = require('./lib/util'),
events = require('events'),
co = require('co'),
WebInterface = require('./lib/webInterface'),
wsServerMgr = require('./lib/wsServerMgr'),
ThrottleGroup = require('stream-throttle').ThrottleGroup;
// const memwatch = require('memwatch-next');
// setInterval(() => {
// console.log(process.memoryUsage());
// const rss = Math.ceil(process.memoryUsage().rss / 1000 / 1000);
// console.log('Program is using ' + rss + ' mb of Heap.');
// }, 1000);
// memwatch.on('stats', (info) => {
// console.log('gc !!');
// console.log(process.memoryUsage());
// const rss = Math.ceil(process.memoryUsage().rss / 1000 / 1000);
// console.log('GC !! Program is using ' + rss + ' mb of Heap.');
// // var heapUsed = Math.ceil(process.memoryUsage().heapUsed / 1000);
// // console.log("Program is using " + heapUsed + " kb of Heap.");
// // console.log(info);
// });
const T_TYPE_HTTP = 'http',
T_TYPE_HTTPS = 'https',
DEFAULT_TYPE = T_TYPE_HTTP;
const PROXY_STATUS_INIT = 'INIT';
const PROXY_STATUS_READY = 'READY';
const PROXY_STATUS_CLOSED = 'CLOSED';
/**
*
* @class ProxyCore
* @extends {events.EventEmitter}
*/
class ProxyCore extends events.EventEmitter {
/**
* Creates an instance of ProxyCore.
*
* @param {object} config - configs
* @param {number} config.port - port of the proxy server
* @param {object} [config.rule=null] - rule module to use
* @param {string} [config.type=http] - type of the proxy server, could be 'http' or 'https'
* @param {strign} [config.hostname=localhost] - host name of the proxy server, required when this is an https proxy
* @param {number} [config.throttle] - speed limit in kb/s
* @param {boolean} [config.forceProxyHttps=false] - if proxy all https requests
* @param {boolean} [config.silent=false] - if keep the console silent
* @param {boolean} [config.dangerouslyIgnoreUnauthorized=false] - if ignore unauthorized server response
* @param {object} [config.recorder] - recorder to use
* @param {boolean} [config.wsIntercept] - whether intercept websocket
*
* @memberOf ProxyCore
*/
constructor(config) {
super();
config = config || {};
this.status = PROXY_STATUS_INIT;
this.proxyPort = config.port;
this.proxyType = /https/i.test(config.type || DEFAULT_TYPE) ? T_TYPE_HTTPS : T_TYPE_HTTP;
this.proxyHostName = config.hostname || 'localhost';
this.recorder = config.recorder;
if (parseInt(process.versions.node.split('.')[0], 10) < 4) {
throw new Error('node.js >= v4.x is required for anyproxy');
} else if (config.forceProxyHttps && !certMgr.ifRootCAFileExists()) {
logUtil.printLog('You can run `anyproxy-ca` to generate one root CA and then re-run this command');
throw new Error('root CA not found. Please run `anyproxy-ca` to generate one first.');
} else if (this.proxyType === T_TYPE_HTTPS && !config.hostname) {
throw new Error('hostname is required in https proxy');
} else if (!this.proxyPort) {
throw new Error('proxy port is required');
} else if (!this.recorder) {
throw new Error('recorder is required');
} else if (config.forceProxyHttps && config.rule && config.rule.beforeDealHttpsRequest) {
logUtil.printLog('both "-i(--intercept)" and rule.beforeDealHttpsRequest are specified, the "-i" option will be ignored.', logUtil.T_WARN);
config.forceProxyHttps = false;
}
this.httpProxyServer = null;
this.requestHandler = null;
// copy the rule to keep the original proxyRule independent
this.proxyRule = config.rule || {};
if (config.silent) {
logUtil.setPrintStatus(false);
}
if (config.throttle) {
logUtil.printLog('throttle :' + config.throttle + 'kb/s');
const rate = parseInt(config.throttle, 10);
if (rate < 1) {
throw new Error('Invalid throttle rate value, should be positive integer');
}
global._throttle = new ThrottleGroup({ rate: 1024 * rate }); // rate - byte/sec
}
// init recorder
this.recorder = config.recorder;
// init request handler
const RequestHandler = util.freshRequire('./requestHandler');
this.requestHandler = new RequestHandler({
wsIntercept: config.wsIntercept,
httpServerPort: config.port, // the http server port for http proxy
forceProxyHttps: !!config.forceProxyHttps,
dangerouslyIgnoreUnauthorized: !!config.dangerouslyIgnoreUnauthorized
}, this.proxyRule, this.recorder);
}
/**
* manage all created socket
* for each new socket, we put them to a map;
* if the socket is closed itself, we remove it from the map
* when the `close` method is called, we'll close the sockes before the server closed
*
* @param {Socket} the http socket that is creating
* @returns undefined
* @memberOf ProxyCore
*/
handleExistConnections(socket) {
const self = this;
self.socketIndex ++;
const key = `socketIndex_${self.socketIndex}`;
self.socketPool[key] = socket;
// if the socket is closed already, removed it from pool
socket.on('close', () => {
delete self.socketPool[key];
});
}
/**
* start the proxy server
*
* @returns ProxyCore
*
* @memberOf ProxyCore
*/
start() {
const self = this;
self.socketIndex = 0;
self.socketPool = {};
if (self.status !== PROXY_STATUS_INIT) {
throw new Error('server status is not PROXY_STATUS_INIT, can not run start()');
}
async.series(
[
//creat proxy server
function (callback) {
if (self.proxyType === T_TYPE_HTTPS) {
certMgr.getCertificate(self.proxyHostName, (err, keyContent, crtContent) => {
if (err) {
callback(err);
} else {
self.httpProxyServer = https.createServer({
key: keyContent,
cert: crtContent
}, self.requestHandler.userRequestHandler);
callback(null);
}
});
} else {
self.httpProxyServer = http.createServer(self.requestHandler.userRequestHandler);
callback(null);
}
},
//handle CONNECT request for https over http
function (callback) {
self.httpProxyServer.on('connect', self.requestHandler.connectReqHandler);
callback(null);
},
function (callback) {
wsServerMgr.getWsServer({
server: self.httpProxyServer,
connHandler: self.requestHandler.wsHandler
});
// remember all sockets, so we can destory them when call the method 'close';
self.httpProxyServer.on('connection', (socket) => {
self.handleExistConnections.call(self, socket);
});
callback(null);
},
//start proxy server
function (callback) {
self.httpProxyServer.listen(self.proxyPort);
callback(null);
},
],
//final callback
(err, result) => {
if (!err) {
const tipText = (self.proxyType === T_TYPE_HTTP ? 'Http' : 'Https') + ' proxy started on port ' + self.proxyPort;
logUtil.printLog(color.green(tipText));
if (self.webServerInstance) {
const webTip = 'web interface started on port ' + self.webServerInstance.webPort;
logUtil.printLog(color.green(webTip));
}
let ruleSummaryString = '';
const ruleSummary = this.proxyRule.summary;
if (ruleSummary) {
co(function *() {
if (typeof ruleSummary === 'string') {
ruleSummaryString = ruleSummary;
} else {
ruleSummaryString = yield ruleSummary();
}
logUtil.printLog(color.green(`Active rule is: ${ruleSummaryString}`));
});
}
self.status = PROXY_STATUS_READY;
self.emit('ready');
} else {
const tipText = 'err when start proxy server :(';
logUtil.printLog(color.red(tipText), logUtil.T_ERR);
logUtil.printLog(err, logUtil.T_ERR);
self.emit('error', {
error: err
});
}
}
);
return self;
}
/**
* close the proxy server
*
* @returns ProxyCore
*
* @memberOf ProxyCore
*/
close() {
// clear recorder cache
return new Promise((resolve) => {
if (this.httpProxyServer) {
// destroy conns & cltSockets when closing proxy server
for (const connItem of this.requestHandler.conns) {
const key = connItem[0];
const conn = connItem[1];
logUtil.printLog(`destorying https connection : ${key}`);
conn.end();
}
for (const cltSocketItem of this.requestHandler.cltSockets) {
const key = cltSocketItem[0];
const cltSocket = cltSocketItem[1];
logUtil.printLog(`endding https cltSocket : ${key}`);
cltSocket.end();
}
if (this.socketPool) {
for (const key in this.socketPool) {
this.socketPool[key].destroy();
}
}
this.httpProxyServer.close((error) => {
if (error) {
console.error(error);
logUtil.printLog(`proxy server close FAILED : ${error.message}`, logUtil.T_ERR);
} else {
this.httpProxyServer = null;
this.status = PROXY_STATUS_CLOSED;
logUtil.printLog(`proxy server closed at ${this.proxyHostName}:${this.proxyPort}`);
}
resolve(error);
});
} else {
resolve();
}
})
}
}
/**
* start proxy server as well as recorder and webInterface
*/
class ProxyServer extends ProxyCore {
/**
*
* @param {object} config - config
* @param {object} [config.webInterface] - config of the web interface
* @param {boolean} [config.webInterface.enable=false] - if web interface is enabled
* @param {number} [config.webInterface.webPort=8002] - http port of the web interface
*/
constructor(config) {
// prepare a recorder
const recorder = new Recorder();
const configForCore = Object.assign({
recorder,
}, config);
super(configForCore);
this.proxyWebinterfaceConfig = config.webInterface;
this.recorder = recorder;
this.webServerInstance = null;
}
start() {
// start web interface if neeeded
if (this.proxyWebinterfaceConfig && this.proxyWebinterfaceConfig.enable) {
this.webServerInstance = new WebInterface(this.proxyWebinterfaceConfig, this.recorder);
// start web server
this.webServerInstance.start().then(() => {
// start proxy core
super.start();
})
.catch((e) => {
this.emit('error', e);
});
} else {
super.start();
}
}
close() {
return new Promise((resolve, reject) => {
super.close()
.then((error) => {
if (error) {
resolve(error);
}
});
if (this.recorder) {
logUtil.printLog('clearing cache file...');
this.recorder.clear();
}
const tmpWebServer = this.webServerInstance;
this.recorder = null;
this.webServerInstance = null;
if (tmpWebServer) {
logUtil.printLog('closing webserver...');
tmpWebServer.close((error) => {
if (error) {
console.error(error);
logUtil.printLog(`proxy web server close FAILED: ${error.message}`, logUtil.T_ERR);
} else {
logUtil.printLog(`proxy web server closed at ${this.proxyHostName} : ${this.webPort}`);
}
resolve(error);
})
} else {
resolve(null);
}
});
}
}
module.exports.ProxyCore = ProxyCore;
module.exports.ProxyServer = ProxyServer;
module.exports.ProxyRecorder = Recorder;
module.exports.ProxyWebServer = WebInterface;
module.exports.utils = {
systemProxyMgr: require('./lib/systemProxyMgr'),
certMgr,
};