forked from xuduo35/simpleproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testproxy.js
362 lines (294 loc) · 10.1 KB
/
testproxy.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
var net = require('net');
var serverip = "127.0.0.1";
var serverport = 8893;
var connectproxy = 0;
var standalone = 0;
var proxyrunning = 1;
var proxypass = '123456'; // please change this password
function usage() {
console.log("usage:");
console.log("\tnode testproxy.js standalone");
console.log("\tnode testproxy.js (localhost|remoteIP)");
console.log("\tnode testproxy.js proxy");
}
if ((process.argv.length < 3) || (process.argv[2] == "--help")) {
usage();
return;
}
if (process.argv[2] == "standalone") {
standalone = 1;
} else if (process.argv[2] == "localhost") {
connectproxy = 1;
} else if (/^\d+\.\d+\.\d+\.\d+$/.test(process.argv[2])) {
connectproxy = 1;
serverip = process.argv[2];
} else if (process.argv[2] == "proxy") {
serverport += 1;
} else {
usage();
return;
}
function encrypt(data) {
for (var i = 0; i < data.length; i++) {
data[i] += -1;
}
return data;
}
function decrypt(data) {
for (var i = 0; i < data.length; i++) {
data[i] -= -1;
}
return data;
}
function startService(client, options, cryptfuncs, connopts) {
//建立到目标服务器的连接
var server = net.createConnection(options);
var client_closeflag = 0;
var server_closeflag = 0;
server.setKeepAlive(true, 15 * 1000);
client.pause();
server.pause();
//交换服务器与浏览器的数据
client.on("data", function (data) {
if (!server_closeflag) {
server.write(cryptfuncs ? cryptfuncs.encrypt(data) : data);
}
});
server.on("data", function (data) {
if (!client_closeflag) {
client.write(cryptfuncs ? cryptfuncs.decrypt(data) : data);
}
});
client.on("end", function () {
client_closeflag = 1;
server.end();
});
server.on("end", function () {
server_closeflag = 1;
client.end();
});
client.on("error", function () {
client_closeflag = 1;
server.destroy();
});
server.on("error", function () {
server_closeflag = 1;
client.destroy();
});
client.on("timeout", function () {
server.destroy();
client.destroy();
});
server.on("timeout", function () {
server.destroy();
client.destroy();
});
server.on("connect", function (socket) {
client.resume();
server.resume();
if (connopts) {
connopts.connectfunc(client, server, connopts.req, connopts.buffer);
}
});
}
function standAloneConnectAction(client, server, req, buffer) {
if (req.method == 'CONNECT') {
client.write(new Buffer("HTTP/1.1 200 Connection established\r\nConnection: close\r\n\r\n"));
} else {
server.write(buffer);
}
}
function proxyConnectAction(client, server, req, buffer) {
if (req.method == 'CONNECT') {
client.write(encrypt(new Buffer("HTTP/1.1 200 Connection established\r\nConnection: close\r\n\r\n")));
} else {
server.write(buffer);
}
}
if (!connectproxy) {
net.createServer(function(client){
var oppass = '';
var fullmessage = 0;
client.on('data', function (data) {
oppass += data;
/*
* it's easy to use telnet for start/stop proxy server on VPS from local PC
* telnet your_server_ip 8000
* to start, input 'O:123456'
* to stop, 'C:123456'
*/
if (!fullmessage && (oppass.length >= 8)) {
fullmessage = 1;
var op = oppass.substr(0, 1);
var pass = oppass.substr(2).replace(/(\r|\n)+$/g, "");
if (pass == proxypass) {
if (op == "O") {
proxyrunning = 1;
console.log('start server successfully!');
client.write('start server successfully!\r\n', function(e){
client.end();
});
} else if (op == "C") {
proxyrunning = 0;
console.log('stop server successfully!');
client.write('stop server successfully!\r\n', function(e){
client.end();
});
}
} else {
console.log('authentication failed!');
client.write('authentication failed!\r\n', function(e){
client.end();
});
}
}
});
}).listen(8000);
}
//在本地创建一个server监听本地serverport端口
net.createServer({ allowHalfOpen: true}, function (client) {
if (connectproxy) {
startService(
client,
{ allowHalfOpen: true, port: serverport + 1, host: serverip},
{ 'encrypt': encrypt, 'decrypt': decrypt },
null
);
return;
}
if (!proxyrunning) {
client.destroy();
console.log("proxy not running, please start it first!");
return;
}
client.setKeepAlive(true, 15 * 1000);
client.on("end", function () {
client.end();
});
client.on("error", function () {
client.destroy();
});
client.on("timeout", function () {
client.destroy();
});
//首先监听浏览器的数据发送事件,直到收到的数据包含完整的http请求头
var buffer = new Buffer(0);
client.on('data', function (data) {
buffer = buffer_add(buffer, data);
if (buffer_find_body(buffer) < 0) {
return;
}
var req = parse_request(buffer);
if (!req) {
return;
}
client.removeAllListeners('data');
client.removeAllListeners('end');
client.removeAllListeners('error');
client.removeAllListeners('timeout');
relay_connection(req);
});
//从http请求头部取得请求信息后,继续监听浏览器发送数据,同时连接目标服务器,并把目标服务器的数据传给浏览器
function relay_connection(req) {
console.log(req.method + ' ' + req.host + ':' + req.port);
//如果请求不是CONNECT方法(GET, POST),那么替换掉头部的一些东西
if (req.method != 'CONNECT') {
//先从buffer中取出头部
var _body_pos = buffer_find_body(buffer);
if (_body_pos < 0) _body_pos = buffer.length;
var header = buffer.slice(0, _body_pos).toString('utf8');
//替换connection头
header = header.replace(/(proxy-)?connection\:.+\r\n/ig, '')
.replace(/Keep-Alive\:.+\r\n/i, '')
.replace("\r\n", '\r\nConnection: close\r\n');
//替换网址格式(去掉域名部分)
if (req.httpVersion == '1.1') {
var url = req.path.replace(/http\:\/\/[^\/]+/, '');
if (url.path != url) header = header.replace(req.path, url);
}
buffer = buffer_add(new Buffer(header, 'utf8'), buffer.slice(_body_pos));
}
// second proxy mode
if (!standalone) {
startService(
client,
{ allowHalfOpen: true, port: req.port, host: req.host},
{ 'encrypt': decrypt, 'decrypt': encrypt },
{ 'connectfunc': proxyConnectAction, 'req': req, 'buffer': buffer }
);
return;
}
// standalone proxy mode
startService(
client,
{ allowHalfOpen: true, port: req.port, host: req.host},
null,
{ 'connectfunc': standAloneConnectAction, 'req': req, 'buffer': buffer }
);
}
}).listen(serverport);
console.log('Proxy server running at ' + serverip + ':' + serverport);
//处理各种错误
process.on('uncaughtException', function (err) {
console.log("\nError!!!!");
console.log(err);
});
/*
从请求头部取得请求详细信息
如果是 CONNECT 方法,那么会返回 { method,host,port,httpVersion}
如果是 GET/POST 方法,那么返回 { metod,host,port,path,httpVersion}
*/
function parse_request(buffer) {
var s = buffer.toString('utf8');
var method = s.split('\n')[0].match(/^([A-Z]+)\s/)[1];
if (method == 'CONNECT') {
var arr = s.match(/^([A-Z]+)\s([^\:\s]+)\:(\d+)\sHTTP\/(\d.\d)/);
if (arr && arr[1] && arr[2] && arr[3] && arr[4])
return {
method: arr[1],
host: arr[2],
port: arr[3],
httpVersion: arr[4]
};
} else {
var arr = s.match(/^([A-Z]+)\s([^\s]+)\sHTTP\/(\d.\d)/);
if (arr && arr[1] && arr[2] && arr[3]) {
var host = s.match(/Host\:\s+([^\n\s\r]+)/)[1];
if (host) {
var _p = host.split(':', 2);
return {
method: arr[1],
host: _p[0],
port: _p[1] ? _p[1] : 80,
path: arr[2],
httpVersion: arr[3]
};
}
}
}
return false;
}
/*
两个buffer对象加起来
*/
function buffer_add(buf1, buf2) {
// second proxy mode
if (!standalone) {
decrypt(buf2);
}
var re = new Buffer(buf1.length + buf2.length);
buf1.copy(re);
buf2.copy(re, buf1.length);
return re;
}
/*
从缓存中找到头部结束标记("\r\n\r\n")的位置
*/
function buffer_find_body(b) {
for (var i = 0, len = b.length - 3; i < len; i++) {
if (b[i] == 0x0d && b[i + 1] == 0x0a && b[i + 2] == 0x0d && b[i + 3] == 0x0a) {
return i + 4;
}
}
return -1;
}