/
proxy_server.js
197 lines (161 loc) · 4.67 KB
/
proxy_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
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
// inspired by https://github.com/asluchevskiy/http-to-socks-proxy
const util = require('util');
const url = require('url');
const http = require('http');
const fs = require('fs');
const Socks = require('socks');
const { logger } = require('./logger');
function randomElement(array) {
return array[Math.floor(Math.random() * array.length)];
}
function getProxyObject(host, port, login, password) {
return {
ipaddress: host,
port: parseInt(port, 10),
type: 5,
authentication: { username: login || '', password: password || '' },
};
}
function parseProxyLine(line) {
const proxyInfo = line.split(':');
if (proxyInfo.length !== 4 && proxyInfo.length !== 2) {
throw new Error(`Incorrect proxy line: ${line}`);
}
return getProxyObject.apply(this, proxyInfo);
}
function requestListener(getProxyInfo, request, response) {
logger.info(`request: ${request.url}`);
const proxy = getProxyInfo();
const ph = url.parse(request.url);
const socksAgent = new Socks.Agent({
proxy,
target: { host: ph.hostname, port: ph.port },
});
const options = {
port: ph.port,
hostname: ph.hostname,
method: request.method,
path: ph.path,
headers: request.headers,
agent: socksAgent,
};
const proxyRequest = http.request(options);
request.on('error', (err) => {
logger.error(`${err.message}`);
proxyRequest.destroy(err);
});
proxyRequest.on('error', (error) => {
logger.error(`${error.message} on proxy ${proxy.ipaddress}:${proxy.port}`);
response.writeHead(500);
response.end('Connection error\n');
});
proxyRequest.on('response', (proxyResponse) => {
proxyResponse.pipe(response);
response.writeHead(proxyResponse.statusCode, proxyResponse.headers);
});
request.pipe(proxyRequest);
}
function connectListener(getProxyInfo, request, socketRequest, head) {
logger.info(`connect: ${request.url}`);
const proxy = getProxyInfo();
const ph = url.parse(`http://${request.url}`);
const { hostname: host, port } = ph;
const options = {
proxy,
target: { host, port },
command: 'connect',
};
let socket;
socketRequest.on('error', (err) => {
logger.error(`${err.message}`);
if (socket) {
socket.destroy(err);
}
});
Socks.createConnection(options, (error, _socket) => {
socket = _socket;
if (error) {
// error in SocksSocket creation
logger.error(`${error.message} connection creating on ${proxy.ipaddress}:${proxy.port}`);
socketRequest.write(`HTTP/${request.httpVersion} 500 Connection error\r\n\r\n`);
return;
}
socket.on('error', (err) => {
logger.error(`${err.message}`);
socketRequest.destroy(err);
});
// tunneling to the host
socket.pipe(socketRequest);
socketRequest.pipe(socket);
socket.write(head);
socketRequest.write(`HTTP/${request.httpVersion} 200 Connection established\r\n\r\n`);
socket.resume();
});
}
function ProxyServer(options) {
// TODO: start point
http.Server.call(this, () => {});
this.proxyList = [];
if (options.socks) {
// stand alone proxy loging
this.loadProxy(options.socks);
} else if (options.socksList) {
// proxy list loading
this.loadProxyFile(options.socksList);
if (options.proxyListReloadTimeout) {
setInterval(
() => {
this.loadProxyFile(options.socksList);
},
options.proxyListReloadTimeout * 1000
);
}
}
this.addListener(
'request',
requestListener.bind(null, () => randomElement(this.proxyList))
);
this.addListener(
'connect',
connectListener.bind(null, () => randomElement(this.proxyList))
);
}
util.inherits(ProxyServer, http.Server);
ProxyServer.prototype.loadProxy = function loadProxy(proxyLine) {
try {
this.proxyList.push(parseProxyLine(proxyLine));
} catch (ex) {
logger.error(ex.message);
}
};
ProxyServer.prototype.loadProxyFile = function loadProxyFile(fileName) {
const self = this;
logger.info(`Loading proxy list from file: ${fileName}`);
fs.readFile(fileName, (err, data) => {
if (err) {
logger.error(
`Impossible to read the proxy file : ${fileName} error : ${err.message}`
);
return;
}
const lines = data.toString().split('\n');
const proxyList = [];
for (let i = 0; i < lines.length; i += 1) {
if (!(lines[i] !== '' && lines[i].charAt(0) !== '#')) {
try {
proxyList.push(parseProxyLine(lines[i]));
} catch (ex) {
logger.error(ex.message);
}
}
}
self.proxyList = proxyList;
});
};
module.exports = {
createServer: options => new ProxyServer(options),
requestListener,
connectListener,
getProxyObject,
parseProxyLine,
};