-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
138 lines (105 loc) · 3.35 KB
/
server.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
const http = require('http');
const url = require('url');
const lib = require('./lib');
const EventEmitter = require('events');
const net = require('net');
const serializeError = require('serialize-error');
const ee = new EventEmitter();
const keepAliveAgent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 50 * 1000,
});
const CONF = require('./config.json');
const server = http.createServer(function (req, res) {
if (req.url === '/proxyhttp') {
let reqcfgRaw = req.headers.reqcfg;
if (!reqcfgRaw) {
res.statusCode = 500;
res.end(JSON.stringify({
msg: 'should provide reqcfg'
}))
return;
}
lib.decompressCfg(reqcfgRaw, function (err, reqcfg) {
reqcfg.agent = keepAliveAgent;
var proxyReq = http.request(reqcfg);
proxyReq.on('response', function (remoteRes) {
res.writeHead(remoteRes.statusCode, remoteRes.headers);
remoteRes.pipe(res);
});
req.pipe(proxyReq);
proxyReq.on('error', function (err) {
let errstr = JSON.stringify(serializeError(err), null, 4);
if ('ENOTFOUND' == err.code) {
res.writeHead(404);
} else {
res.writeHead(500);
}
res.end(errstr);
});
});
} else if (req.url === '/httpsconnect') {
let conncfgRaw = Buffer.from(req.headers.conncfg, 'base64');
let conncfg = JSON.parse(conncfgRaw);
let uid = req.headers.uid;
if (!conncfg) {
res.statusCode = 500;
res.end('should provide reqcfg');
return;
}
let target = net.connect(conncfg);
let connected = false;
let err = null;
target.on('connect', function () {
connected = true;
res.writeHead(200, {});
res._send('');
});
target.on('data', function (data) {
res.write(data);
});
ee.on(uid, function (data) {
target.write(data);
});
target.on('close', function () {
if (err) {
let errstr = JSON.stringify(serializeError(err), null, 4);
res.end(errstr);
} else {
res.end();
}
ee.removeAllListeners(uid);
});
target.on('error', function (_err) {
err = _err;
if (!connected) {
res.writeHead(500);
}
});
} else if (req.url === '/httpsup') {
let uid = req.headers.uid;
if (!uid) {
res.statusCode = 500;
res.end('should provide uid');
return;
}
req.on('data', function (data) {
ee.emit(uid, data);
});
req.on('end', function () {
res.statusCode = 200;
res.end();
});
} else {
res.end('asd');
}
});
let port;
if (process.env.PORT) {
port = parseInt(process.env.PORT);
} else {
port = parseInt(CONF.remote_port);
}
server.listen(port, '0.0.0.0', function () {
console.log(`listening on ${port}`);
});