/
https-proxy.js
59 lines (46 loc) · 1.42 KB
/
https-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
const net = require('net')
const parse = require('./utils/parse')
module.exports = function (req, clientSocket, bodyhead, cb) {
const [host, port] = parse.getHostPortFromString(req.url, 443);
const shouldContinueProxying = cb({
req,
host,
port,
socket: clientSocket,
head: bodyhead,
})
// stop the proxy if this returns false
if (!shouldContinueProxying) {
return
}
const proxySocket = new net.Socket();
clientSocket.setNoDelay(true)
proxySocket.setNoDelay(true)
proxySocket.connect(port, host, function (err) {
if (err) {
clientSocket.write("HTTP/" + req.httpVersion + " 500 Connection error\r\n\r\n");
clientSocket.end();
return
}
clientSocket.write("HTTP/" + req.httpVersion + " 200 Connection established\r\n\r\n");
proxySocket.write(bodyhead);
});
proxySocket.on('data', function (chunk) {
clientSocket.write(chunk);
});
proxySocket.on('end', function () {
clientSocket.end();
});
proxySocket.on('error', function (err) {
clientSocket.destroy(err)
});
clientSocket.on('data', function (chunk) {
proxySocket.write(chunk);
});
clientSocket.on('end', function () {
proxySocket.end();
});
clientSocket.on('error', function (err) {
proxySocket.destroy(err);
});
}