Removed unneeded file
Bryan Roe committed
Jun 17, 2020 at 23:59 UTC
560483034de172124d957a22a865076177208687
1 file changed
-750
agents/modules_meshcmd/user-sessions.js
deleted
-750
@@ -1,750 +0,0 @@
1
-/*
2
-Copyright 2018 Intel Corporation
3
-
4
-Licensed under the Apache License, Version 2.0 (the "License");
5
-you may not use this file except in compliance with the License.
6
-You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
-Unless required by applicable law or agreed to in writing, software
11
-distributed under the License is distributed on an "AS IS" BASIS,
12
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
-See the License for the specific language governing permissions and
14
-limitations under the License.
15
-*/
16
-
17
-var NOTIFY_FOR_THIS_SESSION = 0;
18
-var NOTIFY_FOR_ALL_SESSIONS = 1;
19
-var WM_WTSSESSION_CHANGE = 0x02B1;
20
-var WM_POWERBROADCAST = 0x218;
21
-var PBT_POWERSETTINGCHANGE = 0x8013;
22
-var PBT_APMSUSPEND = 0x4;
23
-var PBT_APMRESUMESUSPEND = 0x7;
24
-var PBT_APMRESUMEAUTOMATIC = 0x12;
25
-var PBT_APMPOWERSTATUSCHANGE = 0xA;
26
-
27
-var WTS_CONSOLE_CONNECT = (0x1);
28
-var WTS_CONSOLE_DISCONNECT = (0x2);
29
-var WTS_REMOTE_CONNECT = (0x3);
30
-var WTS_REMOTE_DISCONNECT = (0x4);
31
-var WTS_SESSION_LOGON = (0x5);
32
-var WTS_SESSION_LOGOFF = (0x6);
33
-var WTS_SESSION_LOCK = (0x7);
34
-var WTS_SESSION_UNLOCK = (0x8);
35
-var WTS_SESSION_REMOTE_CONTROL = (0x9);
36
-var WTS_SESSION_CREATE = (0xA);
37
-var WTS_SESSION_TERMINATE = (0xB);
38
-
39
-var GUID_ACDC_POWER_SOURCE;
40
-var GUID_BATTERY_PERCENTAGE_REMAINING;
41
-var GUID_CONSOLE_DISPLAY_STATE;
42
-
43
-function UserSessions()
44
-{
45
- this._ObjectID = 'user-sessions';
46
- require('events').EventEmitter.call(this, true)
47
- .createEvent('changed')
48
- .createEvent('locked')
49
- .createEvent('unlocked');
50
-
51
- this.enumerateUsers = function enumerateUsers()
52
- {
53
- var promise = require('promise');
54
- var p = new promise(function (res, rej)
55
- {
56
- this.__resolver = res;
57
- this.__rejector = rej;
58
- });
59
- p.__handler = function __handler(users)
60
- {
61
- p.__resolver(users);
62
- };
63
- try
64
- {
65
- this.Current(p.__handler);
66
- }
67
- catch(e)
68
- {
69
- p.__rejector(e);
70
- }
71
- p.parent = this;
72
- return (p);
73
- }
74
-
75
- if (process.platform == 'win32')
76
- {
77
- this._serviceHooked = false;
78
- this._marshal = require('_GenericMarshal');
79
- this._kernel32 = this._marshal.CreateNativeProxy('Kernel32.dll');
80
- this._kernel32.CreateMethod('GetLastError');
81
-
82
- try
83
- {
84
- this._wts = this._marshal.CreateNativeProxy('Wtsapi32.dll');
85
- this._wts.CreateMethod('WTSEnumerateSessionsA');
86
- this._wts.CreateMethod('WTSQuerySessionInformationA');
87
- this._wts.CreateMethod('WTSRegisterSessionNotification');
88
- this._wts.CreateMethod('WTSUnRegisterSessionNotification');
89
- this._wts.CreateMethod('WTSFreeMemory');
90
- }
91
- catch(exc)
92
- {
93
- }
94
-
95
- this._advapi = this._marshal.CreateNativeProxy('Advapi32.dll');
96
- this._advapi.CreateMethod('AllocateAndInitializeSid');
97
- this._advapi.CreateMethod('CheckTokenMembership');
98
- this._advapi.CreateMethod('FreeSid');
99
-
100
- this._user32 = this._marshal.CreateNativeProxy('user32.dll');
101
- this._user32.CreateMethod({ method: 'RegisterPowerSettingNotification', threadDispatch: 1});
102
- this._user32.CreateMethod('UnregisterPowerSettingNotification');
103
- this._rpcrt = this._marshal.CreateNativeProxy('Rpcrt4.dll');
104
- this._rpcrt.CreateMethod('UuidFromStringA');
105
- this._rpcrt.StringToUUID = function StringToUUID(guid)
106
- {
107
- var retVal = StringToUUID.us._marshal.CreateVariable(16);
108
- if(StringToUUID.us._rpcrt.UuidFromStringA(StringToUUID.us._marshal.CreateVariable(guid), retVal).Val == 0)
109
- {
110
- return (retVal);
111
- }
112
- else
113
- {
114
- throw ('Could not convert string to UUID');
115
- }
116
- }
117
- this._rpcrt.StringToUUID.us = this;
118
-
119
- GUID_ACDC_POWER_SOURCE = this._rpcrt.StringToUUID('5d3e9a59-e9D5-4b00-a6bd-ff34ff516548');
120
- GUID_BATTERY_PERCENTAGE_REMAINING = this._rpcrt.StringToUUID('a7ad8041-b45a-4cae-87a3-eecbb468a9e1');
121
- GUID_CONSOLE_DISPLAY_STATE = this._rpcrt.StringToUUID('6fe69556-704a-47a0-8f24-c28d936fda47');
122
-
123
- this.SessionStates = ['Active', 'Connected', 'ConnectQuery', 'Shadow', 'Disconnected', 'Idle', 'Listening', 'Reset', 'Down', 'Init'];
124
- this.InfoClass =
125
- {
126
- 'WTSInitialProgram': 0,
127
- 'WTSApplicationName': 1,
128
- 'WTSWorkingDirectory': 2,
129
- 'WTSOEMId': 3,
130
- 'WTSSessionId': 4,
131
- 'WTSUserName': 5,
132
- 'WTSWinStationName': 6,
133
- 'WTSDomainName': 7,
134
- 'WTSConnectState': 8,
135
- 'WTSClientBuildNumber': 9,
136
- 'WTSClientName': 10,
137
- 'WTSClientDirectory': 11,
138
- 'WTSClientProductId': 12,
139
- 'WTSClientHardwareId': 13,
140
- 'WTSClientAddress': 14,
141
- 'WTSClientDisplay': 15,
142
- 'WTSClientProtocolType': 16,
143
- 'WTSIdleTime': 17,
144
- 'WTSLogonTime': 18,
145
- 'WTSIncomingBytes': 19,
146
- 'WTSOutgoingBytes': 20,
147
- 'WTSIncomingFrames': 21,
148
- 'WTSOutgoingFrames': 22,
149
- 'WTSClientInfo': 23,
150
- 'WTSSessionInfo': 24,
151
- 'WTSSessionInfoEx': 25,
152
- 'WTSConfigInfo': 26,
153
- 'WTSValidationInfo': 27,
154
- 'WTSSessionAddressV4': 28,
155
- 'WTSIsRemoteSession': 29
156
- };
157
-
158
- this.isRoot = function isRoot()
159
- {
160
- var NTAuthority = this._marshal.CreateVariable(6);
161
- NTAuthority.toBuffer().writeInt8(5, 5);
162
-
163
- var AdministratorsGroup = this._marshal.CreatePointer();
164
- var admin = false;
165
-
166
- if (this._advapi.AllocateAndInitializeSid(NTAuthority, 2, 32, 544, 0, 0, 0, 0, 0, 0, AdministratorsGroup).Val != 0)
167
- {
168
- var member = this._marshal.CreateInteger();
169
- if (this._advapi.CheckTokenMembership(0, AdministratorsGroup.Deref(), member).Val != 0)
170
- {
171
- if (member.toBuffer().readUInt32LE() != 0) { admin = true; }
172
- }
173
- this._advapi.FreeSid(AdministratorsGroup.Deref());
174
- }
175
- return admin;
176
- }
177
-
178
- this.getSessionAttribute = function getSessionAttribute(sessionId, attr)
179
- {
180
- var buffer = this._marshal.CreatePointer();
181
- var bytesReturned = this._marshal.CreateVariable(4);
182
-
183
- if (this._wts.WTSQuerySessionInformationA(0, sessionId, attr, buffer, bytesReturned).Val == 0)
184
- {
185
- throw ('Error calling WTSQuerySessionInformation: ' + this._kernel32.GetLastError.Val);
186
- }
187
-
188
- var retVal = buffer.Deref().String;
189
-
190
- this._wts.WTSFreeMemory(buffer.Deref());
191
- return (retVal);
192
- };
193
-
194
- this.Current = function Current(cb)
195
- {
196
- var retVal = {};
197
- var pinfo = this._marshal.CreatePointer();
198
- var count = this._marshal.CreateVariable(4);
199
- if (this._wts.WTSEnumerateSessionsA(0, 0, 1, pinfo, count).Val == 0)
200
- {
201
- throw ('Error calling WTSEnumerateSessionsA: ' + this._kernel32.GetLastError().Val);
202
- }
203
-
204
- for (var i = 0; i < count.toBuffer().readUInt32LE() ; ++i)
205
- {
206
- var info = pinfo.Deref().Deref(i * (this._marshal.PointerSize == 4 ? 12 : 24), this._marshal.PointerSize == 4 ? 12 : 24);
207
- var j = { SessionId: info.toBuffer().readUInt32LE() };
208
- j.StationName = info.Deref(this._marshal.PointerSize == 4 ? 4 : 8, this._marshal.PointerSize).Deref().String;
209
- j.State = this.SessionStates[info.Deref(this._marshal.PointerSize == 4 ? 8 : 16, 4).toBuffer().readUInt32LE()];
210
- if (j.State == 'Active') {
211
- j.Username = this.getSessionAttribute(j.SessionId, this.InfoClass.WTSUserName);
212
- j.Domain = this.getSessionAttribute(j.SessionId, this.InfoClass.WTSDomainName);
213
- }
214
- retVal[j.SessionId] = j;
215
- }
216
-
217
- this._wts.WTSFreeMemory(pinfo.Deref());
218
-
219
- Object.defineProperty(retVal, 'Active', { value: showActiveOnly(retVal) });
220
- if (cb) { cb(retVal); }
221
- return (retVal);
222
- };
223
-
224
-
225
- // We need to spin up a message pump, and fetch a window handle
226
- var message_pump = require('win-message-pump');
227
- this._messagepump = new message_pump({ filter: WM_WTSSESSION_CHANGE }); this._messagepump.parent = this;
228
- this._messagepump.on('exit', function (code) { this.parent._wts.WTSUnRegisterSessionNotification(this.parent.hwnd); });
229
- this._messagepump.on('hwnd', function (h)
230
- {
231
- this.parent.hwnd = h;
232
-
233
- // We need to yield, and do this in the next event loop pass, becuase we don't want to call 'RegisterPowerSettingNotification'
234
- // from the messagepump 'thread', because we are actually on the microstack thread, such that the message pump thread, is holding
235
- // on a semaphore for us to return. If we call now, we may deadlock on Windows 7, becuase it will try to notify immediately
236
- this.immediate = setImmediate(function (self)
237
- {
238
- // Now that we have a window handle, we can register it to receive Windows Messages
239
- if (self.parent._wts) { self.parent._wts.WTSRegisterSessionNotification(self.parent.hwnd, NOTIFY_FOR_ALL_SESSIONS); }
240
- self.parent._user32.ACDC_H = self.parent._user32.RegisterPowerSettingNotification(self.parent.hwnd, GUID_ACDC_POWER_SOURCE, 0);
241
- self.parent._user32.BATT_H = self.parent._user32.RegisterPowerSettingNotification(self.parent.hwnd, GUID_BATTERY_PERCENTAGE_REMAINING, 0);
242
- self.parent._user32.DISP_H = self.parent._user32.RegisterPowerSettingNotification(self.parent.hwnd, GUID_CONSOLE_DISPLAY_STATE, 0);
243
- //console.log(self.parent._user32.ACDC_H.Val, self.parent._user32.BATT_H.Val, self.parent._user32.DISP_H.Val);
244
- }, this);
245
- });
246
- this._messagepump.on('message', function (msg)
247
- {
248
- switch(msg.message)
249
- {
250
- case WM_WTSSESSION_CHANGE:
251
- switch(msg.wparam)
252
- {
253
- case WTS_SESSION_LOCK:
254
- this.parent.enumerateUsers().then(function (users)
255
- {
256
- if (users[msg.lparam]) { this.parent.emit('locked', users[msg.lparam]); }
257
- });
258
- break;
259
- case WTS_SESSION_UNLOCK:
260
- this.parent.enumerateUsers().then(function (users)
261
- {
262
- if (users[msg.lparam]) { this.parent.emit('unlocked', users[msg.lparam]); }
263
- });
264
- break;
265
- case WTS_SESSION_LOGON:
266
- case WTS_SESSION_LOGOFF:
267
- this.parent.emit('changed');
268
- break;
269
- }
270
- break;
271
- case WM_POWERBROADCAST:
272
- switch(msg.wparam)
273
- {
274
- default:
275
- console.log('WM_POWERBROADCAST [UNKNOWN wparam]: ' + msg.wparam);
276
- break;
277
- case PBT_APMSUSPEND:
278
- require('power-monitor').emit('sx', 'SLEEP');
279
- break;
280
- case PBT_APMRESUMEAUTOMATIC:
281
- require('power-monitor').emit('sx', 'RESUME_NON_INTERACTIVE');
282
- break;
283
- case PBT_APMRESUMESUSPEND:
284
- require('power-monitor').emit('sx', 'RESUME_INTERACTIVE');
285
- break;
286
- case PBT_APMPOWERSTATUSCHANGE:
287
- require('power-monitor').emit('changed');
288
- break;
289
- case PBT_POWERSETTINGCHANGE:
290
- var lparam = this.parent._marshal.CreatePointer(Buffer.from(msg.lparam_hex, 'hex'));
291
- var data = lparam.Deref(20, lparam.Deref(16, 4).toBuffer().readUInt32LE(0)).toBuffer();
292
- switch(lparam.Deref(0, 16).toBuffer().toString('hex'))
293
- {
294
- case GUID_ACDC_POWER_SOURCE.Deref(0, 16).toBuffer().toString('hex'):
295
- switch(data.readUInt32LE(0))
296
- {
297
- case 0:
298
- require('power-monitor').emit('acdc', 'AC');
299
- break;
300
- case 1:
301
- require('power-monitor').emit('acdc', 'BATTERY');
302
- break;
303
- case 2:
304
- require('power-monitor').emit('acdc', 'HOT');
305
- break;
306
- }
307
- break;
308
- case GUID_BATTERY_PERCENTAGE_REMAINING.Deref(0, 16).toBuffer().toString('hex'):
309
- require('power-monitor').emit('batteryLevel', data.readUInt32LE(0));
310
- break;
311
- case GUID_CONSOLE_DISPLAY_STATE.Deref(0, 16).toBuffer().toString('hex'):
312
- switch(data.readUInt32LE(0))
313
- {
314
- case 0:
315
- require('power-monitor').emit('display', 'OFF');
316
- break;
317
- case 1:
318
- require('power-monitor').emit('display', 'ON');
319
- break;
320
- case 2:
321
- require('power-monitor').emit('display', 'DIMMED');
322
- break;
323
- }
324
- break;
325
- }
326
- break;
327
- }
328
- break;
329
- default:
330
- break;
331
- }
332
- });
333
- }
334
- else if(process.platform == 'linux')
335
- {
336
- var dbus = require('linux-dbus');
337
- this._linuxWatcher = require('fs').watch('/var/run/utmp');
338
- this._linuxWatcher.user_session = this;
339
- this._linuxWatcher.on('change', function (a, b)
340
- {
341
- this.user_session.emit('changed');
342
- });
343
- this._users = function _users()
344
- {
345
- var child = require('child_process').execFile('/bin/sh', ['sh']);
346
- child.stdout.str = '';
347
- child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
348
- child.stdin.write('awk -F: \'($3 >= 0) {printf "%s:%s\\n", $1, $3}\' /etc/passwd\nexit\n');
349
- child.waitExit();
350
-
351
- var lines = child.stdout.str.split('\n');
352
- var ret = {}, tokens;
353
- for (var ln in lines)
354
- {
355
- tokens = lines[ln].split(':');
356
- if (tokens[0]) { ret[tokens[0]] = tokens[1]; }
357
- }
358
- return (ret);
359
- }
360
- this._uids = function _uids() {
361
- var child = require('child_process').execFile('/bin/sh', ['sh']);
362
- child.stdout.str = '';
363
- child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
364
- child.stdin.write('awk -F: \'($3 >= 0) {printf "%s:%s\\n", $1, $3}\' /etc/passwd\nexit\n');
365
- child.waitExit();
366
-
367
- var lines = child.stdout.str.split('\n');
368
- var ret = {}, tokens;
369
- for (var ln in lines) {
370
- tokens = lines[ln].split(':');
371
- if (tokens[0]) { ret[tokens[1]] = tokens[0]; }
372
- }
373
- return (ret);
374
- }
375
- this.Self = function Self()
376
- {
377
- var promise = require('promise');
378
- var p = new promise(function (res, rej)
379
- {
380
- this.__resolver = res; this.__rejector = rej;
381
- this.__child = require('child_process').execFile('/usr/bin/id', ['id', '-u']);
382
- this.__child.promise = this;
383
- this.__child.stdout._txt = '';
384
- this.__child.stdout.on('data', function (chunk) { this._txt += chunk.toString(); });
385
- this.__child.on('exit', function (code)
386
- {
387
- try
388
- {
389
- parseInt(this.stdout._txt);
390
- }
391
- catch (e)
392
- {
393
- this.promise.__rejector('invalid uid');
394
- return;
395
- }
396
-
397
- var id = parseInt(this.stdout._txt);
398
- this.promise.__resolver(id);
399
- });
400
- });
401
- return (p);
402
- };
403
- this.Current = function Current(cb)
404
- {
405
- var retVal = {};
406
- retVal._ObjectID = 'UserSession'
407
- Object.defineProperty(retVal, '_callback', { value: cb });
408
- Object.defineProperty(retVal, '_child', { value: require('child_process').execFile('/usr/bin/last', ['last', '-f', '/var/run/utmp']) });
409
-
410
- retVal._child.Parent = retVal;
411
- retVal._child._txt = '';
412
- retVal._child.on('exit', function (code)
413
- {
414
- var lines = this._txt.split('\n');
415
- var sessions = [];
416
- var users = {};
417
-
418
- for(var i in lines)
419
- {
420
- if (lines[i])
421
- {
422
- var tokens = getTokens(lines[i]);
423
- var s = { Username: tokens[0], SessionId: tokens[1] }
424
- if (tokens[3].includes('still logged in'))
425
- {
426
- s.State = 'Active';
427
- }
428
- else
429
- {
430
- s.LastActive = tokens[3];
431
- }
432
-
433
- sessions.push(s);
434
- }
435
- }
436
- sessions.pop();
437
-
438
-
439
- var usernames = {};
440
- var promises = [];
441
-
442
- for (var i in sessions)
443
- {
444
- if (sessions[i].Username != 'reboot')
445
- {
446
- users[sessions[i].SessionId] = sessions[i];
447
- if(usernames[sessions[i].Username] == null)
448
- {
449
- usernames[sessions[i].Username] = -1;
450
- }
451
- }
452
- }
453
-
454
- try
455
- {
456
- require('promise');
457
- }
458
- catch(e)
459
- {
460
- Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
461
- if (this.Parent._callback) { this.Parent._callback.call(this.Parent, users); }
462
- return;
463
- }
464
-
465
- var promise = require('promise');
466
- for (var n in usernames)
467
- {
468
- var p = new promise(function (res, rej)
469
- {
470
- this.__username = n;
471
- this.__resolver = res; this.__rejector = rej;
472
- this.__child = require('child_process').execFile('/usr/bin/id', ['id', '-u', n]);
473
- this.__child.promise = this;
474
- this.__child.stdout._txt = '';
475
- this.__child.stdout.on('data', function (chunk) { this._txt += chunk.toString(); });
476
- this.__child.on('exit', function (code)
477
- {
478
- try
479
- {
480
- parseInt(this.stdout._txt);
481
- }
482
- catch(e)
483
- {
484
- this.promise.__rejector('invalid uid');
485
- return;
486
- }
487
-
488
- var id = parseInt(this.stdout._txt);
489
- this.promise.__resolver(id);
490
- });
491
- });
492
- promises.push(p);
493
- }
494
- promise.all(promises).then(function (plist)
495
- {
496
- // Done
497
- var table = {};
498
- for(var i in plist)
499
- {
500
- table[plist[i].__username] = plist[i]._internal.completedArgs[0];
501
- }
502
- for(var i in users)
503
- {
504
- users[i].uid = table[users[i].Username];
505
- }
506
- Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
507
- if (retVal._callback) { retVal._callback.call(retVal, users); }
508
- }, function (reason)
509
- {
510
- // Failed
511
- Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
512
- if (retVal._callback) { retVal._callback.call(retVal, users); }
513
- });
514
- });
515
- retVal._child.stdout.Parent = retVal._child;
516
- retVal._child.stdout.on('data', function (chunk) { this.Parent._txt += chunk.toString(); });
517
-
518
- return (retVal);
519
- }
520
- this._recheckLoggedInUsers = function _recheckLoggedInUsers()
521
- {
522
- this.enumerateUsers().then(function (u)
523
- {
524
-
525
- if (u.Active.length > 0)
526
- {
527
- // There is already a user logged in, so we can monitor DBUS for lock/unlock
528
- if (this.parent._linux_lock_watcher != null && this.parent._linux_lock_watcher.uid != u.Active[0].uid)
529
- {
530
- delete this.parent._linux_lock_watcher;
531
- }
532
- this.parent._linux_lock_watcher = new dbus(process.env['XDG_CURRENT_DESKTOP'] == 'Unity' ? 'com.ubuntu.Upstart0_6' : 'org.gnome.ScreenSaver', u.Active[0].uid);
533
- this.parent._linux_lock_watcher.user_session = this.parent;
534
- this.parent._linux_lock_watcher.on('signal', function (s)
535
- {
536
- var p = this.user_session.enumerateUsers();
537
- p.signalData = s.data[0];
538
- p.then(function (u)
539
- {
540
- switch (this.signalData)
541
- {
542
- case true:
543
- case 'desktop-lock':
544
- this.parent.emit('locked', u.Active[0]);
545
- break;
546
- case false:
547
- case 'desktop-unlock':
548
- this.parent.emit('unlocked', u.Active[0]);
549
- break;
550
- }
551
- });
552
- });
553
- }
554
- else if (this.parent._linux_lock_watcher != null)
555
- {
556
- delete this.parent._linux_lock_watcher;
557
- }
558
- });
559
-
560
- };
561
- this.on('changed', this._recheckLoggedInUsers); // For linux Lock/Unlock monitoring, we need to watch for LogOn/LogOff, and keep track of the UID.
562
-
563
-
564
- // First step, is to see if there is a user logged in:
565
- this._recheckLoggedInUsers();
566
- }
567
- else if(process.platform == 'darwin')
568
- {
569
- this._users = function ()
570
- {
571
- var child = require('child_process').execFile('/usr/bin/dscl', ['dscl', '.', 'list', '/Users', 'UniqueID']);
572
- child.stdout.str = '';
573
- child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
574
- child.stdin.write('exit\n');
575
- child.waitExit();
576
-
577
- var lines = child.stdout.str.split('\n');
578
- var tokens, i;
579
- var users = {};
580
-
581
- for (i = 0; i < lines.length; ++i) {
582
- tokens = lines[i].split(' ');
583
- if (tokens[0]) { users[tokens[0]] = tokens[tokens.length - 1]; }
584
- }
585
-
586
- return (users);
587
- }
588
- this._uids = function () {
589
- var child = require('child_process').execFile('/usr/bin/dscl', ['dscl', '.', 'list', '/Users', 'UniqueID']);
590
- child.stdout.str = '';
591
- child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
592
- child.stdin.write('exit\n');
593
- child.waitExit();
594
-
595
- var lines = child.stdout.str.split('\n');
596
- var tokens, i;
597
- var users = {};
598
-
599
- for (i = 0; i < lines.length; ++i) {
600
- tokens = lines[i].split(' ');
601
- if (tokens[0]) { users[tokens[tokens.length - 1]] = tokens[0]; }
602
- }
603
-
604
- return (users);
605
- }
606
- this._idTable = function()
607
- {
608
- var table = {};
609
- var child = require('child_process').execFile('/usr/bin/id', ['id']);
610
- child.stdout.str = '';
611
- child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
612
- child.waitExit();
613
-
614
- var lines = child.stdout.str.split('\n')[0].split(' ');
615
- for (var i = 0; i < lines.length; ++i) {
616
- var types = lines[i].split('=');
617
- var tokens = types[1].split(',');
618
- table[types[0]] = {};
619
-
620
- for (var j in tokens) {
621
- var idarr = tokens[j].split('(');
622
- var id = idarr[0];
623
- var name = idarr[1].substring(0, idarr[1].length - 1).trim();
624
- table[types[0]][name] = id;
625
- table[types[0]][id] = name;
626
- }
627
- }
628
- return (table);
629
- }
630
- this.Current = function (cb)
631
- {
632
- var users = {};
633
- var table = this._idTable();
634
- var child = require('child_process').execFile('/usr/bin/last', ['last']);
635
- child.stdout.str = '';
636
- child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
637
- child.waitExit();
638
-
639
- var lines = child.stdout.str.split('\n');
640
- for (var i = 0; i < lines.length && lines[i].length > 0; ++i)
641
- {
642
- if (!users[lines[i].split(' ')[0]])
643
- {
644
- try
645
- {
646
- users[lines[i].split(' ')[0]] = { Username: lines[i].split(' ')[0], State: lines[i].split('still logged in').length > 1 ? 'Active' : 'Inactive', uid: table.uid[lines[i].split(' ')[0]] };
647
- }
648
- catch(e)
649
- {}
650
- }
651
- else
652
- {
653
- if(users[lines[i].split(' ')[0]].State != 'Active' && lines[i].split('still logged in').length > 1)
654
- {
655
- users[lines[i].split(' ')[0]].State = 'Active';
656
- }
657
- }
658
- }
659
-
660
- Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
661
- if (cb) { cb.call(this, users); }
662
- }
663
- }
664
-
665
- if(process.platform == 'linux' || process.platform == 'darwin')
666
- {
667
- this._self = function _self()
668
- {
669
- var child = require('child_process').execFile('/usr/bin/id', ['id', '-u']);
670
- child.stdout.str = '';
671
- child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
672
- child.waitExit();
673
- return (parseInt(child.stdout.str));
674
- }
675
- this.isRoot = function isRoot()
676
- {
677
- return (this._self() == 0);
678
- }
679
- this.consoleUid = function consoleUid()
680
- {
681
- var checkstr = process.platform == 'darwin' ? 'console' : ((process.env['DISPLAY'])?process.env['DISPLAY']:':0')
682
- var child = require('child_process').execFile('/bin/sh', ['sh']);
683
- child.stdout.str = '';
684
- child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
685
- child.stdin.write('who\nexit\n');
686
- child.waitExit();
687
-
688
- var lines = child.stdout.str.split('\n');
689
- var tokens, i, j;
690
- for (i in lines)
691
- {
692
- tokens = lines[i].split(' ');
693
- for (j = 1; j < tokens.length; ++j)
694
- {
695
- if (tokens[j].length > 0)
696
- {
697
- return (parseInt(this._users()[tokens[0]]));
698
- }
699
- }
700
- }
701
-
702
- throw ('nobody logged into console');
703
- }
704
- }
705
-
706
-
707
-}
708
-function showActiveOnly(source)
709
-{
710
- var retVal = [];
711
- var unique = {};
712
- var usernames = [];
713
- var tmp;
714
-
715
- for (var i in source)
716
- {
717
- if (source[i].State == 'Active')
718
- {
719
- retVal.push(source[i]);
720
- tmp = (source[i].Domain ? (source[i].Domain + '\\') : '') + source[i].Username;
721
- if (!unique[tmp]) { unique[tmp] = tmp;}
722
- }
723
- }
724
-
725
- for (var i in unique)
726
- {
727
- usernames.push(i);
728
- }
729
-
730
- Object.defineProperty(retVal, 'usernames', { value: usernames });
731
- return (retVal);
732
-}
733
-function getTokens(str)
734
-{
735
- var columns = [];
736
- var i;
737
-
738
- columns.push(str.substring(0, (i=str.indexOf(' '))));
739
- while (str[++i] == ' ');
740
- columns.push(str.substring(i, (i=str.substring(i).indexOf(' ') + i)));
741
- while (str[++i] == ' ');
742
- columns.push(str.substring(i, (i=str.substring(i).indexOf(' ') + i)));
743
- while (str[++i] == ' ');
744
- var status = str.substring(i).trim();
745
- columns.push(status);
746
-
747
- return (columns);
748
-}
749
-
750
-module.exports = new UserSessions();
\ No newline at end of file