-
Notifications
You must be signed in to change notification settings - Fork 1
/
wsprocessor.js
421 lines (350 loc) · 12.8 KB
/
wsprocessor.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
var https = require('https');
var fs = require('fs');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var WebSocketClient = require('websocket').client;
var WebSocketServer = require('websocket').server;
var wsServer = null;
var connection = null;
var verbose = false;
var webserver = true;
var ignoreRules = [];
var replaceRules = [];
var expect = null;
var reuseSocket = false;
var savedReqs = {};
var savedOutgoing = {};
var savedIncoming = {};
var wsOutgoingConnections = {};
var wsIncomingConnections = {};
var doLog = null;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/scripts'));
app.set('view engine', 'pug');
ignoreMessage = function(direction,data){
var ignore = false;
if (direction === 0){
if (ignoreRules["in"].length === 0){
return false;
}
for(var i = 0; i < ignoreRules["in"].length; i++) {
if(data.match(ignoreRules["in"][i]) != null){
return true
}
}
}
else if (direction===1){
if(ignoreRules["out"].length === 0){
return false;
}
for (var i = 0; i< ignoreRules["out"].length; i++){
if(data.match(ignoreRules["out"][i]) != null){
return true
}
}
}
return ignore
};
exports.getTimeStamp = function(){
var cd = new Date();
var d = cd.getDate();
var m = cd.getMonth()+1;
var y = cd.getFullYear();
var h = cd.getHours();
var mi = cd.getMinutes();
var s = cd.getSeconds();
var dt = y+((m<10)?"0":"")+m+((d<10)?"0":"")+d;
var t = ((h<10)?"0":"")+h+((mi<10)?"0":"")+mi+((s<10)?"0":"")+s;
return dt + t;
};
exports.initRules = function(config, logFunc){
ignoreRules = config.web.ignoreRules;
replaceRules = config.web.replaceRules;
expect = config.web.eEchos;
reuseSocket = config.web.reuseSocket;
doLog = logFunc;
verbose = config.verbose;
};
exports.ignore = function(direction,data){
return ignoreMessage(data)
};
exports.replace = function(data){
var tmp_data = data;
return tmp_data
};
exports.mangle = function(data){
var tmp_data = data;
return tmp_data
};
exports.securityCheck = function(data){
};
exports.setWsOutgoingConnection = function(channel, conn){
wsOutgoingConnections[channel] = conn;
};
exports.setWsIncomingConnection = function(channel, conn){
wsIncomingConnections[channel] = conn;
};
exports.saveReq = function(request){
if(!savedReqs[request.resourceURL.path]) {
savedReqs[request.resourceURL.path] = [];
}
var proto = (request.resourceURL.protocol === 'http:' || request.resourceURL.protocol === 'http') ? 'ws://':'wss://';
if(request.resourceURL.protocol == null){
if (request.httpRequest.headers['origin'] == null) {
proto = request.httpRequest.connection.encrypted ? 'wss://':'ws://';
}
else {
proto = request.httpRequest.headers['origin'].split(':')[0] === 'http' ? 'ws://':'wss://';
}
}
savedReqs[request.resourceURL.path] = {proto:proto,headers:request.httpRequest.headers};
if(webserver){
sendToInterface({type:'channel',title:request.resourceURL.path,id:request.resourceURL.path})
}
};
exports.saveOutgoing = function(channel,message){
if(message.type==='utf8' && ignoreMessage(1,message.utf8Data)){
return 1; //don't save request as it's in the ignore list
}
if(!savedOutgoing[channel]){
savedOutgoing[channel] = [];
}
savedOutgoing[channel].push(message);
var msg = "Outgoing: "+savedOutgoing[channel].length-1;
if(message.type==='utf8'){
msg = ""+message.utf8Data.substring(0,30);
}
if(webserver){
sendToInterface({type:'outgoing',title:msg,channel:channel,id:savedOutgoing[channel].length-1})
}
};
exports.saveIncoming = function(channel,message){
if(message.type==='utf8' && ignoreMessage(0,message.utf8Data)){
return 1; //don't save request as it's in the ignore list
}
if(!savedIncoming[channel]){
savedIncoming[channel] = [];
}
savedIncoming[channel].push(message);
var msg = "Incoming: "+savedIncoming[channel].length-1;
if(message.type==='utf8'){
msg = ""+message.utf8Data.substring(0,30);
}
if(webserver){
sendToInterface({type:'incoming',title:msg,channel:channel,id:savedIncoming[channel].length-1})
}
};
exports.startServer = function(port){
webserver = true;
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
httpsserver = https.createServer(options,app).listen(parseInt(port));
wsServer = new WebSocketServer({
httpServer: httpsserver,
autoAcceptConnections: false
});
wsServer.on('request', function(request) {
connection = request.accept('share-protocol', request.origin);
connection.on('message', function(message) {
if (message.type === 'utf8') {
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
//console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
};
exports.socketClosed = function(channel){
sendToInterface({type:'socketclosed',channel:channel})
};
exports.socketOpen = function(channel){
sendToInterface({type:'socketopen',channel:channel})
};
sendToInterface = function(message){
if(connection)
connection.sendUTF(JSON.stringify(message))
};
// returns true if socket is open
checkSocket = function(sock) {
return (sock.connected && sock.state == 'open');
};
// inform web interface of client<->proxy socket state
sendSocketState = function(channel) {
if (wsIncomingConnections[channel] && reuseSocket) {
if (checkSocket(wsIncomingConnections[channel])) {
exports.socketOpen(channel);
} else {
exports.socketClosed(channel);
}
}
};
// refill channels list
fillChannels = function() {
Object.keys(savedReqs).forEach(function(key){
sendToInterface({type:'channel',title:key,id:key})
})
};
app.get('/', function (req, res) {
res.render('main',{reuseSocket:reuseSocket,expect:expect,ignore:{_in:ignoreRules["in"],_out:ignoreRules["out"]}});
//setTimeout(sendSocketState, 2000);
setTimeout(fillChannels, 2000);
});
app.get('/channels/:id', function(req,res){
res.send(savedReqs[req.params.id])
});
app.get('/channels',function(req,res){
res.send(Object.keys(savedReqs))
});
app.get('/outgoing/:channel/:id', function(req,res){
var resp = {request:savedReqs[req.params.channel],channel:req.params.channel,data:savedOutgoing[req.params.channel][parseInt(req.params.id)]};
res.json(resp)
});
app.get('/incoming/:channel/:id', function(req,res){
var resp = {request:savedReqs[req.params.channel],channel:req.params.channel,data:savedIncoming[req.params.channel][parseInt(req.params.id)]};
sendSocketState(wsIncomingConnections[req.params.channel], req.params.channel);
res.json(resp)
});
app.post('/config',function(req,res){
expect = parseInt(req.body.echo);
reuseSocket = (req.body.reuseSocket == 'true');
ignoreRules["in"] = [];
ignoreRules["out"] = [];
var inc = req.body.incoming.split(',');
var outc = req.body.outgoing.split(',');
for(var i=0;i<inc.length; i++){
v = inc[i].replace(/\//g,'');
if(v!=="")
ignoreRules["in"].push(new RegExp(v))
}
for(var i=0;i<outc.length; i++){
v = outc[i].replace(/\//g,'');
if(v !== "")
ignoreRules["out"].push(new RegExp(v))
}
res.send({success:0})
});
app.post('/repeat',function(req,res){
var headers = JSON.parse(req.body.headers);
var host = req.body.host;
var path = req.body.channel;
var data = req.body.data;
var direction = req.body.direction;
var client = new WebSocketClient();
var origin = headers['origin'] || null;
var tmpexpect = expect;
if (direction === 'incoming'){
if (checkSocket(wsIncomingConnections[path]) && reuseSocket) {
wsIncomingConnections[path].sendUTF(data);
res.end(exports.getTimeStamp() + ' Sent using existing connection. Response will be in Messages.');
if (verbose){
doLog(['Resent data on existing incoming connection:',path,'Data:',data]);
}
}
else {
// existing socket not open
res.end('Websocket not open, could not send.');
}
}
if (direction === 'outgoing') {
// try and reuse existing connection if configured to
if (checkSocket(wsOutgoingConnections[path]) && reuseSocket) {
wsOutgoingConnections[path].sendUTF(data);
res.end(exports.getTimeStamp() + ' Sent using existing connection. Response will be in Messages.');
if (verbose)
doLog(['Resent data on existing outgoing connection:',path,'Data:',data]);
}
else {
client.connect(host+path, null,origin,headers);
client.on('httpResponse',function(resp){
res.end("Got a NON-Websocket response. Are you authenticated?")
});
client.on('connect',function(clconn){
clconn.sendUTF(data);
if (verbose)
doLog(['Resent data on new outgoing connection:',data]);
clconn.on('message', function(d) {
//console.log(d)
if(tmpexpect-- === 0){
//clconn.close()
if(d.type==='utf8')
res.send(d.utf8Data);
else
res.end("Binary data - Can't display")
}
});
})
}
}
});
app.post('/berude',function(req,res){
var headers = JSON.parse(req.body.headers);
var host = req.body.host;
var path = req.body.channel;
var data = req.body.data;
var direction = req.body.direction;
var client = new WebSocketClient();
var origin = headers['origin'] || null;
var b = new Buffer(req.body.payload, 'base64');
var payload = b.toString().split('\n');
if (direction === 'incoming'){
if (checkSocket(wsIncomingConnections[path]) && reuseSocket) {
res.json({result:0,message:"Starting session using existing socket"});
for(var i=0; i<payload.length; i++){
var dd = data.replace(/«\b\w+\b«/i,payload[i]);
//console.log(dd)
wsIncomingConnections[path].sendUTF(dd);
if (verbose)
doLog(['Sent "rude" data on existing incoming connection:',path,'Data:',data]);
}
}
else {
// existing socket not open
res.json({result:1,message:"Websocket not open, could not send."})
}
}
if (direction === 'outgoing') {
// try and reuse existing connection
if (checkSocket(wsOutgoingConnections[path]) && reuseSocket) {
res.json({result:0,message:"Starting session using existing socket"});
for(var i=0; i<payload.length; i++){
var dd = data.replace(/«\b\w+\b«/i,payload[i]);
//console.log(dd)
wsOutgoingConnections[path].sendUTF(dd);
if (verbose)
doLog(['Sent "rude" data on existing outgoing connection:',path,'Data:',data]);
}
}
else {
res.json({result:0,message:"Starting session using new socket"});
client.connect(host+path, null,origin,headers);
client.on('httpResponse',function(resp){
res.json({result:1,message:"Got a NON-Websocket response. Are you authenticated?"})
});
client.on('connect',function(clconn){
clconn.on('message', function(d) {
//console.log("message",d)
if(d.type==='utf8')
sendToInterface({type:'rude',message:d.utf8Data,payload:""});
else
sendToInterface({type:'rude',message:"Binary Data",payload:""})
});
for(var i=0; i<payload.length; i++){
var dd = data.replace(/«\b\w+\b«/i,payload[i]);
//console.log(dd)
clconn.sendUTF(dd);
if (verbose)
doLog(['Sent "rude" data on new outgoing connection:',data]);
}
})
}
}
});