-
Notifications
You must be signed in to change notification settings - Fork 9
/
proxy.js
93 lines (77 loc) · 2.54 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
var dgram = require('dgram'),
packet = require('packet'),
__slice = [].slice;
var client = dgram.createSocket('udp4'),
server = dgram.createSocket('udp4'),
info;
function die () {
console.log.apply(console, __slice.call(arguments, 0));
process.exit(1);
}
function say () { console.log.apply(console, __slice.call(arguments, 0)) }
function extend (to, from) {
for (var key in from) to[key] = from[key];
return to;
}
function proxy (input, output, remote, interceptor) {
if (!interceptor) interceptor = function () {}
var types = "Handshake Keep-alive Acknowledgement Negative-acknowledgement \
Unused Shutdown Acknowledgement-acknowledgement Drop".split(/\s+/);
var parser = packet.createParser();
var packets = require('./common').packets;
parser.packet('header', packets.header);
parser.packet('handshake', packets.handshake);
client.bind(input, '127.0.0.1');
server.bind(output, '127.0.0.1');
client.on('message', function (buffer, $info) {
info = $info;
log('Client', buffer, function (buffer) {
server.send(buffer, 0, buffer.length, remote, '127.0.0.1');
});
});
var epoch = process.hrtime();
function log (participant, buffer, callback) {
parser.reset();
parser.extract('header', function (header) {
epoch = process.hrtime();
if (header.control) {
console.log(participant + ': Control ' + types[header.type], header);
switch (header.type) {
case 0:
parser.extract('handshake', function (handshake) {
console.log(handshake);
callback(buffer);
})
break;
default:
callback(buffer);
}
} else {
console.log(participant + ': Data');
console.log(extend(header, { parser: parser.length, buffer: buffer.length }));
if (participant == 'Client' && buffer.length - parser.length == 4) {
callback(buffer);
} else {
console.log(toArray(buffer));
callback(buffer);
}
}
});
parser.parse(buffer);
}
function toArray (buffer) {
return buffer.toString('hex').replace(/(..)/g, ':$1')
.replace(/(.{12})/g, '\n$1')
.replace(/\n:/g, '\n');
}
server.on('message', function (buffer) {
log('Server', buffer, function (buffer) {
client.send(buffer, 0, buffer.length, info.port, '127.0.0.1');
});
});
}
if (!module.parent) {
proxy(9293, 9593, 9000, function (buffer) { return buffer });
} else {
exports.proxy = proxy;
}