forked from commenthol/bandwidth-limiter-http-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.js
475 lines (425 loc) · 13 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
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
"use strict";
/*!
* bandwidth-limiter-http-proxy
* Copyright (c) 2012 <[email protected]>
* MIT Licensed
*/
var
http = require('http'),
net = require('net'),
url = require('url');
/*
* settings
*/
var
port = 8080, // port under which proxy is available
bandwidth_down = 64000, // in bps
bandwidth_up = 32000, // in bps
latency = 150; // in ms
/*
The below stated values are an approximation of what we like to test.
It is obsolete to state that in different propagation situations like
pedestrian, car at high speed, things definitely get worse.
This proxy does *not* consider any packet-loss, retransmission, etc.
On the other hand a propagation model with one user in a cell, right
next to the antenna, things should be far better.
Never use raw bandwidths as given below as packet overhead on radio-link,
mac-layer and tcp needs to be considered as well.
From http://publik.tuwien.ac.at/files/pub-et_12521.pdf
Table 1. Measured ping times (32 bytes)
Technology Bandwidth (down/up) Mean Std
GPRS 80/40 kbit/s 488 ms 146 ms
EDGE 240/120 kbit/s 504 ms 89 ms
UMTS 384/128 kbit/s 142 ms 58 ms
HSDPA 1800/384 kbit/s 91 ms 43 ms
ADSL 1000/256 kbit/s 10.9 ms 0.8 ms
*/
var settingspage = '<!doctype html><html><head><meta charset="utf-8" /><title>Proxy Settings</title><style type="text/css"> *{margin:0px;padding:3px;font-family:Sans-Serif}body{margin:0px auto;max-width:320px}ul{list-style:none}li{clear:both}section{margin:7px;border:1px solid #ccc}.r{float:right}</style></head><body><h1>Proxy Settings</h1><section><h2>Current</h2><ul><li>Bandwidth Download: <span class="r">#bandwidth_down# bps</span></li><li>Bandwidth Upload: <span class="r">#bandwidth_up# bps</span></li><li>Latency: <span class="r">#latency# ms</span></li></ul></section><section><h2>Profile</h2><ul><li><a href="/?dn=64000&up=32000&la=200">GPRS</a></li><li><a href="/?dn=128000&up=64000&la=200">EDGE</a></li><li><a href="/?dn=256000&up=96000&la=90">UMTS</a></li><li><a href="/?dn=1200000&up=256000&la=60">HSDPA</a></li><li><a href="/?dn=1200000&up=1200000&la=25">LTE 4G</a></li><li><a href="/?dn=33600&up=33600&la=100">V.34 33kbps modem</a></li><li><a href="/?dn=56000&up=48000&la=100">V.92 56kbps modem</a></li><li><a href="/?dn=64000&up=64000&la=25">ISDN</a></li><li><a href="/?dn=128000&up=128000&la=25">ISDN (2 channels)</a></li><li><a href="/?dn=384000&up=64000&la=25">DSL light</a></li><li><a href="/?dn=900000&up=256000&la=25">ADSL</a></li></ul></section><section><h2>Custom</h2><form method="get" action="/"><ul><li><label for="dn">Bandwidth Download (>1000 bps)</label><br/><input name="dn" value="#bandwidth_down#"/></li><li><label for="up">Bandwidth Upload (>1000 bps)</label><br/><input name="up" value="#bandwidth_up#"/></li><li><label for="la">Latency (<1000 ms)</label><br/><input name="la" value="#latency#"/></li><li><input type="submit"/></li></ul></form></section></body></html>';
//settingspage = require('fs').readFileSync(__dirname + '/p.html') + '';
/**
* simple logger
*/
var log = {
level: 'info',
conv: function(str, depth) {
var s = '';
depth = depth || 0;
switch (typeof(str)) {
case 'number':
return str;
case 'string':
return "'" + str + "'";
case 'object':
if (depth > 3) {
return "'[Object]'";
}
s += "{";
for (var i in str) {
//s += "\n";
s += " '"+ i +"': " + this.conv(str[i], depth+1);
if (s[s.length-1] !== ',') {
s += ',';
}
}
if (s[s.length-1] === ',') {
s = s.substring (0, s.length-1);
}
s += " },";
return s;
default:
return;
}
},
log: function (str) {
console.log(this.conv(str));
},
debug: function(str) {
if (this.level === 'debug') {
this.log({time: Date.now(), debug: str});
}
},
info: function(str) {
if (this.level === 'debug' ||
this.level === 'info') {
this.log({time: Date.now(), info: str});
}
},
warn: function(str) {
if (this.level === 'debug' ||
this.level === 'info' ||
this.level === 'warn') {
this.log({time: Date.now(), warn: str});
}
},
error: function(str) {
this.log({time: Date.now(), error: str});
}
};
/**
* calculate the delay based on bandwith
*
* @param length {number}, length of chunk
* @param bandwidth {number}, bandwidth in bit per second
* @returns {number}, delay in milliseconds required to transfer the
* `length` bytes over a network with a given `bandwidth`.
*/
function calcDelay(length, bandwidth) {
return parseInt(0.5 + length * 8 * 1000 / bandwidth, 10);
}
/**
* calculate the length of the http header
*
* @param headers {object}, contains http headers
* @returns {number}, length in bytes used for the headers
*/
function calcHeaderLength(headers) {
var
reslen = 15; // approx "HTTP/1.1 200 OK"
if (headers) {
for (var i in headers) {
reslen += i.length + headers[i].length + 4; // 4 ": " + "\r\n"
}
}
return reslen;
}
/**
* proxy connection to connection2
* delay the connection by a given latency and bandwidth
*
* @param options {object},
* bandwidth {number}, bandwidth in bit per second
* delay {number}, initial delay in milliseconds (use to add latency)
* type {string} optional, used for debugging, defaults to ''
* @param connection {object}, connection with is proxied
* Can be either a http req, res object or a socket
* @param connection2 {object}, proxied connection
* Can be either a http req, res object or a socket
*/
function proxy(options, connection, connection2) {
var
delay = 0, // single delay of one packet
quene = [], // array to store timestamps to measure the jitter
timeref = 0, // correct the time jitter between packets
type = options.type || '',
bytes = options.bytes || 0,
next;
// print out some info on throughput
function transfer(bytes, timeref) {
var
d = 0,
bw = 0;
d = Date.now() - timeref;
if (d !== 0 && bytes > 0) {
bw = parseInt(bytes * 8 * 1000 / d, 10);
log.info({type: type, duration: d, bytes: bytes, bandwidth: bw,
url: options.url});
}
}
// process quene
function procQuene(quene) {
var
now = Date.now(),
jitter,
qo;
qo = quene.shift(1) || {};
if (qo.chunk !== undefined) {
jitter = parseInt(qo.time - now, 10);
log.debug({type: type, jitter: jitter, now: now,
packetlength: qo.chunk.length});
connection2.write(qo.chunk, 'binary');
}
else {
log.debug({type: type, msg: 'event end - connection.end'});
connection2.end();
}
if (quene.length === 0) {
transfer(bytes, timeref);
}
}
// get next timestamp
function timestamp(quene, delay) {
var
timeout,
next = 0;
if (quene[quene.length-1] && quene[quene.length-1].time) {
next = quene[quene.length-1].time;
}
next += delay;
timeout = next - Date.now();
if (timeout < 0) {
timeout = delay;
next = Date.now() + delay;
}
return { time: next, timeout: timeout };
}
// data received
connection.on('data', function (chunk) {
if (timeref === 0) {
timeref = Date.now();
delay = options.delay || 0; // consider initial delay
log.debug({type: type, timeref: timeref});
} else {
delay = 0;
}
// calc the latency
delay += calcDelay(chunk.length, options.bandwidth);
bytes += chunk.length;
// add timestamp to quene
next = timestamp(quene, delay);
quene.push({time: next.time, chunk: chunk});
log.debug({type: type, data: chunk.length, next: next.time,
delay: delay});
setTimeout(function() {
procQuene(quene);
}, next.timeout);
});
// connection ends
connection.on('end', function() {
delay = options.delay || 0;
if (timeref === 0) {
timeref = Date.now();
}
next = timestamp(quene, delay);
quene.push({time: next.time});
setTimeout(function() {
procQuene(quene);
}, next.timeout);
});
}
/**
* the proxy stuff
*/
var server = http.createServer( /*options,*/ );
server.listen(port);
// http proxy
server.on('request', function(request, response) {
var
options = {}, // options object for the http proxy request
headers = {}, // headers object for the http proxy request
_url, // url parsing
bytes,
delay;
/*
// this will not work if the request is made to local servers
// therefore use url parsing and set the request
options = {
host: request.headers['host'],
};
*/
_url = url.parse(request.url);
//log.info({url: request.url});
headers = request.headers;
headers && log.debug(headers);
options = {
hostname: _url.hostname || "localhost",
port: _url.port || 80,
method: request.method,
path: _url.path || "/",
headers: headers
};
// proxy settings page
if (request.headers.host === ('localhost:' + port)) {
if ( _url.pathname === '/' ) {
var p, q, qq, v, i;
// change settings
if (_url.query) {
q = _url.query.split('&');
for (i in q) {
qq = q[i].split('=');
if (qq[1]) {
v = parseInt(qq[1], 10);
if (typeof(v) === 'number') {
switch (qq[0]) {
case 'dn':
if (v > 1000) {
bandwidth_down = v;
}
break;
case 'up':
if (v > 1000) {
bandwidth_up = v;
}
break;
case 'la':
if (qq[1] < 1000) {
latency = v;
}
break;
}
}
}
}
log.info({'new settings' : { bandwidth_down: bandwidth_down,
bandwidth_up: bandwidth_up, latency: latency } });
response.writeHead('302', {'Location': '/'});
response.end();
return;
}
p = settingspage;
p = p.replace(/#bandwidth_down#/g, bandwidth_down);
p = p.replace(/#bandwidth_up#/g, bandwidth_up);
p = p.replace(/#latency#/g, latency);
response.writeHead('200', {'Content-Type': 'text/html', 'Content-Length' : p.length });
response.end(p);
}
else {
response.end('404');
}
}
else {
// handle proxy requests
var proxyRequest = http.request(options, function(proxyResponse) {
var
bytes,
delay;
// calc the http headers length as this influences throughput on low speed networks
// length of the response header bytes is initial delay
bytes = calcHeaderLength(proxyResponse.headers);
delay = calcDelay(bytes, bandwidth_down) + latency;
response.writeHead(proxyResponse.statusCode, proxyResponse.headers);
proxy({
url: request.url,
type: 'http-res',
delay: delay,
bytes: bytes,
bandwidth: bandwidth_down },
proxyResponse, response);
});
proxyRequest.on('error', function(e) {
log.error('problem with request: ' + e.message);
response.writeHead(500, { 'content-type': 'text/html' });
response.write(e.message, 'utf-8');
response.end();
});
proxyRequest.on('timeout', function(e) {
log.error('problem with request: ' + e.message);
response.writeHead(408, { 'content-type': 'text/html' });
response.write(e.message, 'utf-8');
response.end();
});
// calc the http headers length as this influences throughput on low speed networks
bytes = calcHeaderLength(request.headers);
delay = calcDelay(bytes, bandwidth_up) + latency;
proxy({
url: request.url,
type: 'http-req',
delay: delay,
bytes: bytes,
bandwidth: bandwidth_up },
request, proxyRequest);
log.debug('-------');
}
});
// ssl tunneling http proxy
// References
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec9
// http://muffin.doit.org/docs/rfc/tunneling_ssl.html
server.on('connect', function(request, socket, head){
var
client, // client socket for SSL
host,
options = {}; // options object for client
if (request.url) {
host = request.url.match(/^(.*):(\d+$)/);
if (host.length === 3) {
options = {
host: host[1],
port: host[2]
};
} else {
socket.destroy();
return;
}
//log.info({url: request.url, protocol: 'https'});
}
// Return SSL-proxy greeting header.
socket.write('HTTP/' + request.httpVersion + ' 200 Connection established\r\n\r\n');
// Now forward SSL packets in both directions until done.
client = net.connect(options,
function() { //'connect' listener
log.debug('client connected');
});
// handle stream from origin
proxy({
url: request.url,
type: 'https-req',
delay: latency,
bandwidth: bandwidth_up },
socket, client);
socket.on('error', function() {
log.debug('socket error');
client.end();
});
socket.on('timeout', function() {
log.debug('socket timeout');
client.end();
});
socket.on('close', function() {
log.debug('socket close');
client.end();
});
// handle stream to target
proxy({
url: request.url,
type: 'https-res',
delay: latency,
bandwidth: bandwidth_down },
client, socket);
client.on('error', function() {
log.debug('client error');
socket.end();
});
client.on('timeout', function() {
log.debug('client timeout');
socket.end();
});
client.on('close', function() {
log.debug('client close');
socket.end();
});
log.debug('-------');
});
log.info("Proxy runs on port "+ port);
log.info("Download bandwidth is " + bandwidth_down + ' bps');
log.info("Upload bandwidth is " + bandwidth_up + ' bps');
log.info("Latency is " + latency + ' ms');