Repository navigation
Expand file tree
/
Copy pathproxy.js
More file actions
671 lines (637 loc) · 21.4 KB
/
Copy pathproxy.js
File metadata and controls
671 lines (637 loc) · 21.4 KB
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
var
http = require('http'),
fs = require('fs'),
path = require('path'),
mkdirp = require('mkdirp'),
util = require('util'),
log = require('log4node'),
url = require('url'),
net = require('net'),
crypto = require('crypto'),
events = require('events'),
spawn = require('child_process').spawn;
sprintf = require('sprintf').sprintf;
http.globalAgent.maxSockets = 100;
var argv = require('optimist').argv;
var port = argv.port || 3128;
var bind = argv.bind || "0.0.0.0";
log.info("Bind to " + bind)
log.setLogLevel('notice');
if (argv.log_file) {
log.reconfigure({file: argv.log_file, level: argv.log_level});
}
else if (argv.log_level) {
log.reconfigure({level: argv.log_level});
}
var http_proxy = undefined;
if (argv.http_proxy) {
http_proxy = url.parse(argv.http_proxy);
}
var https_proxy = undefined;
if (argv.https_proxy) {
https_proxy = url.parse(argv.https_proxy);
}
function formatSize(n) {
if (!n) {
return 'undefined';
}
if (n < 1000) {
return n;
}
n = n / 1000;
if (n < 1000) {
return sprintf('%0.3f k', n);
}
n = n / 1000;
if (n < 1000) {
return sprintf('%0.3f M', n);
}
n = n / 1000;
return sprintf('%0.3f G', n);
}
function log_operation(c) {
process.stdout.write(c || '.');
}
function file_exist(filename, exist, not_exist) {
fs.stat(filename, function(err, stats) {
if (err) {
not_exist(filename);
}
else {
exist(filename, stats);
}
});
}
var headers_to_copy_from_disk = [
'Content-Length',
'Content-Type',
'Last-Modified',
'Expires',
'Etag',
'Cache-Control',
'Server',
];
var proxy_map = {
302: function(result, ctx) {
fs.writeFile(ctx.directory + "/302", result.headers.location, function(err) {
if (err) {
log.error(ctx.from + "Unable to write file " + ctx.directory + "/302 : " + err);
ctx.events.emit('error');
return;
}
ctx.events.emit('no_body');
});
},
301: function(result, ctx) {
fs.writeFile(ctx.directory + "/301", result.headers.location, function(err) {
if (err) {
log.error(ctx.from + "Unable to write file " + ctx.directory + "/301 : " + err);
ctx.events.emit('error');
return;
}
ctx.events.emit('no_body');
});
},
307: function(result, ctx) {
fs.writeFile(ctx.directory + "/307", result.headers.location, function(err) {
if (err) {
log.error(ctx.from + "Unable to write file " + ctx.directory + "/307 : " + err);
ctx.events.emit('error');
return;
}
ctx.events.emit('no_body');
});
},
404: function(result, ctx) {
fs.writeFile(ctx.directory + "/404", "", function(err) {
if (err) {
log.error(ctx.from + "Unable to write file " + ctx.directory + "/404 : " + err);
ctx.events.emit('error');
return;
}
ctx.events.emit('no_body');
});
},
200: function(result, ctx) {
var length = result.headers['content-length'];
log.notice(ctx.from + "Start receiving data for " + ctx.directory + ", Content-Length " + formatSize(length));
fs.writeFile(ctx.directory + "/200.headers", JSON.stringify(result.headers), function(err) {
if (err) {
log.error(ctx.from + "Unable to write headers file " + ctx.directory + "/200.headers: " + err);
ctx.events.emit('error');
return;
}
});
var stream = fs.createWriteStream(ctx.directory + "/200.temp", {flags : 'w'});
ctx.counter = 0;
stream.on('error', function(err) {
log.error(ctx.from + "Unable to write file " + ctx.directory + "/200.temp: " + err);
});
stream.on('open', function() {
ctx.status = 'streaming';
ctx.result_headers = result.headers;
ctx.filename = ctx.directory + "/200.temp";
ctx.events.emit('streaming', result.headers);
});
result.on('data', function(chunk) {
ctx.counter += chunk.length;
log.info(ctx.from + 'Received ' + ctx.directory + ': ' + formatSize(ctx.counter) + '/' + formatSize(length));
stream.write(chunk);
ctx.events.emit('data');
});
result.on('end', function() {
stream.end();
log.notice(ctx.from + "End of proxy request ok " + ctx.directory + ", size " + formatSize(ctx.counter));
setTimeout(function() {
fs.rename(ctx.directory + "/200.temp", ctx.directory + "/200", function(err) {
if (err) {
log.error(ctx.from + "Unable to rename file to " + ctx.directory + "/200: " + err);
ctx.events.emit('error');
return;
}
ctx.events.emit('end', ctx.counter, ctx.directory + "/200");
});
}, 200);
});
result.on('close', function() {
//HTTP Client never emit this event
});
}
}
function copyHeadersIfExists(headers, from_headers, callback) {
headers.forEach(function(h) {
var hh = from_headers[h.toLowerCase()];
if (hh) {
log.debug("copied header " + hh);
callback(h, hh);
}
});
}
var current_request = {}
function proxy(response, headers, parsed_url, directory, body_chunks) {
if (!current_request[directory]) {
current_request[directory] = {
status: 'wait_headers',
events: new events.EventEmitter,
headers: headers,
parsed_url: parsed_url,
directory: directory,
body_chunks: body_chunks,
from: response.from,
}
current_request[directory].events.on('error', function() {
delete current_request[directory];
});
current_request[directory].events.on('no_body', function() {
delete current_request[directory];
});
current_request[directory].events.on('end', function() {
delete current_request[directory];
});
process.nextTick(function() {
run_proxy_request(current_request[directory]);
});
}
current_request[directory].events.on('error', function() {
response.statusCode = 500;
response.end();
});
var ctx = current_request[directory];
var fd = undefined;
var current = 0;
var buffer_in = new Buffer(64 * 1024);
var stop = false;
var read_data = function() {
fs.read(fd, buffer_in, 0, buffer_in.length, current, function(err, bytesRead, buffer_in) {
if (err) {
log.error(ctx.from + 'Error reading', filename, err);
fd.close();
return;
}
if (stop) {
return;
}
current += bytesRead;
if (bytesRead > 0) {
log.debug(ctx.from + 'Sent', bytesRead, 'from temp file, current', current, ' for', ctx.directory);
var buffer_out = new Buffer(bytesRead);
buffer_in.copy(buffer_out, 0, 0, bytesRead);
response.write(buffer_out.slice(0, bytesRead));
}
if (bytesRead == buffer_in.length) {
read_data();
}
else {
ctx.events.once('data', read_data);
}
});
};
var start_streaming = function() {
log.info(ctx.from + 'Starting streaming', ctx.directory);
copyHeadersIfExists(headers_to_copy_from_disk, ctx.result_headers, function(k, v) {response.setHeader(k, v)});
fs.open(ctx.filename, 'r', function(err, file_fd) {
if (err) {
response.statusCode = 500;
response.end();
log.error(ctx.from + 'Unable to open file for reading', ctx.filename, err);
}
fd = file_fd;
log.debug(ctx.from + 'File opened', ctx.filename);
ctx.events.once('data', read_data);
});
ctx.events.on('end', function(size, filename) {
fs.close(fd);
stop = true;
if (current != size) {
log.info(ctx.from + 'Have sent to client', current, 'expected', size, ', getting data from', filename, 'request', ctx.directory);
fs.open(filename, 'r', function(err, fd) {
if (err) {
log.error(ctx.from + 'Unable to open file', filename, err);
return;
}
var to_be_read = size - current;
var buffer_in = new Buffer(64 * 1024);
var r = function() {
fs.read(fd, buffer_in, 0, buffer_in.length, current, function(err, bytesRead, buffer_in) {
if (err) {
log.error(ctx.from + 'Error reading', filename, err);
return;
}
to_be_read -= bytesRead;
current += bytesRead;
log.debug(ctx.from + 'Sent', bytesRead, 'from real file, current', current, 'for', ctx.directory);
var buffer_out = new Buffer(bytesRead);
buffer_in.copy(buffer_out, 0, 0, bytesRead);
response.write(buffer_out);
if (to_be_read == 0) {
log.info(ctx.from + 'All data sent to client', ctx.directory);
response.end();
fs.close(fd);
return;
}
if (bytesRead != buffer_in.length) {
log.error(ctx.from + 'Wrong reading length', bytesRead, 'exptected', buffer_in.length, 'remaining', to_be_read, 'reading position', current - bytesRead);
return;
}
r();
})
};
r();
})
}
else {
log.info(ctx.from + 'All data has been sent to client from temp file', ctx.directory)
response.end();
}
});
};
if (ctx.status == 'wait_headers') {
log.info(ctx.from + 'Waiting headers for', ctx.directory);
ctx.events.on('no_body', function() {
process_req(response, headers, parsed_url, directory, body_chunks, function() {
response.statusCode = 500;
response.end();
log.error(ctx.from + 'Internal error, no file found after proxy request', ctx.directory);
});
});
ctx.events.on('streaming', function() {
start_streaming();
});
}
else {
start_streaming();
}
}
function run_proxy_request(ctx) {
log.debug(ctx.from + "Create directory " + ctx.directory);
mkdirp(ctx.directory, function(err) {
if (err) {
log.error(ctx.from + "Unable to create directory " + ctx.directory + " : " + err);
ctx.events.emit('error');
return;
}
log.debug(ctx.from + "Directory created " + ctx.directory);
log.info(ctx.from + "Start proxy request " + ctx.directory);
if (http_proxy) {
var full_path = ctx.parsed_url.protocol + '//' + ctx.parsed_url.hostname;
if (ctx.parsed_url.port) {
full_path += ':' + ctx.parsed_url.port;
}
full_path += ctx.parsed_url.path;
ctx.parsed_url.path = full_path;
ctx.parsed_url.protocol = http_proxy.protocol;
ctx.parsed_url.hostname = http_proxy.hostname;
ctx.parsed_url.port = http_proxy.port;
}
ctx.parsed_url.headers = {};
copyHeadersIfExists([
'Authorization',
], ctx.headers, function(k, v) {ctx.parsed_url.headers[k] = v;});
if (ctx.body_chunks) {
ctx.parsed_url.method = 'POST';
copyHeadersIfExists([
'Content-Type',
'Accept',
'User-Agent',
'Content-Encoding',
'Accept-Encoding',
'Content-length',
], ctx.headers, function(k, v) {ctx.parsed_url.headers[k] = v;});
}
var proxy_req = http.request(ctx.parsed_url, function(result) {
var f = proxy_map[result.statusCode];
if (!f) {
log.notice(ctx.from + "Wrong return code " + result.statusCode + " for proxy request " + ctx.directory);
ctx.events.emit('error');
return;
}
f(result, ctx);
});
proxy_req.on('error', function(e) {
log.error(ctx.from + "Error while proxy request " + ctx.directory + " : " + e);
ctx.events.emit('error');
});
if (ctx.body_chunks) {
ctx.body_chunks.forEach(function(chunk) {
proxy_req.write(chunk);
})
}
proxy_req.end();
});
}
function send_redirect(response, code, filename) {
fs.readFile(filename, function(err, data) {
if (err) {
log.error(response.from + "Unable to read file " + filename);
response.statusCode = 500;
response.end();
return;
}
response.statusCode = code;
response.setHeader("Location", data);
response.end();
log_operation();
});
}
function streamFile(filename, response) {
var stream = fs.createReadStream(filename, { flags: 'r', bufferSize: 64 * 1024});
stream.pipe(response);
stream.on('error', function(err) {
log.error(response.from + "Unable to read file " + filename + " : " + err);
response.statusCode = 500;
response.end();
}).on('close', function() {
log_operation();
// Nothing to do
});
}
var process_map = {
301: function(response, headers, filename, stats) {
send_redirect(response, 301, filename);
},
302: function(response, headers, filename, stats) {
send_redirect(response, 302, filename);
},
307: function(response, headers, filename, stats) {
send_redirect(response, 302, filename);
},
404: function(response, headers, filename, stats) {
log.info(response.from + "Return 404 for request " + filename);
response.statusCode = 404;
response.end();
log_operation();
},
200: function(response, headers, filename, stats) {
file_exist(filename + '.headers', function(filename2, stats) {
fs.readFile(filename + '.headers', function(err, data) {
if (err) {
log.error(response.from + 'Unable to read ' + filename + '.headers file:' + err);
response.statusCode = 500;
response.end();
return;
}
orig_headers = JSON.parse(data.toString());
if (headers['if-modified-since'] && orig_headers['last-modified']) {
if_modified = Date.parse(headers['if-modified-since']);
last_modified = Date.parse(orig_headers['last-modified']);
if (if_modified >= last_modified) {
log.debug(response.from + "Return 304 for request " + filename);
response.statusCode = 304;
response.end();
log_operation(':');
return;
}
}
copyHeadersIfExists(headers_to_copy_from_disk, orig_headers, function(k, v) {response.setHeader(k, v)});
streamFile(filename, response);
});
}, function() {
response.setHeader('Content-Length', stats.size);
streamFile(filename, response);
});
}
}
var responses = [];
for(var i in process_map) {
responses.push(i);
}
function process_req(response, headers, parsed_url, directory, body_chunks, not_found) {
process_req_internal(responses.slice(0), response, headers, parsed_url, directory, body_chunks, not_found);
}
function process_req_internal(l, response, headers, parsed_url, directory, body_chunks, not_found) {
if (l.length == 0) {
return not_found(response, headers, parsed_url, directory, body_chunks);
}
var code = l.shift();
log.debug(response.from + 'Searching', code, 'for', directory);
file_exist(directory + '/' + code, function(filename, stats) {
process_map[code](response, headers, filename, stats);
}, function(filename) {
process_req_internal(l, response, headers, parsed_url, directory, body_chunks, not_found);
});
}
var current_git_clone = {}
function extract_git_path(string) {
if (path.basename(string).match(/\.git$/)) {
return string;
}
var dirname = path.dirname(string);
return dirname == string ? null : extract_git_path(dirname);
}
function process_git_request(response, url, directory) {
var git_repo_path = extract_git_path(directory);
if (!git_repo_path) {
log.error(response.from + 'Unable to extract git path ' + directory);
response.statusCode = 500;
response.end();
return;
}
var serve_static_file = function(response) {
file_exist(directory, function() {
var s = fs.createReadStream(directory);
response.statusCode = 200;
s.pipe(response);
}, function() {
log.debug(response.from + 'Git file not found', directory);
response.statusCode= 404;
response.end();
});
};
log.debug(response.from + 'Serving git request on repo', git_repo_path, 'file', directory);
fs.exists(git_repo_path, function(exists) {
if (exists && !current_git_clone[git_repo_path]) {
serve_static_file(response);
}
else {
if (!current_git_clone[git_repo_path]) {
var git_repo_url = extract_git_path(url);
if (!git_repo_url) {
log.error(response.from + 'Unable to extract git path ' + url);
response.statusCode = 500;
response.end();
return;
}
current_git_clone[git_repo_path] = new events.EventEmitter;
log.notice(response.from + 'Cloning ' + git_repo_url + ' to ' + git_repo_path);
var command = '';
if (argv.http_proxy) {
command += 'export http_proxy=' + argv.http_proxy + ' && ';
}
if (argv.https_proxy) {
command += 'export https_proxy=' + argv.https_proxy + ' && ';
}
command += 'git clone --mirror ' + git_repo_url + ' ' + git_repo_path + ' && cd ' + git_repo_path + ' && git update-server-info';
var child = spawn('/bin/sh', ['-c', command]);
log.debug(response.from + 'Launching command', command);
child.on('exit', function(code) {
log.debug(response.from + 'Command result', code);
if (code == 0) {
log.notice(response.from + 'Git clone ok', git_repo_url);
current_git_clone[git_repo_path].emit('end');
}
else {
log.info(response.from + 'Wrong return code for command', command, ':', code);
current_git_clone[git_repo_path].emit('error');
}
delete current_git_clone[git_repo_path];
});
}
current_git_clone[git_repo_path].on('end', function() {
serve_static_file(response);
});
current_git_clone[git_repo_path].on('error', function() {
response.statusCode = 500;
response.end();
return;
});
}
});
}
function extract_from(request) {
return "[" + (request.headers['x-forwarded-for'] || request.connection.remoteAddress) + "] ";
}
http.createServer(function (request, response) {
if (request.method != 'GET' && request.method != 'POST') {
response.statusCode = 405;
response.end();
return;
}
response.from = extract_from(request);
var parsed_url = url.parse(request.url);
if (! parsed_url) {
log.error(response.from + "Unable to parse url " + request.url);
response.statusCode = 500;
response.end();
return;
}
if (request.method == 'GET' && parsed_url.path == '/reload_all_git_repos') {
var command = '';
if (argv.http_proxy) {
command += 'export http_proxy=' + argv.http_proxy + ' && ';
}
if (argv.http_proxy) {
command += 'export https_proxy=' + argv.https_proxy + ' && ';
}
command += 'cd storage && export home_dir=`pwd`; for i in `find . -name "packed-refs"`; do echo "Reloading `dirname $i`" && cd $home_dir && cd `dirname $i` && git fetch -q origin && git update-server-info || exit 1; done && echo "OK";';
var child = spawn('/bin/sh', ['-c', command]);
var out = '';
log.debug(response.from + 'Launching command', command);
child.stdout.on('data', function(d) {
out += d.toString();
});
child.on('exit', function(code) {
log.debug(response.from + 'Command result', code);
if (code == 0) {
response.statusCode = 200;
response.setHeader('Content-Type', 'text/plain');
response.end(out);
}
else {
response.statusCode = 500;
response.end();
}
});
return;
}
if (parsed_url.protocol != 'http:') {
log.error(response.from + "Wrong protoocol " + parsed_url.protocol);
response.statusCode = 500;
response.end();
return;
}
var directory = "storage/" + parsed_url.host + (parsed_url.pathname || '');
log.debug(response.from + "Incoming request " + parsed_url.href);
if (request.headers['user-agent'] && request.headers['user-agent'].match(/^git/)) {
process_git_request(response, request.url, directory);
return;
}
if (parsed_url.query) {
var shasum = crypto.createHash('sha1');
shasum.update(parsed_url.query);
var hash = shasum.digest('hex');
directory += '/' + hash;
}
var not_found = argv.no_proxy ? function(response, headers, parsed_url, directory) {
response.statusCode = 500;
response.end();
log.error(response.from + 'File not found on proxy', directory);
} : proxy;
if (request.method == 'GET') {
process_req(response, request.headers, parsed_url, directory, undefined, not_found);
}
else {
var shasum = crypto.createHash('sha1');
var body_chunks = [];
request.on('data', function(chunk) {
shasum.update(chunk);
body_chunks.push(chunk);
})
request.on('end', function() {
var hash = shasum.digest('hex');
directory += '/' + hash;
process_req(response, request.headers, parsed_url, directory, body_chunks, not_found);
})
}
}).on('clientError', function(e) {
console.log(e);
}).on('error', function(err) {
log.error("HTTP ERROR : " + err);
}).on('connect', function(request, socket, head) {
var from = extract_from(request);
var splitted = request.url.split(':');
log.notice(from + 'HTTP CONNECT to', splitted[0], splitted[1]);
var connection = net.createConnection(splitted[1], splitted[0], function() {
socket.write('HTTP/1.0 200 Connection established\r\n\r\n');
socket.pipe(connection);
connection.pipe(socket);
socket.on('end', function() {
log.notice(from + 'End HTTP CONNECT to', splitted[0], splitted[1]);
});
});
connection.on('error', function(err) {
log.notice(from + 'HTTP CONNECT error', err);
socket.write('HTTP/1.0 500 Error\r\n\r\n');
socket.end();
})
}).listen(port, bind);
log.notice("Offline Proxy ready on port " + port);