-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrsserver.js
617 lines (542 loc) · 18 KB
/
rsserver.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
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
//Copyright (c) Anna Alekseeva 2013-2016
//Use DEBUG variable to set amount of logs.
//0: no logs
//1: warnings and errors
//2: logs for important events, like opening and closing connections
//3: all debug logs
var DEBUG = 0;
{ var d = process.argv[1].match(/debug([0-9]*)/); if (d) DEBUG = d[1]; }
var port = process.argv[3] || 1729;
var serverUrl = process.argv[2] || "127.0.0.1";
var tcpPort = process.argv[4] || 1728;
var http = require("http");
var path = require("path");
var fs = require("fs");
var net = require("net");
var xml2js = require("xml2js");
var tcpSocket = null;
var tcpSocketServer = net.createServer(function(c) { //'connection' listener
showLog('tcp client connected');
tcpSocket = c;
var clist = getConnectionsList();
if (clist) c.write(clist);
c.on('end', function() {
showLog('tcp client disconnected');
tcpSocket = null;
});
c.on('error', function(err){
showWarning("Error in TCP connection");
showWarning(err.stack);
tcpSocket = null;
});
c.on('data', function(data){
processDownData(data, function(id, data, err){
debugLog("downdata processed", id, err, data);
if (!err || err == "null") {
if (id) {
if (id instanceof Array){//broadcast to several connections
for (var i = 0; i < id.length; i ++) {
if (connections[id[i]] != null) {
connections[id[i]].send(data, {binary: false});
}//if
}//for
}// id is array
else if (connections[id] != null) {
connections[id].send(data, {binary: false});
}// valid connection id
} else {
for (var w in connections)
if (connections.hasOwnProperty(w) && connections[w] != null)
connections[w].send(data, {binary: false});
} //id is empty
} //no error
else {
displayError(err);
}
});
} );
if (DEBUG > 2) c.pipe(process.stdout);
});
tcpSocketServer.listen(tcpPort, function() {
console.log('TCP server is running at localhost, port', tcpPort);
});
var WebSocketServer = require('ws').Server;
var now = new Date();
console.log(now + " Creating WebSocket server at URL " + serverUrl);
var server = http.createServer( function(req, res) {
var filename = require('url').parse(req.url).pathname || "index.html";
if (filename == "/") filename = "/index.html";
var ext = path.extname(filename);
var localPath = __dirname;
var validExtensions = {
".html" : "text/html",
".js": "application/javascript",
".css": "text/css",
".txt": "text/plain",
".jpg": "image/jpeg",
".gif": "image/gif",
".png": "image/png",
".ico": "image/x-icon"
};
var isValidExt = validExtensions[ext];
if (isValidExt) {
localPath += filename;
fs.exists(localPath, function(exists) {
if(exists) {
getFile(localPath, res, isValidExt);
} else {
res.writeHead(404);
res.end();
}
});
} else {
displayError("Invalid file extension detected: " + ext);
}
}).listen(port, serverUrl);
var wss = new WebSocketServer({server: server});
console.log("WebSocket server is running. Type http://" + serverUrl.toString() + ":" + port + "/ in a browser to start.");
wss.on('connection', function(ws) {
showLog((new Date()) + ' Connection from origin ' + ws.origin + '.');
addConnection (ws);
ws.on('message', function(message) {
debugLog("message received", message);
processUpData(ws.id, message, function(result) {
debugLog("going to send to tcp: " + result);
if (tcpSocket) tcpSocket.write(result + "\n");});
});
ws.on('close', function(message) {
removeConnection (ws);
//Remove the disconnecting client from the list of clients
});
});
//-------------Managing connections-------------
var activeWebSocket = null;
var connections = [];
function addConnection (ws) {
activeWebSocket = ws;
var id = ws.id || getNewWsId();
ws.id = id;
connections[id] = ws;
connectionsNum ++;
}
var connectionsNum = 0;
function getNewWsId () {
var s = "rs" + connectionsNum;
var curIdNum = connectionsNum;
while (connections.hasOwnProperty(s)) {
curIdNum ++;
s = "rs" + curIdNum;
}
return s;
}
function getConnectionId (ws) {
if (ws.id) return ws.id;
ws.id = getNewWsId();
return ws.id;
}
function removeConnection (ws) {
showLog ("Closing connection " + ws.id);
var dataObj = {updata: {$: {status: "removed", session: ws.session, object: ws.window}}};
var str = xmlBuilder.buildObject(dataObj).replace(/"/g, "'") + "\n"; //"
if (tcpSocket) tcpSocket.write(str);
connections[ws.id] = null;
connectionsNum --;
if (activeWebSocket == ws) {
if (connectionsNum > 0) {
for (var s in connections){
if (connections.hasOwnProperty(s) && connections[s] != null ) {
activeWebSocket = connections[s];
break;
}
}
} else {
activeWebSocket = null;
}
}
}
//----------------------------------------------------------------------------
//--------------Managing sessions and objects ids-----------------------------
//Every connection has a .session, .window and .objects properties.
//Window id (.window property) must be unique inside the session.
//.objects property contains the list of the ids of the objects in the window.
//Each object id must be unique inside the session
//The connection.id property is for internal use only
function isWindowIdNew(session, id) {
for (var w in connections)
if (connections.hasOwnProperty(w) && connections[w] && connections[w].session == session && connections[w].window == id )
return false;
return true;
}
function generateWindowId (session) {
return generateObjectId(session, "w");
}
var maxSessionId = 0;
function generateSessionId() {
var res = "";
while(!isSessionIdNew(res="s" + (++maxSessionId))) {}
return res;
}
function isSessionIdNew(id) {
for (var w in connections){
if (connections.hasOwnProperty(w) && connections[w] && connections[w].session == id)
return false;
}
return true;
}
function isObjectIdNew(session, id, tempUsedIds) {
for (var w in connections) {
if (connections.hasOwnProperty(w) && connections[w] && connections[w].session == session) {
if (connections[w].window == id) return false;
if ( connections[w].objects ) {
for (var o in connections[w].objects)
if (connections[w].objects.hasOwnProperty(o) && connections[w].objects[o] == id)
return false;
}
}
}
if (tempUsedIds)
for (var i in tempUsedIds)
if (tempUsedIds[i] == id) return false;
return true;
}
function generateObjectId(session, type, tempUsedIds) {
var i = 0;
var res = "";
while (!isObjectIdNew(session, res = type + (i++), tempUsedIds)){};
return res;
}
//--------------------------------
var xmlBuilder = new xml2js.Builder({headless: true, renderOpts:{pretty: false}});
var xmlParser = new xml2js.Parser({explicitArray: true, explicitCharkey: true, emptyTag: "empty"});
function processDownData(data, callback){
xmlParser.parseString(data, function (err, resultObj){
if (err || !resultObj) err = err || "Invalid xml or parsing error";
else {
var sId = "";
var id = "";
if (!err) {
if (!resultObj ) err = "invalid xml " + data;
else if (!resultObj.downdata || resultObj.downdata == "empty" || resultObj.downdata[0] == "empty") err = ("invalid xml tag (downdata expected) or empty element" + data);//throw console.error("invalid xml tag (downdata expected) " + data);
else if (!resultObj.downdata || !resultObj.downdata.$) {
err = "No attributes"
} else if( !resultObj.downdata.$.session) {
if( !(resultObj.downdata.$.action == "request"))//only 'request' action is valid without session attribute
err = "No session id attribute";
}
else {
var a = resultObj.downdata.$;
a.action = a.action || "create";
if (!(a.action == "create" || a.action == "update" || a.action == "populate" || a.action == "remove" || a.action == "request"))
err = "Invalid action attribute " + a.action;
var curSessionConnections = {};
var curSessionConnectionsNum = 0;
for (var w in connections)
if (connections.hasOwnProperty(w) && connections[w] && connections[w].session == a.session) {
curSessionConnections[w] = connections[w];
curSessionConnectionsNum ++;
}
if (curSessionConnectionsNum == 0) {
err = "No connections for session " + a.session + " open";
}
else if (!a.object) {
//The only valid cases without object attribute are to create new window or request info about all session windows
if (a.action == "create" && resultObj.downdata.hasOwnProperty("window") && resultObj.downdata.window)
{
if (resultObj.downdata.window == "empty") resultObj.downdata.window = { $:""};
for (var w in curSessionConnections)
if (curSessionConnections.hasOwnProperty(w) && curSessionConnections[w])
{id = w;}
if (id == "") err = "No registered session " + a.session;
} //create new window in given session
else if (a.action == "request") {
id = [];
for (var w in curSessionConnections)
if (curSessionConnections.hasOwnProperty(w) && curSessionConnections[w])
{id.push(w)}
} //request without object attribute
else err = "No object attribute";
} //no object attribute
else {
for (var w in curSessionConnections)
if (curSessionConnections[w].window == a.object) {
id = w;
if (a.action == "remove") a.object = "";//signal to client to close entire window
}
else if (curSessionConnections[w].objects) {
for (var o in curSessionConnections[w].objects )
if (curSessionConnections[w].objects[o] == a.object)
id = w;
}
debugLog("Connection id", id);
if (id == "") err = "No registered object " + a.object;
else if (a.action == "create"){
var usedIds = [];
for (var f in resultObj.downdata) {
if (f != "$" && resultObj.downdata.hasOwnProperty(f) && resultObj.downdata[f]) {
if (resultObj.downdata[f] instanceof Array) {
for (var ff in resultObj.downdata[f]){
if (resultObj.downdata[f].hasOwnProperty(ff) && resultObj.downdata[f][ff]) {
if (resultObj.downdata[f][ff] == "empty") resultObj.downdata[f][ff] = {$: {id: ""}};
err = checkObjectID(a.session, resultObj.downdata[f][ff], f, usedIds);
}
}
} else {
if (resultObj.downdata[f][ff] == "empty") resultObj.downdata[f] = {$: {id: ""}};
err = checkObjectID(a.session, resultObj.downdata[f], f, usedIds);
}
}
}
}//action == create
}
}
}
}
var resStr ="";
if (resultObj) resStr = xmlBuilder.buildObject(resultObj)
else err = "Unknown xml parsing error";
callback(id, resStr, err);
});
}
function checkObjectID(session, object, type, tempUsedIds) {
var err="";
if (object.$ && object.$.id) {
if (!isObjectIdNew(session, object.$.id)) err = "Id " + object.$.id + " is already in use";
} else {
if (!object.$) object.$ = new Object();
if (!object.$) err = object + "is not an object";
else object.$.id = generateObjectId(session, type, tempUsedIds);
}
tempUsedIds.push(object.$.id);
return err;
}
function processUpData (id, message, callback) {
xmlParser.parseString(message, function (err, resultObj) {
if (!err) {
if (!resultObj) {
err = "Error parsing updata";
}
else if (!resultObj.updata) {
if (resultObj.error) err = resultObj.error
else err = "invalid xml tag (updata expected) or empty element";
} else {
if (resultObj.updata == "empty") resultObj.updata = {};
if (!resultObj.updata.$) resultObj.updata.$ = {};
var a = resultObj.updata.$;
var ws = connections[id];
if (resultObj.updata.hasOwnProperty("window") && (!a.status || a.status == "created"))
{
//TODO process a case when a window is removed
if (!a.session) a.session = generateSessionId();
ws.session = a.session;
a.status = "created";
var wId = a.id || a.object || a.window;
if (!wId) {
wId = generateWindowId(a.session);
} else if (!isWindowIdNew(a.session, wId)) {
err = "Window id " + wId + " is already in use";
}
ws.window = wId;
resultObj.updata.window = {$ : {id: wId}};
}
else {
//TODO process info
if (!a.status) a.status = "updated";
a.session = ws.session;
if (!a.object) {
if (a.status == "created" || a.status == "info") a.object = ws.window;
else err = "Object id not defined";
}
if (a.status == "created") {
if (!ws.objects) ws.objects = [];
for (var f in resultObj.updata) {
if (f != "$" && resultObj.updata.hasOwnProperty(f) && resultObj.updata[f]) {
if (resultObj.updata[f] instanceof Array) {
for (var o in resultObj.updata[f]) {
if (o != "$" && resultObj.updata[f].hasOwnProperty(o) && resultObj.updata[f][o]) {
if (!resultObj.updata[f][o].$ || !resultObj.updata[f][o].$.id)
err = "No id for created object " + f;
else ws.objects.push(resultObj.updata[f][o].$.id);
}
}
} else {
if (!resultObj.updata[f].$ || !resultObj.updata[f].$.id)
err = "No id for created object " + f;
else ws.objects.push(resultObj.updata[f].$.id);
}
}
}
}
if (a.status == "updated" || a.status == "removed") {
if (!ws.objects) err = "No registered objects for session " + ws.session + ", window " + ws.window;
else {
var i = ws.objects.indexOf(a.object);
if (i < 0) err = "No object " + a.object + " is registered in session " + ws.session + ", window " + ws.window;
else if (a.status == "removed") ws.objects.splice(i, 1);
}
}
}
}
}
if (err) displayError(err);
else {
callback(xmlBuilder.buildObject(resultObj).replace(/"/g, "'").replace(/>empty</g, "><"));
}
});
}
function getConnectionsList() {
if (true) {
var list = {updata: {session: []}};
for (var w in connections)
if (connections.hasOwnProperty(w) && connections[w]) {
var sessionItem = {"$":{}, "window": []};
for (var i = 0; i < list.updata.session.length; i++) {
if (list.updata.session[i].$ && list.updata.session[i].$.id == connections[w].session)
sessionItem = list.updata.session[i];
}
if (!sessionItem.$.id) {
sessionItem.$.id = connections[w].session;
list.updata.session.push(sessionItem);
}
sessionItem.window.push({"$" : {"id" : connections[w].window}});
}
var str = xmlBuilder.buildObject(list);
return (str.replace(/"/g, "'") + "\n");
} else {
return "<updata/>";
}
}
function displayError(err) {
showWarning(err);
if (err.toString().substring(0, 7) != "<updata") err = "<updata status='error'>" + err.toString() + "</updata>\n";
if (tcpSocket) tcpSocket.write(err);
}
process.stdin.setEncoding('utf8');
//TODO config changing in command line
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
parseCommand(chunk);
}
});
process.stdin.on('end', function() {
process.stdout.write('end');
});
function parseCommand (line /*String*/) {
//TODO chanche active connection
if (line.charAt(line.length-1) == "\n") line = line.slice(0, -1);
//var sp_ind = line.indexOf(" ");
var command = cutCommand(line, 0);
//sendOutput("parseCommand", command);
//if (sp_ind > -1) command = line.slice(0, sp_ind)
//else command = line;
if (command == "config") {
updateConfig (line);
} else if (command == "help" || command == "h" || command == "?") {
showHelp();
} else
{
sendOutput("Unknown command", command);
}
//var parts = line.split(" ");
//parts = removeElements(parts, ""," ", "\n");
//if (parts[0] == "config") updateConfig (parts);
}
function removeElements(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
function showHelp() {
//TODO
sendOutput("Here should be help. " + arguments[0] + "\n");
}
function sendOutput() {
var argsString = Array.prototype.join.call(arguments, '\n');
process.stdout.write(argsString + '\n');
//console.log(argsString);
}
function debugLog () {
showLogImpl (3, arguments);
}
function showLog() {
showLogImpl(2, arguments);
}
function showWarning() {
showLogImpl(1, arguments);
}
function showLogImpl(level, data) {
if (DEBUG >= level) console.log(Array.prototype.join.call(data, ' '));
}
function cutCommand(line, index){
//console.log("cutCommand", line, index);
if (index == undefined) index = 0;
var i = 0;
var sp_index = 0;
var sp_index_old = 0;
while (i <= index && sp_index > -1) {
sp_index_old = sp_index;
sp_index = line.indexOf(" ", sp_index_old+1);
i++;
}
var res;
if (sp_index > -1) res = line.slice(sp_index_old, sp_index);
else res = line.slice (sp_index_old);
//console.log("cutCommand", index, i, sp_index_old, sp_index, res);
if (res.charAt(0) == " ") res = res.slice(1);
return res;
}
function updateConfig (line) {
var action = cutCommand (line, 1);
switch (action) {
case "get":
var key = cutCommand(line, 2);
sendOutput(key + " requested");
activeWebSocket.send(line);
break;
case "set":
if (activeWebSocket) {
sendOutput("sending new config values");
activeWebSocket.send(line);
} else {
sendOutput("no open socket");
}
break;
case "help":
case "?":
showHelp("config");
break;
case "load":
//break;
case "save":
//break;
default :
sendOutput("Unknown config command", action);
showHelp("config");
}
}
var filesLoaded = 0;
function getFile(localPath, res, mimeType) {
var contents = fs.readFileSync(localPath);//TODO how to load multiple javasccript files
//res.setHeader("Content-Length", contents.length);
res.setHeader("Content-Type", mimeType);
res.statusCode = 200;
res.end(contents, "UTF-8", function() {});
debugLog("Loaded: ", localPath);
/*
fs.readFile(localPath, function(err, contents) {
if(!err) {
res.setHeader("Content-Length", contents.length);
res.setHeader("Content-Type", mimeType);
res.statusCode = 200;
res.end(contents);
} else {
res.writeHead(500);
res.end();
}
});*/
}