forked from Ylianst/MeshCentral
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmeshuser.js
3283 lines (2974 loc) · 214 KB
/
meshuser.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
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @description MeshCentral MeshAgent
* @author Ylian Saint-Hilaire & Bryan Roe
* @copyright Intel Corporation 2018-2019
* @license Apache-2.0
* @version v0.0.1
*/
/*jslint node: true */
/*jshint node: true */
/*jshint strict:false */
/*jshint -W097 */
/*jshint esversion: 6 */
"use strict";
// Construct a MeshAgent object, called upon connection
module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, user) {
const fs = require('fs');
const path = require('path');
const common = parent.common;
// Mesh Rights
const MESHRIGHT_EDITMESH = 1;
const MESHRIGHT_MANAGEUSERS = 2;
const MESHRIGHT_MANAGECOMPUTERS = 4;
const MESHRIGHT_REMOTECONTROL = 8;
const MESHRIGHT_AGENTCONSOLE = 16;
const MESHRIGHT_SERVERFILES = 32;
const MESHRIGHT_WAKEDEVICE = 64;
const MESHRIGHT_SETNOTES = 128;
const MESHRIGHT_REMOTEVIEWONLY = 256;
const MESHRIGHT_NOTERMINAL = 512;
const MESHRIGHT_NOFILES = 1024;
const MESHRIGHT_NOAMT = 2048;
const MESHRIGHT_DESKLIMITEDINPUT = 4096;
const MESHRIGHT_LIMITEVENTS = 8192;
const MESHRIGHT_CHATNOTIFY = 16384;
const MESHRIGHT_UNINSTALL = 32768;
// Site rights
const SITERIGHT_SERVERBACKUP = 1;
const SITERIGHT_MANAGEUSERS = 2;
const SITERIGHT_SERVERRESTORE = 4;
const SITERIGHT_FILEACCESS = 8;
const SITERIGHT_SERVERUPDATE = 16;
const SITERIGHT_LOCKED = 32; // 0x00000020
const SITERIGHT_NONEWGROUPS = 64; // 0x00000040
const SITERIGHT_NOMESHCMD = 128; // 0x00000080
var obj = {};
obj.user = user;
obj.domain = domain;
obj.ws = ws;
// Server side Intel AMT stack
const WsmanComm = require('./amt/amt-wsman-comm.js');
const Wsman = require('./amt/amt-wsman.js');
const Amt = require('./amt/amt.js');
// Send a message to the user
//obj.send = function (data) { try { if (typeof data == 'string') { ws.send(Buffer.from(data, 'binary')); } else { ws.send(data); } } catch (e) { } }
// Clean a IPv6 address that encodes a IPv4 address
function cleanRemoteAddr(addr) { if (addr.startsWith('::ffff:')) { return addr.substring(7); } else { return addr; } }
// Disconnect this user
obj.close = function (arg) {
if ((arg == 1) || (arg == null)) { try { ws.close(); parent.parent.debug('user', 'Soft disconnect'); } catch (e) { console.log(e); } } // Soft close, close the websocket
if (arg == 2) { try { ws._socket._parent.end(); parent.parent.debug('user', 'Hard disconnect'); } catch (e) { console.log(e); } } // Hard close, close the TCP socket
// Perform cleanup
parent.parent.RemoveAllEventDispatch(ws);
if (obj.serverStatsTimer != null) { clearInterval(obj.serverStatsTimer); delete obj.serverStatsTimer; }
if (req.session && req.session.ws && req.session.ws == ws) { delete req.session.ws; }
if (parent.wssessions2[ws.sessionId]) { delete parent.wssessions2[ws.sessionId]; }
if ((obj.user != null) && (parent.wssessions[obj.user._id])) {
var i = parent.wssessions[obj.user._id].indexOf(ws);
if (i >= 0) {
parent.wssessions[obj.user._id].splice(i, 1);
var user = parent.users[obj.user._id];
if (user) {
if (parent.parent.multiServer == null) {
var targets = ['*', 'server-users'];
if (obj.user.groups) { for (var i in obj.user.groups) { targets.push('server-users:' + i); } }
parent.parent.DispatchEvent(targets, obj, { action: 'wssessioncount', userid: user._id, username: user.name, count: parent.wssessions[obj.user._id].length, nolog: 1, domain: domain.id });
} else {
parent.recountSessions(ws.sessionId); // Recount sessions
}
}
if (parent.wssessions[obj.user._id].length == 0) { delete parent.wssessions[obj.user._id]; }
}
}
// If we have peer servers, inform them of the disconnected session
if (parent.parent.multiServer != null) { parent.parent.multiServer.DispatchMessage({ action: 'sessionEnd', sessionid: ws.sessionId }); }
// Aggressive cleanup
if (obj.user) { delete obj.user; }
if (obj.domain) { delete obj.domain; }
if (ws.userid) { delete ws.userid; }
if (ws.domainid) { delete ws.domainid; }
if (ws.sessionId) { delete ws.sessionId; }
if (ws.HandleEvent) { delete ws.HandleEvent; }
ws.removeAllListeners(["message", "close", "error"]);
};
// Convert a mesh path array into a real path on the server side
function meshPathToRealPath(meshpath, user) {
if (common.validateArray(meshpath, 1) == false) return null;
var splitid = meshpath[0].split('/');
if (splitid[0] == 'user') {
// Check user access
if (meshpath[0] != user._id) return null; // Only allow own user folder
} else if (splitid[0] == 'mesh') {
// Check mesh access
var meshrights = user.links[meshpath[0]];
if (meshrights == null) return null; // No meth rights for this user
meshrights = meshrights.rights; // Get the rights bit mask
if ((meshrights == null) || ((meshrights & 32) == 0)) return null; // This user must have mesh rights to "server files"
} else return null;
var rootfolder = meshpath[0], rootfoldersplit = rootfolder.split('/'), domainx = 'domain';
if (rootfoldersplit[1].length > 0) domainx = 'domain-' + rootfoldersplit[1];
var path = parent.path.join(parent.filespath, domainx, rootfoldersplit[0] + '-' + rootfoldersplit[2]);
for (var i = 1; i < meshpath.length; i++) { if (common.IsFilenameValid(meshpath[i]) == false) { path = null; break; } path += ("/" + meshpath[i]); }
return path;
}
// Copy a file using the best technique available
function copyFile(src, dest, func, tag) {
if (fs.copyFile) {
// NodeJS v8.5 and higher
fs.copyFile(src, dest, function (err) { func(tag); })
} else {
// Older NodeJS
try {
var ss = fs.createReadStream(src), ds = fs.createWriteStream(dest);
ss.on('error', function () { func(tag); });
ds.on('error', function () { func(tag); });
ss.pipe(ds);
ds.ss = ss;
if (arguments.length == 3 && typeof arguments[2] === 'function') { ds.on('close', arguments[2]); }
else if (arguments.length == 4 && typeof arguments[3] === 'function') { ds.on('close', arguments[3]); }
ds.on('close', function () { func(tag); });
} catch (ex) { }
}
}
// Route a command to a target node
function routeCommandToNode(command) {
if (common.validateString(command.nodeid, 8, 128) == false) return false;
var splitnodeid = command.nodeid.split('/');
// Check that we are in the same domain and the user has rights over this node.
if ((splitnodeid[0] == 'node') && (splitnodeid[1] == domain.id)) {
// See if the node is connected
var agent = parent.wsagents[command.nodeid];
if (agent != null) {
// Check if we have permission to send a message to that node
var rights = user.links[agent.dbMeshKey];
var mesh = parent.meshes[agent.dbMeshKey];
if ((rights != null) && (mesh != null) && ((rights.rights & 8) || (rights.rights & 256))) { // 8 is remote control permission, 256 is desktop read only
command.sessionid = ws.sessionId; // Set the session id, required for responses
command.rights = rights.rights; // Add user rights flags to the message
command.consent = mesh.consent; // Add user consent
if (typeof domain.userconsentflags == 'number') { command.consent |= domain.userconsentflags; } // Add server required consent flags
command.username = user.name; // Add user name
command.userid = user._id; // Add user id
command.remoteaddr = cleanRemoteAddr(req.ip); // User's IP address
delete command.nodeid; // Remove the nodeid since it's implied
try { agent.send(JSON.stringify(command)); } catch (ex) { }
}
} else {
// Check if a peer server is connected to this agent
var routing = parent.parent.GetRoutingServerId(command.nodeid, 1); // 1 = MeshAgent routing type
if (routing != null) {
// Check if we have permission to send a message to that node
var rights = user.links[routing.meshid];
var mesh = parent.meshes[routing.meshid];
if ((rights != null) && (mesh != null) && ((rights.rights & 8) || (rights.rights & 256))) { // 8 is remote control permission
command.fromSessionid = ws.sessionId; // Set the session id, required for responses
command.rights = rights.rights; // Add user rights flags to the message
command.consent = mesh.consent; // Add user consent
if (typeof domain.userconsentflags == 'number') { command.consent |= domain.userconsentflags; } // Add server required consent flags
command.username = user.name; // Add user name
command.userid = user._id; // Add user id
command.remoteaddr = cleanRemoteAddr(req.ip); // User's IP address
parent.parent.multiServer.DispatchMessageSingleServer(command, routing.serverid);
}
}
}
}
return true;
}
// Route a command to all targets in a mesh
function routeCommandToMesh(meshid, command) {
// Send the request to all peer servers
// TODO !!!!
// See if the node is connected
for (var nodeid in parent.wsagents) {
var agent = parent.wsagents[nodeid];
if (agent.dbMeshKey == meshid) { try { agent.send(JSON.stringify(command)); } catch (ex) { } }
}
return true;
}
try {
// Check if the user is logged in
if (user == null) { try { ws.close(); } catch (e) { } return; }
// Check if we have exceeded the user session limit
if ((typeof domain.limits.maxusersessions == 'number') || (typeof domain.limits.maxsingleusersessions == 'number')) {
// Count the number of user sessions for this domain
var domainUserSessionCount = 0, selfUserSessionCount = 0;
for (var i in parent.wssessions2) {
if (parent.wssessions2[i].domainid == domain.id) {
domainUserSessionCount++; if (parent.wssessions2[i].userid == user._id) { selfUserSessionCount++; }
}
}
// Check if we have too many user sessions
if (((typeof domain.limits.maxusersessions == 'number') && (domainUserSessionCount >= domain.limits.maxusersessions)) || ((typeof domain.limits.maxsingleusersessions == 'number') && (selfUserSessionCount >= domain.limits.maxsingleusersessions))) {
ws.send(JSON.stringify({ action: 'stopped', msg: 'Session count exceed' }));
try { ws.close(); } catch (e) { }
return;
}
}
// Associate this websocket session with the web session
ws.userid = user._id;
ws.domainid = domain.id;
// Create a new session id for this user.
parent.crypto.randomBytes(20, function (err, randombuf) {
ws.sessionId = user._id + '/' + randombuf.toString('hex');
// Add this web socket session to session list
parent.wssessions2[ws.sessionId] = ws;
if (!parent.wssessions[user._id]) { parent.wssessions[user._id] = [ws]; } else { parent.wssessions[user._id].push(ws); }
if (parent.parent.multiServer == null) {
var targets = ['*', 'server-users'];
if (obj.user.groups) { for (var i in obj.user.groups) { targets.push('server-users:' + i); } }
parent.parent.DispatchEvent(targets, obj, { action: 'wssessioncount', userid: user._id, username: user.name, count: parent.wssessions[user._id].length, nolog: 1, domain: domain.id });
} else {
parent.recountSessions(ws.sessionId); // Recount sessions
}
// If we have peer servers, inform them of the new session
if (parent.parent.multiServer != null) { parent.parent.multiServer.DispatchMessage({ action: 'sessionStart', sessionid: ws.sessionId }); }
// Handle events
ws.HandleEvent = function (source, event, ids, id) {
if (!event.domain || event.domain == domain.id) {
try {
if (event == 'close') { try { delete req.session; } catch (ex) { } obj.close(); }
else if (event == 'resubscribe') { user.subscriptions = parent.subscribe(user._id, ws); }
else if (event == 'updatefiles') { updateUserFiles(user, ws, domain); }
else {
// Because of the device group "Show Self Events Only", we need to do more checks here.
if (id.startsWith('mesh/')) {
// Check if we have rights to get this message. If we have limited events on this mesh, don't send the event to the user.
var meshlink = obj.user.links[id];
if ((meshlink != null) && ((meshlink.rights == 0xFFFFFFFF) || ((meshlink.rights & 8192) == 0) || (ids.indexOf(user._id) >= 0))) {
// We have the device group rights to see this event or we are directly targetted by the event
ws.send(JSON.stringify({ action: 'event', event: event }));
} else {
// Check if no other users are targeted by the event, if not, we can get this event.
var userTarget = false;
for (var i in ids) { if (ids[i].startsWith('user/')) { userTarget = true; } }
if (userTarget == false) { ws.send(JSON.stringify({ action: 'event', event: event })); }
}
} else {
// This is not a device group event, we can get this event.
ws.send(JSON.stringify({ action: 'event', event: event }));
}
}
} catch (e) { }
}
};
user.subscriptions = parent.subscribe(user._id, ws); // Subscribe to events
try { ws._socket.setKeepAlive(true, 240000); } catch (ex) { } // Set TCP keep alive
// Send current server statistics
obj.SendServerStats = function () {
// Take a look at server stats
var os = require('os');
var stats = { action: 'serverstats', totalmem: os.totalmem(), freemem: os.freemem() };
if (parent.parent.platform != 'win32') { stats.cpuavg = os.loadavg(); } // else { stats.cpuavg = [ 0.2435345, 0.523234234, 0.6435345345 ]; }
var serverStats = {
"User Accounts": Object.keys(parent.users).length,
"Device Groups": Object.keys(parent.meshes).length,
"Agent Sessions": Object.keys(parent.wsagents).length,
"Connected Users": Object.keys(parent.wssessions).length,
"Users Sessions": Object.keys(parent.wssessions2).length,
"Relay Sessions": parent.relaySessionCount,
"Relay Count": Object.keys(parent.wsrelays).length
};
if (parent.relaySessionErrorCount != 0) { serverStats['Relay Errors'] = parent.relaySessionErrorCount; }
if (parent.parent.mpsserver != null) { serverStats['Connected Intel® AMT'] = Object.keys(parent.parent.mpsserver.ciraConnections).length; }
// Take a look at agent errors
var agentstats = parent.getAgentStats();
var errorCounters = {}, errorCountersCount = 0;
if (agentstats.meshDoesNotExistCount > 0) { errorCountersCount++; errorCounters["Unknown Group"] = agentstats.meshDoesNotExistCount; }
if (agentstats.invalidPkcsSignatureCount > 0) { errorCountersCount++; errorCounters["Invalid PKCS signature"] = agentstats.invalidPkcsSignatureCount; }
if (agentstats.invalidRsaSignatureCount > 0) { errorCountersCount++; errorCounters["Invalid RSA siguature"] = agentstats.invalidRsaSignatureCount; }
if (agentstats.invalidJsonCount > 0) { errorCountersCount++; errorCounters["Invalid JSON"] = agentstats.invalidJsonCount; }
if (agentstats.unknownAgentActionCount > 0) { errorCountersCount++; errorCounters["Unknown Action"] = agentstats.unknownAgentActionCount; }
if (agentstats.agentBadWebCertHashCount > 0) { errorCountersCount++; errorCounters["Bad Web Certificate"] = agentstats.agentBadWebCertHashCount; }
if ((agentstats.agentBadSignature1Count + agentstats.agentBadSignature2Count) > 0) { errorCountersCount++; errorCounters["Bad Signature"] = (agentstats.agentBadSignature1Count + agentstats.agentBadSignature2Count); }
if (agentstats.agentMaxSessionHoldCount > 0) { errorCountersCount++; errorCounters["Max Sessions Reached"] = agentstats.agentMaxSessionHoldCount; }
if ((agentstats.invalidDomainMeshCount + agentstats.invalidDomainMesh2Count) > 0) { errorCountersCount++; errorCounters["Unknown Device Group"] = (agentstats.invalidDomainMeshCount + agentstats.invalidDomainMesh2Count); }
if ((agentstats.invalidMeshTypeCount + agentstats.invalidMeshType2Count) > 0) { errorCountersCount++; errorCounters["Invalid Device Group Type"] = (agentstats.invalidMeshTypeCount + agentstats.invalidMeshType2Count); }
//if (agentstats.duplicateAgentCount > 0) { errorCountersCount++; errorCounters["Duplicate Agent"] = agentstats.duplicateAgentCount; }
// Send out the stats
stats.values = { "Server State": serverStats }
if (errorCountersCount > 0) { stats.values["Agent Error Counters"] = errorCounters; }
try { ws.send(JSON.stringify(stats)); } catch (ex) { }
}
// When data is received from the web socket
ws.on('message', processWebSocketData);
// If error, do nothing
ws.on('error', function (err) { console.log(err); obj.close(0); });
// If the web socket is closed
ws.on('close', function (req) { obj.close(0); });
// Figure out the MPS port, use the alias if set
var mpsport = ((args.mpsaliasport != null) ? args.mpsaliasport : args.mpsport);
var httpport = ((args.aliasport != null) ? args.aliasport : args.port);
// Build server information object
var serverinfo = { name: domain.dns ? domain.dns : parent.certificates.CommonName, mpsname: parent.certificates.AmtMpsName, mpsport: mpsport, mpspass: args.mpspass, port: httpport, emailcheck: ((parent.parent.mailserver != null) && (domain.auth != 'sspi') && (domain.auth != 'ldap') && (args.lanonly != true) && (parent.certificates.CommonName != null) && (parent.certificates.CommonName.indexOf('.') != -1)), domainauth: ((domain.auth == 'sspi') || (domain.auth == 'ldap')), serverTime: Date.now() };
serverinfo.languages = parent.renderLanguages;
serverinfo.tlshash = Buffer.from(parent.webCertificateHashs[domain.id], 'binary').toString('hex').toUpperCase(); // SHA384 of server HTTPS certificate
if ((parent.parent.config.domains[domain.id].amtacmactivation != null) && (parent.parent.config.domains[domain.id].amtacmactivation.acmmatch != null)) {
var matchingDomains = [];
for (var i in parent.parent.config.domains[domain.id].amtacmactivation.acmmatch) {
var cn = parent.parent.config.domains[domain.id].amtacmactivation.acmmatch[i].cn;
if ((cn != '*') && (matchingDomains.indexOf(cn) == -1)) { matchingDomains.push(cn); }
}
if (matchingDomains.length > 0) { serverinfo.amtAcmFqdn = matchingDomains; }
}
if (args.notls == true) { serverinfo.https = false; } else { serverinfo.https = true; serverinfo.redirport = args.redirport; }
if (typeof domain.userconsentflags == 'number') { serverinfo.consent = domain.userconsentflags; }
if ((typeof domain.usersessionidletimeout == 'number') && (domain.usersessionidletimeout > 0)) { serverinfo.timeout = (domain.usersessionidletimeout * 60 * 1000); }
// Send server information
try { ws.send(JSON.stringify({ action: 'serverinfo', serverinfo: serverinfo })); } catch (ex) { }
// Send user information to web socket, this is the first thing we send
try { ws.send(JSON.stringify({ action: 'userinfo', userinfo: parent.CloneSafeUser(parent.users[user._id]) })); } catch (ex) { }
// Send server tracing information
if (user.siteadmin == 0xFFFFFFFF) {
try { ws.send(JSON.stringify({ action: 'traceinfo', traceSources: parent.parent.debugRemoteSources })); } catch (ex) { }
}
// We are all set, start receiving data
ws._socket.resume();
});
} catch (e) { console.log(e); }
// Process incoming web socket data from the browser
function processWebSocketData(msg) {
var command, i = 0, mesh = null, meshid = null, nodeid = null, meshlinks = null, change = 0;
try { command = JSON.parse(msg.toString('utf8')); } catch (e) { return; }
if (common.validateString(command.action, 3, 32) == false) return; // Action must be a string between 3 and 32 chars
switch (command.action) {
case 'ping': { try { ws.send(JSON.stringify({ action: 'pong' })); } catch (ex) { } break; }
case 'authcookie':
{
// Renew the authentication cookie
try {
ws.send(JSON.stringify({
action: 'authcookie',
cookie: parent.parent.encodeCookie({ userid: user._id, domainid: domain.id, ip: cleanRemoteAddr(req.ip) }, parent.parent.loginCookieEncryptionKey),
rcookie: parent.parent.encodeCookie({ ruserid: user._id }, parent.parent.loginCookieEncryptionKey)
}));
} catch (ex) { }
break;
}
case 'logincookie':
{
// If allowed, return a login cookie
if (parent.parent.config.settings.allowlogintoken === true) {
try { ws.send(JSON.stringify({ action: 'logincookie', cookie: parent.parent.encodeCookie({ u: user._id, a: 3 }, parent.parent.loginCookieEncryptionKey) })); } catch (ex) { }
}
break;
}
case 'servertimelinestats':
{
if ((user.siteadmin & 21) == 0) return; // Only site administrators with "site backup" or "site restore" or "site update" permissions can use this.
if (common.validateInt(command.hours, 0, 24 * 30) == false) return;
db.GetServerStats(command.hours, function (err, docs) {
if (err == null) { ws.send(JSON.stringify({ action: 'servertimelinestats', events: docs })); }
});
break;
}
case 'serverstats':
{
if ((user.siteadmin & 21) == 0) return; // Only site administrators with "site backup" or "site restore" or "site update" permissions can use this.
if (common.validateInt(command.interval, 1000, 1000000) == false) {
// Clear the timer
if (obj.serverStatsTimer != null) { clearInterval(obj.serverStatsTimer); delete obj.serverStatsTimer; }
} else {
// Set the timer
obj.SendServerStats();
obj.serverStatsTimer = setInterval(obj.SendServerStats, command.interval);
}
break;
}
case 'meshes':
{
// Request a list of all meshes this user as rights to
var docs = [];
for (i in user.links) {
if ((parent.meshes[i]) && (parent.meshes[i].deleted == null)) {
// Remove the Intel AMT password if present
docs.push(parent.CloneSafeMesh(parent.meshes[i]));
}
}
try { ws.send(JSON.stringify({ action: 'meshes', meshes: docs, tag: command.tag })); } catch (ex) { }
break;
}
case 'nodes':
{
var links = [], err = null;
try {
if (command.meshid == null) {
// Request a list of all meshes this user as rights to
for (i in user.links) { links.push(i); }
} else {
// Request list of all nodes for one specific meshid
meshid = command.meshid;
if (common.validateString(meshid, 0, 128) == false) { err = 'Invalid group id'; } else {
if (meshid.split('/').length == 1) { meshid = 'mesh/' + domain.id + '/' + command.meshid; }
if (user.links[meshid] != null) { links.push(meshid); } else { err = 'Invalid group id'; }
}
}
} catch (ex) { err = 'Validation exception: ' + ex; }
// Handle any errors
if (err != null) {
if (command.responseid != null) { try { ws.send(JSON.stringify({ action: 'nodes', responseid: command.responseid, result: err })); } catch (ex) { } }
break;
}
// Request a list of all nodes
db.GetAllTypeNoTypeFieldMeshFiltered(links, domain.id, 'node', command.id, function (err, docs) {
if (docs == null) { docs = []; }
var r = {};
for (i in docs) {
// Remove any connectivity and power state information, that should not be in the database anyway.
// TODO: Find why these are sometimes saves in the db.
if (docs[i].conn != null) { delete docs[i].conn; }
if (docs[i].pwr != null) { delete docs[i].pwr; }
if (docs[i].agct != null) { delete docs[i].agct; }
if (docs[i].cict != null) { delete docs[i].cict; }
// Add the connection state
var state = parent.parent.GetConnectivityState(docs[i]._id);
if (state) {
docs[i].conn = state.connectivity;
docs[i].pwr = state.powerState;
if ((state.connectivity & 1) != 0) { var agent = parent.wsagents[docs[i]._id]; if (agent != null) { docs[i].agct = agent.connectTime; } }
if ((state.connectivity & 2) != 0) { var cira = parent.parent.mpsserver.ciraConnections[docs[i]._id]; if (cira != null) { docs[i].cict = cira.tag.connectTime; } }
}
// Compress the meshid's
meshid = docs[i].meshid;
if (!r[meshid]) { r[meshid] = []; }
delete docs[i].meshid;
// Remove Intel AMT credential if present
if (docs[i].intelamt != null && docs[i].intelamt.pass != null) { delete docs[i].intelamt.pass; }
// If GeoLocation not enabled, remove any node location information
if (domain.geolocation != true) {
if (docs[i].iploc != null) { delete docs[i].iploc; }
if (docs[i].wifiloc != null) { delete docs[i].wifiloc; }
if (docs[i].gpsloc != null) { delete docs[i].gpsloc; }
if (docs[i].userloc != null) { delete docs[i].userloc; }
}
r[meshid].push(docs[i]);
}
try { ws.send(JSON.stringify({ action: 'nodes', responseid: command.responseid, nodes: r, tag: command.tag })); } catch (ex) { }
});
break;
}
case 'powertimeline':
{
// Perform pre-validation
if (common.validateString(command.nodeid, 0, 128) == false) break;
var snode = command.nodeid.split('/');
if ((snode.length != 3) || (snode[1] != domain.id)) break;
// Check that we have permissions for this node.
if (obj.user.links == null) return;
db.Get(command.nodeid, function (err, nodes) {
if (nodes == null || nodes.length != 1) return;
const node = nodes[0];
var meshlink = obj.user.links[node.meshid];
if ((meshlink != null) && (meshlink.rights != 0)) {
// Query the database for the power timeline for a given node
// The result is a compacted array: [ startPowerState, startTimeUTC, powerState ] + many[ deltaTime, powerState ]
db.getPowerTimeline(command.nodeid, function (err, docs) {
if ((err == null) && (docs != null) && (docs.length > 0)) {
var timeline = [], time = null, previousPower;
for (i in docs) {
var doc = docs[i], j = parseInt(i);
doc.time = Date.parse(doc.time);
if (time == null) { // First element
// Skip all starting power 0 events.
if ((doc.power == 0) && ((doc.oldPower == null) || (doc.oldPower == 0))) continue;
time = doc.time;
if (doc.oldPower) { timeline.push(doc.oldPower, time / 1000, doc.power); } else { timeline.push(0, time / 1000, doc.power); }
} else if (previousPower != doc.power) { // Delta element
// If this event is of a short duration (2 minutes or less), skip it.
if ((docs.length > (j + 1)) && ((Date.parse(docs[j + 1].time) - doc.time) < 120000)) continue;
timeline.push((doc.time - time) / 1000, doc.power);
time = doc.time;
}
previousPower = doc.power;
}
try { ws.send(JSON.stringify({ action: 'powertimeline', nodeid: command.nodeid, timeline: timeline, tag: command.tag })); } catch (ex) { }
} else {
// No records found, send current state if we have it
var state = parent.parent.GetConnectivityState(command.nodeid);
if (state != null) { try { ws.send(JSON.stringify({ action: 'powertimeline', nodeid: command.nodeid, timeline: [state.powerState, Date.now(), state.powerState], tag: command.tag })); } catch (ex) { } }
}
});
}
});
break;
}
case 'getsysinfo':
{
// Perform pre-validation
if (common.validateString(command.nodeid, 0, 128) == false) break;
var snode = command.nodeid.split('/');
if ((snode.length != 3) || (snode[1] != domain.id)) break;
// Check that we have permissions for this node.
if (obj.user.links == null) return;
db.Get(command.nodeid, function (err, nodes) {
if (nodes == null || nodes.length != 1) return;
const node = nodes[0];
var meshlink = obj.user.links[node.meshid];
if ((meshlink != null) && (meshlink.rights != 0)) {
// Query the database system information
db.Get('si' + command.nodeid, function (err, docs) {
if ((docs != null) && (docs.length > 0)) {
var doc = docs[0];
doc.action = 'getsysinfo';
doc.nodeid = command.nodeid;
doc.tag = command.tag;
delete doc.type;
delete doc.domain;
delete doc._id;
try { ws.send(JSON.stringify(doc)); } catch (ex) { }
} else {
try { ws.send(JSON.stringify({ action: 'getsysinfo', nodeid: command.nodeid, tag: command.tag, noinfo: true })); } catch (ex) { }
}
});
}
});
break;
}
case 'lastconnect':
{
// Perform pre-validation
if (common.validateString(command.nodeid, 0, 128) == false) return;
var snode = command.nodeid.split('/');
if ((snode.length != 3) || (snode[1] != domain.id)) break;
// Check that we have permissions for this node.
if (obj.user.links == null) return;
db.Get(command.nodeid, function (err, nodes) {
if (nodes == null || nodes.length != 1) return;
const node = nodes[0];
var meshlink = obj.user.links[node.meshid];
if ((meshlink != null) && (meshlink.rights != 0)) {
// Query the database for the last time this node connected
db.Get('lc' + command.nodeid, function (err, docs) {
if ((docs != null) && (docs.length > 0)) {
try { ws.send(JSON.stringify({ action: 'lastconnect', nodeid: command.nodeid, time: docs[0].time, addr: docs[0].addr })); } catch (ex) { }
}
});
}
});
break;
}
case 'files':
{
// Send the full list of server files to the browser app
updateUserFiles(user, ws, domain);
break;
}
case 'fileoperation':
{
// Check permissions
if ((user.siteadmin & 8) != 0) {
// Perform a file operation (Create Folder, Delete Folder, Delete File...)
if (common.validateString(command.fileop, 4, 16) == false) return;
var sendUpdate = true, path = meshPathToRealPath(command.path, user); // This will also check access rights
if (path == null) break;
if ((command.fileop == 'createfolder') && (common.IsFilenameValid(command.newfolder) == true)) {
// Create a new folder
try { fs.mkdirSync(path + '/' + command.newfolder); } catch (ex) {
try { fs.mkdirSync(path); } catch (ex) { }
try { fs.mkdirSync(path + '/' + command.newfolder); } catch (ex) { }
}
}
else if (command.fileop == 'delete') {
// Delete a file
if (common.validateArray(command.delfiles, 1) == false) return;
for (i in command.delfiles) {
if (common.IsFilenameValid(command.delfiles[i]) == true) {
var fullpath = parent.path.join(path, command.delfiles[i]);
if (command.rec == true) {
try { deleteFolderRecursive(fullpath); } catch (ex) { } // TODO, make this an async function
} else {
try { fs.rmdirSync(fullpath); } catch (ex) { try { fs.unlinkSync(fullpath); } catch (xe) { } }
}
}
}
// If we deleted something in the mesh root folder and the entire mesh folder is empty, remove it.
if (command.path.length == 1) {
try {
if (command.path[0].startsWith('mesh//')) {
path = meshPathToRealPath([command.path[0]], user);
fs.readdir(path, function (err, dir) { if ((err == null) && (dir.length == 0)) { fs.rmdir(path, function (err) { }); } });
}
} catch (ex) { }
}
}
else if ((command.fileop == 'rename') && (common.IsFilenameValid(command.oldname) == true) && (common.IsFilenameValid(command.newname) == true)) {
// Rename
try { fs.renameSync(path + "/" + command.oldname, path + "/" + command.newname); } catch (e) { }
}
else if ((command.fileop == 'copy') || (command.fileop == 'move')) {
if (common.validateArray(command.names, 1) == false) return;
var scpath = meshPathToRealPath(command.scpath, user); // This will also check access rights
if (scpath == null) break;
// TODO: Check quota if this is a copy!!!!!!!!!!!!!!!!
for (i in command.names) {
var s = parent.path.join(scpath, command.names[i]), d = parent.path.join(path, command.names[i]);
sendUpdate = false;
copyFile(s, d, function (op) { if (op != null) { fs.unlink(op, function (err) { parent.parent.DispatchEvent([user._id], obj, 'updatefiles'); }); } else { parent.parent.DispatchEvent([user._id], obj, 'updatefiles'); } }, ((command.fileop == 'move') ? s : null));
}
}
if (sendUpdate == true) { parent.parent.DispatchEvent([user._id], obj, 'updatefiles'); } // Fire an event causing this user to update this files
}
break;
}
case 'serverconsole':
{
// This is a server console message, only process this if full administrator
if (user.siteadmin != 0xFFFFFFFF) break;
var r = '';
var cmdargs = splitArgs(command.value);
if (cmdargs.length == 0) break;
const cmd = cmdargs[0].toLowerCase();
cmdargs = parseArgs(cmdargs);
switch (cmd) {
case 'help': {
r = 'Available commands: help, info, versions, args, resetserver, showconfig, usersessions, tasklimiter, setmaxtasks, cores,\r\n'
r += 'migrationagents, agentstats, webstats, mpsstats, swarmstats, acceleratorsstats, updatecheck, serverupdate, nodeconfig,\r\n';
r += 'heapdump, relays, autobackup, backupconfig, dupagents, dispatchtable.';
break;
}
case 'dispatchtable': {
r = '';
for (var i in parent.parent.eventsDispatch) {
r += (i + ', ' + parent.parent.eventsDispatch[i].length + '\r\n');
}
break;
}
case 'dupagents': {
for (var i in parent.duplicateAgentsLog) { r += JSON.stringify(parent.duplicateAgentsLog[i]) + '\r\n'; }
if (r == '') { r = 'No duplicate agents in log.'; }
break;
}
case 'agentstats': {
var stats = parent.getAgentStats();
for (var i in stats) {
if (typeof stats[i] == 'object') { r += (i + ': ' + JSON.stringify(stats[i]) + '\r\n'); } else { r += (i + ': ' + stats[i] + '\r\n'); }
}
break;
}
case 'webstats': {
var stats = parent.getStats();
for (var i in stats) {
if (typeof stats[i] == 'object') { r += (i + ': ' + JSON.stringify(stats[i]) + '\r\n'); } else { r += (i + ': ' + stats[i] + '\r\n'); }
}
break;
}
case 'acceleratorsstats': {
var stats = parent.parent.certificateOperations.getAcceleratorStats();
for (var i in stats) {
if (typeof stats[i] == 'object') { r += (i + ': ' + JSON.stringify(stats[i]) + '\r\n'); } else { r += (i + ': ' + stats[i] + '\r\n'); }
}
break;
}
case 'mpsstats': {
var stats = parent.parent.mpsserver.getStats();
for (var i in stats) {
if (typeof stats[i] == 'object') { r += (i + ': ' + JSON.stringify(stats[i]) + '\r\n'); } else { r += (i + ': ' + stats[i] + '\r\n'); }
}
break;
}
case 'serverupdate': {
r = 'Performing server update...';
if (parent.parent.performServerUpdate() == false) { r = 'Server self-update not possible.'; }
break;
}
case 'print': {
console.log(cmdargs["_"][0]);
break;
}
case 'updatecheck': {
parent.parent.getLatestServerVersion(function (currentVer, newVer, error) {
var r2 = 'Current Version: ' + currentVer + '\r\n';
if (newVer != null) { r2 += 'Available Version: ' + newVer + '\r\n'; }
if (error != null) { r2 += 'Exception: ' + error + '\r\n'; }
try { ws.send(JSON.stringify({ action: 'serverconsole', value: r2, tag: command.tag })); } catch (ex) { }
});
r = 'Checking server update...';
break;
}
case 'info': {
var info = process.memoryUsage();
info.dbType = ['None', 'NeDB', 'MongoJS', 'MongoDB'][parent.db.databaseType];
if (parent.db.databaseType == 3) { info.dbChangeStream = parent.db.changeStream; }
try { info.platform = process.platform; } catch (ex) { }
try { info.arch = process.arch; } catch (ex) { }
try { info.pid = process.pid; } catch (ex) { }
try { info.uptime = process.uptime(); } catch (ex) { }
try { info.version = process.version; } catch (ex) { }
try { info.cpuUsage = process.cpuUsage(); } catch (ex) { }
r = JSON.stringify(info, null, 4);
break;
}
case 'nodeconfig': {
r = JSON.stringify(process.config, null, 4);
break;
}
case 'versions': {
r = JSON.stringify(process.versions, null, 4);
break;
}
case 'args': {
r = cmd + ': ' + JSON.stringify(cmdargs);
break;
}
case 'usersessions': {
for (var i in parent.wssessions) {
r += (i + ', ' + parent.wssessions[i].length + ' session' + ((parent.wssessions[i].length > 1) ? 'a' : '') + '.<br />');
for (var j in parent.wssessions[i]) {
var addr = parent.wssessions[i][j]._socket.remoteAddress;
if (addr.startsWith('::ffff:')) { addr = addr.substring(7); }
r += ' ' + addr + ' --> ' + parent.wssessions[i][j].sessionId + '.<br />';
}
}
break;
}
case 'resetserver': {
console.log('Server restart...');
process.exit(0);
break;
}
case 'tasklimiter': {
if (parent.parent.taskLimiter != null) {
//var obj = { maxTasks: maxTasks, maxTaskTime: (maxTaskTime * 1000), nextTaskId: 0, currentCount: 0, current: {}, pending: [[], [], []], timer: null };
const tl = parent.parent.taskLimiter;
r += 'MaxTasks: ' + tl.maxTasks + ', NextTaskId: ' + tl.nextTaskId + '<br />';
r += 'MaxTaskTime: ' + (tl.maxTaskTime / 1000) + ' seconds, Timer: ' + (tl.timer != null) + '<br />';
var c = [];
for (var i in tl.current) { c.push(i); }
r += 'Current (' + tl.currentCount + '): [' + c.join(', ') + ']<br />';
r += 'Pending (High/Med/Low): ' + tl.pending[0].length + ', ' + tl.pending[1].length + ', ' + tl.pending[2].length + '<br />';
}
break;
}
case 'setmaxtasks': {
if ((cmdargs["_"].length != 1) || (parseInt(cmdargs["_"][0]) < 1) || (parseInt(cmdargs["_"][0]) > 1000)) {
r = 'Usage: setmaxtasks [1 to 1000]';
} else {
parent.parent.taskLimiter.maxTasks = parseInt(cmdargs["_"][0]);
r = 'MaxTasks set to ' + parent.parent.taskLimiter.maxTasks + '.';
}
break;
}
case 'cores': {
if (parent.parent.defaultMeshCores != null) { for (var i in parent.parent.defaultMeshCores) { r += i + ': ' + parent.parent.defaultMeshCores[i].length + ' bytes<br />'; } }
break;
}
case 'showconfig': {
// Make a copy of the configuration and hide any secrets
var config = common.Clone(parent.parent.config);
if (config.settings) {
if (config.settings.configkey) { config.settings.configkey = '(present)'; }
if (config.settings.sessionkey) { config.settings.sessionkey = '(present)'; }
if (config.settings.dbencryptkey) { config.settings.dbencryptkey = '(present)'; }
}
if (config.domains) {
for (var i in config.domains) {
if (config.domains[i].yubikey && config.domains[i].yubikey.secret) { config.domains[i].yubikey.secret = '(present)'; }
}
}
r = JSON.stringify(removeAllUnderScore(config), null, 4);
break;
}
case 'migrationagents': {
if (parent.parent.swarmserver == null) {
r = 'Swarm server not running.';
} else {
for (var i in parent.parent.swarmserver.migrationAgents) {
var arch = parent.parent.swarmserver.migrationAgents[i];
for (var j in arch) { var agent = arch[j]; r += 'Arch ' + agent.arch + ', Ver ' + agent.ver + ', Size ' + ((agent.binary == null) ? 0 : agent.binary.length) + '<br />'; }
}
}
break;
}
case 'swarmstats': {
if (parent.parent.swarmserver == null) {
r = 'Swarm server not running.';
} else {
for (var i in parent.parent.swarmserver.stats) {
if (typeof parent.parent.swarmserver.stats[i] == 'object') {
r += i + ': ' + JSON.stringify(parent.parent.swarmserver.stats[i]) + '\r\n';
} else {
r += i + ': ' + parent.parent.swarmserver.stats[i] + '\r\n';
}
}
}
break;
}
case 'heapdump': {
var heapdump = null;
try { heapdump = require('heapdump'); } catch (ex) { }
if (heapdump == null) {
r = 'Heapdump module not installed, run "npm install heapdump".';
} else {
heapdump.writeSnapshot(function (err, filename) {
if (err != null) {
try { ws.send(JSON.stringify({ action: 'serverconsole', value: 'Unable to write heapdump: ' + err })); } catch (ex) { }
} else {
try { ws.send(JSON.stringify({ action: 'serverconsole', value: 'Wrote heapdump at ' + filename })); } catch (ex) { }
}
});
}
break;
}
case 'relays': {
for (var i in parent.wsrelays) {
r += 'id: ' + i + ', state: ' + parent.wsrelays[i].state;
if (parent.wsrelays[i].peer1 != null) { r += ', peer1: ' + cleanRemoteAddr(parent.wsrelays[i].peer1.req.ip); }
if (parent.wsrelays[i].peer2 != null) { r += ', peer2: ' + cleanRemoteAddr(parent.wsrelays[i].peer2.req.ip); }
r += '<br />';
}
if (r == '') { r = 'No relays.'; }
break;
}
case 'autobackup': {
var backupResult = parent.db.performBackup();
if (backupResult == 0) { r = 'Starting auto-backup...'; } else { r = 'Backup alreay in progress.'; }
break;
}
case 'backupconfig': {
r = parent.db.getBackupConfig();
break;
}
default: { // This is an unknown command, return an error message
r = 'Unknown command \"' + cmd + '\", type \"help\" for list of avaialble commands.';
break;
}
}
if (r != '') { try { ws.send(JSON.stringify({ action: 'serverconsole', value: r, tag: command.tag })); } catch (ex) { } }
break;
}
case 'msg':
{
// Route this command to a target node
routeCommandToNode(command);
break;
}
case 'events':
{
// User filtered events
if ((command.user != null) && ((user.siteadmin & 2) != 0)) { // SITERIGHT_MANAGEUSERS
// TODO: Add the meshes command.user has access to (???)
var filter = ['user/' + domain.id + '/' + command.user.toLowerCase()];
if ((command.limit == null) || (typeof command.limit != 'number')) {
// Send the list of all events for this session
db.GetUserEvents(filter, domain.id, command.user, function (err, docs) {
if (err != null) return;
try { ws.send(JSON.stringify({ action: 'events', events: docs, user: command.user, tag: command.tag })); } catch (ex) { }
});
} else {
// Send the list of most recent events for this session, up to 'limit' count
db.GetUserEventsWithLimit(filter, domain.id, command.user, command.limit, function (err, docs) {
if (err != null) return;
try { ws.send(JSON.stringify({ action: 'events', events: docs, user: command.user, tag: command.tag })); } catch (ex) { }
});
}
} else if (common.validateString(command.nodeid, 0, 128) == true) { // Device filtered events
// Check that the user has access to this nodeid
if (obj.user.links == null) return;
db.Get(command.nodeid, function (err, nodes) {
if ((nodes == null) || (nodes.length != 1)) return;
const node = nodes[0];
var meshlink = obj.user.links[node.meshid];
if ((meshlink != null) && (meshlink.rights != 0)) {
// Put a limit on the number of returned entries if present
var limit = 10000;
if (common.validateInt(command.limit, 1, 60000) == true) { limit = command.limit; }
if ((meshlink.rights & 8192) != 0) {
// Send the list of most recent events for this nodeid that only apply to us, up to 'limit' count
db.GetNodeEventsSelfWithLimit(command.nodeid, domain.id, user._id, limit, function (err, docs) {
if (err != null) return;
try { ws.send(JSON.stringify({ action: 'events', events: docs, nodeid: command.nodeid, tag: command.tag })); } catch (ex) { }
});
} else {
// Send the list of most recent events for this nodeid, up to 'limit' count
db.GetNodeEventsWithLimit(command.nodeid, domain.id, limit, function (err, docs) {
if (err != null) return;
try { ws.send(JSON.stringify({ action: 'events', events: docs, nodeid: command.nodeid, tag: command.tag })); } catch (ex) { }
});
}
}
});
} else {
// Create a filter for device groups
if (obj.user.links == null) return;
// All events
var exGroupFilter2 = [], filter = [], filter2 = user.subscriptions;
// Remove MeshID's that we do not have rights to see events for
for (var link in obj.user.links) { if (((obj.user.links[link].rights & 8192) != 0) && ((obj.user.links[link].rights != 0xFFFFFFFF))) { exGroupFilter2.push(link); } }
for (var i in filter2) { if (exGroupFilter2.indexOf(filter2[i]) == -1) { filter.push(filter2[i]); } }
if ((command.limit == null) || (typeof command.limit != 'number')) {
// Send the list of all events for this session
db.GetEvents(filter, domain.id, function (err, docs) {
if (err != null) return;
try { ws.send(JSON.stringify({ action: 'events', events: docs, user: command.user, tag: command.tag })); } catch (ex) { }
});
} else {
// Send the list of most recent events for this session, up to 'limit' count
db.GetEventsWithLimit(filter, domain.id, command.limit, function (err, docs) {
if (err != null) return;
try { ws.send(JSON.stringify({ action: 'events', events: docs, user: command.user, tag: command.tag })); } catch (ex) { }
});
}
}
break;
}
case 'users':
{
// Request a list of all users
if ((user.siteadmin & 2) == 0) break;
var docs = [];
for (i in parent.users) {
if ((parent.users[i].domain == domain.id) && (parent.users[i].name != '~')) {
// If we are part of a user group, we can only see other members of our own group
if ((user.groups == null) || (user.groups.length == 0) || ((parent.users[i].groups != null) && (findOne(parent.users[i].groups, user.groups)))) {
docs.push(parent.CloneSafeUser(parent.users[i]));
}
}
}
try { ws.send(JSON.stringify({ action: 'users', users: docs, tag: command.tag })); } catch (ex) { }
break;
}
case 'changelang':
{
if (common.validateString(command.lang, 1, 6) == false) return;
// Always lowercase the email address
command.lang = command.lang.toLowerCase();