-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathproxy.js
executable file
·90 lines (74 loc) · 2.07 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
#!/usr/bin/env node
"use strict";
const http = require('http');
const net = require('net');
const socks = require('socks');
const url = require('url');
const SOCKS_HOST = "127.0.0.1";
const SOCKS_PORT = 1080;
const BYPASS_HEADERS = ["connection", "proxy-connection", "transfer-encoding"];
function prepare_headers(headers) {
for (let key of BYPASS_HEADERS) {
delete headers[key];
}
return headers;
}
function doProxy(sReq, sRes) {
console.log('Proxy', sReq.url);
let sUrl = url.parse(sReq.url);
let cOptions = {
method : sReq.method,
hostname : sUrl.hostname,
port : sUrl.port || 80,
path : sUrl.path,
headers : prepare_headers(sReq.headers),
agent : new socks.Agent({
proxy: {
ipaddress: SOCKS_HOST,
port: SOCKS_PORT,
type: 5,
}}),
};
let cReq = http.request(cOptions);
cReq.on('response', (cRes) => {
sRes.writeHead(cRes.statusCode, cRes.statusMessage,
prepare_headers(cRes.headers));
cRes.pipe(sRes);
});
cReq.on('error', (err) => {
console.error(err);
sRes.end();
});
sReq.pipe(cReq);
}
function doTunnel(sReq, sSock) {
console.log('Tunnel', sReq.url);
let sUrl = url.parse(`http://${sReq.url}/`);
let dOpts = {
proxy: {
ipaddress: SOCKS_HOST,
port: SOCKS_PORT,
type: 5,
},
target: {
host: sUrl.hostname,
port: sUrl.port || 80,
},
};
socks.createConnection(dOpts, (err, dSock, info) => {
if (err) {
console.error(err);
return sSock.end();
}
sSock.write('HTTP/1.1 200 Connection Established\r\n\r\n');
dSock.pipe(sSock);
sSock.pipe(dSock);
sSock.on('close', () => dSock.end());
dSock.on('close', () => sSock.end());
dSock.resume();
});
}
let httpd = http.createServer();
httpd.on('request', doProxy);
httpd.on('connect', doTunnel);
httpd.listen(8080);