-
Notifications
You must be signed in to change notification settings - Fork 0
/
tunnel.js
43 lines (29 loc) · 1003 Bytes
/
tunnel.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
var util = require('util');
var net = require('net');
exports.open = function(host, port, target, callback) {
util.log('Connecting to ' + host + ':' + port);
var proxy = new net.Socket();
proxy.connect(port, host, function() {
util.log('Tunneling to ' + target + ' through ' + host + ':' + port);
proxy.write('CONNECT ' + target + " HTTP/1.0\r\n\r\n");
});
var buffer = '';
var handler = function(data) {
buffer += data.toString();
if (buffer.indexOf("\r\n\r\n") > 0) {
var captures = buffer.match(/([0-9]{3}) (.+)/);
if (!captures || captures.length < 2 || captures[1] != '200') {
return callback(null);
}
buffer = buffer.slice(buffer.indexOf("\r\n\r\n") + 4);
util.log('Tunnel connected, handing socket back');
proxy.removeListener('data', handler);
callback(buffer);
}
}
proxy.addListener('data', handler);
proxy.addListener('error', function(){
return callback(null);
});
return proxy;
}