New MeshAgent, new border blinking feature.
Ylian Saint-Hilaire committed
Aug 29, 2018 at 18:47 UTC
1b3255e844e48f632a3fe2a47054e45f50c916f6
35 files changed
+7423
-177
agents/MeshCmd-signed.exe
Binary files a/agents/MeshCmd-signed.exe and b/agents/MeshCmd-signed.exe differ
agents/MeshCmd64-signed.exe
Binary files a/agents/MeshCmd64-signed.exe and b/agents/MeshCmd64-signed.exe differ
agents/MeshService-signed.exe
Binary files a/agents/MeshService-signed.exe and b/agents/MeshService-signed.exe differ
agents/MeshService.exe
Binary files a/agents/MeshService.exe and b/agents/MeshService.exe differ
agents/MeshService64-signed.exe
Binary files a/agents/MeshService64-signed.exe and b/agents/MeshService64-signed.exe differ
agents/MeshService64.exe
Binary files a/agents/MeshService64.exe and b/agents/MeshService64.exe differ
agents/meshcmd.js
+1
-1
@@ -1532,7 +1532,7 @@ if (serviceName == null) {
1532
if (serviceInstall == 0) {
1533
run(process.argv);
1534
} else {
1535
- var serviceHost = require('serviceHost');
1535
+ var serviceHost = require('service-host');
1536
var meshcmdService = new serviceHost({ name: serviceName, startType: 'AUTO_START' });
1537
1538
// Called when the background service is started.
agents/meshcore.js
+87
-3
@@ -14,12 +14,59 @@ See the License for the specific language governing permissions and
14
limitations under the License.
15
*/
16
17
+
18
+function borderController()
19
+{
20
+ this.container = null;
21
+ this.Start = function Start(user)
22
+ {
23
+ if (this.container == null) {
24
+ if (process.platform == 'win32') {
25
+ this.container = require('ScriptContainer').Create({ processIsolation: 1, sessionId: user.SessionId });
26
+ }
27
+ else {
28
+ this.container = require('ScriptContainer').Create({ processIsolation: 1, sessionId: user.uid });
29
+ }
30
+ this.container.addModule('monitor-info', getJSModule('monitor-info'));
31
+ this.container.addModule('monitor-border', getJSModule('monitor-border'));
32
+ this.container.addModule('promise', getJSModule('promise'));
33
+ this.container.ExecuteString("var border = require('monitor-border'); border.Start();");
34
+ }
35
+ }
36
+ this.Stop = function Stop()
37
+ {
38
+ if (this.container != null)
39
+ {
40
+ this._container = this.container;
41
+ this._container.parent = this;
42
+ this.container = null;
43
+
44
+ this._container.once('exit', function () { this.parent._container = null; });
45
+ this._container.exit();
46
+ }
47
+ }
48
+}
49
+
50
function createMeshCore(agent) {
51
var obj = {};
52
53
+ require('events').EventEmitter.call(obj, true).createEvent('loggedInUsers_Updated');
54
+ obj.on('loggedInUsers_Updated', function ()
55
+ {
56
+ var users = []
57
+ for(var i = 0; i < obj.loggedInUsers.length; ++i)
58
+ {
59
+ users.push((obj.loggedInUsers[i].Domain ? (obj.loggedInUsers[i].Domain + '\\') : '') + obj.loggedInUsers[i].Username);
60
+ }
61
+ sendConsoleText('LogOn Status Changed. Active Users => [' + users.join(', ') + ']');
62
+ });
63
+ obj.borderManager = new borderController();
64
+
65
// MeshAgent JavaScript Core Module. This code is sent to and running on the mesh agent.
66
obj.meshCoreInfo = "MeshCore v5";
67
obj.meshCoreCapabilities = 14; // Capability bitmask: 1 = Desktop, 2 = Terminal, 4 = Files, 8 = Console, 16 = JavaScript
68
+ obj.loggedInUsers = [];
69
+
70
var meshServerConnectionState = 0;
71
var tunnels = {};
72
var lastSelfInfo = null;
@@ -863,9 +910,36 @@ function createMeshCore(agent) {
910
var response = null;
911
switch (cmd) {
912
case 'help': { // Displays available commands
866
- response = 'Available commands: help, info, args, print, type, dbget, dbset, dbcompact, eval, parseuri, httpget,\r\nwslist, wsconnect, wssend, wsclose, notify, ls, ps, kill, amt, netinfo, location, power, wakeonlan, scanwifi,\r\nscanamt, setdebug, smbios, rawsmbios, toast, lock.';
913
+ response = 'Available commands: help, info, args, print, type, dbget, dbset, dbcompact, eval, parseuri, httpget,\r\nwslist, wsconnect, wssend, wsclose, notify, ls, ps, kill, amt, netinfo, location, power, wakeonlan, scanwifi,\r\nscanamt, setdebug, smbios, rawsmbios, toast, lock, users, border.';
914
break;
915
}
916
+ case 'border':
917
+ {
918
+ if ((args['_'].length == 1) && (args['_'][0] == 'on')) {
919
+ if (obj.loggedInUsers.length > 0) {
920
+ obj.borderManager.Start(obj.loggedInUsers[0]);
921
+ response = 'Border blinking is on.';
922
+ } else {
923
+ response = 'Cannot turn on border blinking, no logged in users.';
924
+ }
925
+ } else if ((args['_'].length == 1) && (args['_'][0] == 'off')) {
926
+ obj.borderManager.Stop();
927
+ response = 'Border blinking is off.';
928
+ } else {
929
+ response = 'Proper usage: border "on|off"'; // Display correct command usage
930
+ }
931
+ }
932
+ break;
933
+ case 'users':
934
+ {
935
+ var retList = [];
936
+ for(var i = 0; i < obj.loggedInUsers.length; ++i)
937
+ {
938
+ retList.push((obj.loggedInUsers[i].Domain ? (obj.loggedInUsers[i].Domain + '\\') : '') + obj.loggedInUsers[i].Username);
939
+ }
940
+ response = 'Active Users => [' + retList.join(', ') + ']';
941
+ }
942
+ break;
943
case 'toast': {
944
if (process.platform == 'win32') {
945
if (args['_'].length < 1) { response = 'Proper usage: toast "message"'; } else {
@@ -878,8 +952,8 @@ function createMeshCore(agent) {
952
break;
953
}
954
case 'setdebug': {
881
- if (args['_'].length < 1) { response = 'Proper usage: setdebug (target), 0 = StdOut, 1 = This Console, * = All Consoles, 2 = WebLog, 3 = Disabled'; } // Display usage
882
- else { if (args['_'][0] == '*') { console.setDestination(1); } else { console.setDestination(parseInt(args['_'][0]), sessionid); } }
955
+ if (args['_'].length < 1) { response = 'Proper usage: setdebug (target), 0 = Disabled, 1 = StdOut, 2 = This Console, * = All Consoles, 4 = WebLog, 8 = Logfile'; } // Display usage
956
+ else { if (args['_'][0] == '*') { console.setDestination(2); } else { console.setDestination(parseInt(args['_'][0]), sessionid); } }
957
break;
958
}
959
case 'ps': {
@@ -1373,6 +1447,16 @@ function createMeshCore(agent) {
1447
sendPeriodicServerUpdate(true); // Send the server update
1448
}
1449
1450
+ require('user-sessions').on('changed', function onUserSessionChanged()
1451
+ {
1452
+ require('user-sessions').enumerateUsers().then(function (users)
1453
+ {
1454
+ obj.loggedInUsers = users.Active;
1455
+ obj.emit('loggedInUsers_Updated');
1456
+ });
1457
+ });
1458
+
1459
+ require('user-sessions').emit('changed');
1460
//console.log('Stopping.');
1461
//process.exit();
1462
}
agents/modules_meshcmd/service-host.js
renamed
+182
-68
@@ -1,24 +1,61 @@
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
18
var SERVICE_WIN32 = 0x00000010 | 0x00000020;
19
var SERVICE_STATE = { STOPPED: 0x00000001, SERVICE_START_PENDING: 0x00000002, SERVICE_STOP_PENDING: 0x00000003, RUNNING: 0x00000004 };
4
-var SERVICE_ACCEPT = { SERVICE_ACCEPT_STOP: 0x00000001, SERVICE_ACCEPT_SHUTDOWN: 0x00000004 };
5
-var SERVICE_CONTROL = { SERVICE_CONTROL_SHUTDOWN: 0x00000005, SERVICE_CONTROL_STOP: 0x00000001 };
20
+var SERVICE_ACCEPT = { SERVICE_ACCEPT_STOP: 0x00000001, SERVICE_ACCEPT_SHUTDOWN: 0x00000004, SERVICE_ACCEPT_POWEREVENT: 0x00000040, SERVICE_ACCEPT_SESSIONCHANGE: 0x00000080 };
21
+
22
+var SERVICE_CONTROL = { SERVICE_CONTROL_SHUTDOWN: 0x00000005, SERVICE_CONTROL_STOP: 0x00000001, SERVICE_CONTROL_POWEREVENT: 0x0000000D, SERVICE_CONTROL_SESSIONCHANGE: 0x0000000E};
23
+var SESSION_CHANGE_TYPE =
24
+{
25
+ WTS_CONSOLE_CONNECT: 0x1,
26
+ WTS_CONSOLE_DISCONNECT: 0x2,
27
+ WTS_REMOTE_CONNECT: 0x3,
28
+ WTS_REMOTE_DISCONNECT: 0x4,
29
+ WTS_SESSION_LOGON: 0x5,
30
+ WTS_SESSION_LOGOFF: 0x6,
31
+ WTS_SESSION_LOCK: 0x7,
32
+ WTS_SESSION_UNLOCK: 0x8,
33
+ WTS_SESSION_REMOTE_CONTROL: 0x9,
34
+ WTS_SESSION_CREATE: 0xa,
35
+ WTS_SESSION_TERMINATE: 0xb
36
+};
37
+
38
+
39
var NO_ERROR = 0;
40
8
-var serviceManager = require('serviceManager');
41
+var serviceManager = require('service-manager');
42
10
-function serviceHost(serviceName) {
11
- this._ObjectID = 'serviceHost';
43
+function serviceHost(serviceName)
44
+{
45
+ this._ObjectID = 'service-host';
46
var emitterUtils = require('events').inherits(this);
47
emitterUtils.createEvent('serviceStart');
48
emitterUtils.createEvent('serviceStop');
49
emitterUtils.createEvent('normalStart');
50
+ emitterUtils.createEvent('session');
51
+ emitterUtils.createEvent('powerStateChange');
52
17
- if (process.platform == 'win32') {
53
+ if (process.platform == 'win32')
54
+ {
55
this.GM = require('_GenericMarshal');
56
this.Advapi = this.GM.CreateNativeProxy('Advapi32.dll');
57
this.Advapi.CreateMethod({ method: 'StartServiceCtrlDispatcherA', threadDispatch: 1 });
21
- this.Advapi.CreateMethod('RegisterServiceCtrlHandlerA');
58
+ this.Advapi.CreateMethod('RegisterServiceCtrlHandlerExA');
59
this.Advapi.CreateMethod('SetServiceStatus');
60
this.Kernel32 = this.GM.CreateNativeProxy('Kernel32.dll');
61
this.Kernel32.CreateMethod('GetLastError');
@@ -31,7 +68,8 @@ function serviceHost(serviceName) {
68
this._ServiceMain = this.GM.GetGenericGlobalCallback(2);
69
this._ServiceMain.Parent = this;
70
this._ServiceMain.GM = this.GM;
34
- this._ServiceMain.on('GlobalCallback', function onGlobalCallback(argc, argv) {
71
+ this._ServiceMain.on('GlobalCallback', function onGlobalCallback(argc, argv)
72
+ {
73
//ToDo: Check to make sure this is for us
74
75
this.Parent._ServiceStatus = this.GM.CreateVariable(28);
@@ -48,8 +86,9 @@ function serviceHost(serviceName) {
86
// Initialise service status
87
this.Parent._ServiceStatus.toBuffer().writeUInt32LE(SERVICE_WIN32);
88
this.Parent._ServiceStatus.toBuffer().writeUInt32LE(SERVICE_STATE.SERVICE_STOPPED, 4);
51
- this.Parent._ServiceStatusHandle = this.Parent.Advapi.RegisterServiceCtrlHandlerA(this.Parent._ServiceName, this.Parent._ServiceControlHandler);
52
- if (this.Parent._ServiceStatusHandle.Val == 0) {
89
+ this.Parent._ServiceStatusHandle = this.Parent.Advapi.RegisterServiceCtrlHandlerExA(this.Parent._ServiceName, this.Parent._ServiceControlHandler, this.Parent.GM.StashObject(this.Parent._ServiceControlHandler));
90
+ if(this.Parent._ServiceStatusHandle.Val == 0)
91
+ {
92
process.exit(1);
93
}
94
@@ -59,11 +98,12 @@ function serviceHost(serviceName) {
98
99
// Service running
100
this.Parent._ServiceStatus.toBuffer().writeUInt32LE(SERVICE_STATE.RUNNING, 4);
62
- this.Parent._ServiceStatus.toBuffer().writeUInt32LE(SERVICE_ACCEPT.SERVICE_ACCEPT_STOP, 8);
101
+ this.Parent._ServiceStatus.toBuffer().writeUInt32LE(SERVICE_ACCEPT.SERVICE_ACCEPT_STOP | SERVICE_ACCEPT.SERVICE_ACCEPT_POWEREVENT | SERVICE_ACCEPT.SERVICE_ACCEPT_SESSIONCHANGE, 8);
102
this.Parent.Advapi.SetServiceStatus(this.Parent._ServiceStatusHandle, this.Parent._ServiceStatus);
103
104
this.Parent.Ole32.CoInitializeEx(0, 2);
66
- this.Parent.on('~', function OnServiceHostFinalizer() {
105
+ this.Parent.on('~', function OnServiceHostFinalizer()
106
+ {
107
var GM = require('_GenericMarshal');
108
var Advapi = GM.CreateNativeProxy('Advapi32.dll');
109
Advapi.CreateMethod('SetServiceStatus');
@@ -82,22 +122,39 @@ function serviceHost(serviceName) {
122
123
this.Ole32.CoUninitialize();
124
});
125
+
126
this.Parent.emit('serviceStart');
127
});
87
- this._ServiceControlHandler = this.GM.GetGenericGlobalCallback(1);
128
+ this._ServiceControlHandler = this.GM.GetGenericGlobalCallback(4);
129
this._ServiceControlHandler.Parent = this;
130
this._ServiceControlHandler.GM = this.GM;
90
- this._ServiceControlHandler.on('GlobalCallback', function onServiceControlHandler(code) {
91
- switch (code.Val) {
92
- case SERVICE_CONTROL.SERVICE_CONTROL_SHUTDOWN:
93
- case SERVICE_CONTROL.SERVICE_CONTROL_STOP:
94
- this.Parent.emit('serviceStop');
95
- return;
96
- default:
97
- break;
98
- }
131
+ this._ServiceControlHandler.on('GlobalCallback', function onServiceControlHandler(code, eventType, eventData, context)
132
+ {
133
+ var j = this.Parent.GM.UnstashObject(context);
134
+ if (j != null && j == this)
135
+ {
136
+ switch (code.Val)
137
+ {
138
+ case SERVICE_CONTROL.SERVICE_CONTROL_SHUTDOWN:
139
+ case SERVICE_CONTROL.SERVICE_CONTROL_STOP:
140
+ this.Parent.emit('serviceStop');
141
+ return;
142
+ case SERVICE_CONTROL.SERVICE_CONTROL_SESSIONCHANGE:
143
+ var sessionId = eventData.Deref(4, 4).toBuffer().readUInt32LE();
144
+ switch(eventType.Val)
145
+ {
146
+ case SESSION_CHANGE_TYPE.WTS_SESSION_LOGON:
147
+ case SESSION_CHANGE_TYPE.WTS_SESSION_LOGOFF:
148
+ require('user-sessions').emit('changed');
149
+ break;
150
+ }
151
+ break;
152
+ default:
153
+ break;
154
+ }
155
100
- this.Parent.Advapi.SetServiceStatus(this.Parent._ServiceStatusHandle, this.Parent._ServiceStatus);
156
+ this.Parent.Advapi.SetServiceStatus(this.Parent._ServiceStatusHandle, this.Parent._ServiceStatus);
157
+ }
158
});
159
}
160
@@ -106,42 +163,54 @@ function serviceHost(serviceName) {
163
{
164
throw ('Must specify either ServiceName or Options');
165
}
109
- if (!this._ServiceOptions.servicePath) {
166
+ if (!this._ServiceOptions.servicePath)
167
+ {
168
this._ServiceOptions.servicePath = process.execPath;
169
}
112
-
113
- this.run = function run() {
170
+
171
+ this.run = function run()
172
+ {
173
var serviceOperation = 0;
174
116
- for (var i = 0; i < process.argv.length; ++i) {
117
- switch (process.argv[i].toLowerCase()) {
118
- case 'install':
175
+ for(var i = 0; i<process.argv.length; ++i)
176
+ {
177
+ switch(process.argv[i])
178
+ {
179
+ case '-install':
180
if (!this._svcManager) { this._svcManager = new serviceManager(); }
120
- try {
181
+ try
182
+ {
183
this._svcManager.installService(this._ServiceOptions);
122
- } catch (e) {
184
+ }
185
+ catch(e)
186
+ {
187
console.log(e);
188
process.exit();
189
}
126
- if (process.platform == 'win32') {
190
+ if (process.platform == 'win32')
191
+ {
192
// Only do this on Windows, becuase Linux is async... It'll complete later
128
- console.log(this._ServiceOptions.name + ' installed.');
193
+ console.log(this._ServiceOptions.name + ' installed');
194
process.exit();
195
}
196
i = process.argv.length;
197
serviceOperation = 1;
198
break;
134
- case 'uninstall':
199
+ case '-uninstall':
200
if (!this._svcManager) { this._svcManager = new serviceManager(); }
136
- try {
201
+ try
202
+ {
203
this._svcManager.uninstallService(this._ServiceOptions);
138
- } catch (e) {
204
+ }
205
+ catch(e)
206
+ {
207
console.log(e);
208
process.exit();
209
}
142
- if (process.platform == 'win32') {
210
+ if (process.platform == 'win32')
211
+ {
212
// Only do this on Windows, becuase Linux is async... It'll complete later
144
- console.log(this._ServiceOptions.name + ' uninstalled.');
213
+ console.log(this._ServiceOptions.name + ' uninstalled');
214
process.exit();
215
}
216
i = process.argv.length;
@@ -149,48 +218,59 @@ function serviceHost(serviceName) {
218
break;
219
case 'start':
220
case '-d':
221
+ if (process.platform != 'win32') { break; }
222
if (!this._svcManager) { this._svcManager = new serviceManager(); }
223
this._svcManager.getService(this._ServiceOptions.name).start();
154
- console.log(this._ServiceOptions.name + ' starting.');
224
+ console.log(this._ServiceOptions.name + ' starting...');
225
process.exit();
226
break;
227
case 'stop':
228
case '-s':
229
+ if (process.platform != 'win32') { break; }
230
if (!this._svcManager) { this._svcManager = new serviceManager(); }
231
this._svcManager.getService(this._ServiceOptions.name).stop();
161
- console.log(this._ServiceOptions.name + ' stopping.');
232
+ console.log(this._ServiceOptions.name + ' stopping...');
233
process.exit();
234
break;
235
236
}
237
}
238
168
- if (process.platform == 'win32') {
239
+ if (process.platform == 'win32')
240
+ {
241
var serviceTable = this.GM.CreateVariable(4 * this.GM.PointerSize);
242
this._ServiceName.pointerBuffer().copy(serviceTable.toBuffer());
243
this._ServiceMain.pointerBuffer().copy(serviceTable.toBuffer(), this.GM.PointerSize);
244
this._sscd = this.Advapi.StartServiceCtrlDispatcherA(serviceTable);
245
this._sscd.parent = this;
246
this._sscd.on('done', function OnStartServiceCtrlDispatcherA(retVal) {
175
- if (retVal.Val == 0) { this.parent.emit('normalStart'); }
247
+ if (retVal.Val == 0)
248
+ {
249
+ this.parent.emit('normalStart');
250
+ }
251
});
252
return;
253
}
179
-
254
+
255
var moduleName = this._ServiceOptions ? this._ServiceOptions.name : process.execPath.substring(1 + process.execPath.lastIndexOf('/'));
256
182
- for (var i = 0; i < process.argv.length; ++i) {
183
- switch (process.argv[i].toLowerCase()) {
257
+ for (var i = 0; i < process.argv.length; ++i)
258
+ {
259
+ switch(process.argv[i])
260
+ {
261
case 'start':
262
case '-d':
263
var child = require('child_process').execFile(process.execPath, [moduleName], { type: require('child_process').SpawnTypes.DETACHED });
264
var pstream = null;
188
- try {
265
+ try
266
+ {
267
pstream = require('fs').createWriteStream('/var/run/' + moduleName + '.pid', { flags: 'w' });
268
}
191
- catch (e) {
269
+ catch(e)
270
+ {
271
}
193
- if (pstream == null) {
272
+ if (pstream == null)
273
+ {
274
pstream = require('fs').createWriteStream('.' + moduleName + '.pid', { flags: 'w' });
275
}
276
pstream.end(child.pid.toString());
@@ -201,26 +281,33 @@ function serviceHost(serviceName) {
281
case 'stop':
282
case '-s':
283
var pid = null;
204
- try {
284
+ try
285
+ {
286
pid = parseInt(require('fs').readFileSync('/var/run/' + moduleName + '.pid', { flags: 'r' }));
287
require('fs').unlinkSync('/var/run/' + moduleName + '.pid');
288
}
208
- catch (e) {
289
+ catch(e)
290
+ {
291
}
210
- if (pid == null) {
211
- try {
292
+ if(pid == null)
293
+ {
294
+ try
295
+ {
296
pid = parseInt(require('fs').readFileSync('.' + moduleName + '.pid', { flags: 'r' }));
297
require('fs').unlinkSync('.' + moduleName + '.pid');
298
}
215
- catch (e) {
299
+ catch(e)
300
+ {
301
}
302
}
303
219
- if (pid) {
304
+ if(pid)
305
+ {
306
process.kill(pid);
307
console.log(moduleName + ' stopped');
308
}
223
- else {
309
+ else
310
+ {
311
console.log(moduleName + ' not running');
312
}
313
process.exit();
@@ -228,30 +315,56 @@ function serviceHost(serviceName) {
315
}
316
}
317
231
- if (serviceOperation == 0) {
318
+ if(serviceOperation == 0)
319
+ {
320
// This is non-windows, so we need to check how this binary was started to determine if this was a service start
321
322
// Start by checking if we were started with start/stop
323
var pid = null;
236
- try { pid = parseInt(require('fs').readFileSync('/var/run/' + moduleName + '.pid', { flags: 'r' })); } catch (e) { }
237
- if (pid == null) { try { pid = parseInt(require('fs').readFileSync('.' + moduleName + '.pid', { flags: 'r' })); } catch (e) { } }
238
-
239
- if (pid != null && pid == process.pid) {
324
+ try
325
+ {
326
+ pid = parseInt(require('fs').readFileSync('/var/run/' + moduleName + '.pid', { flags: 'r' }));
327
+ }
328
+ catch (e)
329
+ {
330
+ }
331
+ if (pid == null)
332
+ {
333
+ try
334
+ {
335
+ pid = parseInt(require('fs').readFileSync('.' + moduleName + '.pid', { flags: 'r' }));
336
+ }
337
+ catch (e)
338
+ {
339
+ }
340
+ }
341
+
342
+ if (pid != null && pid == process.pid)
343
+ {
344
this.emit('serviceStart');
241
- } else {
345
+ }
346
+ else
347
+ {
348
// Now we need to check if we were started with systemd
243
- if (require('processManager').getProcessInfo(1).Name == 'systemd') {
349
+ if (require('process-manager').getProcessInfo(1).Name == 'systemd')
350
+ {
351
this._checkpid = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM });
352
this._checkpid.result = '';
353
this._checkpid.parent = this;
247
- this._checkpid.on('exit', function onCheckPIDExit() {
354
+ this._checkpid.on('exit', function onCheckPIDExit()
355
+ {
356
var lines = this.result.split('\r\n');
249
- for (i in lines) {
250
- if (lines[i].startsWith(' Main PID:')) {
357
+ for (i in lines)
358
+ {
359
+ if(lines[i].startsWith(' Main PID:'))
360
+ {
361
var tokens = lines[i].split(' ');
252
- if (parseInt(tokens[3]) == process.pid) {
362
+ if (parseInt(tokens[3]) == process.pid)
363
+ {
364
this.parent.emit('serviceStart');
254
- } else {
365
+ }
366
+ else
367
+ {
368
this.parent.emit('normalStart');
369
}
370
delete this.parent._checkpid;
@@ -265,7 +378,8 @@ function serviceHost(serviceName) {
378
this._checkpid.stdin.write("systemctl status " + moduleName + " | grep 'Main PID:'\n");
379
this._checkpid.stdin.write('exit\n');
380
}
268
- else {
381
+ else
382
+ {
383
// This isn't even a systemd platform, so this couldn't have been a service start
384
this.emit('normalStart');
385
}
agents/modules_meshcmd/service-manager.js
renamed
+119
-49
@@ -1,6 +1,21 @@
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
3
-function parseServiceStatus(token) {
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
+function parseServiceStatus(token)
18
+{
19
var j = {};
20
var serviceType = token.Deref(0, 4).IntVal;
21
j.isFileSystemDriver = ((serviceType & 0x00000002) == 0x00000002);
@@ -8,7 +23,8 @@ function parseServiceStatus(token) {
23
j.isSharedProcess = ((serviceType & 0x00000020) == 0x00000020);
24
j.isOwnProcess = ((serviceType & 0x00000010) == 0x00000010);
25
j.isInteractive = ((serviceType & 0x00000100) == 0x00000100);
11
- switch (token.Deref((1 * 4), 4).toBuffer().readUInt32LE()) {
26
+ switch (token.Deref((1 * 4), 4).toBuffer().readUInt32LE())
27
+ {
28
case 0x00000005:
29
j.state = 'CONTINUE_PENDING';
30
break;
@@ -33,7 +49,8 @@ function parseServiceStatus(token) {
49
}
50
var controlsAccepted = token.Deref((2 * 4), 4).toBuffer().readUInt32LE();
51
j.controlsAccepted = [];
36
- if ((controlsAccepted & 0x00000010) == 0x00000010) {
52
+ if ((controlsAccepted & 0x00000010) == 0x00000010)
53
+ {
54
j.controlsAccepted.push('SERVICE_CONTROL_NETBINDADD');
55
j.controlsAccepted.push('SERVICE_CONTROL_NETBINDREMOVE');
56
j.controlsAccepted.push('SERVICE_CONTROL_NETBINDENABLE');
@@ -51,8 +68,11 @@ function parseServiceStatus(token) {
68
return (j);
69
}
70
54
-function serviceManager() {
55
- if (process.platform == 'win32') {
71
+function serviceManager()
72
+{
73
+ this._ObjectID = 'service-manager';
74
+ if (process.platform == 'win32')
75
+ {
76
this.GM = require('_GenericMarshal');
77
this.proxy = this.GM.CreateNativeProxy('Advapi32.dll');
78
this.proxy.CreateMethod('OpenSCManagerA');
@@ -78,21 +98,40 @@ function serviceManager() {
98
var AdministratorsGroup = this.GM.CreatePointer();
99
var admin = false;
100
81
- if (this.proxy.AllocateAndInitializeSid(NTAuthority, 2, 32, 544, 0, 0, 0, 0, 0, 0, AdministratorsGroup).Val != 0) {
101
+ if (this.proxy.AllocateAndInitializeSid(NTAuthority, 2, 32, 544, 0, 0, 0, 0, 0, 0, AdministratorsGroup).Val != 0)
102
+ {
103
var member = this.GM.CreateInteger();
83
- if (this.proxy.CheckTokenMembership(0, AdministratorsGroup.Deref(), member).Val != 0) {
104
+ if (this.proxy.CheckTokenMembership(0, AdministratorsGroup.Deref(), member).Val != 0)
105
+ {
106
if (member.toBuffer().readUInt32LE() != 0) { admin = true; }
107
}
108
this.proxy.FreeSid(AdministratorsGroup.Deref());
109
}
110
return admin;
111
};
90
- this.getProgramFolder = function getProgramFolder() {
91
- if ((require('os').arch() == 'x64') && (this.GM.PointerSize == 4)) { return process.env['ProgramFiles(x86)']; } // 64 bit Windows with 32 Bit App
92
- return process.env['ProgramFiles']; // All other cases: 32 bit Windows or 64 bit App
93
- };
94
- this.getServiceFolder = function getServiceFolder() {
95
- return getProgramFolder() + '\\Open Source\\MeshCmd';
112
+ this.getServiceFolder = function getServiceFolder()
113
+ {
114
+ var destinationFolder = null;
115
+ if (require('os').arch() == 'x64')
116
+ {
117
+ // 64 bit Windows
118
+ if (this.GM.PointerSize == 4)
119
+ {
120
+ // 32 Bit App
121
+ destinationFolder = process.env['ProgramFiles(x86)'];
122
+ }
123
+ else
124
+ {
125
+ // 64 bit App
126
+ destinationFolder = process.env['ProgramFiles'];
127
+ }
128
+ }
129
+ else
130
+ {
131
+ // 32 bit Windows
132
+ destinationFolder = process.env['ProgramFiles'];
133
+ }
134
+ return (destinationFolder + '\\mesh');
135
};
136
137
this.enumerateService = function () {
@@ -105,7 +144,9 @@ function serviceManager() {
144
var resumeHandle = this.GM.CreatePointer();
145
//var services = this.proxy.CreateVariable(262144);
146
var success = this.proxy.EnumServicesStatusExA(handle, 0, 0x00000030, 0x00000003, 0x00, 0x00, bytesNeeded, servicesReturned, resumeHandle, 0x00);
108
- if (bytesNeeded.IntVal <= 0) { throw('Error enumerating services'); }
147
+ if (bytesNeeded.IntVal <= 0) {
148
+ throw ('error enumerating services');
149
+ }
150
var sz = bytesNeeded.IntVal;
151
var services = this.GM.CreateVariable(sz);
152
this.proxy.EnumServicesStatusExA(handle, 0, 0x00000030, 0x00000003, services, sz, bytesNeeded, servicesReturned, resumeHandle, 0x00);
@@ -131,7 +172,7 @@ function serviceManager() {
172
var ptr = this.GM.CreatePointer();
173
var bytesNeeded = this.GM.CreateVariable(ptr._size);
174
var handle = this.proxy.OpenSCManagerA(0x00, 0x00, 0x0001 | 0x0004 | 0x0020 | 0x0010);
134
- if (handle.Val == 0) { throw('Could not open ServiceManager'); }
175
+ if (handle.Val == 0) { throw ('could not open ServiceManager'); }
176
var h = this.proxy.OpenServiceA(handle, serviceName, 0x0004 | 0x0020 | 0x0010 | 0x00010000);
177
if (h.Val != 0) {
178
var success = this.proxy.QueryServiceStatusEx(h, 0, 0, 0, bytesNeeded);
@@ -156,48 +197,51 @@ function serviceManager() {
197
}
198
}
199
else {
159
- throw ('Cannot call ' + this.name + '.stop(), when current state is: ' + this.status.state);
200
+ throw ('cannot call ' + this.name + '.stop(), when current state is: ' + this.status.state);
201
}
202
}
203
retVal.start = function () {
204
if (this.status.state == 'STOPPED') {
205
var success = this._proxy.StartServiceA(this._service, 0, 0);
165
- if (success == 0) { throw (this.name + '.start() failed'); }
166
- } else {
167
- throw ('Cannot call ' + this.name + '.start(), when current state is: ' + this.status.state);
206
+ if (success == 0) {
207
+ throw (this.name + '.start() failed');
208
+ }
209
+ }
210
+ else {
211
+ throw ('cannot call ' + this.name + '.start(), when current state is: ' + this.status.state);
212
}
213
}
214
return (retVal);
171
- } else {
215
+ }
216
+ else {
217
218
}
219
}
220
221
this.proxy.CloseServiceHandle(handle);
177
- throw ('Could not find service: ' + name);
222
+ throw ('could not find service: ' + name);
223
}
224
}
180
- this.installService = function installService(options) {
181
- if (process.platform == 'win32') {
182
- if (!this.isAdmin()) { throw ('Installing as Service, requires administrator permissions.'); }
225
+ this.installService = function installService(options)
226
+ {
227
+ if (process.platform == 'win32')
228
+ {
229
+ if (!this.isAdmin()) { throw ('Installing as Service, requires admin'); }
230
231
// Before we start, we need to copy the binary to the right place
185
- var folder = this.getProgramFolder() + '\\Open Source';
186
- if (!require('fs').existsSync(folder)) { require('fs').mkdirSync(folder); } // Create the "Open Source" folder
187
- folder += '\\MeshCmd';
188
- if (!require('fs').existsSync(folder)) { require('fs').mkdirSync(folder); } // Create the "MeshCmd" folder
232
+ var folder = this.getServiceFolder();
233
+ if (!require('fs').existsSync(folder)) { require('fs').mkdirSync(folder); }
234
require('fs').copyFileSync(options.servicePath, folder + '\\' + options.name + '.exe');
235
options.servicePath = folder + '\\' + options.name + '.exe';
191
- console.log('Installing to "' + options.servicePath + '"');
236
237
var servicePath = this.GM.CreateVariable('"' + options.servicePath + '"');
238
var handle = this.proxy.OpenSCManagerA(0x00, 0x00, 0x0002);
195
- if (handle.Val == 0) { throw ('Error opening SCManager'); }
239
+ if (handle.Val == 0) { throw ('error opening SCManager'); }
240
var serviceName = this.GM.CreateVariable(options.name);
241
var displayName = this.GM.CreateVariable(options.name);
242
var allAccess = 0x000F01FF;
243
var serviceType;
200
-
244
+
245
246
switch (options.startType) {
247
case 'BOOT_START':
@@ -235,11 +279,13 @@ function serviceManager() {
279
this.proxy.CloseServiceHandle(handle);
280
return (this.getService(options.name));
281
}
238
- if (process.platform == 'linux') {
239
- switch (this.getServiceType()) {
282
+ if(process.platform == 'linux')
283
+ {
284
+ switch (this.getServiceType())
285
+ {
286
case 'init':
287
require('fs').copyFileSync(options.servicePath, '/etc/init.d/' + options.name);
242
- console.log('Copying ' + options.servicePath);
288
+ console.log('copying ' + options.servicePath);
289
var m = require('fs').statSync('/etc/init.d/' + options.name).mode;
290
m |= (require('fs').CHMOD_MODES.S_IXUSR | require('fs').CHMOD_MODES.S_IXGRP);
291
require('fs').chmodSync('/etc/init.d/' + options.name, m);
@@ -274,25 +320,40 @@ function serviceManager() {
320
}
321
}
322
}
277
- this.uninstallService = function uninstallService(name) {
323
+ this.uninstallService = function uninstallService(name)
324
+ {
325
if (typeof (name) == 'object') { name = name.name; }
279
- if (process.platform == 'win32') {
280
- if (!this.isAdmin()) { throw ('Uninstalling a service, requires administrator permissions.'); }
326
+ if (process.platform == 'win32')
327
+ {
328
+ if (!this.isAdmin()) { throw ('Uninstalling a service, requires admin'); }
329
330
var service = this.getService(name);
283
- if (service.status.state == undefined || service.status.state == 'STOPPED') {
284
- if (this.proxy.DeleteService(service._service) == 0) {
331
+ if (service.status.state == undefined || service.status.state == 'STOPPED')
332
+ {
333
+ if (this.proxy.DeleteService(service._service) == 0)
334
+ {
335
throw ('Uninstall Service for: ' + name + ', failed with error: ' + this.proxy2.GetLastError());
286
- } else {
287
- try { require('fs').unlinkSync(this.getServiceFolder() + '\\' + name + '.exe'); } catch (e) { }
336
+ }
337
+ else
338
+ {
339
+ try
340
+ {
341
+ require('fs').unlinkSync(this.getServiceFolder() + '\\' + name + '.exe');
342
+ }
343
+ catch(e)
344
+ {
345
+ }
346
}
347
}
290
- else {
348
+ else
349
+ {
350
throw ('Cannot uninstall service: ' + name + ', because it is: ' + service.status.state);
351
}
352
}
294
- else if (process.platform == 'linux') {
295
- switch (this.getServiceType()) {
353
+ else if(process.platform == 'linux')
354
+ {
355
+ switch (this.getServiceType())
356
+ {
357
case 'init':
358
this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM });
359
this._update._svcname = name;
@@ -300,7 +361,11 @@ function serviceManager() {
361
try {
362
require('fs').unlinkSync('/etc/init.d/' + this._svcname);
363
console.log(this._svcname + ' uninstalled');
303
- } catch (e) { console.log(this._svcname + ' could not be uninstalled'); }
364
+
365
+ }
366
+ catch (e) {
367
+ console.log(this._svcname + ' could not be uninstalled')
368
+ }
369
process.exit();
370
});
371
this._update.stdout.on('data', function (chunk) { });
@@ -316,7 +381,10 @@ function serviceManager() {
381
require('fs').unlinkSync('/usr/local/mesh/' + this._svcname);
382
require('fs').unlinkSync('/lib/systemd/system/' + this._svcname + '.service');
383
console.log(this._svcname + ' uninstalled');
319
- } catch (e) { console.log(this._svcname + ' could not be uninstalled'); }
384
+ }
385
+ catch (e) {
386
+ console.log(this._svcname + ' could not be uninstalled')
387
+ }
388
process.exit();
389
});
390
this._update.stdout.on('data', function (chunk) { });
@@ -329,9 +397,11 @@ function serviceManager() {
397
}
398
}
399
}
332
- if (process.platform == 'linux') {
333
- this.getServiceType = function getServiceType() {
334
- return (require('processManager').getProcessInfo(1).Name);
400
+ if(process.platform == 'linux')
401
+ {
402
+ this.getServiceType = function getServiceType()
403
+ {
404
+ return (require('process-manager').getProcessInfo(1).Name);
405
};
406
}
407
}
agents/modules_meshcmd/user-sessions.js
+154
-15
@@ -16,9 +16,27 @@ limitations under the License.
16
17
function UserSessions()
18
{
19
- this._ObjectID = 'UserSessions';
19
+ this._ObjectID = 'user-sessions';
20
+ require('events').EventEmitter.call(this, true).createEvent('changed');
21
21
- if (process.platform == 'win32') {
22
+ this.enumerateUsers = function enumerateUsers()
23
+ {
24
+ var promise = require('promise');
25
+ var p = new promise(function (res, rej)
26
+ {
27
+ this.__resolver = res;
28
+ this.__rejector = rej;
29
+ });
30
+ p.__handler = function __handler(users)
31
+ {
32
+ p.__resolver(users);
33
+ };
34
+ this.Current(p.__handler);
35
+ return (p);
36
+ }
37
+
38
+ if (process.platform == 'win32')
39
+ {
40
this._marshal = require('_GenericMarshal');
41
this._kernel32 = this._marshal.CreateNativeProxy('Kernel32.dll');
42
this._kernel32.CreateMethod('GetLastError');
@@ -77,7 +95,7 @@ function UserSessions()
95
return (retVal);
96
};
97
80
- this.Current = function Current()
98
+ this.Current = function Current(cb)
99
{
100
var retVal = {};
101
var pinfo = this._marshal.CreatePointer();
@@ -102,36 +120,152 @@ function UserSessions()
120
121
this._wts.WTSFreeMemory(pinfo.Deref());
122
105
- Object.defineProperty(retVal, 'connected', { value: showActiveOnly(retVal) });
123
+ Object.defineProperty(retVal, 'Active', { value: showActiveOnly(retVal) });
124
+ if (cb) { cb(retVal); }
125
return (retVal);
126
};
127
}
128
else
129
{
111
- this.Current = function Current()
130
+ this.Self = function Self()
131
+ {
132
+ var promise = require('promise');
133
+ var p = new promise(function (res, rej)
134
+ {
135
+ this.__resolver = res; this.__rejector = rej;
136
+ this.__child = require('child_process').execFile('/usr/bin/id', ['id', '-u']);
137
+ this.__child.promise = this;
138
+ this.__child.stdout._txt = '';
139
+ this.__child.stdout.on('data', function (chunk) { this._txt += chunk.toString(); });
140
+ this.__child.on('exit', function (code)
141
+ {
142
+ try
143
+ {
144
+ parseInt(this.stdout._txt);
145
+ }
146
+ catch (e)
147
+ {
148
+ this.promise.__rejector('invalid uid');
149
+ return;
150
+ }
151
+
152
+ var id = parseInt(this.stdout._txt);
153
+ this.promise.__resolver(id);
154
+ });
155
+ });
156
+ return (p);
157
+ };
158
+ this.Current = function Current(cb)
159
{
160
var retVal = {};
114
- var emitterUtils = require('events').inherits(retVal);
115
- emitterUtils.createEvent('logon');
161
+ retVal._ObjectID = 'UserSession'
162
+ Object.defineProperty(retVal, '_callback', { value: cb });
163
+ Object.defineProperty(retVal, '_child', { value: require('child_process').execFile('/usr/bin/last', ['last', '-f', '/var/run/utmp']) });
164
117
- retVal._child = require('child_process').execFile('/usr/bin/last', ['last', '-f', '/var/run/utmp']);
165
retVal._child.Parent = retVal;
166
retVal._child._txt = '';
167
retVal._child.on('exit', function (code)
168
{
169
var lines = this._txt.split('\n');
170
var sessions = [];
171
+ var users = {};
172
+
173
for(var i in lines)
174
{
175
if (lines[i])
176
{
128
- console.log(getTokens(lines[i]));
129
- var user = lines[i].substring(0, lines[i].indexOf(' '));
130
- sessions.push(user);
177
+ var tokens = getTokens(lines[i]);
178
+ var s = { Username: tokens[0], SessionId: tokens[1] }
179
+ if (tokens[3].includes('still logged in'))
180
+ {
181
+ s.State = 'Active';
182
+ }
183
+ else
184
+ {
185
+ s.LastActive = tokens[3];
186
+ }
187
+
188
+ sessions.push(s);
189
}
190
}
191
sessions.pop();
134
- console.log(sessions);
192
+
193
+
194
+ var usernames = {};
195
+ var promises = [];
196
+
197
+ for (var i in sessions)
198
+ {
199
+ if (sessions[i].Username != 'reboot')
200
+ {
201
+ users[sessions[i].SessionId] = sessions[i];
202
+ if(usernames[sessions[i].Username] == null)
203
+ {
204
+ usernames[sessions[i].Username] = -1;
205
+ }
206
+ }
207
+ }
208
+
209
+ try
210
+ {
211
+ require('promise');
212
+ }
213
+ catch(e)
214
+ {
215
+ Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
216
+ if (this.Parent._callback) { this.Parent._callback.call(this.Parent, users); }
217
+ return;
218
+ }
219
+
220
+ var promise = require('promise');
221
+ for (var n in usernames)
222
+ {
223
+ var p = new promise(function (res, rej)
224
+ {
225
+ this.__username = n;
226
+ this.__resolver = res; this.__rejector = rej;
227
+ this.__child = require('child_process').execFile('/usr/bin/id', ['id', '-u', n]);
228
+ this.__child.promise = this;
229
+ this.__child.stdout._txt = '';
230
+ this.__child.stdout.on('data', function (chunk) { this._txt += chunk.toString(); });
231
+ this.__child.on('exit', function (code)
232
+ {
233
+ try
234
+ {
235
+ parseInt(this.stdout._txt);
236
+ }
237
+ catch(e)
238
+ {
239
+ this.promise.__rejector('invalid uid');
240
+ return;
241
+ }
242
+
243
+ var id = parseInt(this.stdout._txt);
244
+ this.promise.__resolver(id);
245
+ });
246
+ });
247
+ promises.push(p);
248
+ }
249
+ promise.all(promises).then(function (plist)
250
+ {
251
+ // Done
252
+ var table = {};
253
+ for(var i in plist)
254
+ {
255
+ table[plist[i].__username] = plist[i]._internal.completedArgs[0];
256
+ }
257
+ for(var i in users)
258
+ {
259
+ users[i].uid = table[users[i].Username];
260
+ }
261
+ Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
262
+ if (retVal._callback) { retVal._callback.call(retVal, users); }
263
+ }, function (reason)
264
+ {
265
+ // Failed
266
+ Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
267
+ if (retVal._callback) { retVal._callback.call(retVal, users); }
268
+ });
269
});
270
retVal._child.stdout.Parent = retVal._child;
271
retVal._child.stdout.on('data', function (chunk) { this.Parent._txt += chunk.toString(); });
@@ -145,7 +279,7 @@ function showActiveOnly(source)
279
var retVal = [];
280
for (var i in source)
281
{
148
- if (source[i].State == 'Active' || source[i].State == 'Connected')
282
+ if (source[i].State == 'Active')
283
{
284
retVal.push(source[i]);
285
}
@@ -159,8 +293,13 @@ function getTokens(str)
293
294
columns.push(str.substring(0, (i=str.indexOf(' '))));
295
while (str[++i] == ' ');
162
- columns.push(str.substring(i, str.substring(i).indexOf(' ') + i));
163
-
296
+ columns.push(str.substring(i, (i=str.substring(i).indexOf(' ') + i)));
297
+ while (str[++i] == ' ');
298
+ columns.push(str.substring(i, (i=str.substring(i).indexOf(' ') + i)));
299
+ while (str[++i] == ' ');
300
+ var status = str.substring(i).trim();
301
+ columns.push(status);
302
+
303
return (columns);
304
}
305
agents/modules_meshcore/monitor-border.js
new
+319
@@ -0,0 +1,319 @@
1
+var red = 0xFF;
2
+var yellow = 0xFFFF;
3
+var GXxor = 0x6; // src XOR dst
4
+var GXclear = 0x0;
5
+var ExposureMask = (1 << 15);
6
+
7
+function windows_monitorborder()
8
+{
9
+ this._ObjectID = 'monitor-info';
10
+ var info = require('monitor-info');
11
+ var gm = require('_GenericMarshal');
12
+ var user32 = gm.CreateNativeProxy('user32.dll');
13
+
14
+ info.monitors = [];
15
+ user32.CreateMethod('GetDC');
16
+ user32.CreateMethod('ReleaseDC');
17
+ user32.CreateMethod('FillRect');
18
+ user32.CreateMethod('InvalidateRect');
19
+
20
+ var gdi32 = gm.CreateNativeProxy('gdi32.dll');
21
+ gdi32.CreateMethod('CreateSolidBrush');
22
+
23
+ var redBrush = gdi32.CreateSolidBrush(red);
24
+ var yellowBrush = gdi32.CreateSolidBrush(yellow);
25
+
26
+ require('events').EventEmitter.call(this);
27
+ this.on('~', function () { this.Stop(); });
28
+
29
+ this.Stop = function Stop()
30
+ {
31
+ info.redInterval = null;
32
+
33
+ var drawRect = gm.CreateVariable(16);
34
+ var drawRectBuffer = drawRect.toBuffer();
35
+
36
+ for (var i in info.monitors)
37
+ {
38
+ // Top
39
+ drawRectBuffer.writeInt32LE(info.monitors[i].left, 0);
40
+ drawRectBuffer.writeInt32LE(info.monitors[i].top, 4);
41
+ drawRectBuffer.writeInt32LE(info.monitors[i].left + (info.monitors[i].right - info.monitors[i].left), 8);
42
+ drawRectBuffer.writeInt32LE(info.monitors[i].bottom - info.monitors[i].top, 12);
43
+ user32.InvalidateRect(0, drawRect, 0);
44
+ }
45
+ }
46
+
47
+ this.Start = function Start()
48
+ {
49
+ info.getInfo().then(function (mon)
50
+ {
51
+ var drawRect = gm.CreateVariable(16);
52
+
53
+ info.monitors = mon;
54
+ info.dc = user32.GetDC(0);
55
+ info.state = 0;
56
+
57
+ info.redInterval = setInterval(function ()
58
+ {
59
+ info.state = (info.state + 1) % 8;
60
+
61
+ var drawRectBuffer = drawRect.toBuffer();
62
+ for(var i in info.monitors)
63
+ {
64
+ drawRectBuffer.writeInt32LE(info.monitors[i].left, 0);
65
+ drawRectBuffer.writeInt32LE(info.monitors[i].top, 4);
66
+ drawRectBuffer.writeInt32LE(info.monitors[i].left + (info.monitors[i].right - info.monitors[i].left)/2, 8);
67
+ drawRectBuffer.writeInt32LE(5, 12);
68
+ user32.FillRect(info.dc, drawRect, (info.state == 0 || info.state == 4) ? yellowBrush : redBrush);
69
+ drawRectBuffer.writeInt32LE(info.monitors[i].left + (info.monitors[i].right - info.monitors[i].left) / 2, 0);
70
+ drawRectBuffer.writeInt32LE(info.monitors[i].top, 4);
71
+ drawRectBuffer.writeInt32LE(info.monitors[i].right, 8);
72
+ drawRectBuffer.writeInt32LE(5, 12);
73
+ user32.FillRect(info.dc, drawRect, (info.state == 1 || info.state == 5) ? yellowBrush : redBrush);
74
+
75
+
76
+ drawRectBuffer.writeInt32LE(info.monitors[i].right - 5, 0);
77
+ drawRectBuffer.writeInt32LE(info.monitors[i].top, 4);
78
+ drawRectBuffer.writeInt32LE(info.monitors[i].right, 8);
79
+ drawRectBuffer.writeInt32LE(info.monitors[i].top + (info.monitors[i].bottom - info.monitors[i].top)/2, 12);
80
+ user32.FillRect(info.dc, drawRect, (info.state == 2 || info.state == 6) ? yellowBrush : redBrush);
81
+ drawRectBuffer.writeInt32LE(info.monitors[i].right - 5, 0);
82
+ drawRectBuffer.writeInt32LE(info.monitors[i].top + (info.monitors[i].bottom - info.monitors[i].top) / 2, 4);
83
+ drawRectBuffer.writeInt32LE(info.monitors[i].right, 8);
84
+ drawRectBuffer.writeInt32LE(info.monitors[i].bottom, 12);
85
+ user32.FillRect(info.dc, drawRect, (info.state == 3 || info.state == 7) ? yellowBrush : redBrush);
86
+
87
+
88
+ drawRectBuffer.writeInt32LE(info.monitors[i].left + (info.monitors[i].right - info.monitors[i].left) / 2, 0);
89
+ drawRectBuffer.writeInt32LE(info.monitors[i].bottom - 5, 4);
90
+ drawRectBuffer.writeInt32LE(info.monitors[i].right, 8);
91
+ drawRectBuffer.writeInt32LE(info.monitors[i].bottom, 12);
92
+ user32.FillRect(info.dc, drawRect, (info.state == 4 || info.state == 0) ? yellowBrush : redBrush);
93
+ drawRectBuffer.writeInt32LE(info.monitors[i].left, 0);
94
+ drawRectBuffer.writeInt32LE(info.monitors[i].bottom - 5, 4);
95
+ drawRectBuffer.writeInt32LE(info.monitors[i].left + (info.monitors[i].right - info.monitors[i].left) / 2, 8);
96
+ drawRectBuffer.writeInt32LE(info.monitors[i].bottom, 12);
97
+ user32.FillRect(info.dc, drawRect, (info.state == 5 || info.state == 1) ? yellowBrush : redBrush);
98
+
99
+
100
+ drawRectBuffer.writeInt32LE(info.monitors[i].left, 0);
101
+ drawRectBuffer.writeInt32LE(info.monitors[i].top + (info.monitors[i].bottom - info.monitors[i].top) / 2, 4);
102
+ drawRectBuffer.writeInt32LE(info.monitors[i].left + 5, 8);
103
+ drawRectBuffer.writeInt32LE(info.monitors[i].bottom, 12);
104
+ user32.FillRect(info.dc, drawRect, (info.state == 6 || info.state == 2) ? yellowBrush : redBrush);
105
+ drawRectBuffer.writeInt32LE(info.monitors[i].left, 0);
106
+ drawRectBuffer.writeInt32LE(info.monitors[i].top, 4);
107
+ drawRectBuffer.writeInt32LE(info.monitors[i].left + 5, 8);
108
+ drawRectBuffer.writeInt32LE(info.monitors[i].top + (info.monitors[i].bottom - info.monitors[i].top) / 2, 12);
109
+ user32.FillRect(info.dc, drawRect, (info.state == 7 || info.state == 3) ? yellowBrush : redBrush);
110
+ }
111
+ }, 450);
112
+ });
113
+ }
114
+}
115
+
116
+function linux_monitorborder()
117
+{
118
+ var self = this;
119
+ this.displays = [];
120
+ this._ObjectID = 'monitor-info';
121
+ this._info = require('monitor-info');
122
+ this._isUnity = this._info.isUnity();
123
+
124
+ console.log('isUnity = ' + this._isUnity);
125
+
126
+ require('events').EventEmitter.call(this);
127
+ this.on('~', function () { this.Stop(); });
128
+
129
+ this.Stop = function Stop()
130
+ {
131
+ this._timeout = null;
132
+ if(!this._isUnity)
133
+ {
134
+ for(var i=0; i < this.displays.length; ++i)
135
+ {
136
+ if(this.displays[i].GC1 && this.displays[i].rootWindow)
137
+ {
138
+ self._info._X11.XSetFunction(self.displays[i].display, self.displays[i].GC1, GXclear);
139
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, 0, self.displays[i].right, 0);
140
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, self.displays[i].right, 0, self.displays[i].right, self.displays[i].bottom);
141
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, self.displays[i].bottom, self.displays[i].right, self.displays[i].bottom);
142
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, 0, 0, self.displays[i].bottom);
143
+
144
+ this._info._X11.XFlush(this.displays[i].display);
145
+ }
146
+ }
147
+ }
148
+ }
149
+ this.Start = function Start()
150
+ {
151
+ this._info.getInfo().then(function (mon)
152
+ {
153
+ self.displays = mon;
154
+ console.log(mon.length + ' displays');
155
+ for(var i = 0; i<mon.length; ++i)
156
+ {
157
+ console.log('Width: ' + mon[i].right + ', Height: ' + mon[i].bottom);
158
+ mon[i].rootWindow = self._info._X11.XRootWindow(mon[i].display, mon[i].screenId);
159
+
160
+ if (self._isUnity)
161
+ {
162
+ // We are unity, so we have to fake the borders with borderless windows
163
+ var white = self._info._X11.XWhitePixel(mon[i].display, mon[i].screenId).Val;
164
+
165
+ // Top
166
+ mon[i].window_top = self._info._X11.XCreateSimpleWindow(mon[i].display, mon[i].rootWindow, 0, 0, mon[i].right, 5, 0, white, white);
167
+ mon[i].window_top.gc = self._info._X11.XCreateGC(mon[i].display, mon[i].window_top, 0, 0);
168
+ self._info._X11.XSetLineAttributes(mon[i].display, mon[i].window_top.gc, 10, 0, 1, 1);
169
+ self._info._X11.XSetSubwindowMode(mon[i].display, mon[i].window_top.gc, 1);
170
+ self._info.unDecorateWindow(mon[i].display, mon[i].window_top);
171
+ self._info.setWindowSizeHints(mon[i].display, mon[i].window_top, 0, 0, mon[i].right, 5);
172
+
173
+ // Right
174
+ mon[i].window_right = self._info._X11.XCreateSimpleWindow(mon[i].display, mon[i].rootWindow, mon[i].right - 5, 0, 5, mon[i].bottom, 0, white, white);
175
+ mon[i].window_right.gc = self._info._X11.XCreateGC(mon[i].display, mon[i].window_right, 0, 0);
176
+ self._info._X11.XSetLineAttributes(mon[i].display, mon[i].window_right.gc, 10, 0, 1, 1);
177
+ self._info._X11.XSetSubwindowMode(mon[i].display, mon[i].window_right.gc, 1);
178
+ self._info.unDecorateWindow(mon[i].display, mon[i].window_right);
179
+ self._info.setWindowSizeHints(mon[i].display, mon[i].window_right, mon[i].right - 5, 0, 5, mon[i].bottom);
180
+
181
+ // Left
182
+ mon[i].window_left = self._info._X11.XCreateSimpleWindow(mon[i].display, mon[i].rootWindow, 0, 0, 5, mon[i].bottom, 0, white, white);
183
+ mon[i].window_left.gc = self._info._X11.XCreateGC(mon[i].display, mon[i].window_left, 0, 0);
184
+ self._info._X11.XSetLineAttributes(mon[i].display, mon[i].window_left.gc, 10, 0, 1, 1);
185
+ self._info._X11.XSetSubwindowMode(mon[i].display, mon[i].window_left.gc, 1);
186
+ self._info.unDecorateWindow(mon[i].display, mon[i].window_left);
187
+ self._info.setWindowSizeHints(mon[i].display, mon[i].window_left, 0, 0, 5, mon[i].bottom);
188
+
189
+ // Bottom
190
+ mon[i].window_bottom = self._info._X11.XCreateSimpleWindow(mon[i].display, mon[i].rootWindow, 0, mon[i].bottom - 5, mon[i].right, 5, 0, white, white);
191
+ mon[i].window_bottom.gc = self._info._X11.XCreateGC(mon[i].display, mon[i].window_bottom, 0, 0);
192
+ self._info._X11.XSetLineAttributes(mon[i].display, mon[i].window_bottom.gc, 10, 0, 1, 1);
193
+ self._info._X11.XSetSubwindowMode(mon[i].display, mon[i].window_bottom.gc, 1);
194
+ self._info.unDecorateWindow(mon[i].display, mon[i].window_bottom);
195
+ self._info.setWindowSizeHints(mon[i].display, mon[i].window_bottom, 0, mon[i].bottom - 5, mon[i].right, 5);
196
+
197
+ self._info._X11.XMapWindow(mon[i].display, mon[i].window_top);
198
+ self._info._X11.XMapWindow(mon[i].display, mon[i].window_right);
199
+ self._info._X11.XMapWindow(mon[i].display, mon[i].window_left);
200
+ self._info._X11.XMapWindow(mon[i].display, mon[i].window_bottom);
201
+
202
+ self._info.setAlwaysOnTop(mon[i].display, mon[i].rootWindow, mon[i].window_top);
203
+ self._info.hideWindowIcon(mon[i].display, mon[i].rootWindow, mon[i].window_top);
204
+ self._info.setAlwaysOnTop(mon[i].display, mon[i].rootWindow, mon[i].window_right);
205
+ self._info.hideWindowIcon(mon[i].display, mon[i].rootWindow, mon[i].window_right);
206
+ self._info.setAlwaysOnTop(mon[i].display, mon[i].rootWindow, mon[i].window_left);
207
+ self._info.hideWindowIcon(mon[i].display, mon[i].rootWindow, mon[i].window_left);
208
+ self._info.setAlwaysOnTop(mon[i].display, mon[i].rootWindow, mon[i].window_bottom);
209
+ self._info.hideWindowIcon(mon[i].display, mon[i].rootWindow, mon[i].window_bottom);
210
+
211
+ self._info._X11.XFlush(mon[i].display);
212
+ mon[i].borderState = 0;
213
+ }
214
+ else
215
+ {
216
+ // If we aren't unity, then we can just draw
217
+ mon[i].GC1 = self._info._X11.XCreateGC(mon[i].display, mon[i].rootWindow, 0, 0);
218
+ mon[i].borderState = 0;
219
+
220
+ self._info._X11.XSetForeground(mon[i].display, mon[i].GC1, self._info._X11.XWhitePixel(mon[i].display, mon[i].screenId).Val); // White
221
+ self._info._X11.XSetLineAttributes(mon[i].display, mon[i].GC1, 10, 0, 1, 1);
222
+ self._info._X11.XSetSubwindowMode(mon[i].display, mon[i].GC1, 1);
223
+ }
224
+ }
225
+ self._info._XEvent = self._info._gm.CreateVariable(192);
226
+ self._timeout = setTimeout(self._isUnity ? self.unity_drawBorder : self.timeoutHandler, 250);
227
+ });
228
+ }
229
+
230
+ this.timeoutHandler = function()
231
+ {
232
+ for (var i = 0; i < self.displays.length; ++i) {
233
+ self.displays[i].borderState = (self.displays[i].borderState + 1) % 8;
234
+
235
+ // Top
236
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 0 || self.displays[i].borderState == 4) ? 0xffff00 : 0xff0000);
237
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, 0, self.displays[i].right / 2, 0);
238
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 1 || self.displays[i].borderState == 5) ? 0xffff00 : 0xff0000);
239
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, self.displays[i].right / 2, 0, self.displays[i].right, 0);
240
+
241
+ // Right
242
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 2 || self.displays[i].borderState == 6) ? 0xffff00 : 0xff0000);
243
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, self.displays[i].right, 0, self.displays[i].right, self.displays[i].bottom / 2);
244
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 3 || self.displays[i].borderState == 7) ? 0xffff00 : 0xff0000);
245
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, self.displays[i].right, self.displays[i].bottom / 2, self.displays[i].right, self.displays[i].bottom);
246
+
247
+ // Bottom
248
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 5 || self.displays[i].borderState == 1) ? 0xffff00 : 0xff0000);
249
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, self.displays[i].bottom, self.displays[i].right / 2, self.displays[i].bottom);
250
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 4 || self.displays[i].borderState == 0) ? 0xffff00 : 0xff0000);
251
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, self.displays[i].right / 2, self.displays[i].bottom, self.displays[i].right, self.displays[i].bottom);
252
+
253
+ // Left
254
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 7 || self.displays[i].borderState == 3) ? 0xffff00 : 0xff0000);
255
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, 0, 0, self.displays[i].bottom / 2);
256
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 6 || self.displays[i].borderState == 2) ? 0xffff00 : 0xff0000);
257
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, self.displays[i].bottom / 2, 0, self.displays[i].bottom);
258
+
259
+
260
+ self._info._X11.XFlush(self.displays[i].display);
261
+ }
262
+ self._timeout = setTimeout(self._isUnity ? self.unity_drawBorder : self.timeoutHandler, 400);
263
+ }
264
+ this.unity_drawBorder = function unity_drawBorder()
265
+ {
266
+ for (var i = 0; i < self.displays.length; ++i)
267
+ {
268
+ self.displays[i].borderState = (self.displays[i].borderState + 1) % 8;
269
+
270
+ // Top
271
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_top.gc, (self.displays[i].borderState == 0 || self.displays[i].borderState == 4) ? 0xffff00 : 0xff0000);
272
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_top, self.displays[i].window_top.gc, 0, 0, self.displays[i].right / 2, 0);
273
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_top.gc, (self.displays[i].borderState == 1 || self.displays[i].borderState == 5) ? 0xffff00 : 0xff0000);
274
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_top, self.displays[i].window_top.gc, self.displays[i].right / 2, 0, self.displays[i].right, 0);
275
+ self._info._X11.XFlush(self.displays[i].display);
276
+
277
+ // Right
278
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_right.gc, (self.displays[i].borderState == 2 || self.displays[i].borderState == 6) ? 0xffff00 : 0xff0000);
279
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_right, self.displays[i].window_right.gc, 0, 0, 0, self.displays[i].bottom / 2);
280
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_right.gc, (self.displays[i].borderState == 3 || self.displays[i].borderState == 7) ? 0xffff00 : 0xff0000);
281
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_right, self.displays[i].window_right.gc, 0, self.displays[i].bottom / 2, 0, self.displays[i].bottom);
282
+ self._info._X11.XFlush(self.displays[i].display);
283
+
284
+ // Bottom
285
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_bottom.gc, (self.displays[i].borderState == 5 || self.displays[i].borderState == 1) ? 0xffff00 : 0xff0000);
286
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_bottom, self.displays[i].window_bottom.gc, 0, 0, self.displays[i].right / 2, 0);
287
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_bottom.gc, (self.displays[i].borderState == 4 || self.displays[i].borderState == 0) ? 0xffff00 : 0xff0000);
288
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_bottom, self.displays[i].window_bottom.gc, self.displays[i].right / 2, 0, self.displays[i].right, 0);
289
+ self._info._X11.XFlush(self.displays[i].display);
290
+
291
+ // Left
292
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_left.gc, (self.displays[i].borderState == 7 || self.displays[i].borderState == 3) ? 0xffff00 : 0xff0000);
293
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_left, self.displays[i].window_left.gc, 0, 0, 0, self.displays[i].bottom / 2);
294
+ self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_left.gc, (self.displays[i].borderState == 6 || self.displays[i].borderState == 2) ? 0xffff00 : 0xff0000);
295
+ self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_left, self.displays[i].window_left.gc, 0, self.displays[i].bottom / 2, 0, self.displays[i].bottom);
296
+ self._info._X11.XFlush(self.displays[i].display);
297
+ }
298
+ self._timeout = setTimeout(self._isUnity ? self.unity_drawBorder : self.timeoutHandler, 400);
299
+ }
300
+}
301
+
302
+switch(process.platform)
303
+{
304
+ case 'win32':
305
+ module.exports = new windows_monitorborder();
306
+ break;
307
+ case 'linux':
308
+ module.exports = new linux_monitorborder();
309
+ break;
310
+ default:
311
+ break;
312
+}
313
+
314
+
315
+
316
+
317
+
318
+
319
+
agents/modules_meshcore/monitor-info.js
new
+194
@@ -0,0 +1,194 @@
1
+
2
+var promise = require('promise');
3
+var PPosition = 4;
4
+var PSize = 8;
5
+var _NET_WM_STATE_REMOVE = 0; // remove/unset property
6
+var _NET_WM_STATE_ADD = 1; // add/set property
7
+var _NET_WM_STATE_TOGGLE = 2; // toggle property
8
+var SubstructureRedirectMask = (1 << 20);
9
+var SubstructureNotifyMask = (1 << 19);
10
+
11
+
12
+function monitorinfo()
13
+{
14
+ this._ObjectID = 'monitor-info';
15
+ this._gm = require('_GenericMarshal');
16
+
17
+ if (process.platform == 'win32')
18
+ {
19
+ this._user32 = this._gm.CreateNativeProxy('user32.dll');
20
+ this._user32.CreateMethod('EnumDisplayMonitors');
21
+ this._kernel32 = this._gm.CreateNativeProxy('kernel32.dll');
22
+ this._kernel32.CreateMethod('GetLastError');
23
+
24
+ this.getInfo = function getInfo()
25
+ {
26
+ var info = this;
27
+ return (new promise(function (resolver, rejector) {
28
+ this._monitorinfo = { resolver: resolver, rejector: rejector, self: info, callback: info._gm.GetGenericGlobalCallback(4) };
29
+ this._monitorinfo.callback.info = this._monitorinfo;
30
+ this._monitorinfo.dwData = info._gm.ObjectToPtr(this._monitorinfo);
31
+
32
+ this._monitorinfo.callback.results = [];
33
+ this._monitorinfo.callback.on('GlobalCallback', function OnMonitorInfo(hmon, hdc, r, user) {
34
+ if (this.ObjectToPtr_Verify(this.info, user)) {
35
+ var rb = r.Deref(0, 16).toBuffer();
36
+ this.results.push({ left: rb.readInt32LE(0), top: rb.readInt32LE(4), right: rb.readInt32LE(8), bottom: rb.readInt32LE(12) });
37
+
38
+ var r = this.info.self._gm.CreateInteger();
39
+ r.Val = 1;
40
+ return (r);
41
+ }
42
+ });
43
+
44
+ if (info._user32.EnumDisplayMonitors(0, 0, this._monitorinfo.callback, this._monitorinfo.dwData).Val == 0) {
45
+ rejector('LastError=' + info._kernel32.GetLastError().Val);
46
+ return;
47
+ }
48
+ else {
49
+ resolver(this._monitorinfo.callback.results);
50
+ }
51
+
52
+ }));
53
+ }
54
+ }
55
+ else if(process.platform == 'linux')
56
+ {
57
+ this._X11 = this._gm.CreateNativeProxy('libX11.so');
58
+ this._X11.CreateMethod('XChangeProperty');
59
+ this._X11.CreateMethod('XCloseDisplay');
60
+ this._X11.CreateMethod('XCreateGC');
61
+ this._X11.CreateMethod('XCreateWindow');
62
+ this._X11.CreateMethod('XCreateSimpleWindow');
63
+ this._X11.CreateMethod('XDefaultColormap');
64
+ this._X11.CreateMethod('XDefaultScreen');
65
+ this._X11.CreateMethod('XDrawLine');
66
+ this._X11.CreateMethod('XDisplayHeight');
67
+ this._X11.CreateMethod('XDisplayWidth');
68
+ this._X11.CreateMethod('XFetchName');
69
+ this._X11.CreateMethod('XFlush');
70
+ this._X11.CreateMethod('XFree');
71
+ this._X11.CreateMethod('XCreateGC');
72
+ this._X11.CreateMethod('XGetWindowProperty');
73
+ this._X11.CreateMethod('XInternAtom');
74
+ this._X11.CreateMethod('XMapWindow');
75
+ this._X11.CreateMethod({ method: 'XNextEvent', threadDispatch: true });
76
+ this._X11.CreateMethod('XOpenDisplay');
77
+ this._X11.CreateMethod('XRootWindow');
78
+ this._X11.CreateMethod('XScreenCount');
79
+ this._X11.CreateMethod('XScreenOfDisplay');
80
+ this._X11.CreateMethod('XSelectInput');
81
+ this._X11.CreateMethod('XSendEvent');
82
+ this._X11.CreateMethod('XSetForeground');
83
+ this._X11.CreateMethod('XSetFunction');
84
+ this._X11.CreateMethod('XSetLineAttributes');
85
+ this._X11.CreateMethod('XSetNormalHints');
86
+ this._X11.CreateMethod('XSetSubwindowMode');
87
+
88
+ this._X11.CreateMethod('XBlackPixel');
89
+ this._X11.CreateMethod('XWhitePixel');
90
+
91
+ this.isUnity = function isUnity()
92
+ {
93
+ var ret = false;
94
+ var display = this._X11.XOpenDisplay(this._gm.CreateVariable(':0'));
95
+ var rootWindow = this._X11.XRootWindow(display, this._X11.XDefaultScreen(display));
96
+
97
+ var a = this._X11.XInternAtom(display, this._gm.CreateVariable('_NET_CLIENT_LIST'), 1);
98
+ var actualType = this._gm.CreateVariable(8);
99
+ var format = this._gm.CreateVariable(4);
100
+ var numItems = this._gm.CreateVariable(8);
101
+ var bytesAfter = this._gm.CreateVariable(8);
102
+ var data = this._gm.CreatePointer();
103
+
104
+ this._X11.XGetWindowProperty(display, rootWindow, a, 0, ~0, 0, 0, actualType, format, numItems, bytesAfter, data);
105
+ for (var i = 0; i < numItems.Deref(0, 4).toBuffer().readUInt32LE(0) ; ++i)
106
+ {
107
+ var w = data.Deref().Deref(i * 8, 8).Deref(8);
108
+ var name = this._gm.CreatePointer();
109
+ var ns = this._X11.XFetchName(display, w, name);
110
+ if (name.Deref().String == 'unity-launcher')
111
+ {
112
+ ret = true;
113
+ break;
114
+ }
115
+ }
116
+ this._X11.XCloseDisplay(display);
117
+ return (ret);
118
+ }
119
+
120
+ this.unDecorateWindow = function unDecorateWindow(display, window)
121
+ {
122
+ var MwmHints = this._gm.CreateVariable(40);
123
+ var mwmHintsProperty = this._X11.XInternAtom(display, this._gm.CreateVariable('_MOTIF_WM_HINTS'), 0);
124
+ MwmHints.Deref(0, 4).toBuffer().writeUInt32LE(1 << 1);
125
+ this._X11.XChangeProperty(display, window, mwmHintsProperty, mwmHintsProperty, 32, 0, MwmHints, 5);
126
+ }
127
+ this.setWindowSizeHints = function setWindowSizeHints(display, window, x, y, width, height)
128
+ {
129
+ var sizeHints = this._gm.CreateVariable(80);
130
+ sizeHints.Deref(0, 4).toBuffer().writeUInt32LE(PPosition | PSize);
131
+ sizeHints.Deref(8, 4).toBuffer().writeUInt32LE(x);
132
+ sizeHints.Deref(12, 4).toBuffer().writeUInt32LE(y);
133
+ sizeHints.Deref(16, 4).toBuffer().writeUInt32LE(width);
134
+ sizeHints.Deref(20, 4).toBuffer().writeUInt32LE(height);
135
+ this._X11.XSetNormalHints(display, window, sizeHints);
136
+ }
137
+ this.setAlwaysOnTop = function setAlwaysOnTop(display, rootWindow, window)
138
+ {
139
+ var wmNetWmState = this._X11.XInternAtom(display, this._gm.CreateVariable('_NET_WM_STATE'), 1);
140
+ var wmStateAbove = this._X11.XInternAtom(display, this._gm.CreateVariable('_NET_WM_STATE_ABOVE'), 1);
141
+
142
+ var xclient = this._gm.CreateVariable(96);
143
+ xclient.Deref(0, 4).toBuffer().writeUInt32LE(33); // ClientMessage type
144
+ xclient.Deref(48, 4).toBuffer().writeUInt32LE(32); // Format 32
145
+ wmNetWmState.pointerBuffer().copy(xclient.Deref(40, 8).toBuffer()); // message_type
146
+ xclient.Deref(56, 8).toBuffer().writeUInt32LE(_NET_WM_STATE_ADD); // data.l[0]
147
+ wmStateAbove.pointerBuffer().copy(xclient.Deref(64, 8).toBuffer()); // data.l[1]
148
+
149
+ window.pointerBuffer().copy(xclient.Deref(32, 8).toBuffer()); // window
150
+ this._X11.XSendEvent(display, rootWindow, 0, SubstructureRedirectMask | SubstructureNotifyMask, xclient);
151
+ }
152
+ this.hideWindowIcon = function hideWindowIcon(display, rootWindow, window)
153
+ {
154
+ var wmNetWmState = this._X11.XInternAtom(display, this._gm.CreateVariable('_NET_WM_STATE'), 1);
155
+ var wmStateSkip = this._X11.XInternAtom(display, this._gm.CreateVariable('_NET_WM_STATE_SKIP_TASKBAR'), 1);
156
+
157
+ var xclient = this._gm.CreateVariable(96);
158
+ xclient.Deref(0, 4).toBuffer().writeUInt32LE(33); // ClientMessage type
159
+ xclient.Deref(48, 4).toBuffer().writeUInt32LE(32); // Format 32
160
+ wmNetWmState.pointerBuffer().copy(xclient.Deref(40, 8).toBuffer()); // message_type
161
+ xclient.Deref(56, 8).toBuffer().writeUInt32LE(_NET_WM_STATE_ADD); // data.l[0]
162
+ wmStateSkip.pointerBuffer().copy(xclient.Deref(64, 8).toBuffer()); // data.l[1]
163
+
164
+ window.pointerBuffer().copy(xclient.Deref(32, 8).toBuffer()); // window
165
+ this._X11.XSendEvent(display, rootWindow, 0, SubstructureRedirectMask | SubstructureNotifyMask, xclient);
166
+ }
167
+
168
+ this.getInfo = function getInfo()
169
+ {
170
+ var info = this;
171
+ return (new promise(function (resolver, rejector)
172
+ {
173
+ var display = info._X11.XOpenDisplay(info._gm.CreateVariable(':0'));
174
+ var screenCount = info._X11.XScreenCount(display).Val;
175
+ var ret = [];
176
+ for(var i=0;i<screenCount;++i)
177
+ {
178
+ var screen = info._X11.XScreenOfDisplay(display, i);
179
+ ret.push({ left: 0, top: 0, right: info._X11.XDisplayWidth(display, i).Val, bottom: info._X11.XDisplayHeight(display, i).Val, screen: screen, screenId: i, display: display });
180
+ }
181
+ resolver(ret);
182
+ }));
183
+ }
184
+ }
185
+ else
186
+ {
187
+ throw (process.platform + ' not supported');
188
+ }
189
+}
190
+
191
+module.exports = new monitorinfo();
192
+
193
+
194
+
agents/modules_meshcore/process-manager.js
+47
-22
@@ -14,12 +14,14 @@ See the License for the specific language governing permissions and
14
limitations under the License.
15
*/
16
17
-// JavaScript source code
17
+
18
var GM = require('_GenericMarshal');
19
20
-function processManager() {
21
- this._ObjectID = 'processManager';
22
- switch (process.platform) {
20
+function processManager()
21
+{
22
+ this._ObjectID = 'process-manager';
23
+ switch(process.platform)
24
+ {
25
case 'win32':
26
this._kernel32 = GM.CreateNativeProxy('kernel32.dll');
27
this._kernel32.CreateMethod('GetLastError');
@@ -32,19 +34,24 @@ function processManager() {
34
break;
35
default:
36
throw (process.platform + ' not supported');
37
+ break;
38
}
36
- this.getProcesses = function getProcesses(callback) {
37
- switch (process.platform) {
39
+ this.getProcesses = function getProcesses(callback)
40
+ {
41
+ switch(process.platform)
42
+ {
43
default:
44
throw ('Enumerating processes on ' + process.platform + ' not supported');
45
+ break;
46
case 'win32':
41
- var retVal = {};
47
+ var retVal = [];
48
var h = this._kernel32.CreateToolhelp32Snapshot(2, 0);
49
var info = GM.CreateVariable(304);
50
info.toBuffer().writeUInt32LE(304, 0);
51
var nextProcess = this._kernel32.Process32First(h, info);
46
- while (nextProcess.Val) {
47
- retVal[info.Deref(8, 4).toBuffer().readUInt32LE(0)] = { cmd: info.Deref(GM.PointerSize == 4 ? 36 : 44, 260).String };
52
+ while (nextProcess.Val)
53
+ {
54
+ retVal.push({ pid: info.Deref(8, 4).toBuffer().readUInt32LE(0), command: info.Deref(GM.PointerSize == 4 ? 36 : 44, 260).String });
55
nextProcess = this._kernel32.Process32Next(h, info);
56
}
57
if (callback) { callback.apply(this, [retVal]); }
@@ -58,21 +65,32 @@ function processManager() {
65
p.callback = callback;
66
p.args = [];
67
for (var i = 1; i < arguments.length; ++i) { p.args.push(arguments[i]); }
61
- p.on('exit', function onGetProcesses() {
62
- delete this.Parent._psp[this.pid];
63
- var retVal = {}, lines = this.ps.split('\x0D\x0A'), key = {}, keyi = 0;
64
- for (var i in lines) {
68
+ p.on('exit', function onGetProcesses()
69
+ {
70
+ delete this.Parent._psp[this.pid];
71
+ var retVal = [];
72
+ var lines = this.ps.split('\x0D\x0A');
73
+ var key = {};
74
+ var keyi = 0;
75
+ for (var i in lines)
76
+ {
77
var tokens = lines[i].split(' ');
78
var tokenList = [];
67
- for (var x in tokens) {
79
+ for(var x in tokens)
80
+ {
81
if (i == 0 && tokens[x]) { key[tokens[x]] = keyi++; }
69
- if (i > 0 && tokens[x]) { tokenList.push(tokens[x]); }
82
+ if (i > 0 && tokens[x]) { tokenList.push(tokens[x]);}
83
}
71
- if ((i > 0) && (tokenList[key.PID])) {
72
- retVal[tokenList[key.PID]] = { user: tokenList[key.USER], cmd: tokenList[key.COMMAND] };
84
+ if(i>0)
85
+ {
86
+ if (tokenList[key.PID])
87
+ {
88
+ retVal.push({ pid: tokenList[key.PID], user: tokenList[key.USER], command: tokenList[key.COMMAND] });
89
+ }
90
}
91
}
75
- if (this.callback) {
92
+ if (this.callback)
93
+ {
94
this.args.unshift(retVal);
95
this.callback.apply(this.parent, this.args);
96
}
@@ -81,18 +99,25 @@ function processManager() {
99
break;
100
}
101
};
84
- this.getProcessInfo = function getProcessInfo(pid) {
85
- switch (process.platform) {
102
+ this.getProcessInfo = function getProcessInfo(pid)
103
+ {
104
+ switch(process.platform)
105
+ {
106
default:
107
throw ('getProcessInfo() not supported for ' + process.platform);
108
+ break;
109
case 'linux':
89
- var status = require('fs').readFileSync('/proc/' + pid + '/status'), info = {}, lines = status.toString().split('\n');
90
- for (var i in lines) {
110
+ var status = require('fs').readFileSync('/proc/' + pid + '/status');
111
+ var info = {};
112
+ var lines = status.toString().split('\n');
113
+ for(var i in lines)
114
+ {
115
var tokens = lines[i].split(':');
116
if (tokens.length > 1) { tokens[1] = tokens[1].trim(); }
117
info[tokens[0]] = tokens[1];
118
}
119
return (info);
120
+ break;
121
}
122
};
123
}
agents/modules_meshcore/promise.js
new
+185
@@ -0,0 +1,185 @@
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 refTable = {};
18
+
19
+function Promise(promiseFunc)
20
+{
21
+ this._ObjectID = 'promise';
22
+ this._internal = { promise: this, func: promiseFunc, completed: false, errors: false, completedArgs: [] };
23
+ require('events').EventEmitter.call(this._internal);
24
+ this._internal.on('_eventHook', function (eventName, eventCallback)
25
+ {
26
+ //console.log('hook', eventName, 'errors/' + this.errors + ' completed/' + this.completed);
27
+ var r = null;
28
+
29
+ if (eventName == 'resolved' && !this.errors && this.completed)
30
+ {
31
+ r = eventCallback.apply(this, this.completedArgs);
32
+ if(r!=null)
33
+ {
34
+ this.emit_returnValue('resolved', r);
35
+ }
36
+ }
37
+ if (eventName == 'rejected' && this.errors && this.completed)
38
+ {
39
+ eventCallback.apply(this, this.completedArgs);
40
+ }
41
+ if (eventName == 'settled' && this.completed)
42
+ {
43
+ eventCallback.apply(this, []);
44
+ }
45
+ });
46
+ this._internal.resolver = function _resolver()
47
+ {
48
+ _resolver._self.errors = false;
49
+ _resolver._self.completed = true;
50
+ _resolver._self.completedArgs = [];
51
+ var args = ['resolved'];
52
+ if (this.emit_returnValue && this.emit_returnValue('resolved') != null)
53
+ {
54
+ _resolver._self.completedArgs.push(this.emit_returnValue('resolved'));
55
+ args.push(this.emit_returnValue('resolved'));
56
+ }
57
+ else
58
+ {
59
+ for (var a in arguments)
60
+ {
61
+ _resolver._self.completedArgs.push(arguments[a]);
62
+ args.push(arguments[a]);
63
+ }
64
+ }
65
+ _resolver._self.emit.apply(_resolver._self, args);
66
+ _resolver._self.emit('settled');
67
+ };
68
+ this._internal.rejector = function _rejector()
69
+ {
70
+ _rejector._self.errors = true;
71
+ _rejector._self.completed = true;
72
+ _rejector._self.completedArgs = [];
73
+ var args = ['rejected'];
74
+ for (var a in arguments)
75
+ {
76
+ _rejector._self.completedArgs.push(arguments[a]);
77
+ args.push(arguments[a]);
78
+ }
79
+
80
+ _rejector._self.emit.apply(_rejector._self, args);
81
+ _rejector._self.emit('settled');
82
+ };
83
+ this.catch = function(func)
84
+ {
85
+ this._internal.once('settled', func);
86
+ }
87
+ this.finally = function (func)
88
+ {
89
+ this._internal.once('settled', func);
90
+ };
91
+ this.then = function (resolved, rejected)
92
+ {
93
+ if (resolved) { this._internal.once('resolved', resolved); }
94
+ if (rejected) { this._internal.once('rejected', rejected); }
95
+
96
+ var retVal = new Promise(function (r, j) { });
97
+
98
+ this._internal.once('resolved', retVal._internal.resolver);
99
+ this._internal.once('rejected', retVal._internal.rejector);
100
+ return (retVal);
101
+ };
102
+
103
+ this._internal.resolver._self = this._internal;
104
+ this._internal.rejector._self = this._internal;;
105
+
106
+ try
107
+ {
108
+ promiseFunc.call(this, this._internal.resolver, this._internal.rejector);
109
+ }
110
+ catch(e)
111
+ {
112
+ this._internal.errors = true;
113
+ this._internal.completed = true;
114
+ this._internal.completedArgs = [e];
115
+ this._internal.emit('rejected', e);
116
+ this._internal.emit('settled');
117
+ }
118
+
119
+ if(!this._internal.completed)
120
+ {
121
+ // Save reference of this object
122
+ refTable[this._internal._hashCode()] = this._internal;
123
+ this._internal.once('settled', function () { refTable[this._hashCode()] = null; });
124
+ }
125
+}
126
+
127
+Promise.resolve = function resolve()
128
+{
129
+ var retVal = new Promise(function (r, j) { });
130
+ var args = [];
131
+ for (var i in arguments)
132
+ {
133
+ args.push(arguments[i]);
134
+ }
135
+ retVal._internal.resolver.apply(retVal._internal, args);
136
+ return (retVal);
137
+};
138
+Promise.reject = function reject() {
139
+ var retVal = new Promise(function (r, j) { });
140
+ var args = [];
141
+ for (var i in arguments) {
142
+ args.push(arguments[i]);
143
+ }
144
+ retVal._internal.rejector.apply(retVal._internal, args);
145
+ return (retVal);
146
+};
147
+Promise.all = function all(promiseList)
148
+{
149
+ var ret = new Promise(function (res, rej)
150
+ {
151
+ this.__rejector = rej;
152
+ this.__resolver = res;
153
+ this.__promiseList = promiseList;
154
+ this.__done = false;
155
+ this.__count = 0;
156
+ });
157
+
158
+ for (var i in promiseList)
159
+ {
160
+ promiseList[i].then(function ()
161
+ {
162
+ // Success
163
+ if(++ret.__count == ret.__promiseList.length)
164
+ {
165
+ ret.__done = true;
166
+ ret.__resolver(ret.__promiseList);
167
+ }
168
+ }, function (arg)
169
+ {
170
+ // Failure
171
+ if(!ret.__done)
172
+ {
173
+ ret.__done = true;
174
+ ret.__rejector(arg);
175
+ }
176
+ });
177
+ }
178
+ if (promiseList.length == 0)
179
+ {
180
+ ret.__resolver(promiseList);
181
+ }
182
+ return (ret);
183
+};
184
+
185
+module.exports = Promise;
\ No newline at end of file
agents/modules_meshcore/user-sessions.js
+154
-15
@@ -16,9 +16,27 @@ limitations under the License.
16
17
function UserSessions()
18
{
19
- this._ObjectID = 'UserSessions';
19
+ this._ObjectID = 'user-sessions';
20
+ require('events').EventEmitter.call(this, true).createEvent('changed');
21
21
- if (process.platform == 'win32') {
22
+ this.enumerateUsers = function enumerateUsers()
23
+ {
24
+ var promise = require('promise');
25
+ var p = new promise(function (res, rej)
26
+ {
27
+ this.__resolver = res;
28
+ this.__rejector = rej;
29
+ });
30
+ p.__handler = function __handler(users)
31
+ {
32
+ p.__resolver(users);
33
+ };
34
+ this.Current(p.__handler);
35
+ return (p);
36
+ }
37
+
38
+ if (process.platform == 'win32')
39
+ {
40
this._marshal = require('_GenericMarshal');
41
this._kernel32 = this._marshal.CreateNativeProxy('Kernel32.dll');
42
this._kernel32.CreateMethod('GetLastError');
@@ -77,7 +95,7 @@ function UserSessions()
95
return (retVal);
96
};
97
80
- this.Current = function Current()
98
+ this.Current = function Current(cb)
99
{
100
var retVal = {};
101
var pinfo = this._marshal.CreatePointer();
@@ -102,36 +120,152 @@ function UserSessions()
120
121
this._wts.WTSFreeMemory(pinfo.Deref());
122
105
- Object.defineProperty(retVal, 'connected', { value: showActiveOnly(retVal) });
123
+ Object.defineProperty(retVal, 'Active', { value: showActiveOnly(retVal) });
124
+ if (cb) { cb(retVal); }
125
return (retVal);
126
};
127
}
128
else
129
{
111
- this.Current = function Current()
130
+ this.Self = function Self()
131
+ {
132
+ var promise = require('promise');
133
+ var p = new promise(function (res, rej)
134
+ {
135
+ this.__resolver = res; this.__rejector = rej;
136
+ this.__child = require('child_process').execFile('/usr/bin/id', ['id', '-u']);
137
+ this.__child.promise = this;
138
+ this.__child.stdout._txt = '';
139
+ this.__child.stdout.on('data', function (chunk) { this._txt += chunk.toString(); });
140
+ this.__child.on('exit', function (code)
141
+ {
142
+ try
143
+ {
144
+ parseInt(this.stdout._txt);
145
+ }
146
+ catch (e)
147
+ {
148
+ this.promise.__rejector('invalid uid');
149
+ return;
150
+ }
151
+
152
+ var id = parseInt(this.stdout._txt);
153
+ this.promise.__resolver(id);
154
+ });
155
+ });
156
+ return (p);
157
+ };
158
+ this.Current = function Current(cb)
159
{
160
var retVal = {};
114
- var emitterUtils = require('events').inherits(retVal);
115
- emitterUtils.createEvent('logon');
161
+ retVal._ObjectID = 'UserSession'
162
+ Object.defineProperty(retVal, '_callback', { value: cb });
163
+ Object.defineProperty(retVal, '_child', { value: require('child_process').execFile('/usr/bin/last', ['last', '-f', '/var/run/utmp']) });
164
117
- retVal._child = require('child_process').execFile('/usr/bin/last', ['last', '-f', '/var/run/utmp']);
165
retVal._child.Parent = retVal;
166
retVal._child._txt = '';
167
retVal._child.on('exit', function (code)
168
{
169
var lines = this._txt.split('\n');
170
var sessions = [];
171
+ var users = {};
172
+
173
for(var i in lines)
174
{
175
if (lines[i])
176
{
128
- console.log(getTokens(lines[i]));
129
- var user = lines[i].substring(0, lines[i].indexOf(' '));
130
- sessions.push(user);
177
+ var tokens = getTokens(lines[i]);
178
+ var s = { Username: tokens[0], SessionId: tokens[1] }
179
+ if (tokens[3].includes('still logged in'))
180
+ {
181
+ s.State = 'Active';
182
+ }
183
+ else
184
+ {
185
+ s.LastActive = tokens[3];
186
+ }
187
+
188
+ sessions.push(s);
189
}
190
}
191
sessions.pop();
134
- console.log(sessions);
192
+
193
+
194
+ var usernames = {};
195
+ var promises = [];
196
+
197
+ for (var i in sessions)
198
+ {
199
+ if (sessions[i].Username != 'reboot')
200
+ {
201
+ users[sessions[i].SessionId] = sessions[i];
202
+ if(usernames[sessions[i].Username] == null)
203
+ {
204
+ usernames[sessions[i].Username] = -1;
205
+ }
206
+ }
207
+ }
208
+
209
+ try
210
+ {
211
+ require('promise');
212
+ }
213
+ catch(e)
214
+ {
215
+ Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
216
+ if (this.Parent._callback) { this.Parent._callback.call(this.Parent, users); }
217
+ return;
218
+ }
219
+
220
+ var promise = require('promise');
221
+ for (var n in usernames)
222
+ {
223
+ var p = new promise(function (res, rej)
224
+ {
225
+ this.__username = n;
226
+ this.__resolver = res; this.__rejector = rej;
227
+ this.__child = require('child_process').execFile('/usr/bin/id', ['id', '-u', n]);
228
+ this.__child.promise = this;
229
+ this.__child.stdout._txt = '';
230
+ this.__child.stdout.on('data', function (chunk) { this._txt += chunk.toString(); });
231
+ this.__child.on('exit', function (code)
232
+ {
233
+ try
234
+ {
235
+ parseInt(this.stdout._txt);
236
+ }
237
+ catch(e)
238
+ {
239
+ this.promise.__rejector('invalid uid');
240
+ return;
241
+ }
242
+
243
+ var id = parseInt(this.stdout._txt);
244
+ this.promise.__resolver(id);
245
+ });
246
+ });
247
+ promises.push(p);
248
+ }
249
+ promise.all(promises).then(function (plist)
250
+ {
251
+ // Done
252
+ var table = {};
253
+ for(var i in plist)
254
+ {
255
+ table[plist[i].__username] = plist[i]._internal.completedArgs[0];
256
+ }
257
+ for(var i in users)
258
+ {
259
+ users[i].uid = table[users[i].Username];
260
+ }
261
+ Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
262
+ if (retVal._callback) { retVal._callback.call(retVal, users); }
263
+ }, function (reason)
264
+ {
265
+ // Failed
266
+ Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
267
+ if (retVal._callback) { retVal._callback.call(retVal, users); }
268
+ });
269
});
270
retVal._child.stdout.Parent = retVal._child;
271
retVal._child.stdout.on('data', function (chunk) { this.Parent._txt += chunk.toString(); });
@@ -145,7 +279,7 @@ function showActiveOnly(source)
279
var retVal = [];
280
for (var i in source)
281
{
148
- if (source[i].State == 'Active' || source[i].State == 'Connected')
282
+ if (source[i].State == 'Active')
283
{
284
retVal.push(source[i]);
285
}
@@ -159,8 +293,13 @@ function getTokens(str)
293
294
columns.push(str.substring(0, (i=str.indexOf(' '))));
295
while (str[++i] == ' ');
162
- columns.push(str.substring(i, str.substring(i).indexOf(' ') + i));
163
-
296
+ columns.push(str.substring(i, (i=str.substring(i).indexOf(' ') + i)));
297
+ while (str[++i] == ' ');
298
+ columns.push(str.substring(i, (i=str.substring(i).indexOf(' ') + i)));
299
+ while (str[++i] == ' ');
300
+ var status = str.substring(i).trim();
301
+ columns.push(status);
302
+
303
return (columns);
304
}
305
agents/modules_meshcore_backup/amt-lme.js
new
+893
@@ -0,0 +1,893 @@
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
+
18
+var MemoryStream = require('MemoryStream');
19
+var lme_id = 0; // Our next channel identifier
20
+var lme_port_offset = 0; // Debug: Set this to "-100" to bind to 16892 & 16893 and IN_ADDRANY. This is for LMS debugging.
21
+var xmlParser = require('amt-xml');
22
+
23
+// Documented in: https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/HTMLDocuments/MPSDocuments/Intel%20AMT%20Port%20Forwarding%20Protocol%20Reference%20Manual.pdf
24
+var APF_DISCONNECT = 1;
25
+var APF_SERVICE_REQUEST = 5;
26
+var APF_SERVICE_ACCEPT = 6;
27
+var APF_USERAUTH_REQUEST = 50;
28
+var APF_USERAUTH_FAILURE = 51;
29
+var APF_USERAUTH_SUCCESS = 52;
30
+var APF_GLOBAL_REQUEST = 80;
31
+var APF_REQUEST_SUCCESS = 81;
32
+var APF_REQUEST_FAILURE = 82;
33
+var APF_CHANNEL_OPEN = 90;
34
+var APF_CHANNEL_OPEN_CONFIRMATION = 91;
35
+var APF_CHANNEL_OPEN_FAILURE = 92;
36
+var APF_CHANNEL_WINDOW_ADJUST = 93;
37
+var APF_CHANNEL_DATA = 94;
38
+var APF_CHANNEL_CLOSE = 97;
39
+var APF_PROTOCOLVERSION = 192;
40
+
41
+function lme_object() {
42
+ this.ourId = ++lme_id;
43
+ this.amtId = -1;
44
+ this.LME_CHANNEL_STATUS = 'LME_CS_FREE';
45
+ this.txWindow = 0;
46
+ this.rxWindow = 0;
47
+ this.localPort = 0;
48
+ this.errorCount = 0;
49
+}
50
+
51
+function stream_bufferedWrite() {
52
+ var emitterUtils = require('events').inherits(this);
53
+ this.buffer = [];
54
+ this._readCheckImmediate = undefined;
55
+ this._ObjectID = "bufferedWriteStream";
56
+ // Writable Events
57
+ emitterUtils.createEvent('close');
58
+ emitterUtils.createEvent('drain');
59
+ emitterUtils.createEvent('error');
60
+ emitterUtils.createEvent('finish');
61
+ emitterUtils.createEvent('pipe');
62
+ emitterUtils.createEvent('unpipe');
63
+
64
+ // Readable Events
65
+ emitterUtils.createEvent('readable');
66
+ this.isEmpty = function () {
67
+ return (this.buffer.length == 0);
68
+ };
69
+ this.isWaiting = function () {
70
+ return (this._readCheckImmediate == undefined);
71
+ };
72
+ this.write = function (chunk) {
73
+ for (var args in arguments) { if (typeof (arguments[args]) == 'function') { this.once('drain', arguments[args]); break; } }
74
+ var tmp = Buffer.alloc(chunk.length);
75
+ chunk.copy(tmp);
76
+ this.buffer.push({ offset: 0, data: tmp });
77
+ this.emit('readable');
78
+ return (this.buffer.length == 0 ? true : false);
79
+ };
80
+ this.read = function () {
81
+ var size = arguments.length == 0 ? undefined : arguments[0];
82
+ var bytesRead = 0;
83
+ var list = [];
84
+ while ((size == undefined || bytesRead < size) && this.buffer.length > 0) {
85
+ var len = this.buffer[0].data.length - this.buffer[0].offset;
86
+ var offset = this.buffer[0].offset;
87
+
88
+ if (len > (size - bytesRead)) {
89
+ // Only reading a subset
90
+ list.push(this.buffer[0].data.slice(offset, offset + size - bytesRead));
91
+ this.buffer[0].offset += (size - bytesRead);
92
+ bytesRead += (size - bytesRead);
93
+ } else {
94
+ // Reading the entire thing
95
+ list.push(this.buffer[0].data.slice(offset));
96
+ bytesRead += len;
97
+ this.buffer.shift();
98
+ }
99
+ }
100
+ this._readCheckImmediate = setImmediate(function (buffered) {
101
+ buffered._readCheckImmediate = undefined;
102
+ if (buffered.buffer.length == 0) {
103
+ buffered.emit('drain'); // Drained
104
+ } else {
105
+ buffered.emit('readable'); // Not drained
106
+ }
107
+ }, this);
108
+ return (Buffer.concat(list));
109
+ };
110
+}
111
+
112
+
113
+function lme_heci(options) {
114
+ var emitterUtils = require('events').inherits(this);
115
+ emitterUtils.createEvent('error');
116
+ emitterUtils.createEvent('connect');
117
+ emitterUtils.createEvent('notify');
118
+ emitterUtils.createEvent('bind');
119
+
120
+ if ((options != null) && (options.debug == true)) { lme_port_offset = -100; } // LMS debug mode
121
+
122
+ var heci = require('heci');
123
+ this.INITIAL_RXWINDOW_SIZE = 4096;
124
+
125
+ this._ObjectID = "lme";
126
+ this._LME = heci.create();
127
+ this._LME._binded = {};
128
+ this._LME.LMS = this;
129
+ this._LME.on('error', function (e) { this.LMS.emit('error', e); });
130
+ this._LME.on('connect', function () {
131
+ this.on('data', function (chunk) {
132
+ // this = HECI
133
+ var cmd = chunk.readUInt8(0);
134
+ //console.log('LME Command ' + cmd + ', ' + chunk.length + ' byte(s).');
135
+
136
+ switch (cmd) {
137
+ default:
138
+ console.log('Unhandled LME Command ' + cmd + ', ' + chunk.length + ' byte(s).');
139
+ break;
140
+ case APF_SERVICE_REQUEST:
141
+ var nameLen = chunk.readUInt32BE(1);
142
+ var name = chunk.slice(5, nameLen + 5);
143
+ //console.log("Service Request for: " + name);
144
+ if (name == 'pfwd@amt.intel.com' || name == 'auth@amt.intel.com') {
145
+ var outBuffer = Buffer.alloc(5 + nameLen);
146
+ outBuffer.writeUInt8(6, 0);
147
+ outBuffer.writeUInt32BE(nameLen, 1);
148
+ outBuffer.write(name.toString(), 5);
149
+ this.write(outBuffer);
150
+ //console.log('Answering APF_SERVICE_REQUEST');
151
+ } else {
152
+ //console.log('UNKNOWN APF_SERVICE_REQUEST');
153
+ }
154
+ break;
155
+ case APF_GLOBAL_REQUEST:
156
+ var nameLen = chunk.readUInt32BE(1);
157
+ var name = chunk.slice(5, nameLen + 5).toString();
158
+
159
+ switch (name) {
160
+ case 'tcpip-forward':
161
+ var len = chunk.readUInt32BE(nameLen + 6);
162
+ var port = chunk.readUInt32BE(nameLen + 10 + len);
163
+ //console.log("[" + chunk.length + "/" + len + "] APF_GLOBAL_REQUEST for: " + name + " on port " + port);
164
+ if (this[name] == undefined) { this[name] = {}; }
165
+ if (this[name][port] != null) { // Close the existing binding
166
+ for (var i in this.sockets) {
167
+ var channel = this.sockets[i];
168
+ if (channel.localPort == port) { this.sockets[i].end(); delete this.sockets[i]; } // Close this socket
169
+ }
170
+ }
171
+ if (this[name][port] == null)
172
+ { // Bind a new server socket if not already present
173
+ this[name][port] = require('net').createServer();
174
+ this[name][port].HECI = this;
175
+ if (lme_port_offset == 0) {
176
+ this[name][port].listen({ port: port, host: '127.0.0.1' }); // Normal mode
177
+ } else {
178
+ this[name][port].listen({ port: (port + lme_port_offset) }); // Debug mode
179
+ }
180
+ this[name][port].on('connection', function (socket) {
181
+ //console.log('New [' + socket.remoteFamily + '] TCP Connection on: ' + socket.remoteAddress + ' :' + socket.localPort);
182
+ this.HECI.LMS.bindDuplexStream(socket, socket.remoteFamily, socket.localPort - lme_port_offset);
183
+ });
184
+ this._binded[port] = true;
185
+ this.LMS.emit('bind', this._binded);
186
+ }
187
+ var outBuffer = Buffer.alloc(5);
188
+ outBuffer.writeUInt8(81, 0);
189
+ outBuffer.writeUInt32BE(port, 1);
190
+ this.write(outBuffer);
191
+ break;
192
+ case 'cancel-tcpip-forward':
193
+ var outBuffer = Buffer.alloc(1);
194
+ outBuffer.writeUInt8(APF_REQUEST_SUCCESS, 0);
195
+ this.write(outBuffer);
196
+ break;
197
+ case 'udp-send-to@amt.intel.com':
198
+ var outBuffer = Buffer.alloc(1);
199
+ outBuffer.writeUInt8(APF_REQUEST_FAILURE, 0);
200
+ this.write(outBuffer);
201
+ break;
202
+ default:
203
+ //console.log("Unknown APF_GLOBAL_REQUEST for: " + name);
204
+ break;
205
+ }
206
+ break;
207
+ case APF_CHANNEL_OPEN_CONFIRMATION:
208
+ var rChannel = chunk.readUInt32BE(1);
209
+ var sChannel = chunk.readUInt32BE(5);
210
+ var wSize = chunk.readUInt32BE(9);
211
+ //console.log('rChannel/' + rChannel + ', sChannel/' + sChannel + ', wSize/' + wSize);
212
+ if (this.sockets[rChannel] != undefined) {
213
+ this.sockets[rChannel].lme.amtId = sChannel;
214
+ this.sockets[rChannel].lme.rxWindow = wSize;
215
+ this.sockets[rChannel].lme.txWindow = wSize;
216
+ this.sockets[rChannel].lme.LME_CHANNEL_STATUS = 'LME_CS_CONNECTED';
217
+ //console.log('LME_CS_CONNECTED');
218
+ this.sockets[rChannel].bufferedStream = new stream_bufferedWrite();
219
+ this.sockets[rChannel].bufferedStream.socket = this.sockets[rChannel];
220
+ this.sockets[rChannel].bufferedStream.on('readable', function () {
221
+ if (this.socket.lme.txWindow > 0) {
222
+ var buffer = this.read(this.socket.lme.txWindow);
223
+ var packet = Buffer.alloc(9 + buffer.length);
224
+ packet.writeUInt8(APF_CHANNEL_DATA, 0);
225
+ packet.writeUInt32BE(this.socket.lme.amtId, 1);
226
+ packet.writeUInt32BE(buffer.length, 5);
227
+ buffer.copy(packet, 9);
228
+ this.socket.lme.txWindow -= buffer.length;
229
+ this.socket.HECI.write(packet);
230
+ }
231
+ });
232
+ this.sockets[rChannel].bufferedStream.on('drain', function () {
233
+ this.socket.resume();
234
+ });
235
+ this.sockets[rChannel].on('data', function (chunk) {
236
+ if (!this.bufferedStream.write(chunk)) { this.pause(); }
237
+ });
238
+ this.sockets[rChannel].on('end', function () {
239
+ var outBuffer = Buffer.alloc(5);
240
+ outBuffer.writeUInt8(APF_CHANNEL_CLOSE, 0);
241
+ outBuffer.writeUInt32BE(this.lme.amtId, 1);
242
+ this.HECI.write(outBuffer);
243
+ });
244
+ this.sockets[rChannel].resume();
245
+ }
246
+
247
+ break;
248
+ case APF_PROTOCOLVERSION:
249
+ var major = chunk.readUInt32BE(1);
250
+ var minor = chunk.readUInt32BE(5);
251
+ var reason = chunk.readUInt32BE(9);
252
+ var outBuffer = Buffer.alloc(93);
253
+ outBuffer.writeUInt8(192, 0);
254
+ outBuffer.writeUInt32BE(1, 1);
255
+ outBuffer.writeUInt32BE(0, 5);
256
+ outBuffer.writeUInt32BE(reason, 9);
257
+ //console.log('Answering PROTOCOL_VERSION');
258
+ this.write(outBuffer);
259
+ break;
260
+ case APF_CHANNEL_WINDOW_ADJUST:
261
+ var rChannelId = chunk.readUInt32BE(1);
262
+ var bytesToAdd = chunk.readUInt32BE(5);
263
+ if (this.sockets[rChannelId] != undefined) {
264
+ this.sockets[rChannelId].lme.txWindow += bytesToAdd;
265
+ if (!this.sockets[rChannelId].bufferedStream.isEmpty() && this.sockets[rChannelId].bufferedStream.isWaiting()) {
266
+ this.sockets[rChannelId].bufferedStream.emit('readable');
267
+ }
268
+ } else {
269
+ console.log('Unknown Recipient ID/' + rChannelId + ' for APF_CHANNEL_WINDOW_ADJUST');
270
+ }
271
+ break;
272
+ case APF_CHANNEL_DATA:
273
+ var rChannelId = chunk.readUInt32BE(1);
274
+ var dataLen = chunk.readUInt32BE(5);
275
+ var data = chunk.slice(9, 9 + dataLen);
276
+ if ((this.sockets != null) && (this.sockets[rChannelId] != undefined)) {
277
+ this.sockets[rChannelId].pendingBytes.push(data.length);
278
+ this.sockets[rChannelId].write(data, function () {
279
+ var written = this.pendingBytes.shift();
280
+ //console.log('adjust', this.lme.amtId, written);
281
+ var outBuffer = Buffer.alloc(9);
282
+ outBuffer.writeUInt8(APF_CHANNEL_WINDOW_ADJUST, 0);
283
+ outBuffer.writeUInt32BE(this.lme.amtId, 1);
284
+ outBuffer.writeUInt32BE(written, 5);
285
+ this.HECI.write(outBuffer);
286
+ });
287
+ } else if ((this.insockets != null) && (this.insockets[rChannelId] != undefined)) {
288
+ var channel = this.insockets[rChannelId];
289
+ if (channel.data == null) { channel.data = data.toString(); } else { channel.data += data.toString(); }
290
+ channel.rxWindow += dataLen;
291
+ //console.log('IN DATA', channel.rxWindow, channel.data.length, dataLen, channel.amtId, data.toString());
292
+ var httpData = parseHttp(channel.data);
293
+ if ((httpData != null) || (channel.data.length >= 8000)) {
294
+ // Parse the WSMAN
295
+ var notify = null;
296
+ try { notify = xmlParser.ParseWsman(httpData); } catch (e) { }
297
+
298
+ // Event the http data
299
+ if (notify != null) { this.LMS.emit('notify', notify, channel.options, _lmsNotifyToString(notify), _lmsNotifyToCode(notify)); }
300
+
301
+ // Send channel close
302
+ var buffer = Buffer.alloc(5);
303
+ buffer.writeUInt8(APF_CHANNEL_CLOSE, 0);
304
+ buffer.writeUInt32BE(amtId, 1);
305
+ this.write(buffer);
306
+ } else {
307
+ if (channel.rxWindow > 6000) {
308
+ // Send window adjust
309
+ var buffer = Buffer.alloc(9);
310
+ buffer.writeUInt8(APF_CHANNEL_WINDOW_ADJUST, 0);
311
+ buffer.writeUInt32BE(channel.amtId, 1);
312
+ buffer.writeUInt32BE(channel.rxWindow, 5);
313
+ this.write(buffer);
314
+ channel.rxWindow = 0;
315
+ }
316
+ }
317
+ } else {
318
+ console.log('Unknown Recipient ID/' + rChannelId + ' for APF_CHANNEL_DATA');
319
+ }
320
+ break;
321
+ case APF_CHANNEL_OPEN_FAILURE:
322
+ var rChannelId = chunk.readUInt32BE(1);
323
+ var reasonCode = chunk.readUInt32BE(5);
324
+ if ((this.sockets != null) && (this.sockets[rChannelId] != undefined)) {
325
+ this.sockets[rChannelId].end();
326
+ delete this.sockets[rChannelId];
327
+ } else if ((this.insockets != null) && (this.insockets[rChannelId] != undefined)) {
328
+ delete this.insockets[rChannelId];
329
+ } else {
330
+ console.log('Unknown Recipient ID/' + rChannelId + ' for APF_CHANNEL_OPEN_FAILURE');
331
+ }
332
+ break;
333
+ case APF_CHANNEL_CLOSE:
334
+ var rChannelId = chunk.readUInt32BE(1);
335
+ if ((this.sockets != null) && (this.sockets[rChannelId] != undefined)) {
336
+ this.sockets[rChannelId].end();
337
+ var amtId = this.sockets[rChannelId].lme.amtId;
338
+ var buffer = Buffer.alloc(5);
339
+ delete this.sockets[rChannelId];
340
+
341
+ buffer.writeUInt8(APF_CHANNEL_CLOSE, 0); // ????????????????????????????
342
+ buffer.writeUInt32BE(amtId, 1);
343
+ this.write(buffer);
344
+ } else if ((this.insockets != null) && (this.insockets[rChannelId] != undefined)) {
345
+ delete this.insockets[rChannelId];
346
+ // Should I send a close back????
347
+ } else {
348
+ console.log('Unknown Recipient ID/' + rChannelId + ' for APF_CHANNEL_CLOSE');
349
+ }
350
+ break;
351
+ case APF_CHANNEL_OPEN:
352
+ var nameLen = chunk.readUInt32BE(1);
353
+ var name = chunk.slice(5, nameLen + 5).toString();
354
+ var channelSender = chunk.readUInt32BE(nameLen + 5);
355
+ var initialWindowSize = chunk.readUInt32BE(nameLen + 9);
356
+ var hostToConnectLen = chunk.readUInt32BE(nameLen + 17);
357
+ var hostToConnect = chunk.slice(nameLen + 21, nameLen + 21 + hostToConnectLen).toString();
358
+ var portToConnect = chunk.readUInt32BE(nameLen + 21 + hostToConnectLen);
359
+ var originatorIpLen = chunk.readUInt32BE(nameLen + 25 + hostToConnectLen);
360
+ var originatorIp = chunk.slice(nameLen + 29 + hostToConnectLen, nameLen + 29 + hostToConnectLen + originatorIpLen).toString();
361
+ var originatorPort = chunk.readUInt32BE(nameLen + 29 + hostToConnectLen + originatorIpLen);
362
+ //console.log('APF_CHANNEL_OPEN', name, channelSender, initialWindowSize, 'From: ' + originatorIp + ':' + originatorPort, 'To: ' + hostToConnect + ':' + portToConnect);
363
+
364
+ if (this.insockets == null) { this.insockets = {}; }
365
+ var ourId = ++lme_id;
366
+ var insocket = new lme_object();
367
+ insocket.ourId = ourId;
368
+ insocket.amtId = channelSender;
369
+ insocket.txWindow = initialWindowSize;
370
+ insocket.rxWindow = 0;
371
+ insocket.options = { target: hostToConnect, targetPort: portToConnect, source: originatorIp, sourcePort: originatorPort };
372
+ this.insockets[ourId] = insocket;
373
+
374
+ var buffer = Buffer.alloc(17);
375
+ buffer.writeUInt8(APF_CHANNEL_OPEN_CONFIRMATION, 0);
376
+ buffer.writeUInt32BE(channelSender, 1); // Intel AMT sender channel
377
+ buffer.writeUInt32BE(ourId, 5); // Our receiver channel id
378
+ buffer.writeUInt32BE(4000, 9); // Initial Window Size
379
+ buffer.writeUInt32BE(0xFFFFFFFF, 13); // Reserved
380
+ this.write(buffer);
381
+
382
+ //var buffer = Buffer.alloc(17);
383
+ //buffer.writeUInt8(APF_CHANNEL_OPEN_FAILURE, 0);
384
+ //buffer.writeUInt32BE(channelSender, 1); // Intel AMT sender channel
385
+ //buffer.writeUInt32BE(2, 5); // Reason code
386
+ //buffer.writeUInt32BE(0, 9); // Reserved
387
+ //buffer.writeUInt32BE(0, 13); // Reserved
388
+ //this.write(buffer);
389
+ //console.log('Sent APF_CHANNEL_OPEN_FAILURE', channelSender);
390
+
391
+ break;
392
+ }
393
+ });
394
+ this.LMS.emit('connect');
395
+ this.resume();
396
+
397
+ });
398
+
399
+ this.bindDuplexStream = function (duplexStream, remoteFamily, localPort) {
400
+ var socket = duplexStream;
401
+ //console.log('New [' + remoteFamily + '] Virtual Connection/' + socket.localPort);
402
+ socket.pendingBytes = [];
403
+ socket.HECI = this._LME;
404
+ socket.LMS = this;
405
+ socket.lme = new lme_object();
406
+ socket.lme.Socket = socket;
407
+ socket.localPort = localPort;
408
+ var buffer = new MemoryStream();
409
+ buffer.writeUInt8(0x5A);
410
+ buffer.writeUInt32BE(15);
411
+ buffer.write('forwarded-tcpip');
412
+ buffer.writeUInt32BE(socket.lme.ourId);
413
+ buffer.writeUInt32BE(this.INITIAL_RXWINDOW_SIZE);
414
+ buffer.writeUInt32BE(0xFFFFFFFF);
415
+ for (var i = 0; i < 2; ++i) {
416
+ if (remoteFamily == 'IPv6') {
417
+ buffer.writeUInt32BE(3);
418
+ buffer.write('::1');
419
+ } else {
420
+ buffer.writeUInt32BE(9);
421
+ buffer.write('127.0.0.1');
422
+ }
423
+ buffer.writeUInt32BE(localPort);
424
+ }
425
+ this._LME.write(buffer.buffer);
426
+ if (this._LME.sockets == undefined) { this._LME.sockets = {}; }
427
+ this._LME.sockets[socket.lme.ourId] = socket;
428
+ socket.pause();
429
+ };
430
+
431
+ this._LME.connect(heci.GUIDS.LME, { noPipeline: 0 });
432
+}
433
+
434
+function parseHttp(httpData) {
435
+ var i = httpData.indexOf('\r\n\r\n');
436
+ if ((i == -1) || (httpData.length < (i + 2))) { return null; }
437
+ var headers = require('http-headers')(httpData.substring(0, i), true);
438
+ var contentLength = parseInt(headers['content-length']);
439
+ if (httpData.length >= contentLength + i + 4) { return httpData.substring(i + 4, i + 4 + contentLength); }
440
+ return null;
441
+}
442
+
443
+function _lmsNotifyToCode(notify) {
444
+ if ((notify == null) || (notify.Body == null) || (notify.Body.MessageID == null)) return null;
445
+ var msgid = notify.Body.MessageID;
446
+ try { msgid += '-' + notify.Body.MessageArguments[0]; } catch (e) { }
447
+ return msgid;
448
+}
449
+
450
+function _lmsNotifyToString(notify) {
451
+ if ((notify == null) || (notify.Body == null) || (notify.Body.MessageID == null)) return null;
452
+ var msgid = notify.Body.MessageID;
453
+ try { msgid += '-' + notify.Body.MessageArguments[0]; } catch (e) { }
454
+ if (lmsEvents[msgid]) { return lmsEvents[msgid]; }
455
+ return null;
456
+}
457
+
458
+var lmsEvents = {
459
+ "iAMT0001": "System Defense Policy %1s triggered.",
460
+ "iAMT0002": "Agent Presence Agent %1s not started.",
461
+ "iAMT0003": "Agent Presence Agent %1s stopped.",
462
+ "iAMT0004": "Agent Presence Agent %1s running.",
463
+ "iAMT0005": "Agent Presence Agent %1s expired.",
464
+ "iAMT0006": "Agent Presence Agent %1s suspended.",
465
+ "iAMT0007": "Host software attempt to disable AMT Network link detected.",
466
+ "iAMT0008": "Host software attempt to disable AMT Network link detected -- Host Network link blocked.",
467
+ "iAMT0009": "AMT clock or FLASH wear-out protection disabled.",
468
+ "iAMT0010": "Intel(R) AMT Network Interface %1s heuristics defense slow threshold trespassed.",
469
+ "iAMT0011": "Intel(R) AMT Network Interface %1s heuristics defense fast threshold trespassed.",
470
+ "iAMT0012": "Intel(R) AMT Network Interface %1s heuristics defense factory defined threshold trespassed.",
471
+ "iAMT0013": "Intel(R) AMT Network Interface %1s heuristics defense Encounter timeout expired.",
472
+ "iAMT0014": "General certificate error.",
473
+ "iAMT0015": "Certificate expired.",
474
+ "iAMT0016": "No trusted root certificate.",
475
+ "iAMT0017": "Not configured to work with server certificate.",
476
+ "iAMT0018": "Certificate revoked.",
477
+ "iAMT0019": "RSA exponent too large.",
478
+ "iAMT0020": "RSA modulus too large.",
479
+ "iAMT0021": "Unsupported digest.",
480
+ "iAMT0022": "Distinguished name too long.",
481
+ "iAMT0023": "Key usage missing.",
482
+ "iAMT0024": "General SSL handshake error.",
483
+ "iAMT0025": "General 802.1x error.",
484
+ "iAMT0026": "AMT Diagnostic AlertEAC error - General NAC error.",
485
+ "iAMT0027": "AMT Diagnostic AlertEAC error - attempt to get a NAC posture while AMT NAC is disabled.",
486
+ "iAMT0028": "AMT Diagnostic AlertEAC error - attempt to get a posture of an unsupported type.",
487
+ "iAMT0029": "Audit log storage is 50% full.",
488
+ "iAMT0030": "Audit log storage is 75% full.",
489
+ "iAMT0031": "Audit log storage is 85% full.",
490
+ "iAMT0032": "Audit log storage is 95% full.",
491
+ "iAMT0033": "Audit log storage is full.",
492
+ "iAMT0034": "Firmware Update Event - Partial.",
493
+ "iAMT0035": "Firmware Update Event - Failure.",
494
+ "iAMT0036": "Remote connectivity initiated.",
495
+ "iAMT0037": "ME Presence event.",
496
+ "iAMT0038-0": "AMT is being unprovisioned using BIOS command.",
497
+ "iAMT0038-1": "AMT is being unprovisioned using Local MEI command.",
498
+ "iAMT0038-2": "AMT is being unprovisioned using Local WS-MAN/SOAP command.",
499
+ "iAMT0038-3": "AMT is being unprovisioned using Remote WS-MAN/SOAP command.",
500
+ "iAMT0039": "HW Asset Error.",
501
+ "iAMT0050": "User Notification Alert - General Notification.",
502
+ "iAMT0050-16": "User Notification Alert - Circuit Breaker notification (CB Drop TX filter hit.).",
503
+ "iAMT0050-17": "User Notification Alert - Circuit Breaker notification (CB Rate Limit TX filter hit.).",
504
+ "iAMT0050-18": "User Notification Alert - Circuit Breaker notification (CB Drop RX filter hit.).",
505
+ "iAMT0050-19": "User Notification Alert - Circuit Breaker notification (CB Rate Limit RX filter hit.).",
506
+ "iAMT0050-32": "User Notification Alert - EAC notification.",
507
+ "iAMT0050-48": "User Notification Alert - Remote diagnostics - (Remote Redirection session started - SOL).",
508
+ "iAMT0050-49": "User Notification Alert - Remote diagnostics - (Remote Redirection session stopped - SOL).",
509
+ "iAMT0050-50": "User Notification Alert - Remote diagnostics. (Remote Redirection session started - IDE-R).",
510
+ "iAMT0050-51": "User Notification Alert - Remote diagnostics. (Remote Redirection session stopped - IDE-R).",
511
+ "iAMT0050-66": "User Notification Alert - WLAN notification (Host profile mismatch - Management Interface ignored).",
512
+ "iAMT0050-67": "User Notification Alert - WLAN notification (Management device overrides host radio).",
513
+ "iAMT0050-68": "User Notification Alert - WLAN notification (Host profile security mismatch).",
514
+ "iAMT0050-69": "User Notification Alert - WLAN notification (Management device relinquishes control over host Radio).",
515
+ "iAMT0051": "User Notification Alert - SecIo event.",
516
+ "iAMT0051-0": "User Notification Alert - SecIo event semaphore at host.",
517
+ "iAMT0051-1": "User Notification Alert - semaphore at ME.",
518
+ "iAMT0051-2": "User Notification Alert - SecIo event - semaphore timeout.",
519
+ "iAMT0052": "User Notification Alert - KVM session event.",
520
+ "iAMT0052-0": "User Notification Alert - KVM session requested.",
521
+ "iAMT0052-1": "User Notification Alert - KVM session started.",
522
+ "iAMT0052-2": "User Notification Alert - KVM session stopped.",
523
+ "iAMT0052-3": "User Notification Alert - KVM data channel.",
524
+ "iAMT0053": "User Notification Alert - RCS notification.",
525
+ "iAMT0053-50": "User Notification Alert - RCS notification (HW button pressed. Connection initiated automatically).",
526
+ "iAMT0053-52": "User Notification Alert - RCS notification (HW button pressed. Connection wasn't initiated automatically).",
527
+ "iAMT0053-53": "User Notification Alert - RCS notification (Contracts updated).",
528
+ "iAMT0054": "User Notification Alert - WLAN notification. Wireless Profile sync enablement state changed.",
529
+ "iAMT0055": "User Notification Alert - Provisioning state change notification.",
530
+ "iAMT0055-0": "User Notification Alert - Provisioning state change notification - Pre-configuration.",
531
+ "iAMT0055-1": "User Notification Alert - Provisioning state change notification - In configuration.",
532
+ "iAMT0055-2": "User Notification Alert - Provisioning state change notification - Post-configuration.",
533
+ "iAMT0055-3": "User Notification Alert - Provisioning state change notification - Unprovision process has started.",
534
+ "iAMT0056": "User Notification Alert - System Defense change notification.",
535
+ "iAMT0057": "User Notification Alert - Network State change notification.",
536
+ "iAMT0058": "User Notification Alert - Remote Access change notification.",
537
+ "iAMT0058-1": "User Notification Alert - Remote Access change notification - tunnel is closed.",
538
+ //"iAMT0058-1": "User Notification Alert - Remote Access change notification - tunnel is open.", // TODO
539
+ "iAMT0059": "User Notification Alert - KVM enabled event.",
540
+ "iAMT0059-0": "User Notification Alert - KVM enabled event - KVM disabled.",
541
+ "iAMT0059-1": "User Notification Alert - KVM enabled event - KVM enabled (both from MEBx and PTNI).",
542
+ "iAMT0060": "User Notification Alert - SecIO configuration event.",
543
+ "iAMT0061": "ME FW reset occurred.",
544
+ "iAMT0062": "User Notification Alert - IpSyncEnabled event.",
545
+ "iAMT0062-0": "User Notification Alert - IpSyncEnabled event - IpSync disabled.",
546
+ "iAMT0062-1": "User Notification Alert - IpSyncEnabled event - IpSync enabled.",
547
+ "iAMT0063": "User Notification Alert - HTTP Proxy sync enabled event.",
548
+ "iAMT0063-0": "User Notification Alert - HTTP Proxy sync enabled event - HTTP Proxy Sync disabled.",
549
+ "iAMT0063-1": "User Notification Alert - HTTP Proxy sync enabled event - HTTP Proxy Sync enabled.",
550
+ "iAMT0064": "User Notification Alert - User Consent event.",
551
+ "iAMT0064-1": "User Notification Alert - User Consent event - User Consent granted.",
552
+ "iAMT0064-2": "User Notification Alert - User Consent event - User Consent ended.",
553
+ "iAMT0067-0": "Graceful Remote Control Operation - Shutdown.",
554
+ "iAMT0067-1": "Graceful Remote Control Operation - Reset.",
555
+ "iAMT0067-2": "Graceful Remote Control Operation - Hibernate.",
556
+ "iAMT0068-0": "Link Protection Notification - No link protection.",
557
+ "iAMT0068-1": "Link Protection Notification - Passive link protection.",
558
+ "iAMT0068-2": "Link Protection Notification - High link protection.",
559
+ "iAMT0069-0": "Local Time Sync Enablement Notification - Local Time Sync Disabled.",
560
+ "iAMT0069-1": "Local Time Sync Enablement Notification - Local Time Sync Enabled.",
561
+ "iAMT0070": "Host Reset Triggered by WD Expiration Notification.",
562
+ "PLAT0004": "The chassis %1s was opened.",
563
+ "PLAT0005": "The chassis %1s was closed.",
564
+ "PLAT0006": "The drive bay %1s was opened.",
565
+ "PLAT0007": "The drive bay %1s was closed.",
566
+ "PLAT0008": "The I/O card area %1s was opened.",
567
+ "PLAT0009": "The I/O card area %1s was closed.",
568
+ "PLAT0010": "The processor area %1s was opened.",
569
+ "PLAT0011": "The processor area %1s was closed.",
570
+ "PLAT0012": "The LAN %1s has been disconnected.",
571
+ "PLAT0013": "The LAN %1s has been connected.",
572
+ "PLAT0016": "The permission to insert package %1s has been granted.",
573
+ "PLAT0017": "The permission to insert package %1s has been removed.",
574
+ "PLAT0018": "The fan card area %1s is open.",
575
+ "PLAT0019": "The fan card area %1s is closed.",
576
+ "PLAT0022": "The computer system %1s has detected a secure mode violation.",
577
+ "PLAT0024": "The computer system %1s has detected a pre-boot user password violation.",
578
+ "PLAT0026": "The computer system %1s has detected a pre-boot setup password violation.",
579
+ "PLAT0028": "The computer system %1s has detected a network boot password violation.",
580
+ "PLAT0030": "The computer system %1s has detected a password violation.",
581
+ "PLAT0032": "The management controller %1s has detected an out-of-band password violation.",
582
+ "PLAT0034": "The processor %1s has been added.",
583
+ "PLAT0035": "The processor %1s has been removed.",
584
+ "PLAT0036": "An over-temperature condition has been detected on the processor %1s.",
585
+ "PLAT0037": "An over-temperature condition has been removed on the processor %1s.",
586
+ "PLAT0038": "The processor %1s is operating in a degraded State.",
587
+ "PLAT0039": "The processor %1s is no longer operating in a degraded State.",
588
+ "PLAT0040": "The processor %1s has failed.",
589
+ "PLAT0042": "The processor %1s has failed.",
590
+ "PLAT0044": "The processor %1s has failed.",
591
+ "PLAT0046": "The processor %1s has failed.",
592
+ "PLAT0048": "The processor %1s has failed.",
593
+ "PLAT0060": "The processor %1s has been enabled.",
594
+ "PLAT0061": "The processor %1s has been disabled.",
595
+ "PLAT0062": "The processor %1s has a configuration mismatch.",
596
+ "PLAT0064": "A terminator has been detected on the processor %1s.",
597
+ "PLAT0084": "The Power Supply %1s has been added.",
598
+ "PLAT0085": "The Power Supply %1s has been removed.",
599
+ "PLAT0086": "The Power Supply %1s has failed.",
600
+ "PLAT0088": "Failure predicted on power supply %1s.",
601
+ "PLAT0096": "The input to power supply %1s has been lost or fallen out of range.",
602
+ "PLAT0098": "The power supply %1s is operating in an input state that is out of range.",
603
+ "PLAT0099": "The power supply %1s has returned to a normal input state.",
604
+ "PLAT0100": "The power supply %1s has lost input.",
605
+ "PLAT0104": "The power supply %1s has a configuration mismatch.",
606
+ "PLAT0106": "Power supply %1s has been disabled.",
607
+ "PLAT0107": "Power supply %1s has been enabled.",
608
+ "PLAT0108": "Power supply %1s has been power cycled.",
609
+ "PLAT0110": "Power supply %1s has encountered an error during power down.",
610
+ "PLAT0112": "Power supply %1s has lost power.",
611
+ "PLAT0114": "Soft power control has failed for power supply %1s.",
612
+ "PLAT0116": "Power supply %1s has failed.",
613
+ "PLAT0118": "Failure predicted on power supply %1s.",
614
+ "PLAT0120": "Memory subsystem failure.",
615
+ "PLAT0122": "DIMM missing.",
616
+ "PLAT0124": "Memory error detected & corrected for DIMM %1s.",
617
+ "PLAT0128": "Memory DIMM %1s added.",
618
+ "PLAT0129": "Memory DIMM %1s removed.",
619
+ "PLAT0130": "Memory DIMM %1s enabled.",
620
+ "PLAT0131": "Memory DIMM %1s disabled.",
621
+ "PLAT0134": "Memory parity error for DIMM %1s.",
622
+ "PLAT0136": "Memory scrub failure for DIMM %1s.",
623
+ "PLAT0138": "Memory uncorrectable error detected for DIMM %1s.",
624
+ "PLAT0140": "Memory sparing initiated for DIMM %1s.",
625
+ "PLAT0141": "Memory sparing concluded for DIMM %1s.",
626
+ "PLAT0142": "Memory DIMM %1s Throttled.",
627
+ "PLAT0144": "Memory logging limit reached for DIMM %1s.",
628
+ "PLAT0145": "Memory logging limit removed for DIMM %1s.",
629
+ "PLAT0146": "An over-temperature condition has been detected on the Memory DIMM %1s.",
630
+ "PLAT0147": "An over-temperature condition has been removed on the Memory DIMM %1s.",
631
+ "PLAT0162": "The drive %1s has been added.",
632
+ "PLAT0163": "The drive %1s has been removed.",
633
+ "PLAT0164": "The drive %1s has been disabled due to a detected fault.",
634
+ "PLAT0167": "The drive %1s has been enabled.",
635
+ "PLAT0168": "Failure predicted on drive %1s.",
636
+ "PLAT0170": "Hot spare enabled for %1s.",
637
+ "PLAT0171": "Hot spare disabled for %1s.",
638
+ "PLAT0172": "Consistency check has begun for %1s.",
639
+ "PLAT0173": "Consistency check completed for %1s.",
640
+ "PLAT0174": "Array %1s is in critical condition.",
641
+ "PLAT0176": "Array %1s has failed.",
642
+ "PLAT0177": "Array %1s has been restored.",
643
+ "PLAT0178": "Rebuild in progress for array %1s.",
644
+ "PLAT0179": "Rebuild completed for array %1s.",
645
+ "PLAT0180": "Rebuild Aborted for array %1s.",
646
+ "PLAT0184": "The system %1s encountered a POST error.",
647
+ "PLAT0186": "The system %1s encountered a firmware hang.",
648
+ "PLAT0188": "The system %1s encountered firmware progress.",
649
+ "PLAT0192": "The log %1s has been disabled.",
650
+ "PLAT0193": "The log %1s has been enabled.",
651
+ "PLAT0194": "The log %1s has been disabled.",
652
+ "PLAT0195": "The log %1s has been enabled.",
653
+ "PLAT0196": "The log %1s has been disabled.",
654
+ "PLAT0198": "The log %1s has been enabled.",
655
+ "PLAT0200": "The log %1s has been cleared.",
656
+ "PLAT0202": "The log %1s is full.",
657
+ "PLAT0203": "The log %1s is no longer full.",
658
+ "PLAT0204": "The log %1s is almost full.",
659
+ "PLAT0208": "The log %1s has a configuration error.",
660
+ "PLAT0210": "The system %1s has been reconfigured.",
661
+ "PLAT0212": "The system %1s has encountered an OEM system boot event.",
662
+ "PLAT0214": "The system %1s has encountered an unknown system hardware fault.",
663
+ "PLAT0216": "The system %1s has generated an auxiliary log entry.",
664
+ "PLAT0218": "The system %1s has executed a PEF action.",
665
+ "PLAT0220": "The system %1s has synchronized the system clock.",
666
+ "PLAT0222": "A diagnostic interrupt has occurred on system %1s.",
667
+ "PLAT0224": "A bus timeout has occurred on system %1s.",
668
+ "PLAT0226": "An I/O channel check NMI has occurred on system %1s.",
669
+ "PLAT0228": "A software NMI has occurred on system %1s.",
670
+ "PLAT0230": "System %1s has recovered from an NMI.",
671
+ "PLAT0232": "A PCI PERR has occurred on system %1s.",
672
+ "PLAT0234": "A PCI SERR has occurred on system %1s.",
673
+ "PLAT0236": "An EISA fail safe timeout occurred on system %1s.",
674
+ "PLAT0238": "A correctable bus error has occurred on system %1s.",
675
+ "PLAT0240": "An uncorrectable bus error has occurred on system %1s.",
676
+ "PLAT0242": "A fatal NMI error has occurred on system %1s.",
677
+ "PLAT0244": "A fatal bus error has occurred on system %1s.",
678
+ "PLAT0246": "A bus on system %1s is operating in a degraded state.",
679
+ "PLAT0247": "A bus on system %1s is no longer operating in a degraded state.",
680
+ "PLAT0248": "The power button %1s has been pressed.",
681
+ "PLAT0249": "The power button %1s has been released.",
682
+ "PLAT0250": "The sleep button %1s has been pressed.",
683
+ "PLAT0251": "The sleep button %1s has been released.",
684
+ "PLAT0252": "The reset button %1s has been pressed.",
685
+ "PLAT0253": "The reset button %1s has been released.",
686
+ "PLAT0254": "The latch to %1s has been opened.",
687
+ "PLAT0255": "The latch to %1s has been closed.",
688
+ "PLAT0256": "The service request %1s has been enabled.",
689
+ "PLAT0257": "The service request %1s has been completed.",
690
+ "PLAT0258": "Power control of system %1s has failed.",
691
+ "PLAT0262": "The network port %1s has been connected.",
692
+ "PLAT0263": "The network port %1s has been disconnected.",
693
+ "PLAT0266": "The connector %1s has encountered a configuration error.",
694
+ "PLAT0267": "The connector %1s configuration error has been repaired.",
695
+ "PLAT0272": "Power on for system %1s.",
696
+ "PLAT0274": "Power cycle hard requested for system %1s.",
697
+ "PLAT0276": "Power cycle soft requested for system %1s.",
698
+ "PLAT0278": "PXE boot requested for system %1s.",
699
+ "PLAT0280": "Diagnostics boot requested for system %1s.",
700
+ "PLAT0282": "System restart requested for system %1s.",
701
+ "PLAT0284": "System restart begun for system %1s.",
702
+ "PLAT0286": "No bootable media available for system %1s.",
703
+ "PLAT0288": "Non-bootable media selected for system %1s.",
704
+ "PLAT0290": "PXE server not found for system %1s.",
705
+ "PLAT0292": "User timeout on boot for system %1s.",
706
+ "PLAT0296": "System %1s boot from floppy initiated.",
707
+ "PLAT0298": "System %1s boot from local drive initiated.",
708
+ "PLAT0300": "System %1s boot from PXE on network port initiated.",
709
+ "PLAT0302": "System %1s boot diagnostics initiated.",
710
+ "PLAT0304": "System %1s boot from CD initiated.",
711
+ "PLAT0306": "System %1s boot from ROM initiated.",
712
+ "PLAT0312": "System %1s boot initiated.",
713
+ "PLAT0320": "Critical stop during OS load on system %1s.",
714
+ "PLAT0322": "Run-time critical stop on system %1s.",
715
+ "PLAT0324": "OS graceful stop on system %1s.",
716
+ "PLAT0326": "OS graceful shutdown begun on system %1s.",
717
+ "PLAT0327": "OS graceful shutdown completed on system %1s.",
718
+ "PLAT0328": "Agent not responding on system %1s.",
719
+ "PLAT0329": "Agent has begun responding on system %1s.",
720
+ "PLAT0330": "Fault in slot on system %1s.",
721
+ "PLAT0331": "Fault condition removed on system %1s.",
722
+ "PLAT0332": "Identifying slot on system %1s.",
723
+ "PLAT0333": "Identify stopped on slot for system %1s.",
724
+ "PLAT0334": "Package installed in slot for system %1s.",
725
+ "PLAT0336": "Slot empty system %1s.",
726
+ "PLAT0338": "Slot in system %1s is ready for installation.",
727
+ "PLAT0340": "Slot in system %1s is ready for removal.",
728
+ "PLAT0342": "Power is off on slot of system %1s.",
729
+ "PLAT0344": "Power is on for slot of system %1s.",
730
+ "PLAT0346": "Removal requested for slot of system %1s.",
731
+ "PLAT0348": "Interlock activated on slot of system %1s.",
732
+ "PLAT0349": "Interlock de-asserted on slot of system %1s.",
733
+ "PLAT0350": "Slot disabled on system %1s.",
734
+ "PLAT0351": "Slot enabled on system %1s.",
735
+ "PLAT0352": "Slot of system %1s holds spare.",
736
+ "PLAT0353": "Slot of system %1s no longer holds spare.",
737
+ "PLAT0354": "Computer system %1s enabled.",
738
+ "PLAT0356": "Computer system %1s is in sleep - light mode.",
739
+ "PLAT0358": "Computer system %1s is in hibernate.",
740
+ "PLAT0360": "Computer system %1s is in standby.",
741
+ "PLAT0362": "Computer system %1s is in soft off mode.",
742
+ "PLAT0364": "Computer system %1s is in hard off mode.",
743
+ "PLAT0366": "Computer system %1s is sleeping.",
744
+ "PLAT0368": "Watchdog timer expired for %1s.",
745
+ "PLAT0370": "Reboot of system initiated by watchdog %1s.",
746
+ "PLAT0372": "Powering off system initiated by watchdog %1s.",
747
+ "PLAT0374": "Power cycle of system initiated by watchdog %1s.",
748
+ "PLAT0376": "Watchdog timer interrupt occurred for %1s.",
749
+ "PLAT0378": "A page alert has been generated for system %1s.",
750
+ "PLAT0380": "A LAN alert has been generated for system %1s.",
751
+ "PLAT0382": "An event trap has been generated for system %1s.",
752
+ "PLAT0384": "An SNMP trap has been generated for system %1s.",
753
+ "PLAT0390": "%1s detected as present.",
754
+ "PLAT0392": "%1s detected as absent.",
755
+ "PLAT0394": "%1s has been disabled.",
756
+ "PLAT0395": "%1s has been enabled.",
757
+ "PLAT0396": "Heartbeat lost for LAN %1s.",
758
+ "PLAT0397": "Heartbeat detected for LAN %1s.",
759
+ "PLAT0398": "Sensor %1s is unavailable or degraded on management system.",
760
+ "PLAT0399": "Sensor %1s has returned to normal on management system.",
761
+ "PLAT0400": "Controller %1s is unavailable or degraded on management system.",
762
+ "PLAT0401": "Controller %1s has returned to normal on management system.",
763
+ "PLAT0402": "Management system %1s is off-line.",
764
+ "PLAT0404": "Management system %1s is disabled.",
765
+ "PLAT0405": "Management system %1s is enabled.",
766
+ "PLAT0406": "Sensor %1s has failed on management system.",
767
+ "PLAT0408": "FRU %1s has failed on management system.",
768
+ "PLAT0424": "The battery %1s is critically low.",
769
+ "PLAT0427": "The battery %1s is no longer critically low.",
770
+ "PLAT0430": "The battery %1s has been removed from unit.",
771
+ "PLAT0431": "The battery %1s has been added.",
772
+ "PLAT0432": "The battery %1s has failed.",
773
+ "PLAT0434": "Session audit is deactivated on system %1s.",
774
+ "PLAT0435": "Session audit is activated on system %1s.",
775
+ "PLAT0436": "A hardware change occurred on system %1s.",
776
+ "PLAT0438": "A firmware or software change occurred on system %1s.",
777
+ "PLAT0440": "A hardware incompatibility was detected on system %1s.",
778
+ "PLAT0442": "A firmware or software incompatibility was detected on system %1s.",
779
+ "PLAT0444": "Invalid or unsupported hardware was detected on system %1s.",
780
+ "PLAT0446": "Invalid or unsupported firmware or software was detected on system %1s.",
781
+ "PLAT0448": "A successful hardware change was detected on system %1s.",
782
+ "PLAT0450": "A successful software or firmware change was detected on system %1s.",
783
+ "PLAT0464": "FRU %1s not installed on system.",
784
+ "PLAT0465": "FRU %1s installed on system.",
785
+ "PLAT0466": "Activation requested for FRU %1s on system.",
786
+ "PLAT0467": "FRU %1s on system is active.",
787
+ "PLAT0468": "Activation in progress for FRU %1s on system.",
788
+ "PLAT0470": "Deactivation request for FRU %1s on system.",
789
+ "PLAT0471": "FRU %1s on system is in standby or \"hot spare\" state.",
790
+ "PLAT0472": "Deactivation in progress for FRU %1s on system.",
791
+ "PLAT0474": "Communication lost with FRU %1s on system.",
792
+ "PLAT0476": "Numeric sensor %1s going low (lower non-critical).",
793
+ "PLAT0478": "Numeric sensor %1s going high (lower non-critical).",
794
+ "PLAT0480": "Numeric sensor %1s going low (lower critical).",
795
+ "PLAT0482": "Numeric sensor %1s going high (lower critical).",
796
+ "PLAT0484": "Numeric sensor %1s going low (lower non-recoverable).",
797
+ "PLAT0486": "Numeric sensor %1s going high (lower non-critical).",
798
+ "PLAT0488": "Numeric sensor %1s going low (upper non-critical).",
799
+ "PLAT0490": "Numeric sensor %1s going high (upper non-critical).",
800
+ "PLAT0492": "Numeric sensor %1s going low (upper critical).",
801
+ "PLAT0494": "Numeric sensor %1s going high (upper critical).",
802
+ "PLAT0496": "Numeric sensor %1s going low (upper non-recoverable).",
803
+ "PLAT0498": "Numeric sensor %1s going high (upper non-recoverable).",
804
+ "PLAT0500": "Sensor %1s has transitioned to idle.",
805
+ "PLAT0502": "Sensor %1s has transitioned to active.",
806
+ "PLAT0504": "Sensor %1s has transitioned to busy.",
807
+ "PLAT0508": "Sensor %1s has asserted.",
808
+ "PLAT0509": "Sensor %1s has de-asserted.",
809
+ "PLAT0510": "Sensor %1s is asserting predictive failure.",
810
+ "PLAT0511": "Sensor %1s is de-asserting predictive failure.",
811
+ "PLAT0512": "Sensor %1s has indicated limit exceeded.",
812
+ "PLAT0513": "Sensor %1s has indicated limit no longer exceeded.",
813
+ "PLAT0514": "Sensor %1s has indicated performance met.",
814
+ "PLAT0516": "Sensor %1s has indicated performance lags.",
815
+ "PLAT0518": "Sensor %1s has transitioned to normal state.",
816
+ "PLAT0520": "Sensor %1s has transitioned from normal to non-critical state.",
817
+ "PLAT0522": "Sensor %1s has transitioned to critical from a less severe state.",
818
+ "PLAT0524": "Sensor %1s has transitioned to non-recoverable from a less severe state.",
819
+ "PLAT0526": "Sensor %1s has transitioned to non-critical from a more severe state.",
820
+ "PLAT0528": "Sensor %1s has transitioned to critical from a non-recoverable state.",
821
+ "PLAT0530": "Sensor %1s has transitioned to non-recoverable.",
822
+ "PLAT0532": "Sensor %1s indicates a monitor state.",
823
+ "PLAT0534": "Sensor %1s has an informational state.",
824
+ "PLAT0536": "Device %1s has been added.",
825
+ "PLAT0537": "Device %1s has been removed from unit.",
826
+ "PLAT0538": "Device %1s has been enabled.",
827
+ "PLAT0539": "Device %1s has been disabled.",
828
+ "PLAT0540": "Sensor %1s has indicated a running state.",
829
+ "PLAT0544": "Sensor %1s has indicated a power off state.",
830
+ "PLAT0546": "Sensor %1s has indicated an on-line state.",
831
+ "PLAT0548": "Sensor %1s has indicated an off-line state.",
832
+ "PLAT0550": "Sensor %1s has indicated an off-duty state.",
833
+ "PLAT0552": "Sensor %1s has indicated a degraded state.",
834
+ "PLAT0554": "Sensor %1s has indicated a power save state.",
835
+ "PLAT0556": "Sensor %1s has indicated an install error.",
836
+ "PLAT0558": "Redundancy %1s has been lost.",
837
+ "PLAT0560": "Redundancy %1s has been reduced.",
838
+ "PLAT0561": "Redundancy %1s has been restored.",
839
+ "PLAT0562": "%1s has transitioned to a D0 power state.",
840
+ "PLAT0564": "%1s has transitioned to a D1 power state.",
841
+ "PLAT0566": "%1s has transitioned to a D2 power state.",
842
+ "PLAT0568": "%1s has transitioned to a D3 power state.",
843
+ "PLAT0720": "The System %1s encountered firmware progress - memory initialization entry.",
844
+ "PLAT0721": "The System %1s encountered firmware progress - memory initialization exit.",
845
+ "PLAT0722": "The System %1s encountered firmware progress - hard drive initialization entry.",
846
+ "PLAT0723": "The System %1s encountered firmware progress - hard drive initialization exit.",
847
+ "PLAT0724": "The System %1s encountered firmware progress - user authentication.",
848
+ "PLAT0728": "The System %1s encountered firmware progress - USR resource configuration entry.",
849
+ "PLAT0729": "The System %1s encountered firmware progress - USR resource configuration exit.",
850
+ "PLAT0730": "The System %1s encountered firmware progress - PCI recource configuration entry.",
851
+ "PLAT0731": "The System %1s encountered firmware progress - PCI recource configuration exit.",
852
+ "PLAT0732": "The System %1s encountered firmware progress - Option ROM initialization entry.",
853
+ "PLAT0733": "The System %1s encountered firmware progress - Option ROM initialization entry exit.",
854
+ "PLAT0734": "The System %1s encountered firmware progress -video initialization entry entry.",
855
+ "PLAT0735": "The System %1s encountered firmware progress - video initialization entry exit.",
856
+ "PLAT0736": "The System %1s encountered firmware progress - cache initialization entry.",
857
+ "PLAT0737": "The System %1s encountered firmware progress - cache initialization exit.",
858
+ "PLAT0738": "The System %1s encountered firmware progress - keyboard controller initialization entry.",
859
+ "PLAT0739": "The System %1s encountered firmware progress - keyboard controller initialization exit.",
860
+ "PLAT0740": "The System %1s encountered firmware progress - motherboard initialization entry.",
861
+ "PLAT0741": "The System %1s encountered firmware progress - motherboard initialization exit.",
862
+ "PLAT0742": "The System %1s encountered firmware progress - floppy disk initialization entry.",
863
+ "PLAT0743": "The System %1s encountered firmware progress - floppy disk initialization exit.",
864
+ "PLAT0744": "The System %1s encountered firmware progress - keyboard test entry.",
865
+ "PLAT0745": "The System %1s encountered firmware progress - keyboard test exit.",
866
+ "PLAT0746": "The System %1s encountered firmware progress - pointing device test entry.",
867
+ "PLAT0747": "The System %1s encountered firmware progress - pointing device test exit.",
868
+ "PLAT0750": "The System %1s encountered firmware progress - dock enable entry.",
869
+ "PLAT0751": "The System %1s encountered firmware progress - dock enable exit.",
870
+ "PLAT0752": "The System %1s encountered firmware progress - dock disable entry.",
871
+ "PLAT0753": "The System %1s encountered firmware progress - dock disable exit.",
872
+ "PLAT0760": "The System %1s encountered firmware progress - start OS boot process.",
873
+ "PLAT0762": "The System %1s encountered firmware progress - call OS wake vector.",
874
+ "PLAT0764": "The System %1s encountered firmware progress - unrecoverable keyboard failure.",
875
+ "PLAT0766": "The System %1s encountered firmware progress - no video device detected.",
876
+ "PLAT0768": "The System %1s encountered firmware progress - SMART alert detected on drive.",
877
+ "PLAT0770": "The System %1s encountered firmware progress - unrecoverable boot device failure.",
878
+ "PLAT0789": "Corrupt BIOS detected.",
879
+ "PLAT0790": "The System %1s encountered PCI configuration failure.",
880
+ "PLAT0791": "The System %1s encountered a video subsystem failure.",
881
+ "PLAT0792": "The System %1s encountered a storage subsystem failure.",
882
+ "PLAT0793": "The System %1s encountered a USB subsystem failure.",
883
+ "PLAT0794": "The System %1s has detected no memory in the system.",
884
+ "PLAT0795": "The System %1s encountered a motherboard failure.",
885
+ "PLAT0796": "The System %1s encountered a memory Regulator Voltage Bad.",
886
+ "PLAT0797": "%1s PCI reset is not deasserting.",
887
+ "PLAT0798": "%1s Non-Motherboard Regulator Failure.",
888
+ "PLAT0799": "%1s Power Supply Cable failure.",
889
+ "PLAT0800": "%1s Motherboard regulator failure.",
890
+ "PLAT0801": "%1s System component compatibility mismatch."
891
+}
892
+
893
+module.exports = lme_heci;
agents/modules_meshcore_backup/amt-mei.js
new
+387
@@ -0,0 +1,387 @@
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 Q = require('queue');
18
+function amt_heci() {
19
+ var emitterUtils = require('events').inherits(this);
20
+ emitterUtils.createEvent('error');
21
+
22
+ var heci = require('heci');
23
+
24
+ this._ObjectID = "pthi";
25
+ this._rq = new Q();
26
+ this._setupPTHI = function _setupPTHI()
27
+ {
28
+ this._amt = heci.create();
29
+ this._amt.BiosVersionLen = 65;
30
+ this._amt.UnicodeStringLen = 20;
31
+
32
+ this._amt.Parent = this;
33
+ this._amt.on('error', function _amtOnError(e) { this.Parent.emit('error', e); });
34
+ this._amt.on('connect', function _amtOnConnect()
35
+ {
36
+ this.on('data', function _amtOnData(chunk)
37
+ {
38
+ //console.log("Received: " + chunk.length + " bytes");
39
+ var header = this.Parent.getCommand(chunk);
40
+ //console.log("CMD = " + header.Command + " (Status: " + header.Status + ") Response = " + header.IsResponse);
41
+
42
+ var user = this.Parent._rq.deQueue();
43
+ var params = user.optional;
44
+ var callback = user.func;
45
+
46
+ params.unshift(header);
47
+ callback.apply(this.Parent, params);
48
+
49
+ if(this.Parent._rq.isEmpty())
50
+ {
51
+ // No More Requests, we can close PTHI
52
+ this.Parent._amt.disconnect();
53
+ this.Parent._amt = null;
54
+ }
55
+ else
56
+ {
57
+ // Send the next request
58
+ this.write(this.Parent._rq.peekQueue().send);
59
+ }
60
+ });
61
+
62
+ // Start sending requests
63
+ this.write(this.Parent._rq.peekQueue().send);
64
+ });
65
+ };
66
+ function trim(x) { var y = x.indexOf('\0'); if (y >= 0) { return x.substring(0, y); } else { return x; } }
67
+ this.getCommand = function getCommand(chunk) {
68
+ var command = chunk.length == 0 ? (this._rq.peekQueue().cmd | 0x800000) : chunk.readUInt32LE(4);
69
+ var ret = { IsResponse: (command & 0x800000) == 0x800000 ? true : false, Command: (command & 0x7FFFFF), Status: chunk.length != 0 ? chunk.readUInt32LE(12) : -1, Data: chunk.length != 0 ? chunk.slice(16) : null };
70
+ return (ret);
71
+ };
72
+
73
+ this.sendCommand = function sendCommand() {
74
+ if (arguments.length < 3 || typeof (arguments[0]) != 'number' || typeof (arguments[1]) != 'object' || typeof (arguments[2]) != 'function') { throw ('invalid parameters'); }
75
+ var args = [];
76
+ for (var i = 3; i < arguments.length; ++i) { args.push(arguments[i]); }
77
+
78
+ var header = Buffer.from('010100000000000000000000', 'hex');
79
+ header.writeUInt32LE(arguments[0] | 0x04000000, 4);
80
+ header.writeUInt32LE(arguments[1] == null ? 0 : arguments[1].length, 8);
81
+ this._rq.enQueue({ cmd: arguments[0], func: arguments[2], optional: args , send: (arguments[1] == null ? header : Buffer.concat([header, arguments[1]]))});
82
+
83
+ if(!this._amt)
84
+ {
85
+ this._setupPTHI();
86
+ this._amt.connect(heci.GUIDS.AMT, { noPipeline: 1 });
87
+ }
88
+ }
89
+
90
+ this.getVersion = function getVersion(callback) {
91
+ var optional = [];
92
+ for (var i = 1; i < arguments.length; ++i) { optional.push(arguments[i]); }
93
+ this.sendCommand(26, null, function (header, fn, opt) {
94
+ if (header.Status == 0) {
95
+ var i, CodeVersion = header.Data, val = { BiosVersion: CodeVersion.slice(0, this._amt.BiosVersionLen).toString(), Versions: [] }, v = CodeVersion.slice(this._amt.BiosVersionLen + 4);
96
+ for (i = 0; i < CodeVersion.readUInt32LE(this._amt.BiosVersionLen) ; ++i) {
97
+ val.Versions[i] = { Description: v.slice(2, v.readUInt16LE(0) + 2).toString(), Version: v.slice(4 + this._amt.UnicodeStringLen, 4 + this._amt.UnicodeStringLen + v.readUInt16LE(2 + this._amt.UnicodeStringLen)).toString() };
98
+ v = v.slice(4 + (2 * this._amt.UnicodeStringLen));
99
+ }
100
+ if (val.BiosVersion.indexOf('\0') > 0) { val.BiosVersion = val.BiosVersion.substring(0, val.BiosVersion.indexOf('\0')); }
101
+ opt.unshift(val);
102
+ } else {
103
+ opt.unshift(null);
104
+ }
105
+ fn.apply(this, opt);
106
+ }, callback, optional);
107
+ };
108
+
109
+ // Fill the left with zeros until the string is of a given length
110
+ function zeroLeftPad(str, len) {
111
+ if ((len == null) && (typeof (len) != 'number')) { return null; }
112
+ if (str == null) str = ''; // If null, this is to generate zero leftpad string
113
+ var zlp = '';
114
+ for (var i = 0; i < len - str.length; i++) { zlp += '0'; }
115
+ return zlp + str;
116
+ }
117
+
118
+ this.getUuid = function getUuid(callback) {
119
+ var optional = [];
120
+ for (var i = 1; i < arguments.length; ++i) { optional.push(arguments[i]); }
121
+ this.sendCommand(0x5c, null, function (header, fn, opt) {
122
+ if (header.Status == 0) {
123
+ var result = {};
124
+ result.uuid = [zeroLeftPad(header.Data.readUInt32LE(0).toString(16), 8),
125
+ zeroLeftPad(header.Data.readUInt16LE(4).toString(16), 4),
126
+ zeroLeftPad(header.Data.readUInt16LE(6).toString(16), 4),
127
+ zeroLeftPad(header.Data.readUInt16BE(8).toString(16), 4),
128
+ zeroLeftPad(header.Data.slice(10).toString('hex').toLowerCase(), 12)].join('-');
129
+ opt.unshift(result);
130
+ } else {
131
+ opt.unshift(null);
132
+ }
133
+ fn.apply(this, opt);
134
+ }, callback, optional);
135
+ };
136
+
137
+ this.getProvisioningState = function getProvisioningState(callback) {
138
+ var optional = [];
139
+ for (var i = 1; i < arguments.length; ++i) { optional.push(arguments[i]); }
140
+ this.sendCommand(17, null, function (header, fn, opt) {
141
+ if (header.Status == 0) {
142
+ var result = {};
143
+ result.state = header.Data.readUInt32LE(0);
144
+ if (result.state < 3) { result.stateStr = ["PRE", "IN", "POST"][result.state]; }
145
+ opt.unshift(result);
146
+ } else {
147
+ opt.unshift(null);
148
+ }
149
+ fn.apply(this, opt);
150
+ }, callback, optional);
151
+ };
152
+ this.getProvisioningMode = function getProvisioningMode(callback) {
153
+ var optional = [];
154
+ for (var i = 1; i < arguments.length; ++i) { optional.push(arguments[i]); }
155
+ this.sendCommand(8, null, function (header, fn, opt) {
156
+ if (header.Status == 0) {
157
+ var result = {};
158
+ result.mode = header.Data.readUInt32LE(0);
159
+ if (result.mode < 4) { result.modeStr = ["NONE", "ENTERPRISE", "SMALL_BUSINESS", "REMOTE_ASSISTANCE"][result.mode]; }
160
+ result.legacy = header.Data.readUInt32LE(4) == 0 ? false : true;
161
+ opt.unshift(result);
162
+ } else {
163
+ opt.unshift(null);
164
+ }
165
+ fn.apply(this, opt);
166
+ }, callback, optional);
167
+ };
168
+ this.getEHBCState = function getEHBCState(callback) {
169
+ var optional = [];
170
+ for (var i = 1; i < arguments.length; ++i) { optional.push(arguments[i]); }
171
+ this.sendCommand(132, null, function (header, fn, opt) {
172
+ if (header.Status == 0) {
173
+ opt.unshift({ EHBC: header.Data.readUInt32LE(0) != 0 });
174
+ } else {
175
+ opt.unshift(null);
176
+ }
177
+ fn.apply(this, opt);
178
+ }, callback, optional);
179
+ };
180
+ this.getControlMode = function getControlMode(callback) {
181
+ var optional = [];
182
+ for (var i = 1; i < arguments.length; ++i) { optional.push(arguments[i]); }
183
+ this.sendCommand(107, null, function (header, fn, opt) {
184
+ if (header.Status == 0) {
185
+ var result = {};
186
+ result.controlMode = header.Data.readUInt32LE(0);
187
+ if (result.controlMode < 3) { result.controlModeStr = ["NONE_RPAT", "CLIENT", "ADMIN", "REMOTE_ASSISTANCE"][result.controlMode]; }
188
+ opt.unshift(result);
189
+ } else {
190
+ opt.unshift(null);
191
+ }
192
+ fn.apply(this, opt);
193
+ }, callback, optional);
194
+ };
195
+ this.getMACAddresses = function getMACAddresses(callback) {
196
+ var optional = [];
197
+ for (var i = 1; i < arguments.length; ++i) { optional.push(arguments[i]); }
198
+ this.sendCommand(37, null, function (header, fn, opt) {
199
+ if (header.Status == 0) {
200
+ opt.unshift({ DedicatedMAC: header.Data.slice(0, 6).toString('hex:'), HostMAC: header.Data.slice(6, 12).toString('hex:') });
201
+ } else { opt.unshift({ DedicatedMAC: null, HostMAC: null }); }
202
+ fn.apply(this, opt);
203
+ }, callback, optional);
204
+ };
205
+ this.getDnsSuffix = function getDnsSuffix(callback) {
206
+ var optional = [];
207
+ for (var i = 1; i < arguments.length; ++i) { optional.push(arguments[i]); }
208
+ this.sendCommand(54, null, function (header, fn, opt) {
209
+ if (header.Status == 0) {
210
+ var resultLen = header.Data.readUInt16LE(0);
211
+ if (resultLen > 0) { opt.unshift(header.Data.slice(2, 2 + resultLen).toString()); } else { opt.unshift(null); }
212
+ } else {
213
+ opt.unshift(null);
214
+ }
215
+ fn.apply(this, opt);
216
+ }, callback, optional);
217
+ };
218
+ this.getHashHandles = function getHashHandles(callback) {
219
+ var optional = [];
220
+ for (var i = 1; i < arguments.length; ++i) { optional.push(arguments[i]); }
221
+ this.sendCommand(0x2C, null, function (header, fn, opt) {
222
+ var result = [];
223
+ if (header.Status == 0) {
224
+ var resultLen = header.Data.readUInt32LE(0);
225
+ for (var i = 0; i < resultLen; ++i) {
226
+ result.push(header.Data.readUInt32LE(4 + (4 * i)));
227
+ }
228
+ }
229
+ opt.unshift(result);
230
+ fn.apply(this, opt);
231
+ }, callback, optional);
232
+ };
233
+ this.getCertHashEntry = function getCertHashEntry(handle, callback) {
234
+ var optional = [];
235
+ for (var i = 2; i < arguments.length; ++i) { optional.push(arguments[i]); }
236
+
237
+ var data = new Buffer(4);
238
+ data.writeUInt32LE(handle, 0);
239
+
240
+ this.sendCommand(0x2D, data, function (header, fn, opt) {
241
+ if (header.Status == 0) {
242
+ var result = {};
243
+ result.isDefault = header.Data.readUInt32LE(0);
244
+ result.isActive = header.Data.readUInt32LE(4);
245
+ result.hashAlgorithm = header.Data.readUInt8(72);
246
+ if (result.hashAlgorithm < 4) {
247
+ result.hashAlgorithmStr = ["MD5", "SHA1", "SHA256", "SHA512"][result.hashAlgorithm];
248
+ result.hashAlgorithmSize = [16, 20, 32, 64][result.hashAlgorithm];
249
+ result.certificateHash = header.Data.slice(8, 8 + result.hashAlgorithmSize).toString('hex');
250
+ }
251
+ result.name = header.Data.slice(73 + 2, 73 + 2 + header.Data.readUInt16LE(73)).toString();
252
+ opt.unshift(result);
253
+ } else {
254
+ opt.unshift(null);
255
+ }
256
+ fn.apply(this, opt);
257
+ }, callback, optional);
258
+ };
259
+ this.getCertHashEntries = function getCertHashEntries(callback) {
260
+ var optional = [];
261
+ for (var i = 1; i < arguments.length; ++i) { optional.push(arguments[i]); }
262
+
263
+ this.getHashHandles(function (handles, fn, opt) {
264
+ var entries = [];
265
+ this.getCertHashEntry(handles.shift(), this._getHashEntrySink, fn, opt, entries, handles);
266
+ }, callback, optional);
267
+ };
268
+
269
+ this._getHashEntrySink = function _getHashEntrySink(result, fn, opt, entries, handles) {
270
+ entries.push(result);
271
+ if (handles.length > 0) {
272
+ this.getCertHashEntry(handles.shift(), this._getHashEntrySink, fn, opt, entries, handles);
273
+ } else {
274
+ opt.unshift(entries);
275
+ fn.apply(this, opt);
276
+ }
277
+ }
278
+ this.getLocalSystemAccount = function getLocalSystemAccount(callback) {
279
+ var optional = [];
280
+ for (var i = 1; i < arguments.length; ++i) { optional.push(arguments[i]); }
281
+ this.sendCommand(103, Buffer.alloc(40), function (header, fn, opt) {
282
+ if (header.Data.length == 68) { opt.unshift({ user: trim(header.Data.slice(0, 33).toString()), pass: trim(header.Data.slice(33, 67).toString()), raw: header.Data }); } else { opt.unshift(null); }
283
+ fn.apply(this, opt);
284
+ }, callback, optional);
285
+ }
286
+ this.getLanInterfaceSettings = function getLanInterfaceSettings(index, callback)
287
+ {
288
+ var optional = [];
289
+ for (var i = 2; i < arguments.length; ++i) { optional.push(arguments[i]); }
290
+ var ifx = Buffer.alloc(4);
291
+ ifx.writeUInt32LE(index);
292
+ this.sendCommand(0x48, ifx, function onGetLanInterfaceSettings(header, fn, opt)
293
+ {
294
+ if(header.Status == 0)
295
+ {
296
+ var info = {};
297
+ info.enabled = header.Data.readUInt32LE(0);
298
+ info.dhcpEnabled = header.Data.readUInt32LE(8);
299
+ switch(header.Data[12])
300
+ {
301
+ case 1:
302
+ info.dhcpMode = 'ACTIVE'
303
+ break;
304
+ case 2:
305
+ info.dhcpMode = 'PASSIVE'
306
+ break;
307
+ default:
308
+ info.dhcpMode = 'UNKNOWN';
309
+ break;
310
+ }
311
+ info.mac = header.Data.slice(14).toString('hex:');
312
+
313
+ var addr = header.Data.readUInt32LE(4);
314
+ info.address = ((addr >> 24) & 255) + '.' + ((addr >> 16) & 255) + '.' + ((addr >> 8) & 255) + '.' + (addr & 255);
315
+ opt.unshift(info);
316
+ fn.apply(this, opt);
317
+ }
318
+ else
319
+ {
320
+ opt.unshift(null);
321
+ fn.apply(this, opt);
322
+ }
323
+ }, callback, optional);
324
+
325
+ };
326
+ this.unprovision = function unprovision(mode, callback) {
327
+ var optional = [];
328
+ for (var i = 2; i < arguments.length; ++i) { optional.push(arguments[i]); }
329
+ var data = new Buffer(4);
330
+ data.writeUInt32LE(mode, 0);
331
+ this.sendCommand(16, data, function (header, fn, opt) {
332
+ opt.unshift(header.Status);
333
+ fn.apply(this, opt);
334
+ }, callback, optional);
335
+ }
336
+ this.startConfiguration = function startConfiguration() {
337
+ var optional = [];
338
+ for (var i = 2; i < arguments.length; ++i) { optional.push(arguments[i]); }
339
+ this.sendCommand(0x29, data, function (header, fn, opt) { opt.unshift(header.Status); fn.apply(this, opt); }, callback, optional);
340
+ }
341
+ this.stopConfiguration = function stopConfiguration() {
342
+ var optional = [];
343
+ for (var i = 2; i < arguments.length; ++i) { optional.push(arguments[i]); }
344
+ this.sendCommand(0x5E, data, function (header, fn, opt) { opt.unshift(header.Status); fn.apply(this, opt); }, callback, optional);
345
+ }
346
+ this.openUserInitiatedConnection = function openUserInitiatedConnection() {
347
+ var optional = [];
348
+ for (var i = 2; i < arguments.length; ++i) { optional.push(arguments[i]); }
349
+ this.sendCommand(0x44, data, function (header, fn, opt) { opt.unshift(header.Status); fn.apply(this, opt); }, callback, optional);
350
+ }
351
+ this.closeUserInitiatedConnection = function closeUnserInitiatedConnected() {
352
+ var optional = [];
353
+ for (var i = 2; i < arguments.length; ++i) { optional.push(arguments[i]); }
354
+ this.sendCommand(0x45, data, function (header, fn, opt) { opt.unshift(header.Status); fn.apply(this, opt); }, callback, optional);
355
+ }
356
+ this.getRemoteAccessConnectionStatus = function getRemoteAccessConnectionStatus() {
357
+ var optional = [];
358
+ for (var i = 2; i < arguments.length; ++i) { optional.push(arguments[i]); }
359
+ this.sendCommand(0x46, data, function (header, fn, opt) {
360
+ if (header.Status == 0) {
361
+ var hostname = v.slice(14, header.Data.readUInt16LE(12) + 14).toString()
362
+ opt.unshift({ status: header.Status, networkStatus: header.Data.readUInt32LE(0), remoteAccessStatus: header.Data.readUInt32LE(4), remoteAccessTrigger: header.Data.readUInt32LE(8), mpsHostname: hostname, raw: header.Data });
363
+ } else {
364
+ opt.unshift({ status: header.Status });
365
+ }
366
+ fn.apply(this, opt);
367
+ }, callback, optional);
368
+ }
369
+ this.getProtocolVersion = function getProtocolVersion(callback) {
370
+ var optional = [];
371
+ for (var i = 1; i < arguments.length; ++i) { opt.push(arguments[i]); }
372
+
373
+ heci.doIoctl(heci.IOCTL.HECI_VERSION, Buffer.alloc(5), Buffer.alloc(5), function (status, buffer, self, fn, opt) {
374
+ if (status == 0) {
375
+ var result = buffer.readUInt8(0).toString() + '.' + buffer.readUInt8(1).toString() + '.' + buffer.readUInt8(2).toString() + '.' + buffer.readUInt16BE(3).toString();
376
+ opt.unshift(result);
377
+ fn.apply(self, opt);
378
+ }
379
+ else {
380
+ opt.unshift(null);
381
+ fn.apply(self, opt);
382
+ }
383
+ }, this, callback, optional);
384
+ }
385
+}
386
+
387
+module.exports = amt_heci;
\ No newline at end of file
agents/modules_meshcore_backup/amt-scanner.js
new
+105
@@ -0,0 +1,105 @@
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
+/**
18
+* @description Meshcentral Intel AMT Local Scanner
19
+* @author Ylian Saint-Hilaire & Joko Sastriawan
20
+* @version v0.0.1
21
+*/
22
+
23
+// Construct a Intel AMT Scanner object
24
+
25
+function AMTScanner() {
26
+ var emitterUtils = require('events').inherits(this);
27
+ emitterUtils.createEvent('found');
28
+
29
+ this.dgram = require('dgram');
30
+
31
+ this.buildRmcpPing = function (tag) {
32
+ var packet = Buffer.from('06000006000011BE80000000', 'hex');
33
+ packet[9] = tag;
34
+ return packet;
35
+ };
36
+
37
+ this.parseRmcpPacket = function (server, data, rinfo, func) {
38
+ if (data == null || data.length < 20) return;
39
+ var res = {};
40
+ if (((data[12] == 0) || (data[13] != 0) || (data[14] != 1) || (data[15] != 0x57)) && (data[21] & 32)) {
41
+ res.servertag = data[9];
42
+ res.minorVersion = data[18] & 0x0F;
43
+ res.majorVersion = (data[18] >> 4) & 0x0F;
44
+ res.provisioningState = data[19] & 0x03; // Pre = 0, In = 1, Post = 2
45
+
46
+ var openPort = (data[16] * 256) + data[17];
47
+ var dualPorts = ((data[19] & 0x04) != 0) ? true : false;
48
+ res.openPorts = [openPort];
49
+ res.address = rinfo.address;
50
+ if (dualPorts == true) { res.openPorts = [16992, 16993]; }
51
+ if (func !== undefined) {
52
+ func(server, res);
53
+ }
54
+ }
55
+ }
56
+
57
+ this.parseIPv4Range = function (range) {
58
+ if (range == undefined || range == null) return null;
59
+ var x = range.split('-');
60
+ if (x.length == 2) { return { min: this.parseIpv4Addr(x[0]), max: this.parseIpv4Addr(x[1]) }; }
61
+ x = range.split('/');
62
+ if (x.length == 2) {
63
+ var ip = this.parseIpv4Addr(x[0]), masknum = parseInt(x[1]), mask = 0;
64
+ if (masknum <= 16 || masknum > 32) return null;
65
+ masknum = 32 - masknum;
66
+ for (var i = 0; i < masknum; i++) { mask = (mask << 1); mask++; }
67
+ return { min: ip & (0xFFFFFFFF - mask), max: (ip & (0xFFFFFFFF - mask)) + mask };
68
+ }
69
+ x = this.parseIpv4Addr(range);
70
+ if (x == null) return null;
71
+ return { min: x, max: x };
72
+ };
73
+
74
+ // Parse IP address. Takes a
75
+ this.parseIpv4Addr = function (addr) {
76
+ var x = addr.split('.');
77
+ if (x.length == 4) { return (parseInt(x[0]) << 24) + (parseInt(x[1]) << 16) + (parseInt(x[2]) << 8) + (parseInt(x[3]) << 0); }
78
+ return null;
79
+ }
80
+
81
+ // IP address number to string
82
+ this.IPv4NumToStr = function (num) {
83
+ return ((num >> 24) & 0xFF) + '.' + ((num >> 16) & 0xFF) + '.' + ((num >> 8) & 0xFF) + '.' + (num & 0xFF);
84
+ }
85
+
86
+ this.scan = function (rangestr, timeout) {
87
+ var iprange = this.parseIPv4Range(rangestr);
88
+ var rmcp = this.buildRmcpPing(0);
89
+ var server = this.dgram.createSocket({ type: 'udp4' });
90
+ server.parent = this;
91
+ server.scanResults = [];
92
+ server.on('error', function (err) { console.log('Error:' + err); });
93
+ server.on('message', function (msg, rinfo) { if (rinfo.size > 4) { this.parent.parseRmcpPacket(this, msg, rinfo, function (s, res) { s.scanResults.push(res); }) }; });
94
+ server.on('listening', function () { for (var i = iprange.min; i <= iprange.max; i++) { server.send(rmcp, 623, server.parent.IPv4NumToStr(i)); } });
95
+ server.bind({ address: '0.0.0.0', port: 0, exclusive: true });
96
+ var tmout = setTimeout(function cb() {
97
+ //console.log("Server closed");
98
+ server.close();
99
+ server.parent.emit('found', server.scanResults);
100
+ delete server;
101
+ }, timeout);
102
+ };
103
+}
104
+
105
+module.exports = AMTScanner;
agents/modules_meshcore_backup/amt-wsman-duk.js
new
+148
@@ -0,0 +1,148 @@
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
+/**
18
+* @description WSMAN communication using duktape http
19
+* @author Ylian Saint-Hilaire
20
+* @version v0.2.0c
21
+*/
22
+
23
+// Construct a WSMAN communication object
24
+function CreateWsmanComm(/*host, port, user, pass, tls, extra*/)
25
+{
26
+ var obj = {};
27
+ obj.PendingAjax = []; // List of pending AJAX calls. When one frees up, another will start.
28
+ obj.ActiveAjaxCount = 0; // Number of currently active AJAX calls
29
+ obj.MaxActiveAjaxCount = 1; // Maximum number of activate AJAX calls at the same time.
30
+ obj.FailAllError = 0; // Set this to non-zero to fail all AJAX calls with that error status, 999 causes responses to be silent.
31
+ obj.digest = null;
32
+ obj.RequestCount = 0;
33
+ obj.requests = {};
34
+
35
+ if (arguments.length == 1 && typeof(arguments[0] == 'object'))
36
+ {
37
+ obj.host = arguments[0].host;
38
+ obj.port = arguments[0].port;
39
+ obj.authToken = arguments[0].authToken;
40
+ obj.tls = arguments[0].tls;
41
+ }
42
+ else
43
+ {
44
+ obj.host = arguments[0];
45
+ obj.port = arguments[1];
46
+ obj.user = arguments[2];
47
+ obj.pass = arguments[3];
48
+ obj.tls = arguments[4];
49
+ }
50
+
51
+
52
+ // Private method
53
+ // pri = priority, if set to 1, the call is high priority and put on top of the stack.
54
+ obj.PerformAjax = function (postdata, callback, tag, pri, url, action) {
55
+ if ((obj.ActiveAjaxCount == 0 || ((obj.ActiveAjaxCount < obj.MaxActiveAjaxCount) && (obj.challengeParams != null))) && obj.PendingAjax.length == 0) {
56
+ // There are no pending AJAX calls, perform the call now.
57
+ obj.PerformAjaxEx(postdata, callback, tag, url, action);
58
+ } else {
59
+ // If this is a high priority call, put this call in front of the array, otherwise put it in the back.
60
+ if (pri == 1) { obj.PendingAjax.unshift([postdata, callback, tag, url, action]); } else { obj.PendingAjax.push([postdata, callback, tag, url, action]); }
61
+ }
62
+ }
63
+
64
+ // Private method
65
+ obj.PerformNextAjax = function () {
66
+ if (obj.ActiveAjaxCount >= obj.MaxActiveAjaxCount || obj.PendingAjax.length == 0) return;
67
+ var x = obj.PendingAjax.shift();
68
+ obj.PerformAjaxEx(x[0], x[1], x[2], x[3], x[4]);
69
+ obj.PerformNextAjax();
70
+ }
71
+
72
+ // Private method
73
+ obj.PerformAjaxEx = function (postdata, callback, tag, url, action) {
74
+ if (obj.FailAllError != 0) { if (obj.FailAllError != 999) { obj.gotNextMessagesError({ status: obj.FailAllError }, 'error', null, [postdata, callback, tag]); } return; }
75
+ if (!postdata) postdata = "";
76
+ //console.log("SEND: " + postdata); // DEBUG
77
+
78
+ // We are in a DukTape environement
79
+ if (obj.digest == null)
80
+ {
81
+ if (obj.authToken)
82
+ {
83
+ obj.digest = require('http-digest').create({ authToken: obj.authToken });
84
+ }
85
+ else
86
+ {
87
+ obj.digest = require('http-digest').create(obj.user, obj.pass);
88
+ }
89
+ obj.digest.http = require('http');
90
+ }
91
+ var request = { protocol: (obj.tls == 1 ? 'https:' : 'http:'), method: 'POST', host: obj.host, path: '/wsman', port: obj.port, rejectUnauthorized: false, checkServerIdentity: function (cert) { console.log('checkServerIdentity', JSON.stringify(cert)); } };
92
+ var req = obj.digest.request(request);
93
+ req.reqid = obj.RequestCount++;
94
+ obj.requests[req.reqid] = req; // Keep a reference to the request object so it does not get disposed.
95
+ //console.log('Request ' + (obj.RequestCount++));
96
+ req.on('error', function (e) { delete obj.requests[this.reqid]; obj.gotNextMessagesError({ status: 600 }, 'error', null, [postdata, callback, tag]); });
97
+ req.on('response', function (response) {
98
+ response.reqid = this.reqid;
99
+ //console.log('Response: ' + response.statusCode);
100
+ if (response.statusCode != 200) {
101
+ //console.log('ERR:' + JSON.stringify(response));
102
+ obj.gotNextMessagesError({ status: response.statusCode }, 'error', null, [postdata, callback, tag]);
103
+ } else {
104
+ response.acc = '';
105
+ response.on('data', function (data2) { this.acc += data2; });
106
+ response.on('end', function () { delete obj.requests[this.reqid]; obj.gotNextMessages(response.acc, 'success', { status: response.statusCode }, [postdata, callback, tag]); });
107
+ }
108
+ });
109
+
110
+ // Send POST body, this work with binary.
111
+ req.end(postdata);
112
+ obj.ActiveAjaxCount++;
113
+ return req;
114
+ }
115
+
116
+ // AJAX specific private method
117
+ obj.pendingAjaxCall = [];
118
+
119
+ // Private method
120
+ obj.gotNextMessages = function (data, status, request, callArgs) {
121
+ obj.ActiveAjaxCount--;
122
+ if (obj.FailAllError == 999) return;
123
+ //console.log("RECV: " + data); // DEBUG
124
+ if (obj.FailAllError != 0) { callArgs[1](null, obj.FailAllError, callArgs[2]); return; }
125
+ if (request.status != 200) { callArgs[1](null, request.status, callArgs[2]); return; }
126
+ callArgs[1](data, 200, callArgs[2]);
127
+ obj.PerformNextAjax();
128
+ }
129
+
130
+ // Private method
131
+ obj.gotNextMessagesError = function (request, status, errorThrown, callArgs) {
132
+ obj.ActiveAjaxCount--;
133
+ if (obj.FailAllError == 999) return;
134
+ if (obj.FailAllError != 0) { callArgs[1](null, obj.FailAllError, callArgs[2]); return; }
135
+ //if (status != 200) { console.log("ERROR, status=" + status + "\r\n\r\nreq=" + callArgs[0]); } // Debug: Display the request & response if something did not work.
136
+ if (obj.FailAllError != 999) { callArgs[1]({ Header: { HttpError: request.status } }, request.status, callArgs[2]); }
137
+ obj.PerformNextAjax();
138
+ }
139
+
140
+ // Cancel all pending queries with given status
141
+ obj.CancelAllQueries = function (s) {
142
+ while (obj.PendingAjax.length > 0) { var x = obj.PendingAjax.shift(); x[1](null, s, x[2]); }
143
+ }
144
+
145
+ return obj;
146
+}
147
+
148
+module.exports = CreateWsmanComm;
agents/modules_meshcore_backup/amt-wsman.js
new
+211
@@ -0,0 +1,211 @@
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
+/**
18
+* @description Intel(r) AMT WSMAN Stack
19
+* @author Ylian Saint-Hilaire
20
+* @version v0.2.0
21
+*/
22
+
23
+// Construct a MeshServer object
24
+function WsmanStackCreateService(/*CreateWsmanComm, host, port, user, pass, tls, extra*/)
25
+{
26
+ var obj = {_ObjectID: 'WSMAN'};
27
+ //obj.onDebugMessage = null; // Set to a function if you want to get debug messages.
28
+ obj.NextMessageId = 1; // Next message number, used to label WSMAN calls.
29
+ obj.Address = '/wsman';
30
+ obj.xmlParser = require('amt-xml');
31
+
32
+ if (arguments.length == 1 && typeof (arguments[0] == 'object'))
33
+ {
34
+ var CreateWsmanComm = arguments[0].transport;
35
+ if (CreateWsmanComm) { obj.comm = new CreateWsmanComm(arguments[0]); }
36
+ }
37
+ else
38
+ {
39
+ var CreateWsmanComm = arguments[0];
40
+ if (CreateWsmanComm) { obj.comm = new CreateWsmanComm(arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6]); }
41
+ }
42
+
43
+ obj.PerformAjax = function PerformAjax(postdata, callback, tag, pri, namespaces) {
44
+ if (namespaces == null) namespaces = '';
45
+ obj.comm.PerformAjax('<?xml version=\"1.0\" encoding=\"utf-8\"?><Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns=\"http://www.w3.org/2003/05/soap-envelope\" ' + namespaces + '><Header><a:Action>' + postdata, function (data, status, tag) {
46
+ if (status != 200) { callback(obj, null, { Header: { HttpError: status } }, status, tag); return; }
47
+ var wsresponse = obj.xmlParser.ParseWsman(data);
48
+ if (!wsresponse || wsresponse == null) { callback(obj, null, { Header: { HttpError: status } }, 601, tag); } else { callback(obj, wsresponse.Header["ResourceURI"], wsresponse, 200, tag); }
49
+ }, tag, pri);
50
+ }
51
+
52
+ // Private method
53
+ //obj.Debug = function (msg) { /*console.log(msg);*/ }
54
+
55
+ // Cancel all pending queries with given status
56
+ obj.CancelAllQueries = function CancelAllQueries(s) { obj.comm.CancelAllQueries(s); }
57
+
58
+ // Get the last element of a URI string
59
+ obj.GetNameFromUrl = function (resuri) {
60
+ var x = resuri.lastIndexOf("/");
61
+ return (x == -1)?resuri:resuri.substring(x + 1);
62
+ }
63
+
64
+ // Perform a WSMAN Subscribe operation
65
+ obj.ExecSubscribe = function ExecSubscribe(resuri, delivery, url, callback, tag, pri, selectors, opaque, user, pass) {
66
+ var digest = "", digest2 = "", opaque = "";
67
+ if (user != null && pass != null) { digest = '<t:IssuedTokens xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust" xmlns:se="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><t:RequestSecurityTokenResponse><t:TokenType>http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#UsernameToken</t:TokenType><t:RequestedSecurityToken><se:UsernameToken><se:Username>' + user + '</se:Username><se:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd#PasswordText">' + pass + '</se:Password></se:UsernameToken></t:RequestedSecurityToken></t:RequestSecurityTokenResponse></t:IssuedTokens>'; digest2 = '<w:Auth Profile="http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/http/digest"/>'; }
68
+ if (opaque != null) { opaque = '<a:ReferenceParameters><m:arg>' + opaque + '</m:arg></a:ReferenceParameters>'; }
69
+ if (delivery == 'PushWithAck') { delivery = 'dmtf.org/wbem/wsman/1/wsman/PushWithAck'; } else if (delivery == 'Push') { delivery = 'xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push'; }
70
+ var data = "http://schemas.xmlsoap.org/ws/2004/08/eventing/Subscribe</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo>" + _PutObjToSelectorsXml(selectors) + digest + '</Header><Body><e:Subscribe><e:Delivery Mode="http://schemas.' + delivery + '"><e:NotifyTo><a:Address>' + url + '</a:Address>' + opaque + '</e:NotifyTo>' + digest2 + '</e:Delivery></e:Subscribe>';
71
+ obj.PerformAjax(data + "</Body></Envelope>", callback, tag, pri, 'xmlns:e="http://schemas.xmlsoap.org/ws/2004/08/eventing" xmlns:m="http://x.com"');
72
+ }
73
+
74
+ // Perform a WSMAN UnSubscribe operation
75
+ obj.ExecUnSubscribe = function ExecUnSubscribe(resuri, callback, tag, pri, selectors) {
76
+ var data = "http://schemas.xmlsoap.org/ws/2004/08/eventing/Unsubscribe</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo>" + _PutObjToSelectorsXml(selectors) + '</Header><Body><e:Unsubscribe/>';
77
+ obj.PerformAjax(data + "</Body></Envelope>", callback, tag, pri, 'xmlns:e="http://schemas.xmlsoap.org/ws/2004/08/eventing"');
78
+ }
79
+
80
+ // Perform a WSMAN PUT operation
81
+ obj.ExecPut = function ExecPut(resuri, putobj, callback, tag, pri, selectors) {
82
+ var data = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Put</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60.000S</w:OperationTimeout>" + _PutObjToSelectorsXml(selectors) + '</Header><Body>' + _PutObjToBodyXml(resuri, putobj);
83
+ obj.PerformAjax(data + "</Body></Envelope>", callback, tag, pri);
84
+ }
85
+
86
+ // Perform a WSMAN CREATE operation
87
+ obj.ExecCreate = function ExecCreate(resuri, putobj, callback, tag, pri, selectors) {
88
+ var objname = obj.GetNameFromUrl(resuri);
89
+ var data = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Create</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60S</w:OperationTimeout>" + _PutObjToSelectorsXml(selectors) + "</Header><Body><g:" + objname + " xmlns:g=\"" + resuri + "\">";
90
+ for (var n in putobj) { data += "<g:" + n + ">" + putobj[n] + "</g:" + n + ">" }
91
+ obj.PerformAjax(data + "</g:" + objname + "></Body></Envelope>", callback, tag, pri);
92
+ }
93
+
94
+ // Perform a WSMAN DELETE operation
95
+ obj.ExecDelete = function ExecDelete(resuri, putobj, callback, tag, pri) {
96
+ var data = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60S</w:OperationTimeout>" + _PutObjToSelectorsXml(putobj) + "</Header><Body /></Envelope>";
97
+ obj.PerformAjax(data, callback, tag, pri);
98
+ }
99
+
100
+ // Perform a WSMAN GET operation
101
+ obj.ExecGet = function ExecGet(resuri, callback, tag, pri) {
102
+ obj.PerformAjax("http://schemas.xmlsoap.org/ws/2004/09/transfer/Get</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60S</w:OperationTimeout></Header><Body /></Envelope>", callback, tag, pri);
103
+ }
104
+
105
+ // Perform a WSMAN method call operation
106
+ obj.ExecMethod = function ExecMethod(resuri, method, args, callback, tag, pri, selectors) {
107
+ var argsxml = "";
108
+ for (var i in args) { if (args[i] != null) { if (Array.isArray(args[i])) { for (var x in args[i]) { argsxml += "<r:" + i + ">" + args[i][x] + "</r:" + i + ">"; } } else { argsxml += "<r:" + i + ">" + args[i] + "</r:" + i + ">"; } } }
109
+ obj.ExecMethodXml(resuri, method, argsxml, callback, tag, pri, selectors);
110
+ }
111
+
112
+ // Perform a WSMAN method call operation. The arguments are already formatted in XML.
113
+ obj.ExecMethodXml = function ExecMethodXml(resuri, method, argsxml, callback, tag, pri, selectors) {
114
+ obj.PerformAjax(resuri + "/" + method + "</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60S</w:OperationTimeout>" + _PutObjToSelectorsXml(selectors) + "</Header><Body><r:" + method + '_INPUT' + " xmlns:r=\"" + resuri + "\">" + argsxml + "</r:" + method + "_INPUT></Body></Envelope>", callback, tag, pri);
115
+ }
116
+
117
+ // Perform a WSMAN ENUM operation
118
+ obj.ExecEnum = function ExecEnum(resuri, callback, tag, pri) {
119
+ obj.PerformAjax("http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60S</w:OperationTimeout></Header><Body><Enumerate xmlns=\"http://schemas.xmlsoap.org/ws/2004/09/enumeration\" /></Body></Envelope>", callback, tag, pri);
120
+ }
121
+
122
+ // Perform a WSMAN PULL operation
123
+ obj.ExecPull = function ExecPull(resuri, enumctx, callback, tag, pri) {
124
+ obj.PerformAjax("http://schemas.xmlsoap.org/ws/2004/09/enumeration/Pull</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60S</w:OperationTimeout></Header><Body><Pull xmlns=\"http://schemas.xmlsoap.org/ws/2004/09/enumeration\"><EnumerationContext>" + enumctx + "</EnumerationContext><MaxElements>999</MaxElements><MaxCharacters>99999</MaxCharacters></Pull></Body></Envelope>", callback, tag, pri);
125
+ }
126
+
127
+ function _PutObjToBodyXml(resuri, putObj) {
128
+ if (!resuri || putObj == null) return '';
129
+ var objname = obj.GetNameFromUrl(resuri);
130
+ var result = '<r:' + objname + ' xmlns:r="' + resuri + '">';
131
+
132
+ for (var prop in putObj) {
133
+ if (!putObj.hasOwnProperty(prop) || prop.indexOf('__') === 0 || prop.indexOf('@') === 0) continue;
134
+ if (putObj[prop] == null || typeof putObj[prop] === 'function') continue;
135
+ if (typeof putObj[prop] === 'object' && putObj[prop]['ReferenceParameters']) {
136
+ result += '<r:' + prop + '><a:Address>' + putObj[prop].Address + '</a:Address><a:ReferenceParameters><w:ResourceURI>' + putObj[prop]['ReferenceParameters']["ResourceURI"] + '</w:ResourceURI><w:SelectorSet>';
137
+ var selectorArray = putObj[prop]['ReferenceParameters']['SelectorSet']['Selector'];
138
+ if (Array.isArray(selectorArray)) {
139
+ for (var i=0; i< selectorArray.length; i++) {
140
+ result += '<w:Selector' + _ObjectToXmlAttributes(selectorArray[i]) + '>' + selectorArray[i]['Value'] + '</w:Selector>';
141
+ }
142
+ }
143
+ else {
144
+ result += '<w:Selector' + _ObjectToXmlAttributes(selectorArray) + '>' + selectorArray['Value'] + '</w:Selector>';
145
+ }
146
+ result += '</w:SelectorSet></a:ReferenceParameters></r:' + prop + '>';
147
+ }
148
+ else {
149
+ if (Array.isArray(putObj[prop])) {
150
+ for (var i = 0; i < putObj[prop].length; i++) {
151
+ result += '<r:' + prop + '>' + putObj[prop][i].toString() + '</r:' + prop + '>';
152
+ }
153
+ } else {
154
+ result += '<r:' + prop + '>' + putObj[prop].toString() + '</r:' + prop + '>';
155
+ }
156
+ }
157
+ }
158
+
159
+ result += '</r:' + objname + '>';
160
+ return result;
161
+ }
162
+
163
+ /*
164
+ convert
165
+ { @Name: 'InstanceID', @AttrName: 'Attribute Value'}
166
+ into
167
+ ' Name="InstanceID" AttrName="Attribute Value" '
168
+ */
169
+ function _ObjectToXmlAttributes(objWithAttributes) {
170
+ if(!objWithAttributes) return '';
171
+ var result = ' ';
172
+ for (var propName in objWithAttributes) {
173
+ if (!objWithAttributes.hasOwnProperty(propName) || propName.indexOf('@') !== 0) continue;
174
+ result += propName.substring(1) + '="' + objWithAttributes[propName] + '" ';
175
+ }
176
+ return result;
177
+ }
178
+
179
+ function _PutObjToSelectorsXml(selectorSet) {
180
+ if (!selectorSet) return '';
181
+ if (typeof selectorSet == 'string') return selectorSet;
182
+ if (selectorSet['InstanceID']) return "<w:SelectorSet><w:Selector Name=\"InstanceID\">" + selectorSet['InstanceID'] + "</w:Selector></w:SelectorSet>";
183
+ var result = '<w:SelectorSet>';
184
+ for(var propName in selectorSet) {
185
+ if (!selectorSet.hasOwnProperty(propName)) continue;
186
+ result += '<w:Selector Name="' + propName + '">';
187
+ if (selectorSet[propName]['ReferenceParameters']) {
188
+ result += '<a:EndpointReference>';
189
+ result += '<a:Address>' + selectorSet[propName]['Address'] + '</a:Address><a:ReferenceParameters><w:ResourceURI>' + selectorSet[propName]['ReferenceParameters']['ResourceURI'] + '</w:ResourceURI><w:SelectorSet>';
190
+ var selectorArray = selectorSet[propName]['ReferenceParameters']['SelectorSet']['Selector'];
191
+ if (Array.isArray(selectorArray)) {
192
+ for (var i = 0; i < selectorArray.length; i++) {
193
+ result += '<w:Selector' + _ObjectToXmlAttributes(selectorArray[i]) + '>' + selectorArray[i]['Value'] + '</w:Selector>';
194
+ }
195
+ } else {
196
+ result += '<w:Selector' + _ObjectToXmlAttributes(selectorArray) + '>' + selectorArray['Value'] + '</w:Selector>';
197
+ }
198
+ result += '</w:SelectorSet></a:ReferenceParameters></a:EndpointReference>';
199
+ } else {
200
+ result += selectorSet[propName];
201
+ }
202
+ result += '</w:Selector>';
203
+ }
204
+ result += '</w:SelectorSet>';
205
+ return result;
206
+ }
207
+
208
+ return obj;
209
+}
210
+
211
+module.exports = WsmanStackCreateService;
agents/modules_meshcore_backup/amt-xml.js
new
+183
@@ -0,0 +1,183 @@
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
+// Parse XML and return JSON
18
+module.exports.ParseWsman = function (xml) {
19
+ try {
20
+ if (!xml.childNodes) xml = _turnToXml(xml);
21
+ var r = { Header: {} }, header = xml.getElementsByTagName("Header")[0], t;
22
+ if (!header) header = xml.getElementsByTagName("a:Header")[0];
23
+ if (!header) return null;
24
+ for (var i = 0; i < header.childNodes.length; i++) {
25
+ var child = header.childNodes[i];
26
+ r.Header[child.localName] = child.textContent;
27
+ }
28
+ var body = xml.getElementsByTagName("Body")[0];
29
+ if (!body) body = xml.getElementsByTagName("a:Body")[0];
30
+ if (!body) return null;
31
+ if (body.childNodes.length > 0) {
32
+ t = body.childNodes[0].localName;
33
+ if (t.indexOf("_OUTPUT") == t.length - 7) { t = t.substring(0, t.length - 7); }
34
+ r.Header['Method'] = t;
35
+ r.Body = _ParseWsmanRec(body.childNodes[0]);
36
+ }
37
+ return r;
38
+ } catch (e) {
39
+ console.log("Unable to parse XML: " + xml);
40
+ return null;
41
+ }
42
+}
43
+
44
+// Private method
45
+function _ParseWsmanRec(node) {
46
+ var data, r = {};
47
+ for (var i = 0; i < node.childNodes.length; i++) {
48
+ var child = node.childNodes[i];
49
+ if ((child.childElementCount == null) || (child.childElementCount == 0)) { data = child.textContent; } else { data = _ParseWsmanRec(child); }
50
+ if (data == 'true') data = true; // Convert 'true' into true
51
+ if (data == 'false') data = false; // Convert 'false' into false
52
+ if ((parseInt(data) + '') === data) data = parseInt(data); // Convert integers
53
+
54
+ var childObj = data;
55
+ if ((child.attributes != null) && (child.attributes.length > 0)) {
56
+ childObj = { 'Value': data };
57
+ for (var j = 0; j < child.attributes.length; j++) {
58
+ childObj['@' + child.attributes[j].name] = child.attributes[j].value;
59
+ }
60
+ }
61
+
62
+ if (r[child.localName] instanceof Array) { r[child.localName].push(childObj); }
63
+ else if (r[child.localName] == null) { r[child.localName] = childObj; }
64
+ else { r[child.localName] = [r[child.localName], childObj]; }
65
+ }
66
+ return r;
67
+}
68
+
69
+function _PutObjToBodyXml(resuri, putObj) {
70
+ if (!resuri || putObj == null) return '';
71
+ var objname = obj.GetNameFromUrl(resuri);
72
+ var result = '<r:' + objname + ' xmlns:r="' + resuri + '">';
73
+
74
+ for (var prop in putObj) {
75
+ if (!putObj.hasOwnProperty(prop) || prop.indexOf('__') === 0 || prop.indexOf('@') === 0) continue;
76
+ if (putObj[prop] == null || typeof putObj[prop] === 'function') continue;
77
+ if (typeof putObj[prop] === 'object' && putObj[prop]['ReferenceParameters']) {
78
+ result += '<r:' + prop + '><a:Address>' + putObj[prop].Address + '</a:Address><a:ReferenceParameters><w:ResourceURI>' + putObj[prop]['ReferenceParameters']["ResourceURI"] + '</w:ResourceURI><w:SelectorSet>';
79
+ var selectorArray = putObj[prop]['ReferenceParameters']['SelectorSet']['Selector'];
80
+ if (Array.isArray(selectorArray)) {
81
+ for (var i = 0; i < selectorArray.length; i++) {
82
+ result += '<w:Selector' + _ObjectToXmlAttributes(selectorArray[i]) + '>' + selectorArray[i]['Value'] + '</w:Selector>';
83
+ }
84
+ }
85
+ else {
86
+ result += '<w:Selector' + _ObjectToXmlAttributes(selectorArray) + '>' + selectorArray['Value'] + '</w:Selector>';
87
+ }
88
+ result += '</w:SelectorSet></a:ReferenceParameters></r:' + prop + '>';
89
+ }
90
+ else {
91
+ if (Array.isArray(putObj[prop])) {
92
+ for (var i = 0; i < putObj[prop].length; i++) {
93
+ result += '<r:' + prop + '>' + putObj[prop][i].toString() + '</r:' + prop + '>';
94
+ }
95
+ } else {
96
+ result += '<r:' + prop + '>' + putObj[prop].toString() + '</r:' + prop + '>';
97
+ }
98
+ }
99
+ }
100
+
101
+ result += '</r:' + objname + '>';
102
+ return result;
103
+}
104
+
105
+// This is a drop-in replacement to _turnToXml() that works without xml parser dependency.
106
+try { Object.defineProperty(Array.prototype, "peek", { value: function () { return (this.length > 0 ? this[this.length - 1] : null); } }); } catch (ex) { }
107
+function _treeBuilder() {
108
+ this.tree = [];
109
+ this.push = function (element) { this.tree.push(element); };
110
+ this.pop = function () { var element = this.tree.pop(); if (this.tree.length > 0) { var x = this.tree.peek(); x.childNodes.push(element); x.childElementCount = x.childNodes.length; } return (element); };
111
+ this.peek = function () { return (this.tree.peek()); }
112
+ this.addNamespace = function (prefix, namespace) { this.tree.peek().nsTable[prefix] = namespace; if (this.tree.peek().attributes.length > 0) { for (var i = 0; i < this.tree.peek().attributes; ++i) { var a = this.tree.peek().attributes[i]; if (prefix == '*' && a.name == a.localName) { a.namespace = namespace; } else if (prefix != '*' && a.name != a.localName) { var pfx = a.name.split(':')[0]; if (pfx == prefix) { a.namespace = namespace; } } } } }
113
+ this.getNamespace = function (prefix) { for (var i = this.tree.length - 1; i >= 0; --i) { if (this.tree[i].nsTable[prefix] != null) { return (this.tree[i].nsTable[prefix]); } } return null; }
114
+}
115
+function _turnToXml(text) { if (text == null) return null; return ({ childNodes: [_turnToXmlRec(text)], getElementsByTagName: _getElementsByTagName, getChildElementsByTagName: _getChildElementsByTagName, getElementsByTagNameNS: _getElementsByTagNameNS }); }
116
+function _getElementsByTagNameNS(ns, name) { var ret = []; _xmlTraverseAllRec(this.childNodes, function (node) { if (node.localName == name && (node.namespace == ns || ns == '*')) { ret.push(node); } }); return ret; }
117
+function _getElementsByTagName(name) { var ret = []; _xmlTraverseAllRec(this.childNodes, function (node) { if (node.localName == name) { ret.push(node); } }); return ret; }
118
+function _getChildElementsByTagName(name) { var ret = []; if (this.childNodes != null) { for (var node in this.childNodes) { if (this.childNodes[node].localName == name) { ret.push(this.childNodes[node]); } } } return (ret); }
119
+function _getChildElementsByTagNameNS(ns, name) { var ret = []; if (this.childNodes != null) { for (var node in this.childNodes) { if (this.childNodes[node].localName == name && (ns == '*' || this.childNodes[node].namespace == ns)) { ret.push(this.childNodes[node]); } } } return (ret); }
120
+function _xmlTraverseAllRec(nodes, func) { for (var i in nodes) { func(nodes[i]); if (nodes[i].childNodes) { _xmlTraverseAllRec(nodes[i].childNodes, func); } } }
121
+function _turnToXmlRec(text) {
122
+ var elementStack = new _treeBuilder(), lastElement = null, x1 = text.split('<'), ret = [], element = null, currentElementName = null;
123
+ for (var i in x1) {
124
+ var x2 = x1[i].split('>'), x3 = x2[0].split(' '), elementName = x3[0];
125
+ if ((elementName.length > 0) && (elementName[0] != '?')) {
126
+ if (elementName[0] != '/') {
127
+ var attributes = [], localName, localname2 = elementName.split(' ')[0].split(':'), localName = (localname2.length > 1) ? localname2[1] : localname2[0];
128
+ Object.defineProperty(attributes, "get",
129
+ {
130
+ value: function () {
131
+ if (arguments.length == 1) {
132
+ for (var a in this) { if (this[a].name == arguments[0]) { return (this[a]); } }
133
+ }
134
+ else if (arguments.length == 2) {
135
+ for (var a in this) { if (this[a].name == arguments[1] && (arguments[0] == '*' || this[a].namespace == arguments[0])) { return (this[a]); } }
136
+ }
137
+ else {
138
+ throw ('attributes.get(): Invalid number of parameters');
139
+ }
140
+ }
141
+ });
142
+ elementStack.push({ name: elementName, localName: localName, getChildElementsByTagName: _getChildElementsByTagName, getElementsByTagNameNS: _getElementsByTagNameNS, getChildElementsByTagNameNS: _getChildElementsByTagNameNS, attributes: attributes, childNodes: [], nsTable: {} });
143
+ // Parse Attributes
144
+ if (x3.length > 0) {
145
+ var skip = false;
146
+ for (var j in x3) {
147
+ if (x3[j] == '/') {
148
+ // This is an empty Element
149
+ elementStack.peek().namespace = elementStack.peek().name == elementStack.peek().localName ? elementStack.getNamespace('*') : elementStack.getNamespace(elementStack.peek().name.substring(0, elementStack.peek().name.indexOf(':')));
150
+ elementStack.peek().textContent = '';
151
+ lastElement = elementStack.pop();
152
+ skip = true;
153
+ break;
154
+ }
155
+ var k = x3[j].indexOf('=');
156
+ if (k > 0) {
157
+ var attrName = x3[j].substring(0, k);
158
+ var attrValue = x3[j].substring(k + 2, x3[j].length - 1);
159
+ var attrNS = elementStack.getNamespace('*');
160
+
161
+ if (attrName == 'xmlns') {
162
+ elementStack.addNamespace('*', attrValue);
163
+ attrNS = attrValue;
164
+ } else if (attrName.startsWith('xmlns:')) {
165
+ elementStack.addNamespace(attrName.substring(6), attrValue);
166
+ } else {
167
+ var ax = attrName.split(':');
168
+ if (ax.length == 2) { attrName = ax[1]; attrNS = elementStack.getNamespace(ax[0]); }
169
+ }
170
+ var x = { name: attrName, value: attrValue }
171
+ if (attrNS != null) x.namespace = attrNS;
172
+ elementStack.peek().attributes.push(x);
173
+ }
174
+ }
175
+ if (skip) { continue; }
176
+ }
177
+ elementStack.peek().namespace = elementStack.peek().name == elementStack.peek().localName ? elementStack.getNamespace('*') : elementStack.getNamespace(elementStack.peek().name.substring(0, elementStack.peek().name.indexOf(':')));
178
+ if (x2[1]) { elementStack.peek().textContent = x2[1]; }
179
+ } else { lastElement = elementStack.pop(); }
180
+ }
181
+ }
182
+ return lastElement;
183
+}
agents/modules_meshcore_backup/amt.js
new
+1019
@@ -0,0 +1,1019 @@
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
+/**
18
+* @fileoverview Intel(r) AMT Communication StackXX
19
+* @author Ylian Saint-Hilaire
20
+* @version v0.2.0b
21
+*/
22
+
23
+/**
24
+ * Construct a AmtStackCreateService object, this ia the main Intel AMT communication stack.
25
+ * @constructor
26
+ */
27
+function AmtStackCreateService(wsmanStack) {
28
+ var obj = new Object();
29
+ obj._ObjectID = 'AMT'
30
+ obj.wsman = wsmanStack;
31
+ obj.pfx = ["http://intel.com/wbem/wscim/1/amt-schema/1/", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/", "http://intel.com/wbem/wscim/1/ips-schema/1/"];
32
+ obj.PendingEnums = [];
33
+ obj.PendingBatchOperations = 0;
34
+ obj.ActiveEnumsCount = 0;
35
+ obj.MaxActiveEnumsCount = 1; // Maximum number of enumerations that can be done at the same time.
36
+ obj.onProcessChanged = null;
37
+ var _MaxProcess = 0;
38
+ var _LastProcess = 0;
39
+
40
+ // Return the number of pending actions
41
+ obj.GetPendingActions = function () { return (obj.PendingEnums.length * 2) + (obj.ActiveEnumsCount) + obj.wsman.comm.PendingAjax.length + obj.wsman.comm.ActiveAjaxCount + obj.PendingBatchOperations; }
42
+
43
+ // Private Method, Update the current processing status, this gives the application an idea of what progress is being done by the WSMAN stack
44
+ function _up() {
45
+ var x = obj.GetPendingActions();
46
+ if (_MaxProcess < x) _MaxProcess = x;
47
+ if (obj.onProcessChanged != null && _LastProcess != x) {
48
+ //console.log("Process Old=" + _LastProcess + ", New=" + x + ", PEnums=" + obj.PendingEnums.length + ", AEnums=" + obj.ActiveEnumsCount + ", PAjax=" + obj.wsman.comm.PendingAjax.length + ", AAjax=" + obj.wsman.comm.ActiveAjaxCount + ", PBatch=" + obj.PendingBatchOperations);
49
+ _LastProcess = x;
50
+ obj.onProcessChanged(x, _MaxProcess);
51
+ }
52
+ if (x == 0) _MaxProcess = 0;
53
+ }
54
+
55
+ // Perform a WSMAN "SUBSCRIBE" operation.
56
+ obj.Subscribe = function Subscribe(name, delivery, url, callback, tag, pri, selectors, opaque, user, pass) { obj.wsman.ExecSubscribe(obj.CompleteName(name), delivery, url, function (ws, resuri, response, xstatus) { _up(); callback.call(obj, obj, name, response, xstatus, tag); }, 0, pri, selectors, opaque, user, pass); _up(); }
57
+
58
+ // Perform a WSMAN "UNSUBSCRIBE" operation.
59
+ obj.UnSubscribe = function UnSubscribe(name, callback, tag, pri, selectors) { obj.wsman.ExecUnSubscribe(obj.CompleteName(name), function (ws, resuri, response, xstatus) { _up(); callback.call(obj, obj, name, response, xstatus, tag); }, 0, pri, selectors); _up(); }
60
+
61
+ // Perform a WSMAN "GET" operation.
62
+ obj.Get = function Get(name, callback, tag, pri) { obj.wsman.ExecGet(obj.CompleteName(name), function (ws, resuri, response, xstatus) { _up(); callback.call(obj, obj, name, response, xstatus, tag); }, 0, pri); _up(); }
63
+
64
+ // Perform a WSMAN "PUT" operation.
65
+ obj.Put = function Put(name, putobj, callback, tag, pri, selectors) { obj.wsman.ExecPut(obj.CompleteName(name), putobj, function (ws, resuri, response, xstatus) { _up(); callback.call(obj, obj, name, response, xstatus, tag); }, 0, pri, selectors); _up(); }
66
+
67
+ // Perform a WSMAN "CREATE" operation.
68
+ obj.Create = function Create(name, putobj, callback, tag, pri) { obj.wsman.ExecCreate(obj.CompleteName(name), putobj, function (ws, resuri, response, xstatus) { _up(); callback.call(obj, obj, name, response, xstatus, tag); }, 0, pri); _up(); }
69
+
70
+ // Perform a WSMAN "DELETE" operation.
71
+ obj.Delete = function Delete(name, putobj, callback, tag, pri) { obj.wsman.ExecDelete(obj.CompleteName(name), putobj, function (ws, resuri, response, xstatus) { _up(); callback.call(obj, obj, name, response, xstatus, tag); }, 0, pri); _up(); }
72
+
73
+ // Perform a WSMAN method call operation.
74
+ obj.Exec = function Exec(name, method, args, callback, tag, pri, selectors) { obj.wsman.ExecMethod(obj.CompleteName(name), method, args, function (ws, resuri, response, xstatus) { _up(); callback.call(obj, obj, name, obj.CompleteExecResponse(response), xstatus, tag); }, 0, pri, selectors); _up(); }
75
+
76
+ // Perform a WSMAN method call operation.
77
+ obj.ExecWithXml = function ExecWithXml(name, method, args, callback, tag, pri, selectors) { obj.wsman.ExecMethodXml(obj.CompleteName(name), method, execArgumentsToXml(args), function (ws, resuri, response, xstatus) { _up(); callback.call(obj, obj, name, obj.CompleteExecResponse(response), xstatus, tag); }, 0, pri, selectors); _up(); }
78
+
79
+ // Perform a WSMAN "ENUMERATE" operation.
80
+ obj.Enum = function Enum(name, callback, tag, pri) {
81
+ if (obj.ActiveEnumsCount < obj.MaxActiveEnumsCount) {
82
+ obj.ActiveEnumsCount++; obj.wsman.ExecEnum(obj.CompleteName(name), function (ws, resuri, response, xstatus, tag0) { _up(); _EnumStartSink(name, response, callback, resuri, xstatus, tag0); }, tag, pri);
83
+ } else {
84
+ obj.PendingEnums.push([name, callback, tag, pri]);
85
+ }
86
+ _up();
87
+ }
88
+
89
+ // Private method
90
+ function _EnumStartSink(name, response, callback, resuri, status, tag, pri) {
91
+ if (status != 200) { callback.call(obj, obj, name, null, status, tag); _EnumDoNext(1); return; }
92
+ if (response == null || response.Header["Method"] != "EnumerateResponse" || !response.Body["EnumerationContext"]) { callback.call(obj, obj, name, null, 603, tag); _EnumDoNext(1); return; }
93
+ var enumctx = response.Body["EnumerationContext"];
94
+ obj.wsman.ExecPull(resuri, enumctx, function (ws, resuri, response, xstatus) { _EnumContinueSink(name, response, callback, resuri, [], xstatus, tag, pri); });
95
+ }
96
+
97
+ // Private method
98
+ function _EnumContinueSink(name, response, callback, resuri, items, status, tag, pri) {
99
+ if (status != 200) { callback.call(obj, obj, name, null, status, tag); _EnumDoNext(1); return; }
100
+ if (response == null || response.Header["Method"] != "PullResponse") { callback.call(obj, obj, name, null, 604, tag); _EnumDoNext(1); return; }
101
+ for (var i in response.Body["Items"]) {
102
+ if (response.Body["Items"][i] instanceof Array) {
103
+ for (var j in response.Body["Items"][i]) { items.push(response.Body["Items"][i][j]); }
104
+ } else {
105
+ items.push(response.Body["Items"][i]);
106
+ }
107
+ }
108
+ if (response.Body["EnumerationContext"]) {
109
+ var enumctx = response.Body["EnumerationContext"];
110
+ obj.wsman.ExecPull(resuri, enumctx, function (ws, resuri, response, xstatus) { _EnumContinueSink(name, response, callback, resuri, items, xstatus, tag, 1); });
111
+ } else {
112
+ _EnumDoNext(1);
113
+ callback.call(obj, obj, name, items, status, tag);
114
+ _up();
115
+ }
116
+ }
117
+
118
+ // Private method
119
+ function _EnumDoNext(dec) {
120
+ obj.ActiveEnumsCount -= dec;
121
+ if (obj.ActiveEnumsCount >= obj.MaxActiveEnumsCount || obj.PendingEnums.length == 0) return;
122
+ var x = obj.PendingEnums.shift();
123
+ obj.Enum(x[0], x[1], x[2]);
124
+ _EnumDoNext(0);
125
+ }
126
+
127
+ // Perform a batch of WSMAN "ENUM" operations.
128
+ obj.BatchEnum = function (batchname, names, callback, tag, continueOnError, pri) {
129
+ obj.PendingBatchOperations += (names.length * 2);
130
+ _BatchNextEnum(batchname, Clone(names), callback, tag, {}, continueOnError, pri); _up();
131
+ }
132
+
133
+ function Clone(v) { return JSON.parse(JSON.stringify(v)); }
134
+
135
+ // Request each enum in the batch, stopping if something does not return status 200
136
+ function _BatchNextEnum(batchname, names, callback, tag, results, continueOnError, pri) {
137
+ obj.PendingBatchOperations -= 2;
138
+ var n = names.shift(), f = obj.Enum;
139
+ if (n[0] == '*') { f = obj.Get; n = n.substring(1); } // If the name starts with a star, do a GET instead of an ENUM. This will reduce round trips.
140
+ //console.log((f == obj.Get?'Get ':'Enum ') + n);
141
+ // Perform a GET/ENUM action
142
+ f(n, function (stack, name, responses, status, tag0) {
143
+ tag0[2][name] = { response: (responses==null?null:responses.Body), responses: responses, status: status };
144
+ if (tag0[1].length == 0 || status == 401 || (continueOnError != true && status != 200 && status != 400)) { obj.PendingBatchOperations -= (names.length * 2); _up(); callback.call(obj, obj, batchname, tag0[2], status, tag); }
145
+ else { _up(); _BatchNextEnum(batchname, names, callback, tag, tag0[2], pri); }
146
+ }, [batchname, names, results], pri);
147
+ _up();
148
+ }
149
+
150
+ // Perform a batch of WSMAN "GET" operations.
151
+ obj.BatchGet = function (batchname, names, callback, tag, pri) {
152
+ _FetchNext({ name: batchname, names: names, callback: callback, current: 0, responses: {}, tag: tag, pri: pri }); _up();
153
+ }
154
+
155
+ // Private method
156
+ function _FetchNext(batch) {
157
+ if (batch.names.length <= batch.current) {
158
+ batch.callback.call(obj, obj, batch.name, batch.responses, 200, batch.tag);
159
+ } else {
160
+ obj.wsman.ExecGet(obj.CompleteName(batch.names[batch.current]), function (ws, resuri, response, xstatus) { _Fetched(batch, response, xstatus); }, batch.pri);
161
+ batch.current++;
162
+ }
163
+ _up();
164
+ }
165
+
166
+ // Private method
167
+ function _Fetched(batch, response, status) {
168
+ if (response == null || status != 200) {
169
+ batch.callback.call(obj, obj, batch.name, null, status, batch.tag);
170
+ } else {
171
+ batch.responses[response.Header["Method"]] = response;
172
+ _FetchNext(batch);
173
+ }
174
+ }
175
+
176
+ // Private method
177
+ obj.CompleteName = function(name) {
178
+ if (name.indexOf("AMT_") == 0) return obj.pfx[0] + name;
179
+ if (name.indexOf("CIM_") == 0) return obj.pfx[1] + name;
180
+ if (name.indexOf("IPS_") == 0) return obj.pfx[2] + name;
181
+ }
182
+
183
+ obj.CompleteExecResponse = function (resp) {
184
+ if (resp && resp != null && resp.Body && (resp.Body["ReturnValue"] != undefined)) { resp.Body.ReturnValueStr = obj.AmtStatusToStr(resp.Body["ReturnValue"]); }
185
+ return resp;
186
+ }
187
+
188
+ obj.RequestPowerStateChange = function (PowerState, callback_func) {
189
+ obj.CIM_PowerManagementService_RequestPowerStateChange(PowerState, "<Address xmlns=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\">http://schemas.xmlsoap.org/ws/2004/08/addressing</Address><ReferenceParameters xmlns=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"><ResourceURI xmlns=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ComputerSystem</ResourceURI><SelectorSet xmlns=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\"><Selector Name=\"CreationClassName\">CIM_ComputerSystem</Selector><Selector Name=\"Name\">ManagedSystem</Selector></SelectorSet></ReferenceParameters>", null, null, callback_func);
190
+ }
191
+
192
+ obj.SetBootConfigRole = function (Role, callback_func) {
193
+ obj.CIM_BootService_SetBootConfigRole("<Address xmlns=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\">http://schemas.xmlsoap.org/ws/2004/08/addressing</Address><ReferenceParameters xmlns=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"><ResourceURI xmlns=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting</ResourceURI><SelectorSet xmlns=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\"><Selector Name=\"InstanceID\">Intel(r) AMT: Boot Configuration 0</Selector></SelectorSet></ReferenceParameters>", Role, callback_func);
194
+ }
195
+
196
+ // Cancel all pending queries with given status
197
+ obj.CancelAllQueries = function (s) {
198
+ obj.wsman.CancelAllQueries(s);
199
+ }
200
+
201
+ // Auto generated methods
202
+ obj.AMT_AgentPresenceWatchdog_RegisterAgent = function (callback_func, tag, pri, selectors) { obj.Exec("AMT_AgentPresenceWatchdog", "RegisterAgent", {}, callback_func, tag, pri, selectors); }
203
+ obj.AMT_AgentPresenceWatchdog_AssertPresence = function (SequenceNumber, callback_func, tag, pri, selectors) { obj.Exec("AMT_AgentPresenceWatchdog", "AssertPresence", { "SequenceNumber": SequenceNumber }, callback_func, tag, pri, selectors); }
204
+ obj.AMT_AgentPresenceWatchdog_AssertShutdown = function (SequenceNumber, callback_func, tag, pri, selectors) { obj.Exec("AMT_AgentPresenceWatchdog", "AssertShutdown", { "SequenceNumber": SequenceNumber }, callback_func, tag, pri, selectors); }
205
+ //obj.AMT_AgentPresenceWatchdog_RegisterAgent = function (callback_func) { obj.Exec("AMT_AgentPresenceWatchdog", "RegisterAgent", {}, callback_func); }
206
+ //obj.AMT_AgentPresenceWatchdog_AssertPresence = function (SequenceNumber, callback_func) { obj.Exec("AMT_AgentPresenceWatchdog", "AssertPresence", { "SequenceNumber": SequenceNumber }, callback_func); }
207
+ //obj.AMT_AgentPresenceWatchdog_AssertShutdown = function (SequenceNumber, callback_func) { obj.Exec("AMT_AgentPresenceWatchdog", "AssertShutdown", { "SequenceNumber": SequenceNumber }, callback_func); }
208
+ obj.AMT_AgentPresenceWatchdog_AddAction = function (OldState, NewState, EventOnTransition, ActionSd, ActionEac, callback_func, tag, pri, selectors) { obj.Exec("AMT_AgentPresenceWatchdog", "AddAction", { "OldState": OldState, "NewState": NewState, "EventOnTransition": EventOnTransition, "ActionSd": ActionSd, "ActionEac": ActionEac }, callback_func, tag, pri, selectors); }
209
+ obj.AMT_AgentPresenceWatchdog_DeleteAllActions = function (callback_func, tag, pri, selectors) { obj.Exec("AMT_AgentPresenceWatchdog", "DeleteAllActions", {}, callback_func, tag, pri, selectors); }
210
+ obj.AMT_AgentPresenceWatchdogAction_GetActionEac = function (callback_func) { obj.Exec("AMT_AgentPresenceWatchdogAction", "GetActionEac", {}, callback_func); }
211
+ obj.AMT_AgentPresenceWatchdogVA_RegisterAgent = function (callback_func) { obj.Exec("AMT_AgentPresenceWatchdogVA", "RegisterAgent", {}, callback_func); }
212
+ obj.AMT_AgentPresenceWatchdogVA_AssertPresence = function (SequenceNumber, callback_func) { obj.Exec("AMT_AgentPresenceWatchdogVA", "AssertPresence", { "SequenceNumber": SequenceNumber }, callback_func); }
213
+ obj.AMT_AgentPresenceWatchdogVA_AssertShutdown = function (SequenceNumber, callback_func) { obj.Exec("AMT_AgentPresenceWatchdogVA", "AssertShutdown", { "SequenceNumber": SequenceNumber }, callback_func); }
214
+ obj.AMT_AgentPresenceWatchdogVA_AddAction = function (OldState, NewState, EventOnTransition, ActionSd, ActionEac, callback_func) { obj.Exec("AMT_AgentPresenceWatchdogVA", "AddAction", { "OldState": OldState, "NewState": NewState, "EventOnTransition": EventOnTransition, "ActionSd": ActionSd, "ActionEac": ActionEac }, callback_func); }
215
+ obj.AMT_AgentPresenceWatchdogVA_DeleteAllActions = function (_method_dummy, callback_func) { obj.Exec("AMT_AgentPresenceWatchdogVA", "DeleteAllActions", { "_method_dummy": _method_dummy }, callback_func); }
216
+ obj.AMT_AlarmClockService_AddAlarm = function AlarmClockService_AddAlarm(alarmInstance, callback_func)
217
+ {
218
+ var id = alarmInstance.InstanceID;
219
+ var nm = alarmInstance.ElementName;
220
+ var start = alarmInstance.StartTime.Datetime;
221
+ var interval = alarmInstance.Interval ? alarmInstance.Interval.Datetime : undefined;
222
+ var doc = alarmInstance.DeleteOnCompletion;
223
+ var tpl = "<d:AlarmTemplate xmlns:d=\"http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AlarmClockService\" xmlns:s=\"http://intel.com/wbem/wscim/1/ips-schema/1/IPS_AlarmClockOccurrence\"><s:InstanceID>" + id + "</s:InstanceID><s:ElementName>" + nm + "</s:ElementName><s:StartTime><p:Datetime xmlns:p=\"http://schemas.dmtf.org/wbem/wscim/1/common\">" + start + "</p:Datetime></s:StartTime>" + ((interval!=undefined)?("<s:Interval><p:Interval xmlns:p=\"http://schemas.dmtf.org/wbem/wscim/1/common\">" + interval + "</p:Interval></s:Interval>"):"") + "<s:DeleteOnCompletion>" + doc + "</s:DeleteOnCompletion></d:AlarmTemplate>"
224
+ obj.wsman.ExecMethodXml(obj.CompleteName("AMT_AlarmClockService"), "AddAlarm", tpl, callback_func);
225
+ };
226
+ obj.AMT_AuditLog_ClearLog = function (callback_func) { obj.Exec("AMT_AuditLog", "ClearLog", {}, callback_func); }
227
+ obj.AMT_AuditLog_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("AMT_AuditLog", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
228
+ obj.AMT_AuditLog_ReadRecords = function (StartIndex, callback_func, tag) { obj.Exec("AMT_AuditLog", "ReadRecords", { "StartIndex": StartIndex }, callback_func, tag); }
229
+ obj.AMT_AuditLog_SetAuditLock = function (LockTimeoutInSeconds, Flag, Handle, callback_func) { obj.Exec("AMT_AuditLog", "SetAuditLock", { "LockTimeoutInSeconds": LockTimeoutInSeconds, "Flag": Flag, "Handle": Handle }, callback_func); }
230
+ obj.AMT_AuditLog_ExportAuditLogSignature = function (SigningMechanism, callback_func) { obj.Exec("AMT_AuditLog", "ExportAuditLogSignature", { "SigningMechanism": SigningMechanism }, callback_func); }
231
+ obj.AMT_AuditLog_SetSigningKeyMaterial = function (SigningMechanismType, SigningKey, LengthOfCertificates, Certificates, callback_func) { obj.Exec("AMT_AuditLog", "SetSigningKeyMaterial", { "SigningMechanismType": SigningMechanismType, "SigningKey": SigningKey, "LengthOfCertificates": LengthOfCertificates, "Certificates": Certificates }, callback_func); }
232
+ obj.AMT_AuditPolicyRule_SetAuditPolicy = function (Enable, AuditedAppID, EventID, PolicyType, callback_func) { obj.Exec("AMT_AuditPolicyRule", "SetAuditPolicy", { "Enable": Enable, "AuditedAppID": AuditedAppID, "EventID": EventID, "PolicyType": PolicyType }, callback_func); }
233
+ obj.AMT_AuditPolicyRule_SetAuditPolicyBulk = function (Enable, AuditedAppID, EventID, PolicyType, callback_func) { obj.Exec("AMT_AuditPolicyRule", "SetAuditPolicyBulk", { "Enable": Enable, "AuditedAppID": AuditedAppID, "EventID": EventID, "PolicyType": PolicyType }, callback_func); }
234
+ obj.AMT_AuthorizationService_AddUserAclEntryEx = function (DigestUsername, DigestPassword, KerberosUserSid, AccessPermission, Realms, callback_func) { obj.Exec("AMT_AuthorizationService", "AddUserAclEntryEx", { "DigestUsername": DigestUsername, "DigestPassword": DigestPassword, "KerberosUserSid": KerberosUserSid, "AccessPermission": AccessPermission, "Realms": Realms }, callback_func); }
235
+ obj.AMT_AuthorizationService_EnumerateUserAclEntries = function (StartIndex, callback_func) { obj.Exec("AMT_AuthorizationService", "EnumerateUserAclEntries", { "StartIndex": StartIndex }, callback_func); }
236
+ obj.AMT_AuthorizationService_GetUserAclEntryEx = function (Handle, callback_func, tag) { obj.Exec("AMT_AuthorizationService", "GetUserAclEntryEx", { "Handle": Handle }, callback_func, tag); }
237
+ obj.AMT_AuthorizationService_UpdateUserAclEntryEx = function (Handle, DigestUsername, DigestPassword, KerberosUserSid, AccessPermission, Realms, callback_func) { obj.Exec("AMT_AuthorizationService", "UpdateUserAclEntryEx", { "Handle": Handle, "DigestUsername": DigestUsername, "DigestPassword": DigestPassword, "KerberosUserSid": KerberosUserSid, "AccessPermission": AccessPermission, "Realms": Realms }, callback_func); }
238
+ obj.AMT_AuthorizationService_RemoveUserAclEntry = function (Handle, callback_func) { obj.Exec("AMT_AuthorizationService", "RemoveUserAclEntry", { "Handle": Handle }, callback_func); }
239
+ obj.AMT_AuthorizationService_SetAdminAclEntryEx = function (Username, DigestPassword, callback_func) { obj.Exec("AMT_AuthorizationService", "SetAdminAclEntryEx", { "Username": Username, "DigestPassword": DigestPassword }, callback_func); }
240
+ obj.AMT_AuthorizationService_GetAdminAclEntry = function (callback_func) { obj.Exec("AMT_AuthorizationService", "GetAdminAclEntry", {}, callback_func); }
241
+ obj.AMT_AuthorizationService_GetAdminAclEntryStatus = function (callback_func) { obj.Exec("AMT_AuthorizationService", "GetAdminAclEntryStatus", {}, callback_func); }
242
+ obj.AMT_AuthorizationService_GetAdminNetAclEntryStatus = function (callback_func) { obj.Exec("AMT_AuthorizationService", "GetAdminNetAclEntryStatus", {}, callback_func); }
243
+ obj.AMT_AuthorizationService_SetAclEnabledState = function (Handle, Enabled, callback_func, tag) { obj.Exec("AMT_AuthorizationService", "SetAclEnabledState", { "Handle": Handle, "Enabled": Enabled }, callback_func, tag); }
244
+ obj.AMT_AuthorizationService_GetAclEnabledState = function (Handle, callback_func, tag) { obj.Exec("AMT_AuthorizationService", "GetAclEnabledState", { "Handle": Handle }, callback_func, tag); }
245
+ obj.AMT_EndpointAccessControlService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("AMT_EndpointAccessControlService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
246
+ obj.AMT_EndpointAccessControlService_GetPosture = function (PostureType, callback_func) { obj.Exec("AMT_EndpointAccessControlService", "GetPosture", { "PostureType": PostureType }, callback_func); }
247
+ obj.AMT_EndpointAccessControlService_GetPostureHash = function (PostureType, callback_func) { obj.Exec("AMT_EndpointAccessControlService", "GetPostureHash", { "PostureType": PostureType }, callback_func); }
248
+ obj.AMT_EndpointAccessControlService_UpdatePostureState = function (UpdateType, callback_func) { obj.Exec("AMT_EndpointAccessControlService", "UpdatePostureState", { "UpdateType": UpdateType }, callback_func); }
249
+ obj.AMT_EndpointAccessControlService_GetEacOptions = function (callback_func) { obj.Exec("AMT_EndpointAccessControlService", "GetEacOptions", {}, callback_func); }
250
+ obj.AMT_EndpointAccessControlService_SetEacOptions = function (EacVendors, PostureHashAlgorithm, callback_func) { obj.Exec("AMT_EndpointAccessControlService", "SetEacOptions", { "EacVendors": EacVendors, "PostureHashAlgorithm": PostureHashAlgorithm }, callback_func); }
251
+ obj.AMT_EnvironmentDetectionSettingData_SetSystemDefensePolicy = function (Policy, callback_func) { obj.Exec("AMT_EnvironmentDetectionSettingData", "SetSystemDefensePolicy", { "Policy": Policy }, callback_func); }
252
+ obj.AMT_EnvironmentDetectionSettingData_EnableVpnRouting = function (Enable, callback_func) { obj.Exec("AMT_EnvironmentDetectionSettingData", "EnableVpnRouting", { "Enable": Enable }, callback_func); }
253
+ obj.AMT_EthernetPortSettings_SetLinkPreference = function (LinkPreference, Timeout, callback_func) { obj.Exec("AMT_EthernetPortSettings", "SetLinkPreference", { "LinkPreference": LinkPreference, "Timeout": Timeout }, callback_func); }
254
+ obj.AMT_HeuristicPacketFilterStatistics_ResetSelectedStats = function (SelectedStatistics, callback_func) { obj.Exec("AMT_HeuristicPacketFilterStatistics", "ResetSelectedStats", { "SelectedStatistics": SelectedStatistics }, callback_func); }
255
+ obj.AMT_KerberosSettingData_GetCredentialCacheState = function (callback_func) { obj.Exec("AMT_KerberosSettingData", "GetCredentialCacheState", {}, callback_func); }
256
+ obj.AMT_KerberosSettingData_SetCredentialCacheState = function (Enable, callback_func) { obj.Exec("AMT_KerberosSettingData", "SetCredentialCacheState", { "Enable": Enable }, callback_func); }
257
+ obj.AMT_MessageLog_CancelIteration = function (IterationIdentifier, callback_func) { obj.Exec("AMT_MessageLog", "CancelIteration", { "IterationIdentifier": IterationIdentifier }, callback_func); }
258
+ obj.AMT_MessageLog_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("AMT_MessageLog", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
259
+ obj.AMT_MessageLog_ClearLog = function (callback_func) { obj.Exec("AMT_MessageLog", "ClearLog", { }, callback_func); }
260
+ obj.AMT_MessageLog_GetRecords = function (IterationIdentifier, MaxReadRecords, callback_func, tag) { obj.Exec("AMT_MessageLog", "GetRecords", { "IterationIdentifier": IterationIdentifier, "MaxReadRecords": MaxReadRecords }, callback_func, tag); }
261
+ obj.AMT_MessageLog_GetRecord = function (IterationIdentifier, PositionToNext, callback_func) { obj.Exec("AMT_MessageLog", "GetRecord", { "IterationIdentifier": IterationIdentifier, "PositionToNext": PositionToNext }, callback_func); }
262
+ obj.AMT_MessageLog_PositionAtRecord = function (IterationIdentifier, MoveAbsolute, RecordNumber, callback_func) { obj.Exec("AMT_MessageLog", "PositionAtRecord", { "IterationIdentifier": IterationIdentifier, "MoveAbsolute": MoveAbsolute, "RecordNumber": RecordNumber }, callback_func); }
263
+ obj.AMT_MessageLog_PositionToFirstRecord = function (callback_func, tag) { obj.Exec("AMT_MessageLog", "PositionToFirstRecord", {}, callback_func, tag); }
264
+ obj.AMT_MessageLog_FreezeLog = function (Freeze, callback_func) { obj.Exec("AMT_MessageLog", "FreezeLog", { "Freeze": Freeze }, callback_func); }
265
+ obj.AMT_PublicKeyManagementService_AddCRL = function (Url, SerialNumbers, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "AddCRL", { "Url": Url, "SerialNumbers": SerialNumbers }, callback_func); }
266
+ obj.AMT_PublicKeyManagementService_ResetCRLList = function (_method_dummy, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "ResetCRLList", { "_method_dummy": _method_dummy }, callback_func); }
267
+ obj.AMT_PublicKeyManagementService_AddCertificate = function (CertificateBlob, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "AddCertificate", { "CertificateBlob": CertificateBlob }, callback_func); }
268
+ obj.AMT_PublicKeyManagementService_AddTrustedRootCertificate = function (CertificateBlob, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "AddTrustedRootCertificate", { "CertificateBlob": CertificateBlob }, callback_func); }
269
+ obj.AMT_PublicKeyManagementService_AddKey = function (KeyBlob, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "AddKey", { "KeyBlob": KeyBlob }, callback_func); }
270
+ obj.AMT_PublicKeyManagementService_GeneratePKCS10Request = function (KeyPair, DNName, Usage, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "GeneratePKCS10Request", { "KeyPair": KeyPair, "DNName": DNName, "Usage": Usage }, callback_func); }
271
+ obj.AMT_PublicKeyManagementService_GeneratePKCS10RequestEx = function (KeyPair, SigningAlgorithm, NullSignedCertificateRequest, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "GeneratePKCS10RequestEx", { "KeyPair": KeyPair, "SigningAlgorithm": SigningAlgorithm, "NullSignedCertificateRequest": NullSignedCertificateRequest }, callback_func); }
272
+ obj.AMT_PublicKeyManagementService_GenerateKeyPair = function (KeyAlgorithm, KeyLength, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "GenerateKeyPair", { "KeyAlgorithm": KeyAlgorithm, "KeyLength": KeyLength }, callback_func); }
273
+ obj.AMT_RedirectionService_RequestStateChange = function (RequestedState, callback_func) { obj.Exec("AMT_RedirectionService", "RequestStateChange", { "RequestedState": RequestedState }, callback_func); }
274
+ obj.AMT_RedirectionService_TerminateSession = function (SessionType, callback_func) { obj.Exec("AMT_RedirectionService", "TerminateSession", { "SessionType": SessionType }, callback_func); }
275
+ obj.AMT_RemoteAccessService_AddMpServer = function (AccessInfo, InfoFormat, Port, AuthMethod, Certificate, Username, Password, CN, callback_func) { obj.Exec("AMT_RemoteAccessService", "AddMpServer", { "AccessInfo": AccessInfo, "InfoFormat": InfoFormat, "Port": Port, "AuthMethod": AuthMethod, "Certificate": Certificate, "Username": Username, "Password": Password, "CN": CN }, callback_func); }
276
+ obj.AMT_RemoteAccessService_AddRemoteAccessPolicyRule = function (Trigger, TunnelLifeTime, ExtendedData, MpServer, callback_func) { obj.Exec("AMT_RemoteAccessService", "AddRemoteAccessPolicyRule", { "Trigger": Trigger, "TunnelLifeTime": TunnelLifeTime, "ExtendedData": ExtendedData, "MpServer": MpServer }, callback_func); }
277
+ obj.AMT_RemoteAccessService_CloseRemoteAccessConnection = function (_method_dummy, callback_func) { obj.Exec("AMT_RemoteAccessService", "CloseRemoteAccessConnection", { "_method_dummy": _method_dummy }, callback_func); }
278
+ obj.AMT_SetupAndConfigurationService_CommitChanges = function (_method_dummy, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "CommitChanges", { "_method_dummy": _method_dummy }, callback_func); }
279
+ obj.AMT_SetupAndConfigurationService_Unprovision = function (ProvisioningMode, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "Unprovision", { "ProvisioningMode": ProvisioningMode }, callback_func); }
280
+ obj.AMT_SetupAndConfigurationService_PartialUnprovision = function (_method_dummy, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "PartialUnprovision", { "_method_dummy": _method_dummy }, callback_func); }
281
+ obj.AMT_SetupAndConfigurationService_ResetFlashWearOutProtection = function (_method_dummy, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "ResetFlashWearOutProtection", { "_method_dummy": _method_dummy }, callback_func); }
282
+ obj.AMT_SetupAndConfigurationService_ExtendProvisioningPeriod = function (Duration, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "ExtendProvisioningPeriod", { "Duration": Duration }, callback_func); }
283
+ obj.AMT_SetupAndConfigurationService_SetMEBxPassword = function (Password, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "SetMEBxPassword", { "Password": Password }, callback_func); }
284
+ obj.AMT_SetupAndConfigurationService_SetTLSPSK = function (PID, PPS, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "SetTLSPSK", { "PID": PID, "PPS": PPS }, callback_func); }
285
+ obj.AMT_SetupAndConfigurationService_GetProvisioningAuditRecord = function (callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "GetProvisioningAuditRecord", {}, callback_func); }
286
+ obj.AMT_SetupAndConfigurationService_GetUuid = function (callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "GetUuid", {}, callback_func); }
287
+ obj.AMT_SetupAndConfigurationService_GetUnprovisionBlockingComponents = function (callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "GetUnprovisionBlockingComponents", {}, callback_func); }
288
+ obj.AMT_SetupAndConfigurationService_GetProvisioningAuditRecordV2 = function (callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "GetProvisioningAuditRecordV2", {}, callback_func); }
289
+ obj.AMT_SystemDefensePolicy_GetTimeout = function (callback_func) { obj.Exec("AMT_SystemDefensePolicy", "GetTimeout", {}, callback_func); }
290
+ obj.AMT_SystemDefensePolicy_SetTimeout = function (Timeout, callback_func) { obj.Exec("AMT_SystemDefensePolicy", "SetTimeout", { "Timeout": Timeout }, callback_func); }
291
+ obj.AMT_SystemDefensePolicy_UpdateStatistics = function (NetworkInterface, ResetOnRead, callback_func, tag, pri, selectors) { obj.Exec("AMT_SystemDefensePolicy", "UpdateStatistics", { "NetworkInterface": NetworkInterface, "ResetOnRead": ResetOnRead }, callback_func, tag, pri, selectors); }
292
+ obj.AMT_SystemPowerScheme_SetPowerScheme = function (callback_func, schemeInstanceId, tag) { obj.Exec("AMT_SystemPowerScheme", "SetPowerScheme", {}, callback_func, tag, 0, { "InstanceID": schemeInstanceId }); }
293
+ obj.AMT_TimeSynchronizationService_GetLowAccuracyTimeSynch = function (callback_func, tag) { obj.Exec("AMT_TimeSynchronizationService", "GetLowAccuracyTimeSynch", {}, callback_func, tag); }
294
+ obj.AMT_TimeSynchronizationService_SetHighAccuracyTimeSynch = function (Ta0, Tm1, Tm2, callback_func, tag) { obj.Exec("AMT_TimeSynchronizationService", "SetHighAccuracyTimeSynch", { "Ta0": Ta0, "Tm1": Tm1, "Tm2": Tm2 }, callback_func, tag); }
295
+ obj.AMT_UserInitiatedConnectionService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("AMT_UserInitiatedConnectionService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
296
+ obj.AMT_WebUIService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func, tag) { obj.Exec("AMT_WebUIService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func, tag); }
297
+ obj.AMT_WiFiPortConfigurationService_AddWiFiSettings = function (WiFiEndpoint, WiFiEndpointSettingsInput, IEEE8021xSettingsInput, ClientCredential, CACredential, callback_func) { obj.ExecWithXml("AMT_WiFiPortConfigurationService", "AddWiFiSettings", { "WiFiEndpoint": WiFiEndpoint, "WiFiEndpointSettingsInput": WiFiEndpointSettingsInput, "IEEE8021xSettingsInput": IEEE8021xSettingsInput, "ClientCredential": ClientCredential, "CACredential": CACredential }, callback_func); }
298
+ obj.AMT_WiFiPortConfigurationService_UpdateWiFiSettings = function (WiFiEndpointSettings, WiFiEndpointSettingsInput, IEEE8021xSettingsInput, ClientCredential, CACredential, callback_func) { obj.ExecWithXml("AMT_WiFiPortConfigurationService", "UpdateWiFiSettings", { "WiFiEndpointSettings": WiFiEndpointSettings, "WiFiEndpointSettingsInput": WiFiEndpointSettingsInput, "IEEE8021xSettingsInput": IEEE8021xSettingsInput, "ClientCredential": ClientCredential, "CACredential": CACredential }, callback_func); }
299
+ obj.AMT_WiFiPortConfigurationService_DeleteAllITProfiles = function (_method_dummy, callback_func) { obj.Exec("AMT_WiFiPortConfigurationService", "DeleteAllITProfiles", { "_method_dummy": _method_dummy }, callback_func); }
300
+ obj.AMT_WiFiPortConfigurationService_DeleteAllUserProfiles = function (_method_dummy, callback_func) { obj.Exec("AMT_WiFiPortConfigurationService", "DeleteAllUserProfiles", { "_method_dummy": _method_dummy }, callback_func); }
301
+ obj.CIM_Account_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_Account", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
302
+ obj.CIM_AccountManagementService_CreateAccount = function (System, AccountTemplate, callback_func) { obj.Exec("CIM_AccountManagementService", "CreateAccount", { "System": System, "AccountTemplate": AccountTemplate }, callback_func); }
303
+ obj.CIM_BootConfigSetting_ChangeBootOrder = function (Source, callback_func) { obj.Exec("CIM_BootConfigSetting", "ChangeBootOrder", { "Source": Source }, callback_func); }
304
+ obj.CIM_BootService_SetBootConfigRole = function (BootConfigSetting, Role, callback_func) { obj.Exec("CIM_BootService", "SetBootConfigRole", { "BootConfigSetting": BootConfigSetting, "Role": Role }, callback_func, 0, 1); }
305
+ obj.CIM_Card_ConnectorPower = function (Connector, PoweredOn, callback_func) { obj.Exec("CIM_Card", "ConnectorPower", { "Connector": Connector, "PoweredOn": PoweredOn }, callback_func); }
306
+ obj.CIM_Card_IsCompatible = function (ElementToCheck, callback_func) { obj.Exec("CIM_Card", "IsCompatible", { "ElementToCheck": ElementToCheck }, callback_func); }
307
+ obj.CIM_Chassis_IsCompatible = function (ElementToCheck, callback_func) { obj.Exec("CIM_Chassis", "IsCompatible", { "ElementToCheck": ElementToCheck }, callback_func); }
308
+ obj.CIM_Fan_SetSpeed = function (DesiredSpeed, callback_func) { obj.Exec("CIM_Fan", "SetSpeed", { "DesiredSpeed": DesiredSpeed }, callback_func); }
309
+ obj.CIM_KVMRedirectionSAP_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_KVMRedirectionSAP", "RequestStateChange", { "RequestedState": RequestedState/*, "TimeoutPeriod": TimeoutPeriod */}, callback_func); }
310
+ obj.CIM_MediaAccessDevice_LockMedia = function (Lock, callback_func) { obj.Exec("CIM_MediaAccessDevice", "LockMedia", { "Lock": Lock }, callback_func); }
311
+ obj.CIM_MediaAccessDevice_SetPowerState = function (PowerState, Time, callback_func) { obj.Exec("CIM_MediaAccessDevice", "SetPowerState", { "PowerState": PowerState, "Time": Time }, callback_func); }
312
+ obj.CIM_MediaAccessDevice_Reset = function (callback_func) { obj.Exec("CIM_MediaAccessDevice", "Reset", {}, callback_func); }
313
+ obj.CIM_MediaAccessDevice_EnableDevice = function (Enabled, callback_func) { obj.Exec("CIM_MediaAccessDevice", "EnableDevice", { "Enabled": Enabled }, callback_func); }
314
+ obj.CIM_MediaAccessDevice_OnlineDevice = function (Online, callback_func) { obj.Exec("CIM_MediaAccessDevice", "OnlineDevice", { "Online": Online }, callback_func); }
315
+ obj.CIM_MediaAccessDevice_QuiesceDevice = function (Quiesce, callback_func) { obj.Exec("CIM_MediaAccessDevice", "QuiesceDevice", { "Quiesce": Quiesce }, callback_func); }
316
+ obj.CIM_MediaAccessDevice_SaveProperties = function (callback_func) { obj.Exec("CIM_MediaAccessDevice", "SaveProperties", {}, callback_func); }
317
+ obj.CIM_MediaAccessDevice_RestoreProperties = function (callback_func) { obj.Exec("CIM_MediaAccessDevice", "RestoreProperties", {}, callback_func); }
318
+ obj.CIM_MediaAccessDevice_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_MediaAccessDevice", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
319
+ obj.CIM_PhysicalFrame_IsCompatible = function (ElementToCheck, callback_func) { obj.Exec("CIM_PhysicalFrame", "IsCompatible", { "ElementToCheck": ElementToCheck }, callback_func); }
320
+ obj.CIM_PhysicalPackage_IsCompatible = function (ElementToCheck, callback_func) { obj.Exec("CIM_PhysicalPackage", "IsCompatible", { "ElementToCheck": ElementToCheck }, callback_func); }
321
+ obj.CIM_PowerManagementService_RequestPowerStateChange = function (PowerState, ManagedElement, Time, TimeoutPeriod, callback_func) { obj.Exec("CIM_PowerManagementService", "RequestPowerStateChange", { "PowerState": PowerState, "ManagedElement": ManagedElement, "Time": Time, "TimeoutPeriod": TimeoutPeriod }, callback_func, 0, 1); }
322
+ obj.CIM_PowerSupply_SetPowerState = function (PowerState, Time, callback_func) { obj.Exec("CIM_PowerSupply", "SetPowerState", { "PowerState": PowerState, "Time": Time }, callback_func); }
323
+ obj.CIM_PowerSupply_Reset = function (callback_func) { obj.Exec("CIM_PowerSupply", "Reset", {}, callback_func); }
324
+ obj.CIM_PowerSupply_EnableDevice = function (Enabled, callback_func) { obj.Exec("CIM_PowerSupply", "EnableDevice", { "Enabled": Enabled }, callback_func); }
325
+ obj.CIM_PowerSupply_OnlineDevice = function (Online, callback_func) { obj.Exec("CIM_PowerSupply", "OnlineDevice", { "Online": Online }, callback_func); }
326
+ obj.CIM_PowerSupply_QuiesceDevice = function (Quiesce, callback_func) { obj.Exec("CIM_PowerSupply", "QuiesceDevice", { "Quiesce": Quiesce }, callback_func); }
327
+ obj.CIM_PowerSupply_SaveProperties = function (callback_func) { obj.Exec("CIM_PowerSupply", "SaveProperties", {}, callback_func); }
328
+ obj.CIM_PowerSupply_RestoreProperties = function (callback_func) { obj.Exec("CIM_PowerSupply", "RestoreProperties", {}, callback_func); }
329
+ obj.CIM_PowerSupply_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_PowerSupply", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
330
+ obj.CIM_Processor_SetPowerState = function (PowerState, Time, callback_func) { obj.Exec("CIM_Processor", "SetPowerState", { "PowerState": PowerState, "Time": Time }, callback_func); }
331
+ obj.CIM_Processor_Reset = function (callback_func) { obj.Exec("CIM_Processor", "Reset", {}, callback_func); }
332
+ obj.CIM_Processor_EnableDevice = function (Enabled, callback_func) { obj.Exec("CIM_Processor", "EnableDevice", { "Enabled": Enabled }, callback_func); }
333
+ obj.CIM_Processor_OnlineDevice = function (Online, callback_func) { obj.Exec("CIM_Processor", "OnlineDevice", { "Online": Online }, callback_func); }
334
+ obj.CIM_Processor_QuiesceDevice = function (Quiesce, callback_func) { obj.Exec("CIM_Processor", "QuiesceDevice", { "Quiesce": Quiesce }, callback_func); }
335
+ obj.CIM_Processor_SaveProperties = function (callback_func) { obj.Exec("CIM_Processor", "SaveProperties", {}, callback_func); }
336
+ obj.CIM_Processor_RestoreProperties = function (callback_func) { obj.Exec("CIM_Processor", "RestoreProperties", {}, callback_func); }
337
+ obj.CIM_Processor_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_Processor", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
338
+ obj.CIM_RecordLog_ClearLog = function (callback_func) { obj.Exec("CIM_RecordLog", "ClearLog", {}, callback_func); }
339
+ obj.CIM_RecordLog_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_RecordLog", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
340
+ obj.CIM_RedirectionService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_RedirectionService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
341
+ obj.CIM_Sensor_SetPowerState = function (PowerState, Time, callback_func) { obj.Exec("CIM_Sensor", "SetPowerState", { "PowerState": PowerState, "Time": Time }, callback_func); }
342
+ obj.CIM_Sensor_Reset = function (callback_func) { obj.Exec("CIM_Sensor", "Reset", {}, callback_func); }
343
+ obj.CIM_Sensor_EnableDevice = function (Enabled, callback_func) { obj.Exec("CIM_Sensor", "EnableDevice", { "Enabled": Enabled }, callback_func); }
344
+ obj.CIM_Sensor_OnlineDevice = function (Online, callback_func) { obj.Exec("CIM_Sensor", "OnlineDevice", { "Online": Online }, callback_func); }
345
+ obj.CIM_Sensor_QuiesceDevice = function (Quiesce, callback_func) { obj.Exec("CIM_Sensor", "QuiesceDevice", { "Quiesce": Quiesce }, callback_func); }
346
+ obj.CIM_Sensor_SaveProperties = function (callback_func) { obj.Exec("CIM_Sensor", "SaveProperties", {}, callback_func); }
347
+ obj.CIM_Sensor_RestoreProperties = function (callback_func) { obj.Exec("CIM_Sensor", "RestoreProperties", {}, callback_func); }
348
+ obj.CIM_Sensor_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_Sensor", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
349
+ obj.CIM_StatisticalData_ResetSelectedStats = function (SelectedStatistics, callback_func) { obj.Exec("CIM_StatisticalData", "ResetSelectedStats", { "SelectedStatistics": SelectedStatistics }, callback_func); }
350
+ obj.CIM_Watchdog_KeepAlive = function (callback_func) { obj.Exec("CIM_Watchdog", "KeepAlive", {}, callback_func); }
351
+ obj.CIM_Watchdog_SetPowerState = function (PowerState, Time, callback_func) { obj.Exec("CIM_Watchdog", "SetPowerState", { "PowerState": PowerState, "Time": Time }, callback_func); }
352
+ obj.CIM_Watchdog_Reset = function (callback_func) { obj.Exec("CIM_Watchdog", "Reset", {}, callback_func); }
353
+ obj.CIM_Watchdog_EnableDevice = function (Enabled, callback_func) { obj.Exec("CIM_Watchdog", "EnableDevice", { "Enabled": Enabled }, callback_func); }
354
+ obj.CIM_Watchdog_OnlineDevice = function (Online, callback_func) { obj.Exec("CIM_Watchdog", "OnlineDevice", { "Online": Online }, callback_func); }
355
+ obj.CIM_Watchdog_QuiesceDevice = function (Quiesce, callback_func) { obj.Exec("CIM_Watchdog", "QuiesceDevice", { "Quiesce": Quiesce }, callback_func); }
356
+ obj.CIM_Watchdog_SaveProperties = function (callback_func) { obj.Exec("CIM_Watchdog", "SaveProperties", {}, callback_func); }
357
+ obj.CIM_Watchdog_RestoreProperties = function (callback_func) { obj.Exec("CIM_Watchdog", "RestoreProperties", {}, callback_func); }
358
+ obj.CIM_Watchdog_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_Watchdog", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
359
+ obj.CIM_WiFiPort_SetPowerState = function (PowerState, Time, callback_func) { obj.Exec("CIM_WiFiPort", "SetPowerState", { "PowerState": PowerState, "Time": Time }, callback_func); }
360
+ obj.CIM_WiFiPort_Reset = function (callback_func) { obj.Exec("CIM_WiFiPort", "Reset", {}, callback_func); }
361
+ obj.CIM_WiFiPort_EnableDevice = function (Enabled, callback_func) { obj.Exec("CIM_WiFiPort", "EnableDevice", { "Enabled": Enabled }, callback_func); }
362
+ obj.CIM_WiFiPort_OnlineDevice = function (Online, callback_func) { obj.Exec("CIM_WiFiPort", "OnlineDevice", { "Online": Online }, callback_func); }
363
+ obj.CIM_WiFiPort_QuiesceDevice = function (Quiesce, callback_func) { obj.Exec("CIM_WiFiPort", "QuiesceDevice", { "Quiesce": Quiesce }, callback_func); }
364
+ obj.CIM_WiFiPort_SaveProperties = function (callback_func) { obj.Exec("CIM_WiFiPort", "SaveProperties", {}, callback_func); }
365
+ obj.CIM_WiFiPort_RestoreProperties = function (callback_func) { obj.Exec("CIM_WiFiPort", "RestoreProperties", {}, callback_func); }
366
+ obj.CIM_WiFiPort_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_WiFiPort", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
367
+ obj.IPS_HostBasedSetupService_Setup = function (NetAdminPassEncryptionType, NetworkAdminPassword, McNonce, Certificate, SigningAlgorithm, DigitalSignature, callback_func) { obj.Exec("IPS_HostBasedSetupService", "Setup", { "NetAdminPassEncryptionType": NetAdminPassEncryptionType, "NetworkAdminPassword": NetworkAdminPassword, "McNonce": McNonce, "Certificate": Certificate, "SigningAlgorithm": SigningAlgorithm, "DigitalSignature": DigitalSignature }, callback_func); }
368
+ obj.IPS_HostBasedSetupService_AddNextCertInChain = function (NextCertificate, IsLeafCertificate, IsRootCertificate, callback_func) { obj.Exec("IPS_HostBasedSetupService", "AddNextCertInChain", { "NextCertificate": NextCertificate, "IsLeafCertificate": IsLeafCertificate, "IsRootCertificate": IsRootCertificate }, callback_func); }
369
+ obj.IPS_HostBasedSetupService_AdminSetup = function (NetAdminPassEncryptionType, NetworkAdminPassword, McNonce, SigningAlgorithm, DigitalSignature, callback_func) { obj.Exec("IPS_HostBasedSetupService", "AdminSetup", { "NetAdminPassEncryptionType": NetAdminPassEncryptionType, "NetworkAdminPassword": NetworkAdminPassword, "McNonce": McNonce, "SigningAlgorithm": SigningAlgorithm, "DigitalSignature": DigitalSignature }, callback_func); }
370
+ obj.IPS_HostBasedSetupService_UpgradeClientToAdmin = function (McNonce, SigningAlgorithm, DigitalSignature, callback_func) { obj.Exec("IPS_HostBasedSetupService", "UpgradeClientToAdmin", { "McNonce": McNonce, "SigningAlgorithm": SigningAlgorithm, "DigitalSignature": DigitalSignature }, callback_func); }
371
+ obj.IPS_HostBasedSetupService_DisableClientControlMode = function (_method_dummy, callback_func) { obj.Exec("IPS_HostBasedSetupService", "DisableClientControlMode", { "_method_dummy": _method_dummy }, callback_func); }
372
+ obj.IPS_KVMRedirectionSettingData_TerminateSession = function (callback_func) { obj.Exec("IPS_KVMRedirectionSettingData", "TerminateSession", {}, callback_func); }
373
+ obj.IPS_KVMRedirectionSettingData_DataChannelRead = function (callback_func) { obj.Exec("IPS_KVMRedirectionSettingData", "DataChannelRead", {}, callback_func); }
374
+ obj.IPS_KVMRedirectionSettingData_DataChannelWrite = function (Data, callback_func) { obj.Exec("IPS_KVMRedirectionSettingData", "DataChannelWrite", { "DataMessage": Data }, callback_func); }
375
+ obj.IPS_OptInService_StartOptIn = function (callback_func) { obj.Exec("IPS_OptInService", "StartOptIn", {}, callback_func); }
376
+ obj.IPS_OptInService_CancelOptIn = function (callback_func) { obj.Exec("IPS_OptInService", "CancelOptIn", {}, callback_func); }
377
+ obj.IPS_OptInService_SendOptInCode = function (OptInCode, callback_func) { obj.Exec("IPS_OptInService", "SendOptInCode", { "OptInCode": OptInCode }, callback_func); }
378
+ obj.IPS_OptInService_StartService = function (callback_func) { obj.Exec("IPS_OptInService", "StartService", {}, callback_func); }
379
+ obj.IPS_OptInService_StopService = function (callback_func) { obj.Exec("IPS_OptInService", "StopService", {}, callback_func); }
380
+ obj.IPS_OptInService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("IPS_OptInService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
381
+ obj.IPS_ProvisioningRecordLog_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("IPS_ProvisioningRecordLog", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
382
+ obj.IPS_ProvisioningRecordLog_ClearLog = function (_method_dummy, callback_func) { obj.Exec("IPS_ProvisioningRecordLog", "ClearLog", { "_method_dummy": _method_dummy }, callback_func); }
383
+ obj.IPS_SecIOService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("IPS_SecIOService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
384
+
385
+ obj.AmtStatusToStr = function (code) { if (obj.AmtStatusCodes[code]) return obj.AmtStatusCodes[code]; else return "UNKNOWN_ERROR" }
386
+ obj.AmtStatusCodes = {
387
+ 0x0000: "SUCCESS",
388
+ 0x0001: "INTERNAL_ERROR",
389
+ 0x0002: "NOT_READY",
390
+ 0x0003: "INVALID_PT_MODE",
391
+ 0x0004: "INVALID_MESSAGE_LENGTH",
392
+ 0x0005: "TABLE_FINGERPRINT_NOT_AVAILABLE",
393
+ 0x0006: "INTEGRITY_CHECK_FAILED",
394
+ 0x0007: "UNSUPPORTED_ISVS_VERSION",
395
+ 0x0008: "APPLICATION_NOT_REGISTERED",
396
+ 0x0009: "INVALID_REGISTRATION_DATA",
397
+ 0x000A: "APPLICATION_DOES_NOT_EXIST",
398
+ 0x000B: "NOT_ENOUGH_STORAGE",
399
+ 0x000C: "INVALID_NAME",
400
+ 0x000D: "BLOCK_DOES_NOT_EXIST",
401
+ 0x000E: "INVALID_BYTE_OFFSET",
402
+ 0x000F: "INVALID_BYTE_COUNT",
403
+ 0x0010: "NOT_PERMITTED",
404
+ 0x0011: "NOT_OWNER",
405
+ 0x0012: "BLOCK_LOCKED_BY_OTHER",
406
+ 0x0013: "BLOCK_NOT_LOCKED",
407
+ 0x0014: "INVALID_GROUP_PERMISSIONS",
408
+ 0x0015: "GROUP_DOES_NOT_EXIST",
409
+ 0x0016: "INVALID_MEMBER_COUNT",
410
+ 0x0017: "MAX_LIMIT_REACHED",
411
+ 0x0018: "INVALID_AUTH_TYPE",
412
+ 0x0019: "AUTHENTICATION_FAILED",
413
+ 0x001A: "INVALID_DHCP_MODE",
414
+ 0x001B: "INVALID_IP_ADDRESS",
415
+ 0x001C: "INVALID_DOMAIN_NAME",
416
+ 0x001D: "UNSUPPORTED_VERSION",
417
+ 0x001E: "REQUEST_UNEXPECTED",
418
+ 0x001F: "INVALID_TABLE_TYPE",
419
+ 0x0020: "INVALID_PROVISIONING_STATE",
420
+ 0x0021: "UNSUPPORTED_OBJECT",
421
+ 0x0022: "INVALID_TIME",
422
+ 0x0023: "INVALID_INDEX",
423
+ 0x0024: "INVALID_PARAMETER",
424
+ 0x0025: "INVALID_NETMASK",
425
+ 0x0026: "FLASH_WRITE_LIMIT_EXCEEDED",
426
+ 0x0027: "INVALID_IMAGE_LENGTH",
427
+ 0x0028: "INVALID_IMAGE_SIGNATURE",
428
+ 0x0029: "PROPOSE_ANOTHER_VERSION",
429
+ 0x002A: "INVALID_PID_FORMAT",
430
+ 0x002B: "INVALID_PPS_FORMAT",
431
+ 0x002C: "BIST_COMMAND_BLOCKED",
432
+ 0x002D: "CONNECTION_FAILED",
433
+ 0x002E: "CONNECTION_TOO_MANY",
434
+ 0x002F: "RNG_GENERATION_IN_PROGRESS",
435
+ 0x0030: "RNG_NOT_READY",
436
+ 0x0031: "CERTIFICATE_NOT_READY",
437
+ 0x0400: "DISABLED_BY_POLICY",
438
+ 0x0800: "NETWORK_IF_ERROR_BASE",
439
+ 0x0801: "UNSUPPORTED_OEM_NUMBER",
440
+ 0x0802: "UNSUPPORTED_BOOT_OPTION",
441
+ 0x0803: "INVALID_COMMAND",
442
+ 0x0804: "INVALID_SPECIAL_COMMAND",
443
+ 0x0805: "INVALID_HANDLE",
444
+ 0x0806: "INVALID_PASSWORD",
445
+ 0x0807: "INVALID_REALM",
446
+ 0x0808: "STORAGE_ACL_ENTRY_IN_USE",
447
+ 0x0809: "DATA_MISSING",
448
+ 0x080A: "DUPLICATE",
449
+ 0x080B: "EVENTLOG_FROZEN",
450
+ 0x080C: "PKI_MISSING_KEYS",
451
+ 0x080D: "PKI_GENERATING_KEYS",
452
+ 0x080E: "INVALID_KEY",
453
+ 0x080F: "INVALID_CERT",
454
+ 0x0810: "CERT_KEY_NOT_MATCH",
455
+ 0x0811: "MAX_KERB_DOMAIN_REACHED",
456
+ 0x0812: "UNSUPPORTED",
457
+ 0x0813: "INVALID_PRIORITY",
458
+ 0x0814: "NOT_FOUND",
459
+ 0x0815: "INVALID_CREDENTIALS",
460
+ 0x0816: "INVALID_PASSPHRASE",
461
+ 0x0818: "NO_ASSOCIATION",
462
+ 0x081B: "AUDIT_FAIL",
463
+ 0x081C: "BLOCKING_COMPONENT",
464
+ 0x0821: "USER_CONSENT_REQUIRED",
465
+ 0x1000: "APP_INTERNAL_ERROR",
466
+ 0x1001: "NOT_INITIALIZED",
467
+ 0x1002: "LIB_VERSION_UNSUPPORTED",
468
+ 0x1003: "INVALID_PARAM",
469
+ 0x1004: "RESOURCES",
470
+ 0x1005: "HARDWARE_ACCESS_ERROR",
471
+ 0x1006: "REQUESTOR_NOT_REGISTERED",
472
+ 0x1007: "NETWORK_ERROR",
473
+ 0x1008: "PARAM_BUFFER_TOO_SHORT",
474
+ 0x1009: "COM_NOT_INITIALIZED_IN_THREAD",
475
+ 0x100A: "URL_REQUIRED"
476
+ }
477
+
478
+ //
479
+ // Methods used for getting the event log
480
+ //
481
+
482
+ obj.GetMessageLog = function (func, tag) {
483
+ obj.AMT_MessageLog_PositionToFirstRecord(_GetMessageLog0, [func, tag, []]);
484
+ }
485
+ function _GetMessageLog0(stack, name, responses, status, tag) {
486
+ if (status != 200 || responses.Body["ReturnValue"] != '0') { tag[0](obj, null, tag[2], status); return; }
487
+ obj.AMT_MessageLog_GetRecords(responses.Body["IterationIdentifier"], 390, _GetMessageLog1, tag);
488
+ }
489
+ function _GetMessageLog1(stack, name, responses, status, tag) {
490
+ if (status != 200 || responses.Body["ReturnValue"] != '0') { tag[0](obj, null, tag[2], status); return; }
491
+ var i, j, x, e, AmtMessages = tag[2], t = new Date(), TimeStamp, ra = responses.Body["RecordArray"];
492
+ if (typeof ra === 'string') { responses.Body["RecordArray"] = [responses.Body["RecordArray"]]; }
493
+
494
+ for (i in ra) {
495
+ e = Buffer.from(ra[i], 'base64');
496
+ if (e != null) {
497
+ TimeStamp = ReadIntX(e, 0);
498
+ if ((TimeStamp > 0) && (TimeStamp < 0xFFFFFFFF)) {
499
+ x = { 'DeviceAddress': e[4], 'EventSensorType': e[5], 'EventType': e[6], 'EventOffset': e[7], 'EventSourceType': e[8], 'EventSeverity': e[9], 'SensorNumber': e[10], 'Entity': e[11], 'EntityInstance': e[12], 'EventData': [], 'Time': new Date((TimeStamp + (t.getTimezoneOffset() * 60)) * 1000) };
500
+ for (j = 13; j < 21; j++) { x['EventData'].push(e[j]); }
501
+ x['EntityStr'] = _SystemEntityTypes[x['Entity']];
502
+ x['Desc'] = _GetEventDetailStr(x['EventSensorType'], x['EventOffset'], x['EventData'], x['Entity']);
503
+ if (!x['EntityStr']) x['EntityStr'] = "Unknown";
504
+ AmtMessages.push(x);
505
+ }
506
+ }
507
+ }
508
+
509
+ if (responses.Body["NoMoreRecords"] != true) { obj.AMT_MessageLog_GetRecords(responses.Body["IterationIdentifier"], 390, _GetMessageLog1, [tag[0], AmtMessages, tag[2]]); } else { tag[0](obj, AmtMessages, tag[2]); }
510
+ }
511
+
512
+ var _EventTrapSourceTypes = "Platform firmware (e.g. BIOS)|SMI handler|ISV system management software|Alert ASIC|IPMI|BIOS vendor|System board set vendor|System integrator|Third party add-in|OSV|NIC|System management card".split('|');
513
+ var _SystemFirmwareError = "Unspecified.|No system memory is physically installed in the system.|No usable system memory, all installed memory has experienced an unrecoverable failure.|Unrecoverable hard-disk/ATAPI/IDE device failure.|Unrecoverable system-board failure.|Unrecoverable diskette subsystem failure.|Unrecoverable hard-disk controller failure.|Unrecoverable PS/2 or USB keyboard failure.|Removable boot media not found.|Unrecoverable video controller failure.|No video device detected.|Firmware (BIOS) ROM corruption detected.|CPU voltage mismatch (processors that share same supply have mismatched voltage requirements)|CPU speed matching failure".split('|');
514
+ var _SystemFirmwareProgress = "Unspecified.|Memory initialization.|Starting hard-disk initialization and test|Secondary processor(s) initialization|User authentication|User-initiated system setup|USB resource configuration|PCI resource configuration|Option ROM initialization|Video initialization|Cache initialization|SM Bus initialization|Keyboard controller initialization|Embedded controller/management controller initialization|Docking station attachment|Enabling docking station|Docking station ejection|Disabling docking station|Calling operating system wake-up vector|Starting operating system boot process|Baseboard or motherboard initialization|reserved|Floppy initialization|Keyboard test|Pointing device test|Primary processor initialization".split('|');
515
+ var _SystemEntityTypes = "Unspecified|Other|Unknown|Processor|Disk|Peripheral|System management module|System board|Memory module|Processor module|Power supply|Add in card|Front panel board|Back panel board|Power system board|Drive backplane|System internal expansion board|Other system board|Processor board|Power unit|Power module|Power management board|Chassis back panel board|System chassis|Sub chassis|Other chassis board|Disk drive bay|Peripheral bay|Device bay|Fan cooling|Cooling unit|Cable interconnect|Memory device|System management software|BIOS|Intel(r) ME|System bus|Group|Intel(r) ME|External environment|Battery|Processing blade|Connectivity switch|Processor/memory module|I/O module|Processor I/O module|Management controller firmware|IPMI channel|PCI bus|PCI express bus|SCSI bus|SATA/SAS bus|Processor front side bus".split('|');
516
+ obj.RealmNames = "||Redirection|PT Administration|Hardware Asset|Remote Control|Storage|Event Manager|Storage Admin|Agent Presence Local|Agent Presence Remote|Circuit Breaker|Network Time|General Information|Firmware Update|EIT|LocalUN|Endpoint Access Control|Endpoint Access Control Admin|Event Log Reader|Audit Log|ACL Realm|||Local System".split('|');
517
+ obj.WatchdogCurrentStates = { 1: 'Not Started', 2: 'Stopped', 4: 'Running', 8: 'Expired', 16: 'Suspended' };
518
+
519
+ function _GetEventDetailStr(eventSensorType, eventOffset, eventDataField, entity) {
520
+
521
+ if (eventSensorType == 15)
522
+ {
523
+ if (eventDataField[0] == 235) return "Invalid Data";
524
+ if (eventOffset == 0) return _SystemFirmwareError[eventDataField[1]];
525
+ return _SystemFirmwareProgress[eventDataField[1]];
526
+ }
527
+
528
+ if (eventSensorType == 18 && eventDataField[0] == 170) // System watchdog event
529
+ {
530
+ return "Agent watchdog " + char2hex(eventDataField[4]) + char2hex(eventDataField[3]) + char2hex(eventDataField[2]) + char2hex(eventDataField[1]) + "-" + char2hex(eventDataField[6]) + char2hex(eventDataField[5]) + "-... changed to " + obj.WatchdogCurrentStates[eventDataField[7]];
531
+ }
532
+
533
+ //if (eventSensorType == 5 && eventOffset == 0) // System chassis
534
+ //{
535
+ // return "Case intrusion";
536
+ //}
537
+
538
+ //if (eventSensorType == 192 && eventOffset == 0 && eventDataField[0] == 170 && eventDataField[1] == 48)
539
+ //{
540
+ // if (eventDataField[2] == 0) return "A remote Serial Over LAN session was established.";
541
+ // if (eventDataField[2] == 1) return "Remote Serial Over LAN session finished. User control was restored.";
542
+ // if (eventDataField[2] == 2) return "A remote IDE-Redirection session was established.";
543
+ // if (eventDataField[2] == 3) return "Remote IDE-Redirection session finished. User control was restored.";
544
+ //}
545
+
546
+ //if (eventSensorType == 36)
547
+ //{
548
+ // long handle = ((long)(eventDataField[1]) << 24) + ((long)(eventDataField[2]) << 16) + ((long)(eventDataField[3]) << 8) + (long)(eventDataField[4]);
549
+ // string nic = string.Format("#{0}", eventDataField[0]);
550
+ // if (eventDataField[0] == 0xAA) nic = "wired"; // TODO: Add wireless *****
551
+ // //if (eventDataField[0] == 0xAA) nic = "wireless";
552
+
553
+ // if (handle == 4294967293) { return string.Format("All received packet filter was matched on {0} interface.", nic); }
554
+ // if (handle == 4294967292) { return string.Format("All outbound packet filter was matched on {0} interface.", nic); }
555
+ // if (handle == 4294967290) { return string.Format("Spoofed packet filter was matched on {0} interface.", nic); }
556
+ // return string.Format("Filter {0} was matched on {1} interface.", handle, nic);
557
+ //}
558
+
559
+ //if (eventSensorType == 192)
560
+ //{
561
+ // if (eventDataField[2] == 0) return "Security policy invoked. Some or all network traffic (TX) was stopped.";
562
+ // if (eventDataField[2] == 2) return "Security policy invoked. Some or all network traffic (RX) was stopped.";
563
+ // return "Security policy invoked.";
564
+ //}
565
+
566
+ //if (eventSensorType == 193)
567
+ //{
568
+ // if (eventDataField[0] == 0xAA && eventDataField[1] == 0x30 && eventDataField[2] == 0x00 && eventDataField[3] == 0x00) { return "User request for remote connection."; }
569
+ // if (eventDataField[0] == 0xAA && eventDataField[1] == 0x20 && eventDataField[2] == 0x03 && eventDataField[3] == 0x01) { return "EAC error: attempt to get posture while NAC in Intel(r) AMT is disabled."; // eventDataField = 0xAA20030100000000 }
570
+ // if (eventDataField[0] == 0xAA && eventDataField[1] == 0x20 && eventDataField[2] == 0x04 && eventDataField[3] == 0x00) { return "Certificate revoked. "; }
571
+ //}
572
+
573
+ if (eventSensorType == 6) return "Authentication failed " + (eventDataField[1] + (eventDataField[2] << 8)) + " times. The system may be under attack.";
574
+ if (eventSensorType == 30) return "No bootable media";
575
+ if (eventSensorType == 32) return "Operating system lockup or power interrupt";
576
+ if (eventSensorType == 35) return "System boot failure";
577
+ if (eventSensorType == 37) return "System firmware started (at least one CPU is properly executing).";
578
+ return "Unknown Sensor Type #" + eventSensorType;
579
+ }
580
+
581
+// ###BEGIN###{AuditLog}
582
+
583
+ // Useful link: https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm?turl=WordDocuments%2Fsecurityadminevents.htm
584
+
585
+ var _AmtAuditStringTable =
586
+ {
587
+ 16: 'Security Admin',
588
+ 17: 'RCO',
589
+ 18: 'Redirection Manager',
590
+ 19: 'Firmware Update Manager',
591
+ 20: 'Security Audit Log',
592
+ 21: 'Network Time',
593
+ 22: 'Network Administration',
594
+ 23: 'Storage Administration',
595
+ 24: 'Event Manager',
596
+ 25: 'Circuit Breaker Manager',
597
+ 26: 'Agent Presence Manager',
598
+ 27: 'Wireless Configuration',
599
+ 28: 'EAC',
600
+ 29: 'KVM',
601
+ 30: 'User Opt-In Events',
602
+ 32: 'Screen Blanking',
603
+ 33: 'Watchdog Events',
604
+ 1600: 'Provisioning Started',
605
+ 1601: 'Provisioning Completed',
606
+ 1602: 'ACL Entry Added',
607
+ 1603: 'ACL Entry Modified',
608
+ 1604: 'ACL Entry Removed',
609
+ 1605: 'ACL Access with Invalid Credentials',
610
+ 1606: 'ACL Entry State',
611
+ 1607: 'TLS State Changed',
612
+ 1608: 'TLS Server Certificate Set',
613
+ 1609: 'TLS Server Certificate Remove',
614
+ 1610: 'TLS Trusted Root Certificate Added',
615
+ 1611: 'TLS Trusted Root Certificate Removed',
616
+ 1612: 'TLS Preshared Key Set',
617
+ 1613: 'Kerberos Settings Modified',
618
+ 1614: 'Kerberos Master Key Modified',
619
+ 1615: 'Flash Wear out Counters Reset',
620
+ 1616: 'Power Package Modified',
621
+ 1617: 'Set Realm Authentication Mode',
622
+ 1618: 'Upgrade Client to Admin Control Mode',
623
+ 1619: 'Unprovisioning Started',
624
+ 1700: 'Performed Power Up',
625
+ 1701: 'Performed Power Down',
626
+ 1702: 'Performed Power Cycle',
627
+ 1703: 'Performed Reset',
628
+ 1704: 'Set Boot Options',
629
+ 1800: 'IDER Session Opened',
630
+ 1801: 'IDER Session Closed',
631
+ 1802: 'IDER Enabled',
632
+ 1803: 'IDER Disabled',
633
+ 1804: 'SoL Session Opened',
634
+ 1805: 'SoL Session Closed',
635
+ 1806: 'SoL Enabled',
636
+ 1807: 'SoL Disabled',
637
+ 1808: 'KVM Session Started',
638
+ 1809: 'KVM Session Ended',
639
+ 1810: 'KVM Enabled',
640
+ 1811: 'KVM Disabled',
641
+ 1812: 'VNC Password Failed 3 Times',
642
+ 1900: 'Firmware Updated',
643
+ 1901: 'Firmware Update Failed',
644
+ 2000: 'Security Audit Log Cleared',
645
+ 2001: 'Security Audit Policy Modified',
646
+ 2002: 'Security Audit Log Disabled',
647
+ 2003: 'Security Audit Log Enabled',
648
+ 2004: 'Security Audit Log Exported',
649
+ 2005: 'Security Audit Log Recovered',
650
+ 2100: 'Intel(R) ME Time Set',
651
+ 2200: 'TCPIP Parameters Set',
652
+ 2201: 'Host Name Set',
653
+ 2202: 'Domain Name Set',
654
+ 2203: 'VLAN Parameters Set',
655
+ 2204: 'Link Policy Set',
656
+ 2205: 'IPv6 Parameters Set',
657
+ 2300: 'Global Storage Attributes Set',
658
+ 2301: 'Storage EACL Modified',
659
+ 2302: 'Storage FPACL Modified',
660
+ 2303: 'Storage Write Operation',
661
+ 2400: 'Alert Subscribed',
662
+ 2401: 'Alert Unsubscribed',
663
+ 2402: 'Event Log Cleared',
664
+ 2403: 'Event Log Frozen',
665
+ 2500: 'CB Filter Added',
666
+ 2501: 'CB Filter Removed',
667
+ 2502: 'CB Policy Added',
668
+ 2503: 'CB Policy Removed',
669
+ 2504: 'CB Default Policy Set',
670
+ 2505: 'CB Heuristics Option Set',
671
+ 2506: 'CB Heuristics State Cleared',
672
+ 2600: 'Agent Watchdog Added',
673
+ 2601: 'Agent Watchdog Removed',
674
+ 2602: 'Agent Watchdog Action Set',
675
+ 2700: 'Wireless Profile Added',
676
+ 2701: 'Wireless Profile Removed',
677
+ 2702: 'Wireless Profile Updated',
678
+ 2800: 'EAC Posture Signer SET',
679
+ 2801: 'EAC Enabled',
680
+ 2802: 'EAC Disabled',
681
+ 2803: 'EAC Posture State',
682
+ 2804: 'EAC Set Options',
683
+ 2900: 'KVM Opt-in Enabled',
684
+ 2901: 'KVM Opt-in Disabled',
685
+ 2902: 'KVM Password Changed',
686
+ 2903: 'KVM Consent Succeeded',
687
+ 2904: 'KVM Consent Failed',
688
+ 3000: 'Opt-In Policy Change',
689
+ 3001: 'Send Consent Code Event',
690
+ 3002: 'Start Opt-In Blocked Event'
691
+ }
692
+
693
+ // Return human readable extended audit log data
694
+ // TODO: Just put some of them here, but many more still need to be added, helpful link here:
695
+ // https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm?turl=WordDocuments%2Fsecurityadminevents.htm
696
+ obj.GetAuditLogExtendedDataStr = function (id, data) {
697
+ if ((id == 1602 || id == 1604) && data[0] == 0) { return bufToArray(data).splice(2, 2 + data[1]).toString(); } // ACL Entry Added/Removed (Digest)
698
+ if (id == 1603) { if (data[1] == 0) { return bufToArray(data).splice(3).toString(); } return null; } // ACL Entry Modified
699
+ if (id == 1605) { return ["Invalid ME access", "Invalid MEBx access"][data[0]]; } // ACL Access with Invalid Credentials
700
+ if (id == 1606) { var r = ["Disabled", "Enabled"][data[0]]; if (data[1] == 0) { r += ", " + data[3]; } return r; } // ACL Entry State
701
+ if (id == 1607) { return "Remote " + ["NoAuth", "ServerAuth", "MutualAuth"][data[0]] + ", Local " + ["NoAuth", "ServerAuth", "MutualAuth"][data[1]]; } // TLS State Changed
702
+ if (id == 1617) { return obj.RealmNames[ReadInt(data, 0)] + ", " + ["NoAuth", "Auth", "Disabled"][data[4]]; } // Set Realm Authentication Mode
703
+ if (id == 1619) { return ["BIOS", "MEBx", "Local MEI", "Local WSMAN", "Remote WSAMN"][data[0]]; } // Intel AMT Unprovisioning Started
704
+ if (id == 1900) { return "From " + ReadShort(data, 0) + "." + ReadShort(data, 2) + "." + ReadShort(data, 4) + "." + ReadShort(data, 6) + " to " + ReadShort(data, 8) + "." + ReadShort(data, 10) + "." + ReadShort(data, 12) + "." + ReadShort(data, 14); } // Firmware Updated
705
+ if (id == 2100) { var t4 = new Date(); t4.setTime(ReadInt(data, 0) * 1000 + (new Date().getTimezoneOffset() * 60000)); return t4.toLocaleString(); } // Intel AMT Time Set
706
+ if (id == 3000) { return "From " + ["None", "KVM", "All"][data[0]] + " to " + ["None", "KVM", "All"][data[1]]; } // Opt-In Policy Change
707
+ if (id == 3001) { return ["Success", "Failed 3 times"][data[0]]; } // Send Consent Code Event
708
+ return null;
709
+ }
710
+
711
+ obj.GetAuditLog = function (func) {
712
+ obj.AMT_AuditLog_ReadRecords(1, _GetAuditLog0, [func, []]);
713
+ }
714
+
715
+ function MakeToArray(v) { if (!v || v == null || typeof v == 'object') return v; return [v]; }
716
+ function ReadShort(v, p) { return (v[p] << 8) + v[p + 1]; }
717
+ function ReadInt(v, p) { return (v[p] * 0x1000000) + (v[p + 1] << 16) + (v[p + 2] << 8) + v[p + 3]; } // We use "*0x1000000" instead of "<<24" because the shift converts the number to signed int32.
718
+ function ReadIntX(v, p) { return (v[p + 3] * 0x1000000) + (v[p + 2] << 16) + (v[p + 1] << 8) + v[p]; }
719
+ function btoa(x) { return Buffer.from(x).toString('base64'); }
720
+ function atob(x) { var z = null; try { z = Buffer.from(x, 'base64').toString(); } catch (e) { console.log(e); } return z; }
721
+ function bufToArray(buf) { var r = []; for (var i in buf) { r.push(buf[i]); } return r; }
722
+
723
+ function _GetAuditLog0(stack, name, responses, status, tag) {
724
+ if (status != 200) { tag[0](obj, [], status); return; }
725
+ var ptr, i, e, es, x, r = tag[1], t = new Date(), TimeStamp;
726
+
727
+ if (responses.Body['RecordsReturned'] > 0) {
728
+ responses.Body['EventRecords'] = MakeToArray(responses.Body['EventRecords']);
729
+
730
+ for (i in responses.Body['EventRecords']) {
731
+ e = null;
732
+ try {
733
+ es = atob(responses.Body['EventRecords'][i]);
734
+ e = new Buffer(es);
735
+ } catch (ex) {
736
+ console.log(ex + " " + responses.Body['EventRecords'][i])
737
+ }
738
+
739
+ x = { 'AuditAppID': ReadShort(e, 0), 'EventID': ReadShort(e, 2), 'InitiatorType': e[4] };
740
+ x['AuditApp'] = _AmtAuditStringTable[x['AuditAppID']];
741
+ x['Event'] = _AmtAuditStringTable[(x['AuditAppID'] * 100) + x['EventID']];
742
+ if (!x['Event']) x['Event'] = '#' + x['EventID'];
743
+
744
+ // Read and process the initiator
745
+ if (x['InitiatorType'] == 0) {
746
+ // HTTP digest
747
+ var userlen = e[5];
748
+ x['Initiator'] = e.slice(6, 6 + userlen).toString();
749
+ ptr = 6 + userlen;
750
+ }
751
+ if (x['InitiatorType'] == 1) {
752
+ // Kerberos
753
+ x['KerberosUserInDomain'] = ReadInt(e, 5);
754
+ var userlen = e[9];
755
+ x['Initiator'] = GetSidString(e.slice(10, 10 + userlen));
756
+ ptr = 10 + userlen;
757
+ }
758
+ if (x['InitiatorType'] == 2) {
759
+ // Local
760
+ x['Initiator'] = 'Local';
761
+ ptr = 5;
762
+ }
763
+ if (x['InitiatorType'] == 3) {
764
+ // KVM Default Port
765
+ x['Initiator'] = 'KVM Default Port';
766
+ ptr = 5;
767
+ }
768
+
769
+ // Read timestamp
770
+ TimeStamp = ReadInt(e, ptr);
771
+ x['Time'] = new Date((TimeStamp + (t.getTimezoneOffset() * 60)) * 1000);
772
+ ptr += 4;
773
+
774
+ // Read network access
775
+ x['MCLocationType'] = e[ptr++];
776
+ var netlen = e[ptr++];
777
+
778
+ x['NetAddress'] = e.slice(ptr, ptr + netlen).toString();
779
+
780
+ // Read extended data
781
+ ptr += netlen;
782
+ var exlen = e[ptr++];
783
+ x['Ex'] = e.slice(ptr, ptr + exlen);
784
+ x['ExStr'] = obj.GetAuditLogExtendedDataStr((x['AuditAppID'] * 100) + x['EventID'], x['Ex']);
785
+ r.push(x);
786
+ }
787
+ }
788
+ if (responses.Body['TotalRecordCount'] > r.length) {
789
+ obj.AMT_AuditLog_ReadRecords(r.length + 1, _GetAuditLog0, [tag[0], r]);
790
+ } else {
791
+ tag[0](obj, r, status);
792
+ }
793
+ }
794
+
795
+ // ###END###{AuditLog}
796
+
797
+ /*
798
+ // ###BEGIN###{Certificates}
799
+
800
+ // Forge MD5
801
+ function hex_md5(str) { return forge.md.md5.create().update(str).digest().toHex(); }
802
+
803
+ // ###END###{Certificates}
804
+
805
+ // ###BEGIN###{!Certificates}
806
+
807
+ // TinyMD5 from https://github.com/jbt/js-crypto
808
+
809
+ // Perform MD5 setup
810
+ var md5_k = [];
811
+ for (var i = 0; i < 64;) { md5_k[i] = 0 | (Math.abs(Math.sin(++i)) * 4294967296); }
812
+
813
+ // Perform MD5 on raw string and return hex
814
+ function hex_md5(str) {
815
+ var b, c, d, j,
816
+ x = [],
817
+ str2 = unescape(encodeURI(str)),
818
+ a = str2.length,
819
+ h = [b = 1732584193, c = -271733879, ~b, ~c],
820
+ i = 0;
821
+
822
+ for (; i <= a;) x[i >> 2] |= (str2.charCodeAt(i) || 128) << 8 * (i++ % 4);
823
+
824
+ x[str = (a + 8 >> 6) * 16 + 14] = a * 8;
825
+ i = 0;
826
+
827
+ for (; i < str; i += 16) {
828
+ a = h; j = 0;
829
+ for (; j < 64;) {
830
+ a = [
831
+ d = a[3],
832
+ ((b = a[1] | 0) +
833
+ ((d = (
834
+ (a[0] +
835
+ [
836
+ b & (c = a[2]) | ~b & d,
837
+ d & b | ~d & c,
838
+ b ^ c ^ d,
839
+ c ^ (b | ~d)
840
+ ][a = j >> 4]
841
+ ) +
842
+ (md5_k[j] +
843
+ (x[[
844
+ j,
845
+ 5 * j + 1,
846
+ 3 * j + 5,
847
+ 7 * j
848
+ ][a] % 16 + i] | 0)
849
+ )
850
+ )) << (a = [
851
+ 7, 12, 17, 22,
852
+ 5, 9, 14, 20,
853
+ 4, 11, 16, 23,
854
+ 6, 10, 15, 21
855
+ ][4 * a + j++ % 4]) | d >>> 32 - a)
856
+ ),
857
+ b,
858
+ c
859
+ ];
860
+ }
861
+ for (j = 4; j;) h[--j] = h[j] + a[j];
862
+ }
863
+
864
+ str = '';
865
+ for (; j < 32;) str += ((h[j >> 3] >> ((1 ^ j++ & 7) * 4)) & 15).toString(16);
866
+ return str;
867
+ }
868
+
869
+ // ###END###{!Certificates}
870
+
871
+ // Perform MD5 on raw string and return raw string result
872
+ function rstr_md5(str) { return hex2rstr(hex_md5(str)); }
873
+ */
874
+ /*
875
+ Convert arguments into selector set and body XML. Used by AMT_WiFiPortConfigurationService_UpdateWiFiSettings.
876
+ args = {
877
+ "WiFiEndpoint": {
878
+ __parameterType: 'reference',
879
+ __resourceUri: 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_WiFiEndpoint',
880
+ Name: 'WiFi Endpoint 0'
881
+ },
882
+ "WiFiEndpointSettingsInput":
883
+ {
884
+ __parameterType: 'instance',
885
+ __namespace: 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_WiFiEndpointSettings',
886
+ ElementName: document.querySelector('#editProfile-profileName').value,
887
+ InstanceID: 'Intel(r) AMT:WiFi Endpoint Settings ' + document.querySelector('#editProfile-profileName').value,
888
+ AuthenticationMethod: document.querySelector('#editProfile-networkAuthentication').value,
889
+ //BSSType: 3, // Intel(r) AMT supports only infrastructure networks
890
+ EncryptionMethod: document.querySelector('#editProfile-encryption').value,
891
+ SSID: document.querySelector('#editProfile-networkName').value,
892
+ Priority: 100,
893
+ PSKPassPhrase: document.querySelector('#editProfile-passPhrase').value
894
+ },
895
+ "IEEE8021xSettingsInput": null,
896
+ "ClientCredential": null,
897
+ "CACredential": null
898
+ },
899
+ */
900
+ function execArgumentsToXml(args) {
901
+ if (args === undefined || args === null) return null;
902
+
903
+ var result = '';
904
+ for (var argName in args) {
905
+ var arg = args[argName];
906
+ if (!arg) continue;
907
+ if (arg['__parameterType'] === 'reference') result += referenceToXml(argName, arg);
908
+ else result += instanceToXml(argName, arg);
909
+ //if(arg['__isInstance']) result += instanceToXml(argName, arg);
910
+ }
911
+ return result;
912
+ }
913
+
914
+ /**
915
+ * Convert JavaScript object into XML
916
+
917
+ <r:WiFiEndpointSettingsInput xmlns:q="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_WiFiEndpointSettings">
918
+ <q:ElementName>Wireless-Profile-Admin</q:ElementName>
919
+ <q:InstanceID>Intel(r) AMT:WiFi Endpoint Settings Wireless-Profile-Admin</q:InstanceID>
920
+ <q:AuthenticationMethod>6</q:AuthenticationMethod>
921
+ <q:EncryptionMethod>4</q:EncryptionMethod>
922
+ <q:Priority>100</q:Priority>
923
+ <q:PSKPassPhrase>P@ssw0rd</q:PSKPassPhrase>
924
+ </r:WiFiEndpointSettingsInput>
925
+ */
926
+ function instanceToXml(instanceName, inInstance) {
927
+ if (inInstance === undefined || inInstance === null) return null;
928
+
929
+ var hasNamespace = !!inInstance['__namespace'];
930
+ var startTag = hasNamespace ? '<q:' : '<';
931
+ var endTag = hasNamespace ? '</q:' : '</';
932
+ var namespaceDef = hasNamespace ? (' xmlns:q="' + inInstance['__namespace'] + '"') : '';
933
+ var result = '<r:' + instanceName + namespaceDef + '>';
934
+ for (var prop in inInstance) {
935
+ if (!inInstance.hasOwnProperty(prop) || prop.indexOf('__') === 0) continue;
936
+
937
+ if (typeof inInstance[prop] === 'function' || Array.isArray(inInstance[prop])) continue;
938
+
939
+ if (typeof inInstance[prop] === 'object') {
940
+ //result += startTag + prop +'>' + instanceToXml('prop', inInstance[prop]) + endTag + prop +'>';
941
+ console.error('only convert one level down...');
942
+ }
943
+ else {
944
+ result += startTag + prop + '>' + inInstance[prop].toString() + endTag + prop + '>';
945
+ }
946
+ }
947
+ result += '</r:' + instanceName + '>';
948
+ return result;
949
+ }
950
+
951
+
952
+ /**
953
+ * Convert a selector set into XML. Expect no nesting.
954
+ * {
955
+ * selectorName : selectorValue,
956
+ * selectorName : selectorValue,
957
+ * ... ...
958
+ * }
959
+
960
+ <r:WiFiEndpoint>
961
+ <a:Address>http://192.168.1.103:16992/wsman</a:Address>
962
+ <a:ReferenceParameters>
963
+ <w:ResourceURI>http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_WiFiEndpoint</w:ResourceURI>
964
+ <w:SelectorSet>
965
+ <w:Selector Name="Name">WiFi Endpoint 0</w:Selector>
966
+ </w:SelectorSet>
967
+ </a:ReferenceParameters>
968
+ </r:WiFiEndpoint>
969
+
970
+ */
971
+ function referenceToXml(referenceName, inReference) {
972
+ if (inReference === undefined || inReference === null) return null;
973
+
974
+ var result = '<r:' + referenceName + '><a:Address>/wsman</a:Address><a:ReferenceParameters><w:ResourceURI>' + inReference['__resourceUri'] + '</w:ResourceURI><w:SelectorSet>';
975
+ for (var selectorName in inReference) {
976
+ if (!inReference.hasOwnProperty(selectorName) || selectorName.indexOf('__') === 0) continue;
977
+
978
+ if (typeof inReference[selectorName] === 'function' ||
979
+ typeof inReference[selectorName] === 'object' ||
980
+ Array.isArray(inReference[selectorName]))
981
+ continue;
982
+
983
+ result += '<w:Selector Name="' + selectorName + '">' + inReference[selectorName].toString() + '</w:Selector>';
984
+ }
985
+
986
+ result += '</w:SelectorSet></a:ReferenceParameters></r:' + referenceName + '>';
987
+ return result;
988
+ }
989
+
990
+ // Convert a byte array of SID into string
991
+ function GetSidString(sid) {
992
+ var r = "S-" + sid.charCodeAt(0) + "-" + sid.charCodeAt(7);
993
+ for (var i = 2; i < (sid.length / 4) ; i++) r += "-" + ReadIntX(sid, i * 4);
994
+ return r;
995
+ }
996
+
997
+ // Convert a SID readable string into bytes
998
+ function GetSidByteArray(sidString) {
999
+ if (!sidString || sidString == null) return null;
1000
+ var sidParts = sidString.split('-');
1001
+
1002
+ // Make sure the SID has at least 4 parts and starts with 'S'
1003
+ if (sidParts.length < 4 || (sidParts[0] != 's' && sidParts[0] != 'S')) return null;
1004
+
1005
+ // Check that each part of the SID is really an integer
1006
+ for (var i = 1; i < sidParts.length; i++) { var y = parseInt(sidParts[i]); if (y != sidParts[i]) return null; sidParts[i] = y; }
1007
+
1008
+ // Version (8 bit) + Id count (8 bit) + 48 bit in big endian -- DO NOT use bitwise right shift operator. JavaScript converts the number into a 32 bit integer before shifting. In real world, it's highly likely this part is always 0.
1009
+ var r = String.fromCharCode(sidParts[1]) + String.fromCharCode(sidParts.length - 3) + ShortToStr(Math.floor(sidParts[2] / Math.pow(2, 32))) + IntToStr((sidParts[2]) & 0xFFFF);
1010
+
1011
+ // the rest are in 32 bit in little endian
1012
+ for (var i = 3; i < sidParts.length; i++) r += IntToStrX(sidParts[i]);
1013
+ return r;
1014
+ }
1015
+
1016
+ return obj;
1017
+}
1018
+
1019
+module.exports = AmtStackCreateService;
agents/modules_meshcore_backup/meshcore.js
new
+1658
@@ -0,0 +1,1658 @@
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
+function createMeshCore(agent) {
18
+ var obj = {};
19
+
20
+ // MeshAgent JavaScript Core Module. This code is sent to and running on the mesh agent.
21
+ obj.meshCoreInfo = "MeshCore v5";
22
+ obj.meshCoreCapabilities = 14; // Capability bitmask: 1 = Desktop, 2 = Terminal, 4 = Files, 8 = Console, 16 = JavaScript
23
+ var meshServerConnectionState = 0;
24
+ var tunnels = {};
25
+ var lastSelfInfo = null;
26
+ var lastNetworkInfo = null;
27
+ var lastPublicLocationInfo = null;
28
+ var selfInfoUpdateTimer = null;
29
+ var http = require('http');
30
+ var net = require('net');
31
+ var fs = require('fs');
32
+ var rtc = require('ILibWebRTC');
33
+ var processManager = require('process-manager');
34
+ var SMBiosTables = require('smbios');
35
+ var amtMei = null, amtLms = null, amtLmsState = 0;
36
+ var amtMeiConnected = 0, amtMeiTmpState = null;
37
+ var wifiScannerLib = null;
38
+ var wifiScanner = null;
39
+ var networkMonitor = null;
40
+ var amtscanner = null;
41
+ var nextTunnelIndex = 1;
42
+
43
+ /*
44
+ var AMTScanner = require("AMTScanner");
45
+ var scan = new AMTScanner();
46
+
47
+ scan.on("found", function (data) {
48
+ if (typeof data === 'string') {
49
+ console.log(data);
50
+ } else {
51
+ console.log(JSON.stringify(data, null, " "));
52
+ }
53
+ });
54
+ scan.scan("10.2.55.140", 1000);
55
+ scan.scan("10.2.55.139-10.2.55.145", 1000);
56
+ scan.scan("10.2.55.128/25", 2000);
57
+ */
58
+
59
+ /*
60
+ // Try to load up the network monitor
61
+ try {
62
+ networkMonitor = require('NetworkMonitor');
63
+ networkMonitor.on('change', function () { sendNetworkUpdateNagle(); });
64
+ networkMonitor.on('add', function (addr) { sendNetworkUpdateNagle(); });
65
+ networkMonitor.on('remove', function (addr) { sendNetworkUpdateNagle(); });
66
+ } catch (e) { networkMonitor = null; }
67
+ */
68
+
69
+ // Try to load up the Intel AMT scanner
70
+ try {
71
+ var AMTScannerModule = require('amt-scanner');
72
+ amtscanner = new AMTScannerModule();
73
+ //amtscanner.on('found', function (data) { if (typeof data != 'string') { data = JSON.stringify(data, null, " "); } sendConsoleText(data); });
74
+ } catch (e) { amtscanner = null; }
75
+
76
+ // Try to load up the MEI module
77
+ try {
78
+ var amtMeiLib = require('amt-mei');
79
+ amtMei = new amtMeiLib();
80
+ amtMei.on('error', function (e) { amtMeiLib = null; amtMei = null; sendPeriodicServerUpdate(); });
81
+ amtMeiConnected = 2;
82
+ //amtMei.on('connect', function () { amtMeiConnected = 2; sendPeriodicServerUpdate(); });
83
+ } catch (e) { amtMeiLib = null; amtMei = null; amtMeiConnected = -1; }
84
+
85
+ // Try to load up the WIFI scanner
86
+ try {
87
+ var wifiScannerLib = require('wifi-scanner');
88
+ wifiScanner = new wifiScannerLib();
89
+ wifiScanner.on('accessPoint', function (data) { sendConsoleText(JSON.stringify(data)); });
90
+ } catch (e) { wifiScannerLib = null; wifiScanner = null; }
91
+
92
+ // If we are running in Duktape, agent will be null
93
+ if (agent == null) {
94
+ // Running in native agent, Import libraries
95
+ db = require('SimpleDataStore').Shared();
96
+ sha = require('SHA256Stream');
97
+ mesh = require('MeshAgent');
98
+ childProcess = require('child_process');
99
+ if (mesh.hasKVM == 1) { obj.meshCoreCapabilities |= 1; }
100
+ } else {
101
+ // Running in nodejs
102
+ obj.meshCoreInfo += '-NodeJS';
103
+ obj.meshCoreCapabilities = 8;
104
+ mesh = agent.getMeshApi();
105
+ }
106
+
107
+ // Get our location (lat/long) using our public IP address
108
+ var getIpLocationDataExInProgress = false;
109
+ var getIpLocationDataExCounts = [0, 0];
110
+ function getIpLocationDataEx(func) {
111
+ if (getIpLocationDataExInProgress == true) { return false; }
112
+ try {
113
+ getIpLocationDataExInProgress = true;
114
+ getIpLocationDataExCounts[0]++;
115
+ var options = http.parseUri("http://ipinfo.io/json");
116
+ options.method = 'GET';
117
+ http.request(options, function (resp) {
118
+ if (resp.statusCode == 200) {
119
+ var geoData = '';
120
+ resp.data = function (geoipdata) { geoData += geoipdata; };
121
+ resp.end = function () {
122
+ var location = null;
123
+ try {
124
+ if (typeof geoData == 'string') {
125
+ var result = JSON.parse(geoData);
126
+ if (result.ip && result.loc) { location = result; }
127
+ }
128
+ } catch (e) { }
129
+ if (func) { getIpLocationDataExCounts[1]++; func(location); }
130
+ }
131
+ } else { func(null); }
132
+ getIpLocationDataExInProgress = false;
133
+ }).end();
134
+ return true;
135
+ }
136
+ catch (e) { return false; }
137
+ }
138
+
139
+ // Remove all Gateway MAC addresses for interface list. This is useful because the gateway MAC is not always populated reliably.
140
+ function clearGatewayMac(str) {
141
+ if (str == null) return null;
142
+ var x = JSON.parse(str);
143
+ for (var i in x.netif) { if (x.netif[i].gatewaymac) { delete x.netif[i].gatewaymac } }
144
+ return JSON.stringify(x);
145
+ }
146
+
147
+ function getIpLocationData(func) {
148
+ // Get the location information for the cache if possible
149
+ var publicLocationInfo = db.Get('publicLocationInfo');
150
+ if (publicLocationInfo != null) { publicLocationInfo = JSON.parse(publicLocationInfo); }
151
+ if (publicLocationInfo == null) {
152
+ // Nothing in the cache, fetch the data
153
+ getIpLocationDataEx(function (locationData) {
154
+ if (locationData != null) {
155
+ publicLocationInfo = {};
156
+ publicLocationInfo.netInfoStr = lastNetworkInfo;
157
+ publicLocationInfo.locationData = locationData;
158
+ var x = db.Put('publicLocationInfo', JSON.stringify(publicLocationInfo)); // Save to database
159
+ if (func) func(locationData); // Report the new location
160
+ } else {
161
+ if (func) func(null); // Report no location
162
+ }
163
+ });
164
+ } else {
165
+ // Check the cache
166
+ if (clearGatewayMac(publicLocationInfo.netInfoStr) == clearGatewayMac(lastNetworkInfo)) {
167
+ // Cache match
168
+ if (func) func(publicLocationInfo.locationData);
169
+ } else {
170
+ // Cache mismatch
171
+ getIpLocationDataEx(function (locationData) {
172
+ if (locationData != null) {
173
+ publicLocationInfo = {};
174
+ publicLocationInfo.netInfoStr = lastNetworkInfo;
175
+ publicLocationInfo.locationData = locationData;
176
+ var x = db.Put('publicLocationInfo', JSON.stringify(publicLocationInfo)); // Save to database
177
+ if (func) func(locationData); // Report the new location
178
+ } else {
179
+ if (func) func(publicLocationInfo.locationData); // Can't get new location, report the old location
180
+ }
181
+ });
182
+ }
183
+ }
184
+ }
185
+
186
+ // Polyfill String.endsWith
187
+ if (!String.prototype.endsWith) {
188
+ String.prototype.endsWith = function (searchString, position) {
189
+ var subjectString = this.toString();
190
+ if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; }
191
+ position -= searchString.length;
192
+ var lastIndex = subjectString.lastIndexOf(searchString, position);
193
+ return lastIndex !== -1 && lastIndex === position;
194
+ };
195
+ }
196
+
197
+ // Polyfill path.join
198
+ obj.path = {
199
+ join: function () {
200
+ var x = [];
201
+ for (var i in arguments) {
202
+ var w = arguments[i];
203
+ if (w != null) {
204
+ while (w.endsWith('/') || w.endsWith('\\')) { w = w.substring(0, w.length - 1); }
205
+ if (i != 0) {
206
+ while (w.startsWith('/') || w.startsWith('\\')) { w = w.substring(1); }
207
+ }
208
+ x.push(w);
209
+ }
210
+ }
211
+ if (x.length == 0) return '/';
212
+ return x.join('/');
213
+ }
214
+ };
215
+
216
+ // Replace a string with a number if the string is an exact number
217
+ function toNumberIfNumber(x) { if ((typeof x == 'string') && (+parseInt(x) === x)) { x = parseInt(x); } return x; }
218
+
219
+ // Convert decimal to hex
220
+ function char2hex(i) { return (i + 0x100).toString(16).substr(-2).toUpperCase(); }
221
+
222
+ // Convert a raw string to a hex string
223
+ function rstr2hex(input) { var r = '', i; for (i = 0; i < input.length; i++) { r += char2hex(input.charCodeAt(i)); } return r; }
224
+
225
+ // Convert a buffer into a string
226
+ function buf2rstr(buf) { var r = ''; for (var i = 0; i < buf.length; i++) { r += String.fromCharCode(buf[i]); } return r; }
227
+
228
+ // Convert a hex string to a raw string // TODO: Do this using Buffer(), will be MUCH faster
229
+ function hex2rstr(d) {
230
+ if (typeof d != "string" || d.length == 0) return '';
231
+ var r = '', m = ('' + d).match(/../g), t;
232
+ while (t = m.shift()) r += String.fromCharCode('0x' + t);
233
+ return r
234
+ }
235
+
236
+ // Convert an object to string with all functions
237
+ function objToString(x, p, pad, ret) {
238
+ if (ret == undefined) ret = '';
239
+ if (p == undefined) p = 0;
240
+ if (x == null) { return '[null]'; }
241
+ if (p > 8) { return '[...]'; }
242
+ if (x == undefined) { return '[undefined]'; }
243
+ if (typeof x == 'string') { if (p == 0) return x; return '"' + x + '"'; }
244
+ if (typeof x == 'buffer') { return '[buffer]'; }
245
+ if (typeof x != 'object') { return x; }
246
+ var r = '{' + (ret ? '\r\n' : ' ');
247
+ for (var i in x) { if (i != '_ObjectID') { r += (addPad(p + 2, pad) + i + ': ' + objToString(x[i], p + 2, pad, ret) + (ret ? '\r\n' : ' ')); } }
248
+ return r + addPad(p, pad) + '}';
249
+ }
250
+
251
+ // Return p number of spaces
252
+ function addPad(p, ret) { var r = ''; for (var i = 0; i < p; i++) { r += ret; } return r; }
253
+
254
+ // Split a string taking into account the quoats. Used for command line parsing
255
+ function splitArgs(str) {
256
+ var myArray = [], myRegexp = /[^\s"]+|"([^"]*)"/gi;
257
+ do { var match = myRegexp.exec(str); if (match != null) { myArray.push(match[1] ? match[1] : match[0]); } } while (match != null);
258
+ return myArray;
259
+ }
260
+
261
+ // Parse arguments string array into an object
262
+ function parseArgs(argv) {
263
+ var results = { '_': [] }, current = null;
264
+ for (var i = 1, len = argv.length; i < len; i++) {
265
+ var x = argv[i];
266
+ if (x.length > 2 && x[0] == '-' && x[1] == '-') {
267
+ if (current != null) { results[current] = true; }
268
+ current = x.substring(2);
269
+ } else {
270
+ if (current != null) { results[current] = toNumberIfNumber(x); current = null; } else { results['_'].push(toNumberIfNumber(x)); }
271
+ }
272
+ }
273
+ if (current != null) { results[current] = true; }
274
+ return results;
275
+ }
276
+
277
+ // Get server target url with a custom path
278
+ function getServerTargetUrl(path) {
279
+ var x = mesh.ServerUrl;
280
+ //sendConsoleText("mesh.ServerUrl: " + mesh.ServerUrl);
281
+ if (x == null) { return null; }
282
+ if (path == null) { path = ''; }
283
+ x = http.parseUri(x);
284
+ if (x == null) return null;
285
+ return x.protocol + '//' + x.host + ':' + x.port + '/' + path;
286
+ }
287
+
288
+ // Get server url. If the url starts with "*/..." change it, it not use the url as is.
289
+ function getServerTargetUrlEx(url) {
290
+ if (url.substring(0, 2) == '*/') { return getServerTargetUrl(url.substring(2)); }
291
+ return url;
292
+ }
293
+
294
+ // Send a wake-on-lan packet
295
+ function sendWakeOnLan(hexMac) {
296
+ var count = 0;
297
+ try {
298
+ var interfaces = require('os').networkInterfaces();
299
+ var magic = 'FFFFFFFFFFFF';
300
+ for (var x = 1; x <= 16; ++x) { magic += hexMac; }
301
+ var magicbin = Buffer.from(magic, 'hex');
302
+
303
+ for (var adapter in interfaces) {
304
+ if (interfaces.hasOwnProperty(adapter)) {
305
+ for (var i = 0; i < interfaces[adapter].length; ++i) {
306
+ var addr = interfaces[adapter][i];
307
+ if ((addr.family == 'IPv4') && (addr.mac != '00:00:00:00:00:00')) {
308
+ var socket = require('dgram').createSocket({ type: "udp4" });
309
+ socket.bind({ address: addr.address });
310
+ socket.setBroadcast(true);
311
+ socket.send(magicbin, 7, "255.255.255.255");
312
+ count++;
313
+ }
314
+ }
315
+ }
316
+ }
317
+ } catch (e) { }
318
+ return count;
319
+ }
320
+
321
+ // Handle a mesh agent command
322
+ function handleServerCommand(data) {
323
+ if (typeof data == 'object') {
324
+ // If this is a console command, parse it and call the console handler
325
+ switch (data.action) {
326
+ case 'msg': {
327
+ switch (data.type) {
328
+ case 'console': { // Process a console command
329
+ if (data.value && data.sessionid) {
330
+ var args = splitArgs(data.value);
331
+ processConsoleCommand(args[0].toLowerCase(), parseArgs(args), data.rights, data.sessionid);
332
+ }
333
+ break;
334
+ }
335
+ case 'tunnel': {
336
+ if (data.value != null) { // Process a new tunnel connection request
337
+ // Create a new tunnel object
338
+ var xurl = getServerTargetUrlEx(data.value);
339
+ if (xurl != null) {
340
+ var woptions = http.parseUri(xurl);
341
+ woptions.rejectUnauthorized = 0;
342
+ //sendConsoleText(JSON.stringify(woptions));
343
+ var tunnel = http.request(woptions);
344
+ tunnel.upgrade = onTunnelUpgrade;
345
+ tunnel.onerror = function (e) { sendConsoleText('ERROR: ' + JSON.stringify(e)); }
346
+ tunnel.sessionid = data.sessionid;
347
+ tunnel.rights = data.rights;
348
+ tunnel.state = 0;
349
+ tunnel.url = xurl;
350
+ tunnel.protocol = 0;
351
+ tunnel.tcpaddr = data.tcpaddr;
352
+ tunnel.tcpport = data.tcpport;
353
+ tunnel.end();
354
+ // Put the tunnel in the tunnels list
355
+ var index = nextTunnelIndex++;;
356
+ tunnel.index = index;
357
+ tunnels[index] = tunnel;
358
+
359
+ sendConsoleText('New tunnel connection #' + index + ': ' + tunnel.url + ', rights: ' + tunnel.rights, data.sessionid);
360
+ }
361
+ }
362
+ break;
363
+ }
364
+ case 'ps': {
365
+ if (data.sessionid) {
366
+ processManager.getProcesses(function (plist) { mesh.SendCommand({ "action": "msg", "type": "ps", "value": JSON.stringify(plist), "sessionid": data.sessionid }); });
367
+ }
368
+ break;
369
+ }
370
+ case 'pskill': {
371
+ //sendConsoleText(JSON.stringify(data));
372
+ try { process.kill(data.value); } catch (e) { sendConsoleText(JSON.stringify(e)); }
373
+ break;
374
+ }
375
+ }
376
+ break;
377
+ }
378
+ case 'wakeonlan': {
379
+ // Send wake-on-lan on all interfaces for all MAC addresses in data.macs array. The array is a list of HEX MAC addresses.
380
+ sendConsoleText('Server requesting wake-on-lan for: ' + data.macs.join(', '));
381
+ for (var i in data.macs) { sendWakeOnLan(data.macs[i]); }
382
+ break;
383
+ }
384
+ case 'poweraction': {
385
+ // Server telling us to execute a power action
386
+ if ((mesh.ExecPowerState != undefined) && (data.actiontype)) {
387
+ var forced = 0;
388
+ if (data.forced == 1) { forced = 1; }
389
+ data.actiontype = parseInt(data.actiontype);
390
+ sendConsoleText('Performing power action=' + data.actiontype + ', forced=' + forced + '.');
391
+ var r = mesh.ExecPowerState(data.actiontype, forced);
392
+ sendConsoleText('ExecPowerState returned code: ' + r);
393
+ }
394
+ break;
395
+ }
396
+ case 'iplocation': {
397
+ // Update the IP location information of this node. Only do this when requested by the server since we have a limited amount of time we can call this per day
398
+ getIpLocationData(function (location) { mesh.SendCommand({ "action": "iplocation", "type": "publicip", "value": location }); });
399
+ break;
400
+ }
401
+ case 'toast': {
402
+ // Display a toast message
403
+ if (data.title && data.msg) { require('toaster').Toast(data.title, data.msg); }
404
+ break;
405
+ }
406
+ }
407
+ }
408
+ }
409
+
410
+ // Called when a file changed in the file system
411
+ /*
412
+ function onFileWatcher(a, b) {
413
+ console.log('onFileWatcher', a, b, this.path);
414
+ var response = getDirectoryInfo(this.path);
415
+ if ((response != undefined) && (response != null)) { this.tunnel.s.write(JSON.stringify(response)); }
416
+ }
417
+ */
418
+
419
+ // Get a formated response for a given directory path
420
+ function getDirectoryInfo(reqpath) {
421
+ var response = { path: reqpath, dir: [] };
422
+ if (((reqpath == undefined) || (reqpath == '')) && (process.platform == 'win32')) {
423
+ // List all the drives in the root, or the root itself
424
+ var results = null;
425
+ try { results = fs.readDrivesSync(); } catch (e) { } // TODO: Anyway to get drive total size and free space? Could draw a progress bar.
426
+ if (results != null) {
427
+ for (var i = 0; i < results.length; ++i) {
428
+ var drive = { n: results[i].name, t: 1 };
429
+ if (results[i].type == 'REMOVABLE') { drive.dt = 'removable'; } // TODO: See if this is USB/CDROM or something else, we can draw icons.
430
+ response.dir.push(drive);
431
+ }
432
+ }
433
+ } else {
434
+ // List all the files and folders in this path
435
+ if (reqpath == '') { reqpath = '/'; }
436
+ var results = null, xpath = obj.path.join(reqpath, '*');
437
+ //if (process.platform == "win32") { xpath = xpath.split('/').join('\\'); }
438
+ try { results = fs.readdirSync(xpath); } catch (e) { }
439
+ if (results != null) {
440
+ for (var i = 0; i < results.length; ++i) {
441
+ if ((results[i] != '.') && (results[i] != '..')) {
442
+ var stat = null, p = obj.path.join(reqpath, results[i]);
443
+ //if (process.platform == "win32") { p = p.split('/').join('\\'); }
444
+ try { stat = fs.statSync(p); } catch (e) { } // TODO: Get file size/date
445
+ if ((stat != null) && (stat != undefined)) {
446
+ if (stat.isDirectory() == true) {
447
+ response.dir.push({ n: results[i], t: 2, d: stat.mtime });
448
+ } else {
449
+ response.dir.push({ n: results[i], t: 3, s: stat.size, d: stat.mtime });
450
+ }
451
+ }
452
+ }
453
+ }
454
+ }
455
+ }
456
+ return response;
457
+ }
458
+
459
+ // Tunnel callback operations
460
+ function onTunnelUpgrade(response, s, head) {
461
+ this.s = s;
462
+ s.httprequest = this;
463
+ s.end = onTunnelClosed;
464
+ s.tunnel = this;
465
+
466
+ if (this.tcpport != null) {
467
+ // This is a TCP relay connection, pause now and try to connect to the target.
468
+ s.pause();
469
+ s.data = onTcpRelayServerTunnelData;
470
+ var connectionOptions = { port: parseInt(this.tcpport) };
471
+ if (this.tcpaddr != null) { connectionOptions.host = this.tcpaddr; } else { connectionOptions.host = '127.0.0.1'; }
472
+ s.tcprelay = net.createConnection(connectionOptions, onTcpRelayTargetTunnelConnect);
473
+ s.tcprelay.peerindex = this.index;
474
+ } else {
475
+ // This is a normal connect for KVM/Terminal/Files
476
+ s.data = onTunnelData;
477
+ }
478
+ }
479
+
480
+ // Called when the TCP relay target is connected
481
+ function onTcpRelayTargetTunnelConnect() {
482
+ var peerTunnel = tunnels[this.peerindex];
483
+ this.pipe(peerTunnel.s); // Pipe Target --> Server
484
+ peerTunnel.s.first = true;
485
+ peerTunnel.s.resume();
486
+ }
487
+
488
+ // Called when we get data from the server for a TCP relay (We have to skip the first received 'c' and pipe the rest)
489
+ function onTcpRelayServerTunnelData(data) {
490
+ if (this.first == true) { this.first = false; this.pipe(this.tcprelay); } // Pipe Server --> Target
491
+ }
492
+
493
+ function onTunnelClosed() {
494
+ if (tunnels[this.httprequest.index] == null) return; // Stop duplicate calls.
495
+ sendConsoleText("Tunnel #" + this.httprequest.index + " closed.", this.httprequest.sessionid);
496
+ delete tunnels[this.httprequest.index];
497
+
498
+ /*
499
+ // Close the watcher if required
500
+ if (this.httprequest.watcher != undefined) {
501
+ //console.log('Closing watcher: ' + this.httprequest.watcher.path);
502
+ //this.httprequest.watcher.close(); // TODO: This line causes the agent to crash!!!!
503
+ delete this.httprequest.watcher;
504
+ }
505
+ */
506
+
507
+ // If there is a upload or download active on this connection, close the file
508
+ if (this.httprequest.uploadFile) { fs.closeSync(this.httprequest.uploadFile); this.httprequest.uploadFile = undefined; }
509
+ if (this.httprequest.downloadFile) { fs.closeSync(this.httprequest.downloadFile); this.httprequest.downloadFile = undefined; }
510
+
511
+ // Clean up WebRTC
512
+ if (this.webrtc != null) {
513
+ if (this.webrtc.rtcchannel) { try { this.webrtc.rtcchannel.close(); } catch (e) { } this.webrtc.rtcchannel.removeAllListeners('data'); this.webrtc.rtcchannel.removeAllListeners('end'); delete this.webrtc.rtcchannel; }
514
+ if (this.webrtc.websocket) { delete this.webrtc.websocket; }
515
+ try { this.webrtc.close(); } catch (e) { }
516
+ this.webrtc.removeAllListeners('connected');
517
+ this.webrtc.removeAllListeners('disconnected');
518
+ this.webrtc.removeAllListeners('dataChannel');
519
+ delete this.webrtc;
520
+ }
521
+
522
+ // Clean up WebSocket
523
+ this.removeAllListeners('data');
524
+ }
525
+ function onTunnelSendOk() { sendConsoleText("Tunnel #" + this.index + " SendOK.", this.sessionid); }
526
+ function onTunnelData(data) {
527
+ //console.log("OnTunnelData");
528
+ //sendConsoleText('OnTunnelData, ' + data.length + ', ' + typeof data + ', ' + data);
529
+
530
+ // If this is upload data, save it to file
531
+ if (this.httprequest.uploadFile) {
532
+ try { fs.writeSync(this.httprequest.uploadFile, data); } catch (e) { this.write(new Buffer(JSON.stringify({ action: 'uploaderror' }))); return; } // Write to the file, if there is a problem, error out.
533
+ this.write(new Buffer(JSON.stringify({ action: 'uploadack', reqid: this.httprequest.uploadFileid }))); // Ask for more data
534
+ return;
535
+ }
536
+ /*
537
+ // If this is a download, send more of the file
538
+ if (this.httprequest.downloadFile) {
539
+ var buf = new Buffer(4096);
540
+ var len = fs.readSync(this.httprequest.downloadFile, buf, 0, 4096, null);
541
+ this.httprequest.downloadFilePtr += len;
542
+ if (len > 0) { this.write(buf.slice(0, len)); } else { fs.closeSync(this.httprequest.downloadFile); this.httprequest.downloadFile = undefined; this.end(); }
543
+ return;
544
+ }
545
+ */
546
+
547
+ if (this.httprequest.state == 0) {
548
+ // Check if this is a relay connection
549
+ if (data == 'c') { this.httprequest.state = 1; sendConsoleText("Tunnel #" + this.httprequest.index + " now active", this.httprequest.sessionid); }
550
+ } else {
551
+ // Handle tunnel data
552
+ if (this.httprequest.protocol == 0) { // 1 = SOL, 2 = KVM, 3 = IDER, 4 = Files, 5 = FileTransfer
553
+ // Take a look at the protocol
554
+ this.httprequest.protocol = parseInt(data);
555
+ if (typeof this.httprequest.protocol != 'number') { this.httprequest.protocol = 0; }
556
+ if (this.httprequest.protocol == 1) {
557
+ // Remote terminal using native pipes
558
+ if (process.platform == "win32") {
559
+ this.httprequest.process = childProcess.execFile("%windir%\\system32\\cmd.exe");
560
+ } else {
561
+ this.httprequest.process = childProcess.execFile("/bin/sh", ["sh"], { type: childProcess.SpawnTypes.TERM });
562
+ }
563
+ this.httprequest.process.tunnel = this;
564
+ this.httprequest.process.on('exit', function (ecode, sig) { this.tunnel.end(); });
565
+ this.httprequest.process.stderr.on('data', function (chunk) { this.parent.tunnel.write(chunk); });
566
+ this.httprequest.process.stdout.pipe(this, { dataTypeSkip: 1 }); // 0 = Binary, 1 = Text.
567
+ this.pipe(this.httprequest.process.stdin, { dataTypeSkip: 1, end: false }); // 0 = Binary, 1 = Text.
568
+ this.prependListener('end', function () { this.httprequest.process.kill(); });
569
+ this.removeAllListeners('data');
570
+ this.on('data', onTunnelControlData);
571
+ //this.write('MeshCore Terminal Hello');
572
+ if (process.platform != 'win32') { this.httprequest.process.stdin.write("stty erase ^H\nalias ls='ls --color=auto'\nclear\n"); }
573
+ } else if (this.httprequest.protocol == 2)
574
+ {
575
+ // Remote desktop using native pipes
576
+ this.httprequest.desktop = { state: 0, kvm: mesh.getRemoteDesktopStream(), tunnel: this };
577
+ this.httprequest.desktop.kvm.parent = this.httprequest.desktop;
578
+ this.desktop = this.httprequest.desktop;
579
+
580
+ // Display a toast message
581
+ //require('toaster').Toast('MeshCentral', 'Remote Desktop Control Started.');
582
+
583
+ this.end = function () {
584
+ --this.desktop.kvm.connectionCount;
585
+ this.unpipe(this.httprequest.desktop.kvm);
586
+ this.httprequest.desktop.kvm.unpipe(this);
587
+ if (this.desktop.kvm.connectionCount == 0) {
588
+ // Display a toast message
589
+ //require('toaster').Toast('MeshCentral', 'Remote Desktop Control Ended.');
590
+ this.httprequest.desktop.kvm.end();
591
+ }
592
+ };
593
+ if (this.httprequest.desktop.kvm.hasOwnProperty("connectionCount")) { this.httprequest.desktop.kvm.connectionCount++; } else { this.httprequest.desktop.kvm.connectionCount = 1; }
594
+ this.pipe(this.httprequest.desktop.kvm, { dataTypeSkip: 1, end: false }); // 0 = Binary, 1 = Text.
595
+ this.httprequest.desktop.kvm.pipe(this, { dataTypeSkip: 1 }); // 0 = Binary, 1 = Text.
596
+ this.removeAllListeners('data');
597
+ this.on('data', onTunnelControlData);
598
+ //this.write('MeshCore KVM Hello!1');
599
+ } else if (this.httprequest.protocol == 5) {
600
+ // Setup files
601
+ // NOP
602
+ }
603
+ } else if (this.httprequest.protocol == 1) {
604
+ // Send data into terminal stdin
605
+ //this.write(data); // Echo back the keys (Does not seem to be a good idea)
606
+ this.httprequest.process.write(data);
607
+ } else if (this.httprequest.protocol == 2) {
608
+ // Send data into remote desktop
609
+ if (this.httprequest.desktop.state == 0) {
610
+ this.write(new Buffer(String.fromCharCode(0x11, 0xFE, 0x00, 0x00, 0x4D, 0x45, 0x53, 0x48, 0x00, 0x00, 0x00, 0x00, 0x02)));
611
+ this.httprequest.desktop.state = 1;
612
+ } else {
613
+ this.httprequest.desktop.write(data);
614
+ }
615
+ } else if (this.httprequest.protocol == 5) {
616
+ // Process files commands
617
+ var cmd = null;
618
+ try { cmd = JSON.parse(data); } catch (e) { };
619
+ if (cmd == null) { return; }
620
+ if ((cmd.ctrlChannel == '102938') || ((cmd.type == 'offer') && (cmd.sdp != null))) { onTunnelControlData(cmd, this); return; } // If this is control data, handle it now.
621
+ if (cmd.action == undefined) { return; }
622
+ //sendConsoleText('CMD: ' + JSON.stringify(cmd));
623
+
624
+ if ((cmd.path != null) && (process.platform != 'win32') && (cmd.path[0] != '/')) { cmd.path = '/' + cmd.path; } // Add '/' to paths on non-windows
625
+ //console.log(objToString(cmd, 0, ' '));
626
+ switch (cmd.action) {
627
+ case 'ls': {
628
+ /*
629
+ // Close the watcher if required
630
+ var samepath = ((this.httprequest.watcher != undefined) && (cmd.path == this.httprequest.watcher.path));
631
+ if ((this.httprequest.watcher != undefined) && (samepath == false)) {
632
+ //console.log('Closing watcher: ' + this.httprequest.watcher.path);
633
+ //this.httprequest.watcher.close(); // TODO: This line causes the agent to crash!!!!
634
+ delete this.httprequest.watcher;
635
+ }
636
+ */
637
+
638
+ // Send the folder content to the browser
639
+ var response = getDirectoryInfo(cmd.path);
640
+ if (cmd.reqid != undefined) { response.reqid = cmd.reqid; }
641
+ this.write(new Buffer(JSON.stringify(response)));
642
+
643
+ /*
644
+ // Start the directory watcher
645
+ if ((cmd.path != '') && (samepath == false)) {
646
+ var watcher = fs.watch(cmd.path, onFileWatcher);
647
+ watcher.tunnel = this.httprequest;
648
+ watcher.path = cmd.path;
649
+ this.httprequest.watcher = watcher;
650
+ //console.log('Starting watcher: ' + this.httprequest.watcher.path);
651
+ }
652
+ */
653
+ break;
654
+ }
655
+ case 'mkdir': {
656
+ // Create a new empty folder
657
+ fs.mkdirSync(cmd.path);
658
+ break;
659
+ }
660
+ case 'rm': {
661
+ // Remove many files or folders
662
+ for (var i in cmd.delfiles) {
663
+ var fullpath = obj.path.join(cmd.path, cmd.delfiles[i]);
664
+ try { fs.unlinkSync(fullpath); } catch (e) { console.log(e); }
665
+ }
666
+ break;
667
+ }
668
+ case 'rename': {
669
+ // Rename a file or folder
670
+ var oldfullpath = obj.path.join(cmd.path, cmd.oldname);
671
+ var newfullpath = obj.path.join(cmd.path, cmd.newname);
672
+ try { fs.renameSync(oldfullpath, newfullpath); } catch (e) { console.log(e); }
673
+ break;
674
+ }
675
+ case 'download': {
676
+ // Download a file
677
+ var sendNextBlock = 0;
678
+ if (cmd.sub == 'start') { // Setup the download
679
+ if (this.filedownload != null) { this.write({ action: 'download', sub: 'cancel', id: this.filedownload.id }); delete this.filedownload; }
680
+ this.filedownload = { id: cmd.id, path: cmd.path, ptr: 0 }
681
+ try { this.filedownload.f = fs.openSync(this.filedownload.path, 'rbN'); } catch (e) { this.write({ action: 'download', sub: 'cancel', id: this.filedownload.id }); delete this.filedownload; }
682
+ if (this.filedownload) { this.write({ action: 'download', sub: 'start', id: cmd.id }); }
683
+ } else if ((this.filedownload != null) && (cmd.id == this.filedownload.id)) { // Download commands
684
+ if (cmd.sub == 'startack') { sendNextBlock = 8; } else if (cmd.sub == 'stop') { delete this.filedownload; } else if (cmd.sub == 'ack') { sendNextBlock = 1; }
685
+ }
686
+ // Send the next download block(s)
687
+ while (sendNextBlock > 0) {
688
+ sendNextBlock--;
689
+ var buf = new Buffer(4096);
690
+ var len = fs.readSync(this.filedownload.f, buf, 4, 4092, null);
691
+ this.filedownload.ptr += len;
692
+ if (len < 4092) { buf.writeInt32BE(0x01000001, 0); fs.closeSync(this.filedownload.f); delete this.filedownload; sendNextBlock = 0; } else { buf.writeInt32BE(0x01000000, 0); }
693
+ this.write(buf.slice(0, len + 4)); // Write as binary
694
+ }
695
+ break;
696
+ }
697
+ /*
698
+ case 'download': {
699
+ // Packet download of a file, agent to browser
700
+ if (cmd.path == undefined) break;
701
+ var filepath = cmd.name ? obj.path.join(cmd.path, cmd.name) : cmd.path;
702
+ //console.log('Download: ' + filepath);
703
+ try { this.httprequest.downloadFile = fs.openSync(filepath, 'rbN'); } catch (e) { this.write(new Buffer(JSON.stringify({ action: 'downloaderror', reqid: cmd.reqid }))); break; }
704
+ this.httprequest.downloadFileId = cmd.reqid;
705
+ this.httprequest.downloadFilePtr = 0;
706
+ if (this.httprequest.downloadFile) { this.write(new Buffer(JSON.stringify({ action: 'downloadstart', reqid: this.httprequest.downloadFileId }))); }
707
+ break;
708
+ }
709
+ case 'download2': {
710
+ // Stream download of a file, agent to browser
711
+ if (cmd.path == undefined) break;
712
+ var filepath = cmd.name ? obj.path.join(cmd.path, cmd.name) : cmd.path;
713
+ try { this.httprequest.downloadFile = fs.createReadStream(filepath, { flags: 'rbN' }); } catch (e) { console.log(e); }
714
+ this.httprequest.downloadFile.pipe(this);
715
+ this.httprequest.downloadFile.end = function () { }
716
+ break;
717
+ }
718
+ */
719
+ case 'upload': {
720
+ // Upload a file, browser to agent
721
+ if (this.httprequest.uploadFile != undefined) { fs.closeSync(this.httprequest.uploadFile); this.httprequest.uploadFile = undefined; }
722
+ if (cmd.path == undefined) break;
723
+ var filepath = cmd.name ? obj.path.join(cmd.path, cmd.name) : cmd.path;
724
+ try { this.httprequest.uploadFile = fs.openSync(filepath, 'wbN'); } catch (e) { this.write(new Buffer(JSON.stringify({ action: 'uploaderror', reqid: cmd.reqid }))); break; }
725
+ this.httprequest.uploadFileid = cmd.reqid;
726
+ if (this.httprequest.uploadFile) { this.write(new Buffer(JSON.stringify({ action: 'uploadstart', reqid: this.httprequest.uploadFileid }))); }
727
+ break;
728
+ }
729
+ case 'copy': {
730
+ // Copy a bunch of files from scpath to dspath
731
+ for (var i in cmd.names) {
732
+ var sc = obj.path.join(cmd.scpath, cmd.names[i]), ds = obj.path.join(cmd.dspath, cmd.names[i]);
733
+ if (sc != ds) { try { fs.copyFileSync(sc, ds); } catch (e) { } }
734
+ }
735
+ break;
736
+ }
737
+ case 'move': {
738
+ // Move a bunch of files from scpath to dspath
739
+ for (var i in cmd.names) {
740
+ var sc = obj.path.join(cmd.scpath, cmd.names[i]), ds = obj.path.join(cmd.dspath, cmd.names[i]);
741
+ if (sc != ds) { try { fs.copyFileSync(sc, ds); fs.unlinkSync(sc); } catch (e) { } }
742
+ }
743
+ break;
744
+ }
745
+ }
746
+ }
747
+ //sendConsoleText("Got tunnel #" + this.httprequest.index + " data: " + data, this.httprequest.sessionid);
748
+ }
749
+ }
750
+
751
+ // Called when receiving control data on WebRTC
752
+ function onTunnelWebRTCControlData(data) {
753
+ if (typeof data != 'string') return;
754
+ var obj;
755
+ try { obj = JSON.parse(data); } catch (e) { sendConsoleText('Invalid control JSON on WebRTC: ' + data); return; }
756
+ if (obj.type == 'close') {
757
+ //sendConsoleText('Tunnel #' + this.xrtc.websocket.tunnel.index + ' WebRTC control close');
758
+ try { this.close(); } catch (e) { }
759
+ try { this.xrtc.close(); } catch (e) { }
760
+ }
761
+ }
762
+
763
+ // Called when receiving control data on websocket
764
+ function onTunnelControlData(data, ws) {
765
+ var obj;
766
+ if (ws == null) { ws = this; }
767
+ if (typeof data == 'string') { try { obj = JSON.parse(data); } catch (e) { sendConsoleText('Invalid control JSON: ' + data); return; } }
768
+ else if (typeof data == 'object') { obj = data; } else { return; }
769
+ //sendConsoleText('onTunnelControlData(' + ws.httprequest.protocol + '): ' + JSON.stringify(data));
770
+ //console.log('onTunnelControlData: ' + JSON.stringify(data));
771
+
772
+ if (obj.action) {
773
+ switch (obj.action) {
774
+ case 'lock': {
775
+ // Lock the current user out of the desktop
776
+ try {
777
+ if (process.platform == 'win32') {
778
+ var child = require('child_process');
779
+ child.execFile(process.env['windir'] + '\\system32\\cmd.exe', ['/c', 'RunDll32.exe user32.dll,LockWorkStation'], { type: 1 });
780
+ }
781
+ } catch (e) { }
782
+ break;
783
+ }
784
+ }
785
+ return;
786
+ }
787
+
788
+ if (obj.type == 'close') {
789
+ // We received the close on the websocket
790
+ //sendConsoleText('Tunnel #' + ws.tunnel.index + ' WebSocket control close');
791
+ try { ws.close(); } catch (e) { }
792
+ } else if (obj.type == 'webrtc0') { // Browser indicates we can start WebRTC switch-over.
793
+ if (ws.httprequest.protocol == 1) { // Terminal
794
+ // This is a terminal data stream, unpipe the terminal now and indicate to the other side that terminal data will no longer be received over WebSocket
795
+ ws.httprequest.process.stdout.unpipe(ws);
796
+ ws.httprequest.process.stderr.unpipe(ws);
797
+ } else if (ws.httprequest.protocol == 2) { // Desktop
798
+ // This is a KVM data stream, unpipe the KVM now and indicate to the other side that KVM data will no longer be received over WebSocket
799
+ ws.httprequest.desktop.kvm.unpipe(ws);
800
+ } else {
801
+ // Switch things around so all WebRTC data goes to onTunnelData().
802
+ ws.rtcchannel.httprequest = ws.httprequest;
803
+ ws.rtcchannel.removeAllListeners('data');
804
+ ws.rtcchannel.on('data', onTunnelData);
805
+ }
806
+ ws.write("{\"ctrlChannel\":\"102938\",\"type\":\"webrtc1\"}"); // End of data marker
807
+ } else if (obj.type == 'webrtc1') {
808
+ if (ws.httprequest.protocol == 1) { // Terminal
809
+ // Switch the user input from websocket to webrtc at this point.
810
+ ws.unpipe(ws.httprequest.process.stdin);
811
+ ws.rtcchannel.pipe(ws.httprequest.process.stdin, { dataTypeSkip: 1 }); // 0 = Binary, 1 = Text.
812
+ ws.resume(); // Resume the websocket to keep receiving control data
813
+ } else if (ws.httprequest.protocol == 2) { // Desktop
814
+ // Switch the user input from websocket to webrtc at this point.
815
+ ws.unpipe(ws.httprequest.desktop.kvm);
816
+ try { ws.webrtc.rtcchannel.pipe(ws.httprequest.desktop.kvm, { dataTypeSkip: 1, end: false }); } catch (e) { sendConsoleText('EX2'); } // 0 = Binary, 1 = Text.
817
+ ws.resume(); // Resume the websocket to keep receiving control data
818
+ }
819
+ ws.write("{\"ctrlChannel\":\"102938\",\"type\":\"webrtc2\"}"); // Indicates we will no longer get any data on websocket, switching to WebRTC at this point.
820
+ } else if (obj.type == 'webrtc2') {
821
+ // Other side received websocket end of data marker, start sending data on WebRTC channel
822
+ if (ws.httprequest.protocol == 1) { // Terminal
823
+ ws.httprequest.process.stdout.pipe(ws.webrtc.rtcchannel, { dataTypeSkip: 1, end: false }); // 0 = Binary, 1 = Text.
824
+ ws.httprequest.process.stderr.pipe(ws.webrtc.rtcchannel, { dataTypeSkip: 1, end: false }); // 0 = Binary, 1 = Text.
825
+ } else if (ws.httprequest.protocol == 2) { // Desktop
826
+ ws.httprequest.desktop.kvm.pipe(ws.webrtc.rtcchannel, { dataTypeSkip: 1 }); // 0 = Binary, 1 = Text.
827
+ }
828
+ } else if (obj.type == 'offer') {
829
+ // This is a WebRTC offer.
830
+ ws.webrtc = rtc.createConnection();
831
+ ws.webrtc.websocket = ws;
832
+ ws.webrtc.on('connected', function () { /*sendConsoleText('Tunnel #' + this.websocket.tunnel.index + ' WebRTC connected');*/ });
833
+ ws.webrtc.on('disconnected', function () { /*sendConsoleText('Tunnel #' + this.websocket.tunnel.index + ' WebRTC disconnected');*/ });
834
+ ws.webrtc.on('dataChannel', function (rtcchannel) {
835
+ //sendConsoleText('WebRTC Datachannel open, protocol: ' + this.websocket.httprequest.protocol);
836
+ rtcchannel.xrtc = this;
837
+ rtcchannel.websocket = this.websocket;
838
+ this.rtcchannel = rtcchannel;
839
+ this.websocket.rtcchannel = rtcchannel;
840
+ this.websocket.rtcchannel.on('data', onTunnelWebRTCControlData);
841
+ this.websocket.rtcchannel.on('end', function () { /*sendConsoleText('Tunnel #' + this.websocket.tunnel.index + ' WebRTC data channel closed');*/ });
842
+ this.websocket.write("{\"ctrlChannel\":\"102938\",\"type\":\"webrtc0\"}"); // Indicate we are ready for WebRTC switch-over.
843
+ });
844
+ var sdp = null;
845
+ try { sdp = ws.webrtc.setOffer(obj.sdp); } catch (ex) { }
846
+ if (sdp != null) { ws.write({ type: 'answer', ctrlChannel: '102938', sdp: sdp }); }
847
+ }
848
+ }
849
+
850
+ // Console state
851
+ var consoleWebSockets = {};
852
+ var consoleHttpRequest = null;
853
+
854
+ // Console HTTP response
855
+ function consoleHttpResponse(response) {
856
+ response.data = function (data) { sendConsoleText(rstr2hex(buf2rstr(data)), this.sessionid); consoleHttpRequest = null; }
857
+ response.close = function () { sendConsoleText('httprequest.response.close', this.sessionid); consoleHttpRequest = null; }
858
+ };
859
+
860
+ // Process a mesh agent console command
861
+ function processConsoleCommand(cmd, args, rights, sessionid) {
862
+ try {
863
+ var response = null;
864
+ switch (cmd) {
865
+ case 'help': { // Displays available commands
866
+ response = 'Available commands: help, info, args, print, type, dbget, dbset, dbcompact, eval, parseuri, httpget,\r\nwslist, wsconnect, wssend, wsclose, notify, ls, ps, kill, amt, netinfo, location, power, wakeonlan, scanwifi,\r\nscanamt, setdebug, smbios, rawsmbios, toast, lock.';
867
+ break;
868
+ }
869
+ case 'toast': {
870
+ if (process.platform == 'win32') {
871
+ if (args['_'].length < 1) { response = 'Proper usage: toast "message"'; } else {
872
+ require('toaster').Toast('MeshCentral', args['_'][0]);
873
+ response = 'ok';
874
+ }
875
+ } else {
876
+ response = 'Only supported on Windows.';
877
+ }
878
+ break;
879
+ }
880
+ case 'setdebug': {
881
+ if (args['_'].length < 1) { response = 'Proper usage: setdebug (target), 0 = StdOut, 1 = This Console, * = All Consoles, 2 = WebLog, 3 = Disabled'; } // Display usage
882
+ else { if (args['_'][0] == '*') { console.setDestination(1); } else { console.setDestination(parseInt(args['_'][0]), sessionid); } }
883
+ break;
884
+ }
885
+ case 'ps': {
886
+ processManager.getProcesses(function (plist) {
887
+ var x = '';
888
+ for (var i in plist) { x += i + ', ' + plist[i].cmd + ((plist[i].user) ? (', ' + plist[i].user):'') + '\r\n'; }
889
+ sendConsoleText(x, sessionid);
890
+ });
891
+ break;
892
+ }
893
+ case 'kill': {
894
+ if ((args['_'].length < 1)) {
895
+ response = 'Proper usage: kill [pid]'; // Display correct command usage
896
+ } else {
897
+ process.kill(parseInt(args['_'][0]));
898
+ response = 'Killed process ' + args['_'][0] + '.';
899
+ }
900
+ break;
901
+ }
902
+ case 'smbios': {
903
+ if (SMBiosTables != null) {
904
+ SMBiosTables.get(function (data) {
905
+ if (data == null) { sendConsoleText('Unable to get SM BIOS data.', sessionid); return; }
906
+ sendConsoleText(objToString(SMBiosTables.parse(data), 0, ' ', true), sessionid);
907
+ });
908
+ } else { response = 'SM BIOS module not available.'; }
909
+ break;
910
+ }
911
+ case 'rawsmbios': {
912
+ if (SMBiosTables != null) {
913
+ SMBiosTables.get(function (data) {
914
+ if (data == null) { sendConsoleText('Unable to get SM BIOS data.', sessionid); return; }
915
+ var out = '';
916
+ for (var i in data) {
917
+ var header = false;
918
+ for (var j in data[i]) {
919
+ if (data[i][j].length > 0) {
920
+ if (header == false) { out += ('Table type #' + i + ((SMBiosTables.smTableTypes[i] == null) ? '' : (', ' + SMBiosTables.smTableTypes[i]))) + '\r\n'; header = true; }
921
+ out += (' ' + data[i][j].toString('hex')) + '\r\n';
922
+ }
923
+ }
924
+ }
925
+ sendConsoleText(out, sessionid);
926
+ });
927
+ } else { response = 'SM BIOS module not available.'; }
928
+ break;
929
+ }
930
+ case 'eval': { // Eval JavaScript
931
+ if (args['_'].length < 1) {
932
+ response = 'Proper usage: eval "JavaScript code"'; // Display correct command usage
933
+ } else {
934
+ response = JSON.stringify(mesh.eval(args['_'][0]));
935
+ }
936
+ break;
937
+ }
938
+ case 'notify': { // Send a notification message to the mesh
939
+ if (args['_'].length != 1) {
940
+ response = 'Proper usage: notify "message" [--session]'; // Display correct command usage
941
+ } else {
942
+ var notification = { "action": "msg", "type": "notify", "value": args['_'][0], "tag": "console" };
943
+ if (args.session) { notification.sessionid = sessionid; } // If "--session" is specified, notify only this session, if not, the server will notify the mesh
944
+ mesh.SendCommand(notification); // no sessionid or userid specified, notification will go to the entire mesh
945
+ response = 'ok';
946
+ }
947
+ break;
948
+ }
949
+ case 'info': { // Return information about the agent and agent core module
950
+ response = 'Current Core: ' + obj.meshCoreInfo + '.\r\nAgent Time: ' + Date() + '.\r\nUser Rights: 0x' + rights.toString(16) + '.\r\nPlatform Info: ' + process.platform + '.\r\nCapabilities: ' + obj.meshCoreCapabilities + '.\r\nServer URL: ' + mesh.ServerUrl + '.';
951
+ if (amtLmsState >= 0) { response += '\r\nBuilt-in LMS: ' + ['Disabled', 'Connecting..', 'Connected'][amtLmsState] + '.'; }
952
+ response += '\r\nModules: ' + addedModules.join(', ');
953
+ response += '\r\nServerConnected: ' + mesh.isControlChannelConnected;
954
+ var oldNodeId = db.Get('OldNodeId');
955
+ if (oldNodeId != null) { response += '\r\nOldNodeID: ' + oldNodeId + '.'; }
956
+ response += '\r\ServerState: ' + meshServerConnectionState + '.';
957
+ break;
958
+ }
959
+ case 'selfinfo': { // Return self information block
960
+ buildSelfInfo(function (info) { sendConsoleText(objToString(info, 0, ' ', true), sessionid); });
961
+ break;
962
+ }
963
+ case 'args': { // Displays parsed command arguments
964
+ response = 'args ' + objToString(args, 0, ' ', true);
965
+ break;
966
+ }
967
+ case 'print': { // Print a message on the mesh agent console, does nothing when running in the background
968
+ var r = [];
969
+ for (var i in args['_']) { r.push(args['_'][i]); }
970
+ console.log(r.join(' '));
971
+ response = 'Message printed on agent console.';
972
+ break;
973
+ }
974
+ case 'type': { // Returns the content of a file
975
+ if (args['_'].length == 0) {
976
+ response = 'Proper usage: type (filepath) [maxlength]'; // Display correct command usage
977
+ } else {
978
+ var max = 4096;
979
+ if ((args['_'].length > 1) && (typeof args['_'][1] == 'number')) { max = args['_'][1]; }
980
+ if (max > 4096) max = 4096;
981
+ var buf = new Buffer(max), fd = fs.openSync(args['_'][0], "r"), r = fs.readSync(fd, buf, 0, max); // Read the file content
982
+ response = buf.toString();
983
+ var i = response.indexOf('\n');
984
+ if ((i > 0) && (response[i - 1] != '\r')) { response = response.split('\n').join('\r\n'); }
985
+ if (r == max) response += '...';
986
+ fs.closeSync(fd);
987
+ }
988
+ break;
989
+ }
990
+ case 'dbkeys': { // Return all data store keys
991
+ response = JSON.stringify(db.Keys);
992
+ break;
993
+ }
994
+ case 'dbget': { // Return the data store value for a given key
995
+ if (db == null) { response = 'Database not accessible.'; break; }
996
+ if (args['_'].length != 1) {
997
+ response = 'Proper usage: dbget (key)'; // Display the value for a given database key
998
+ } else {
999
+ response = db.Get(args['_'][0]);
1000
+ }
1001
+ break;
1002
+ }
1003
+ case 'dbset': { // Set a data store key and value pair
1004
+ if (db == null) { response = 'Database not accessible.'; break; }
1005
+ if (args['_'].length != 2) {
1006
+ response = 'Proper usage: dbset (key) (value)'; // Set a database key
1007
+ } else {
1008
+ var r = db.Put(args['_'][0], args['_'][1]);
1009
+ response = 'Key set: ' + r;
1010
+ }
1011
+ break;
1012
+ }
1013
+ case 'dbcompact': { // Compact the data store
1014
+ if (db == null) { response = 'Database not accessible.'; break; }
1015
+ var r = db.Compact();
1016
+ response = 'Database compacted: ' + r;
1017
+ break;
1018
+ }
1019
+ case 'httpget': {
1020
+ if (consoleHttpRequest != null) {
1021
+ response = 'HTTP operation already in progress.';
1022
+ } else {
1023
+ if (args['_'].length != 1) {
1024
+ response = 'Proper usage: httpget (url)';
1025
+ } else {
1026
+ var options = http.parseUri(args['_'][0]);
1027
+ options.method = 'GET';
1028
+ if (options == null) {
1029
+ response = 'Invalid url.';
1030
+ } else {
1031
+ try { consoleHttpRequest = http.request(options, consoleHttpResponse); } catch (e) { response = 'Invalid HTTP GET request'; }
1032
+ consoleHttpRequest.sessionid = sessionid;
1033
+ if (consoleHttpRequest != null) {
1034
+ consoleHttpRequest.end();
1035
+ response = 'HTTPGET ' + options.protocol + '//' + options.host + ':' + options.port + options.path;
1036
+ }
1037
+ }
1038
+ }
1039
+ }
1040
+ break;
1041
+ }
1042
+ case 'wslist': { // List all web sockets
1043
+ response = '';
1044
+ for (var i in consoleWebSockets) {
1045
+ var httprequest = consoleWebSockets[i];
1046
+ response += 'Websocket #' + i + ', ' + httprequest.url + '\r\n';
1047
+ }
1048
+ if (response == '') { response = 'no websocket sessions.'; }
1049
+ break;
1050
+ }
1051
+ case 'wsconnect': { // Setup a web socket
1052
+ if (args['_'].length == 0) {
1053
+ response = 'Proper usage: wsconnect (url)\r\nFor example: wsconnect wss://localhost:443/meshrelay.ashx?id=abc'; // Display correct command usage
1054
+ } else {
1055
+ var httprequest = null;
1056
+ try {
1057
+ var options = http.parseUri(args['_'][0]);
1058
+ options.rejectUnauthorized = 0;
1059
+ httprequest = http.request(options);
1060
+ } catch (e) { response = 'Invalid HTTP websocket request'; }
1061
+ if (httprequest != null) {
1062
+ httprequest.upgrade = onWebSocketUpgrade;
1063
+ httprequest.onerror = function (e) { sendConsoleText('ERROR: ' + JSON.stringify(e)); }
1064
+
1065
+ var index = 1;
1066
+ while (consoleWebSockets[index]) { index++; }
1067
+ httprequest.sessionid = sessionid;
1068
+ httprequest.index = index;
1069
+ httprequest.url = args['_'][0];
1070
+ consoleWebSockets[index] = httprequest;
1071
+ response = 'New websocket session #' + index;
1072
+ }
1073
+ }
1074
+ break;
1075
+ }
1076
+ case 'wssend': { // Send data on a web socket
1077
+ if (args['_'].length == 0) {
1078
+ response = 'Proper usage: wssend (socketnumber)\r\n'; // Display correct command usage
1079
+ for (var i in consoleWebSockets) {
1080
+ var httprequest = consoleWebSockets[i];
1081
+ response += 'Websocket #' + i + ', ' + httprequest.url + '\r\n';
1082
+ }
1083
+ } else {
1084
+ var i = parseInt(args['_'][0]);
1085
+ var httprequest = consoleWebSockets[i];
1086
+ if (httprequest != undefined) {
1087
+ httprequest.s.write(args['_'][1]);
1088
+ response = 'ok';
1089
+ } else {
1090
+ response = 'Invalid web socket number';
1091
+ }
1092
+ }
1093
+ break;
1094
+ }
1095
+ case 'wsclose': { // Close a websocket
1096
+ if (args['_'].length == 0) {
1097
+ response = 'Proper usage: wsclose (socketnumber)'; // Display correct command usage
1098
+ } else {
1099
+ var i = parseInt(args['_'][0]);
1100
+ var httprequest = consoleWebSockets[i];
1101
+ if (httprequest != undefined) {
1102
+ if (httprequest.s != null) { httprequest.s.end(); } else { httprequest.end(); }
1103
+ response = 'ok';
1104
+ } else {
1105
+ response = 'Invalid web socket number';
1106
+ }
1107
+ }
1108
+ break;
1109
+ }
1110
+ case 'tunnels': { // Show the list of current tunnels
1111
+ response = '';
1112
+ for (var i in tunnels) { response += 'Tunnel #' + i + ', ' + tunnels[i].url + '\r\n'; }
1113
+ if (response == '') { response = 'No websocket sessions.'; }
1114
+ break;
1115
+ }
1116
+ case 'ls': { // Show list of files and folders
1117
+ response = '';
1118
+ var xpath = '*';
1119
+ if (args['_'].length > 0) { xpath = obj.path.join(args['_'][0], '*'); }
1120
+ response = 'List of ' + xpath + '\r\n';
1121
+ var results = fs.readdirSync(xpath);
1122
+ for (var i = 0; i < results.length; ++i) {
1123
+ var stat = null, p = obj.path.join(args['_'][0], results[i]);
1124
+ try { stat = fs.statSync(p); } catch (e) { }
1125
+ if ((stat == null) || (stat == undefined)) {
1126
+ response += (results[i] + "\r\n");
1127
+ } else {
1128
+ response += (results[i] + " " + ((stat.isDirectory()) ? "(Folder)" : "(File)") + "\r\n");
1129
+ }
1130
+ }
1131
+ break;
1132
+ }
1133
+ case 'lsx': { // Show list of files and folders
1134
+ response = objToString(getDirectoryInfo(args['_'][0]), 0, ' ', true);
1135
+ break;
1136
+ }
1137
+ case 'lock': { // Lock the current user out of the desktop
1138
+ if (process.platform == 'win32') { var child = require('child_process'); child.execFile(process.env['windir'] + '\\system32\\cmd.exe', ['/c', 'RunDll32.exe user32.dll,LockWorkStation'], { type: 1 }); response = 'Ok'; }
1139
+ else { response = 'Not supported on the platform'; }
1140
+ break;
1141
+ }
1142
+ case 'amt': { // Show Intel AMT status
1143
+ getAmtInfo(function (state) {
1144
+ var resp = 'Intel AMT not detected.';
1145
+ if (state != null) { resp = objToString(state, 0, ' ', true); }
1146
+ sendConsoleText(resp, sessionid);
1147
+ });
1148
+ break;
1149
+ }
1150
+ case 'netinfo': { // Show network interface information
1151
+ //response = objToString(mesh.NetInfo, 0, ' ');
1152
+ var interfaces = require('os').networkInterfaces();
1153
+ response = objToString(interfaces, 0, ' ', true);
1154
+ break;
1155
+ }
1156
+ case 'netinfo2': { // Show network interface information
1157
+ response = objToString(mesh.NetInfo, 0, ' ', true);
1158
+ break;
1159
+ }
1160
+ case 'wakeonlan': { // Send wake-on-lan
1161
+ if ((args['_'].length != 1) || (args['_'][0].length != 12)) {
1162
+ response = 'Proper usage: wakeonlan [mac], for example "wakeonlan 010203040506".';
1163
+ } else {
1164
+ var count = sendWakeOnLan(args['_'][0]);
1165
+ response = 'Sent wake-on-lan on ' + count + ' interface(s).';
1166
+ }
1167
+ break;
1168
+ }
1169
+ case 'sendall': { // Send a message to all consoles on this mesh
1170
+ sendConsoleText(args['_'].join(' '));
1171
+ break;
1172
+ }
1173
+ case 'power': { // Execute a power action on this computer
1174
+ if (mesh.ExecPowerState == undefined) {
1175
+ response = 'Power command not supported on this agent.';
1176
+ } else {
1177
+ if ((args['_'].length == 0) || (typeof args['_'][0] != 'number')) {
1178
+ response = 'Proper usage: power (actionNumber), where actionNumber is:\r\n LOGOFF = 1\r\n SHUTDOWN = 2\r\n REBOOT = 3\r\n SLEEP = 4\r\n HIBERNATE = 5\r\n DISPLAYON = 6\r\n KEEPAWAKE = 7\r\n BEEP = 8\r\n CTRLALTDEL = 9\r\n VIBRATE = 13\r\n FLASH = 14'; // Display correct command usage
1179
+ } else {
1180
+ var r = mesh.ExecPowerState(args['_'][0], args['_'][1]);
1181
+ response = 'Power action executed with return code: ' + r + '.';
1182
+ }
1183
+ }
1184
+ break;
1185
+ }
1186
+ case 'location': {
1187
+ getIpLocationData(function (location) {
1188
+ sendConsoleText(objToString({ "action": "iplocation", "type": "publicip", "value": location }, 0, ' '));
1189
+ });
1190
+ break;
1191
+ }
1192
+ case 'parseuri': {
1193
+ response = JSON.stringify(http.parseUri(args['_'][0]));
1194
+ break;
1195
+ }
1196
+ case 'scanwifi': {
1197
+ if (wifiScanner != null) {
1198
+ var wifiPresent = wifiScanner.hasWireless;
1199
+ if (wifiPresent) { response = "Perfoming Wifi scan..."; wifiScanner.Scan(); } else { response = "Wifi absent."; }
1200
+ } else { response = "Wifi module not present."; }
1201
+ break;
1202
+ }
1203
+ case 'scanamt': {
1204
+ if (amtscanner != null) {
1205
+ if (args['_'].length != 1) {
1206
+ response = 'Usage examples:\r\n scanamt 1.2.3.4\r\n scanamt 1.2.3.0-1.2.3.255\r\n scanamt 1.2.3.0/24\r\n'; // Display correct command usage
1207
+ } else {
1208
+ response = 'Scanning: ' + args['_'][0] + '...';
1209
+ amtscanner.scan(args['_'][0], 2000, function (data) {
1210
+ if (data.length > 0) {
1211
+ var r = '', pstates = ['NotActivated', 'InActivation', 'Activated'];
1212
+ for (var i in data) {
1213
+ var x = data[i];
1214
+ if (r != '') { r += '\r\n'; }
1215
+ r += x.address + ' - Intel AMT v' + x.majorVersion + '.' + x.minorVersion;
1216
+ if (x.provisioningState < 3) { r += (', ' + pstates[x.provisioningState]); }
1217
+ if (x.provisioningState == 2) { r += (', ' + x.openPorts.join(', ')); }
1218
+ r += '.';
1219
+ }
1220
+ } else {
1221
+ r = 'No Intel AMT found.';
1222
+ }
1223
+ sendConsoleText(r);
1224
+ });
1225
+ }
1226
+ } else { response = "Intel AMT scanner module not present."; }
1227
+ break;
1228
+ }
1229
+ case 'modules': {
1230
+ response = JSON.stringify(addedModules);
1231
+ break;
1232
+ }
1233
+ default: { // This is an unknown command, return an error message
1234
+ response = 'Unknown command \"' + cmd + '\", type \"help\" for list of avaialble commands.';
1235
+ break;
1236
+ }
1237
+ }
1238
+ } catch (e) { response = 'Command returned an exception error: ' + e; console.log(e); }
1239
+ if (response != null) { sendConsoleText(response, sessionid); }
1240
+ }
1241
+
1242
+ // Send a mesh agent console command
1243
+ function sendConsoleText(text, sessionid) {
1244
+ if (typeof text == 'object') { text = JSON.stringify(text); }
1245
+ mesh.SendCommand({ "action": "msg", "type": "console", "value": text, "sessionid": sessionid });
1246
+ }
1247
+
1248
+ // Called before the process exits
1249
+ //process.exit = function (code) { console.log("Exit with code: " + code.toString()); }
1250
+
1251
+ // Called when the server connection state changes
1252
+ function handleServerConnection(state) {
1253
+ meshServerConnectionState = state;
1254
+ if (meshServerConnectionState == 0) {
1255
+ // Server disconnected
1256
+ if (selfInfoUpdateTimer != null) { clearInterval(selfInfoUpdateTimer); selfInfoUpdateTimer = null; }
1257
+ lastSelfInfo = null;
1258
+ } else {
1259
+ // Server connected, send mesh core information
1260
+ var oldNodeId = db.Get('OldNodeId');
1261
+ if (oldNodeId != null) { mesh.SendCommand({ action: 'mc1migration', oldnodeid: oldNodeId }); }
1262
+ sendPeriodicServerUpdate(true);
1263
+ //if (selfInfoUpdateTimer == null) { selfInfoUpdateTimer = setInterval(sendPeriodicServerUpdate, 60000); } // Should be a long time, like 20 minutes. For now, 1 minute.
1264
+ }
1265
+ }
1266
+
1267
+ // Build a bunch a self information data that will be sent to the server
1268
+ // We need to do this periodically and if anything changes, send the update to the server.
1269
+ function buildSelfInfo(func) {
1270
+ getAmtInfo(function (meinfo) {
1271
+ var r = { "action": "coreinfo", "value": obj.meshCoreInfo, "caps": obj.meshCoreCapabilities };
1272
+ if (meinfo != null) {
1273
+ var intelamt = {}, p = false;
1274
+ if (meinfo.Versions && meinfo.Versions.AMT) { intelamt.ver = meinfo.Versions.AMT; p = true; }
1275
+ if (meinfo.ProvisioningState) { intelamt.state = meinfo.ProvisioningState; p = true; }
1276
+ if (meinfo.Flags) { intelamt.flags = meinfo.Flags; p = true; }
1277
+ if (meinfo.OsHostname) { intelamt.host = meinfo.OsHostname; p = true; }
1278
+ if (meinfo.UUID) { intelamt.uuid = meinfo.UUID; p = true; }
1279
+ if (p == true) { r.intelamt = intelamt }
1280
+ }
1281
+ func(r);
1282
+ });
1283
+ }
1284
+
1285
+ // Update the server with the latest network interface information
1286
+ var sendNetworkUpdateNagleTimer = null;
1287
+ function sendNetworkUpdateNagle() { if (sendNetworkUpdateNagleTimer != null) { clearTimeout(sendNetworkUpdateNagleTimer); sendNetworkUpdateNagleTimer = null; } sendNetworkUpdateNagleTimer = setTimeout(sendNetworkUpdate, 5000); }
1288
+ function sendNetworkUpdate(force) {
1289
+ sendNetworkUpdateNagleTimer = null;
1290
+
1291
+ // Update the network interfaces information data
1292
+ var netInfo = mesh.NetInfo;
1293
+ netInfo.action = 'netinfo';
1294
+ var netInfoStr = JSON.stringify(netInfo);
1295
+ if ((force == true) || (clearGatewayMac(netInfoStr) != clearGatewayMac(lastNetworkInfo))) { mesh.SendCommand(netInfo); lastNetworkInfo = netInfoStr; }
1296
+ }
1297
+
1298
+ // Called periodically to check if we need to send updates to the server
1299
+ function sendPeriodicServerUpdate(force) {
1300
+ if ((amtMeiConnected != 1) || (force == true)) { // If we are pending MEI connection, hold off on updating the server on self-info
1301
+ // Update the self information data
1302
+ buildSelfInfo(function (selfInfo) {
1303
+ selfInfoStr = JSON.stringify(selfInfo);
1304
+ if ((force == true) || (selfInfoStr != lastSelfInfo)) { mesh.SendCommand(selfInfo); lastSelfInfo = selfInfoStr; }
1305
+ });
1306
+ }
1307
+
1308
+ // Update network information
1309
+ sendNetworkUpdateNagle(force);
1310
+ }
1311
+
1312
+ // Get Intel AMT information using MEI
1313
+ function getAmtInfo(func) {
1314
+ if (amtMei == null || amtMeiConnected != 2) { if (func != null) { func(null); } return; }
1315
+ try {
1316
+ amtMeiTmpState = { Flags: 0 }; // Flags: 1=EHBC, 2=CCM, 4=ACM
1317
+ amtMei.getProtocolVersion(function (result) { if (result != null) { amtMeiTmpState.MeiVersion = result; } });
1318
+ amtMei.getVersion(function (val) { amtMeiTmpState.Versions = {}; for (var version in val.Versions) { amtMeiTmpState.Versions[val.Versions[version].Description] = val.Versions[version].Version; } });
1319
+ amtMei.getProvisioningMode(function (result) { amtMeiTmpState.ProvisioningMode = result.mode; });
1320
+ amtMei.getProvisioningState(function (result) { amtMeiTmpState.ProvisioningState = result.state; });
1321
+ amtMei.getEHBCState(function (result) { if ((result != null) && (result.EHBC == true)) { amtMeiTmpState.Flags += 1; } });
1322
+ amtMei.getControlMode(function (result) { if (result != null) { if (result.controlMode == 1) { amtMeiTmpState.Flags += 2; } if (result.controlMode == 2) { amtMeiTmpState.Flags += 4; } } });
1323
+ amtMei.getUuid(function (result) { if ((result != null) && (result.uuid != null)) { amtMeiTmpState.UUID = result.uuid; } });
1324
+ //amtMei.getMACAddresses(function (result) { amtMeiTmpState.mac = result; });
1325
+ amtMei.getDnsSuffix(function (result) { if (result != null) { amtMeiTmpState.dns = result; } if (func != null) { func(amtMeiTmpState); } });
1326
+ } catch (e) { if (func != null) { func(null); } return; }
1327
+ }
1328
+
1329
+ // Called on MicroLMS Intel AMT user notification
1330
+ function handleAmtNotification(notifyMsg) {
1331
+ if ((notifyMsg == null) || (notifyMsg.Body == null) || (notifyMsg.Body.MessageID == null) || (notifyMsg.Body.MessageArguments == null)) return null;
1332
+ var amtMessage = notifyMsg.Body.MessageID, amtMessageArg = notifyMsg.Body.MessageArguments[0], notify = null;
1333
+
1334
+ switch (amtMessage) {
1335
+ case 'iAMT0050': { if (amtMessageArg == '48') { notify = 'Intel® AMT Serial-over-LAN connected'; } else if (amtMessageArg == '49') { notify = 'Intel® AMT Serial-over-LAN disconnected'; } break; } // SOL
1336
+ case 'iAMT0052': { if (amtMessageArg == '1') { notify = 'Intel® AMT KVM connected'; } else if (amtMessageArg == '2') { notify = 'Intel® AMT KVM disconnected'; } break; } // KVM
1337
+ }
1338
+
1339
+ // Send to the entire mesh, no sessionid or userid specified.
1340
+ if (notify != null) { mesh.SendCommand({ "action": "msg", "type": "notify", "value": notify, "tag": "general" }); }
1341
+ }
1342
+
1343
+ // Starting function
1344
+ obj.start = function () {
1345
+ // Setup the mesh agent event handlers
1346
+ mesh.AddCommandHandler(handleServerCommand);
1347
+ mesh.AddConnectHandler(handleServerConnection);
1348
+
1349
+ // Parse input arguments
1350
+ //var args = parseArgs(process.argv);
1351
+ //console.log(args);
1352
+
1353
+ // Launch LMS
1354
+ try {
1355
+ var lme_heci = require('amt-lme');
1356
+ amtLmsState = 1;
1357
+ amtLms = new lme_heci();
1358
+ amtLms.on('error', function (e) { amtLmsState = 0; amtLms = null; obj.setupMeiOsAdmin(null, 1); });
1359
+ amtLms.on('connect', function () { amtLmsState = 2; obj.setupMeiOsAdmin(null, 2); });
1360
+ //amtLms.on('bind', function (map) { });
1361
+ amtLms.on('notify', function (data, options, str, code) {
1362
+ if (code == 'iAMT0052-3') {
1363
+ kvmGetData();
1364
+ } else {
1365
+ //if (str != null) { sendConsoleText('Intel AMT LMS: ' + str); }
1366
+ handleAmtNotification(data);
1367
+ }
1368
+ });
1369
+ } catch (e) { amtLmsState = -1; amtLms = null; }
1370
+
1371
+ // Check if the control channel is connected
1372
+ if (mesh.isControlChannelConnected) {
1373
+ sendPeriodicServerUpdate(true); // Send the server update
1374
+ }
1375
+
1376
+ //console.log('Stopping.');
1377
+ //process.exit();
1378
+ }
1379
+
1380
+ obj.stop = function () {
1381
+ mesh.AddCommandHandler(null);
1382
+ mesh.AddConnectHandler(null);
1383
+ }
1384
+
1385
+ function onWebSocketClosed() { sendConsoleText("WebSocket #" + this.httprequest.index + " closed.", this.httprequest.sessionid); delete consoleWebSockets[this.httprequest.index]; }
1386
+ function onWebSocketData(data) { sendConsoleText("Got WebSocket #" + this.httprequest.index + " data: " + data, this.httprequest.sessionid); }
1387
+ function onWebSocketSendOk() { sendConsoleText("WebSocket #" + this.index + " SendOK.", this.sessionid); }
1388
+
1389
+ function onWebSocketUpgrade(response, s, head) {
1390
+ sendConsoleText("WebSocket #" + this.index + " connected.", this.sessionid);
1391
+ this.s = s;
1392
+ s.httprequest = this;
1393
+ s.end = onWebSocketClosed;
1394
+ s.data = onWebSocketData;
1395
+ }
1396
+
1397
+
1398
+ //
1399
+ // KVM Data Channel
1400
+ //
1401
+
1402
+ obj.setupMeiOsAdmin = function(func, state) {
1403
+ amtMei.getLocalSystemAccount(function (x) {
1404
+ var transport = require('amt-wsman-duk');
1405
+ var wsman = require('amt-wsman');
1406
+ var amt = require('amt');
1407
+ oswsstack = new wsman(transport, '127.0.0.1', 16992, x.user, x.pass, false);
1408
+ obj.osamtstack = new amt(oswsstack);
1409
+ if (func) { func(state); }
1410
+ //var AllWsman = "CIM_SoftwareIdentity,IPS_SecIOService,IPS_ScreenSettingData,IPS_ProvisioningRecordLog,IPS_HostBasedSetupService,IPS_HostIPSettings,IPS_IPv6PortSettings".split(',');
1411
+ //obj.osamtstack.BatchEnum(null, AllWsman, startLmsWsmanResponse, null, true);
1412
+ //*************************************
1413
+ // Setup KVM data channel if this is Intel AMT 12 or above
1414
+ amtMei.getVersion(function (x) {
1415
+ var amtver = null;
1416
+ try { for (var i in x.Versions) { if (x.Versions[i].Description == 'AMT') amtver = parseInt(x.Versions[i].Version.split('.')[0]); } } catch (e) { }
1417
+ if ((amtver != null) && (amtver >= 12)) {
1418
+ obj.kvmGetData('skip'); // Clear any previous data, this is a dummy read to about handling old data.
1419
+ obj.kvmTempTimer = setInterval(function () { obj.kvmGetData(); }, 2000); // Start polling for KVM data.
1420
+ obj.kvmSetData(JSON.stringify({ action: 'restart', ver: 1 })); // Send a restart command to advise the console if present that MicroLMS just started.
1421
+ }
1422
+ });
1423
+ });
1424
+ }
1425
+
1426
+ obj.kvmGetData = function(tag) {
1427
+ obj.osamtstack.IPS_KVMRedirectionSettingData_DataChannelRead(obj.kvmDataGetResponse, tag);
1428
+ }
1429
+
1430
+ obj.kvmDataGetResponse = function (stack, name, response, status, tag) {
1431
+ if ((tag != 'skip') && (status == 200) && (response.Body.ReturnValue == 0)) {
1432
+ var val = null;
1433
+ try { val = Buffer.from(response.Body.DataMessage, 'base64').toString(); } catch (e) { return }
1434
+ if (val != null) { obj.kvmProcessData(response.Body.RealmsBitmap, response.Body.MessageId, val); }
1435
+ }
1436
+ }
1437
+
1438
+ var webRtcDesktop = null;
1439
+ obj.kvmProcessData = function (realms, messageId, val) {
1440
+ var data = null;
1441
+ try { data = JSON.parse(val) } catch (e) { }
1442
+ if ((data != null) && (data.action)) {
1443
+ if (data.action == 'present') { obj.kvmSetData(JSON.stringify({ action: 'present', ver: 1, platform: process.platform })); }
1444
+ if (data.action == 'offer') {
1445
+ webRtcDesktop = {};
1446
+ var rtc = require('ILibWebRTC');
1447
+ webRtcDesktop.webrtc = rtc.createConnection();
1448
+ webRtcDesktop.webrtc.on('connected', function () { });
1449
+ webRtcDesktop.webrtc.on('disconnected', function () { webRtcCleanUp(); });
1450
+ webRtcDesktop.webrtc.on('dataChannel', function (rtcchannel) {
1451
+ webRtcDesktop.rtcchannel = rtcchannel;
1452
+ webRtcDesktop.kvm = mesh.getRemoteDesktopStream();
1453
+ webRtcDesktop.kvm.pipe(webRtcDesktop.rtcchannel, { dataTypeSkip: 1, end: false });
1454
+ webRtcDesktop.rtcchannel.on('end', function () { obj.webRtcCleanUp(); });
1455
+ webRtcDesktop.rtcchannel.on('data', function (x) { obj.kvmCtrlData(this, x); });
1456
+ webRtcDesktop.rtcchannel.pipe(webRtcDesktop.kvm, { dataTypeSkip: 1, end: false });
1457
+ //webRtcDesktop.kvm.on('end', function () { console.log('WebRTC DataChannel closed2'); webRtcCleanUp(); });
1458
+ //webRtcDesktop.rtcchannel.on('data', function (data) { console.log('WebRTC data: ' + data); });
1459
+ });
1460
+ obj.kvmSetData(JSON.stringify({ action: 'answer', ver: 1, sdp: webRtcDesktop.webrtc.setOffer(data.sdp) }));
1461
+ }
1462
+ }
1463
+ }
1464
+
1465
+ // Polyfill path.join
1466
+ var path = {
1467
+ join: function () {
1468
+ var x = [];
1469
+ for (var i in arguments) {
1470
+ var w = arguments[i];
1471
+ if (w != null) {
1472
+ while (w.endsWith('/') || w.endsWith('\\')) { w = w.substring(0, w.length - 1); }
1473
+ if (i != 0) { while (w.startsWith('/') || w.startsWith('\\')) { w = w.substring(1); } }
1474
+ x.push(w);
1475
+ }
1476
+ }
1477
+ if (x.length == 0) return '/';
1478
+ return x.join('/');
1479
+ }
1480
+ };
1481
+
1482
+ // Process KVM control channel data
1483
+ obj.kvmCtrlData = function(channel, cmd) {
1484
+ if (cmd.length > 0 && cmd.charCodeAt(0) != 123) {
1485
+ // This is upload data
1486
+ if (this.fileupload != null) {
1487
+ cmd = Buffer.from(cmd, 'base64');
1488
+ var header = cmd.readUInt32BE(0);
1489
+ if ((header == 0x01000000) || (header == 0x01000001)) {
1490
+ fs.writeSync(this.fileupload.fp, cmd.slice(4));
1491
+ channel.write({ action: 'upload', sub: 'ack', reqid: this.fileupload.reqid });
1492
+ if (header == 0x01000001) { fs.closeSync(this.fileupload.fp); this.fileupload = null; } // Close the file
1493
+ }
1494
+ }
1495
+ return;
1496
+ }
1497
+ //console.log('KVM Ctrl Data', cmd);
1498
+ //sendConsoleText('KVM Ctrl Data: ' + cmd);
1499
+
1500
+ try { cmd = JSON.parse(cmd); } catch (ex) { console.error('Invalid JSON: ' + cmd); return; }
1501
+ if ((cmd.path != null) && (process.platform != 'win32') && (cmd.path[0] != '/')) { cmd.path = '/' + cmd.path; } // Add '/' to paths on non-windows
1502
+ switch (cmd.action) {
1503
+ case 'ping': {
1504
+ // This is a keep alive
1505
+ channel.write({ action: 'pong' });
1506
+ break;
1507
+ }
1508
+ case 'lock': {
1509
+ // Lock the current user out of the desktop
1510
+ if (process.platform == 'win32') { var child = require('child_process'); child.execFile(process.env['windir'] + '\\system32\\cmd.exe', ['/c', 'RunDll32.exe user32.dll,LockWorkStation'], { type: 1 }); }
1511
+ break;
1512
+ }
1513
+ case 'ls': {
1514
+ /*
1515
+ // Close the watcher if required
1516
+ var samepath = ((this.httprequest.watcher != undefined) && (cmd.path == this.httprequest.watcher.path));
1517
+ if ((this.httprequest.watcher != undefined) && (samepath == false)) {
1518
+ //console.log('Closing watcher: ' + this.httprequest.watcher.path);
1519
+ //this.httprequest.watcher.close(); // TODO: This line causes the agent to crash!!!!
1520
+ delete this.httprequest.watcher;
1521
+ }
1522
+ */
1523
+
1524
+ // Send the folder content to the browser
1525
+ var response = getDirectoryInfo(cmd.path);
1526
+ if (cmd.reqid != undefined) { response.reqid = cmd.reqid; }
1527
+ channel.write(response);
1528
+
1529
+ /*
1530
+ // Start the directory watcher
1531
+ if ((cmd.path != '') && (samepath == false)) {
1532
+ var watcher = fs.watch(cmd.path, onFileWatcher);
1533
+ watcher.tunnel = this.httprequest;
1534
+ watcher.path = cmd.path;
1535
+ this.httprequest.watcher = watcher;
1536
+ //console.log('Starting watcher: ' + this.httprequest.watcher.path);
1537
+ }
1538
+ */
1539
+ break;
1540
+ }
1541
+ case 'mkdir': {
1542
+ // Create a new empty folder
1543
+ fs.mkdirSync(cmd.path);
1544
+ break;
1545
+ }
1546
+ case 'rm': {
1547
+ // Remove many files or folders
1548
+ for (var i in cmd.delfiles) {
1549
+ var fullpath = path.join(cmd.path, cmd.delfiles[i]);
1550
+ try { fs.unlinkSync(fullpath); } catch (e) { console.log(e); }
1551
+ }
1552
+ break;
1553
+ }
1554
+ case 'rename': {
1555
+ // Rename a file or folder
1556
+ try { fs.renameSync(path.join(cmd.path, cmd.oldname), path.join(cmd.path, cmd.newname)); } catch (e) { console.log(e); }
1557
+ break;
1558
+ }
1559
+ case 'download': {
1560
+ // Download a file, to browser
1561
+ var sendNextBlock = 0;
1562
+ if (cmd.sub == 'start') { // Setup the download
1563
+ if (this.filedownload != null) { channel.write({ action: 'download', sub: 'cancel', id: this.filedownload.id }); delete this.filedownload; }
1564
+ this.filedownload = { id: cmd.id, path: cmd.path, ptr: 0 }
1565
+ try { this.filedownload.f = fs.openSync(this.filedownload.path, 'rbN'); } catch (e) { channel.write({ action: 'download', sub: 'cancel', id: this.filedownload.id }); delete this.filedownload; }
1566
+ if (this.filedownload) { channel.write({ action: 'download', sub: 'start', id: cmd.id }); }
1567
+ } else if ((this.filedownload != null) && (cmd.id == this.filedownload.id)) { // Download commands
1568
+ if (cmd.sub == 'startack') { sendNextBlock = 8; } else if (cmd.sub == 'stop') { delete this.filedownload; } else if (cmd.sub == 'ack') { sendNextBlock = 1; }
1569
+ }
1570
+ // Send the next download block(s)
1571
+ while (sendNextBlock > 0) {
1572
+ sendNextBlock--;
1573
+ var buf = new Buffer(4096);
1574
+ var len = fs.readSync(this.filedownload.f, buf, 4, 4092, null);
1575
+ this.filedownload.ptr += len;
1576
+ if (len < 4092) { buf.writeInt32BE(0x01000001, 0); fs.closeSync(this.filedownload.f); delete this.filedownload; sendNextBlock = 0; } else { buf.writeInt32BE(0x01000000, 0); }
1577
+ channel.write(buf.slice(0, len + 4).toString('base64')); // Write as Base64
1578
+ }
1579
+ break;
1580
+ }
1581
+ case 'upload': {
1582
+ // Upload a file, from browser
1583
+ if (cmd.sub == 'start') { // Start the upload
1584
+ if (this.fileupload != null) { fs.closeSync(this.fileupload.fp); }
1585
+ if (!cmd.path || !cmd.name) break;
1586
+ this.fileupload = { reqid: cmd.reqid };
1587
+ var filepath = path.join(cmd.path, cmd.name);
1588
+ try { this.fileupload.fp = fs.openSync(filepath, 'wbN'); } catch (e) { }
1589
+ if (this.fileupload.fp) { channel.write({ action: 'upload', sub: 'start', reqid: this.fileupload.reqid }); } else { this.fileupload = null; channel.write({ action: 'upload', sub: 'error', reqid: this.fileupload.reqid }); }
1590
+ }
1591
+ else if (cmd.sub == 'cancel') { // Stop the upload
1592
+ if (this.fileupload != null) { fs.closeSync(this.fileupload.fp); this.fileupload = null; }
1593
+ }
1594
+ break;
1595
+ }
1596
+ case 'copy': {
1597
+ // Copy a bunch of files from scpath to dspath
1598
+ for (var i in cmd.names) {
1599
+ var sc = path.join(cmd.scpath, cmd.names[i]), ds = path.join(cmd.dspath, cmd.names[i]);
1600
+ if (sc != ds) { try { fs.copyFileSync(sc, ds); } catch (e) { } }
1601
+ }
1602
+ break;
1603
+ }
1604
+ case 'move': {
1605
+ // Move a bunch of files from scpath to dspath
1606
+ for (var i in cmd.names) {
1607
+ var sc = path.join(cmd.scpath, cmd.names[i]), ds = path.join(cmd.dspath, cmd.names[i]);
1608
+ if (sc != ds) { try { fs.copyFileSync(sc, ds); fs.unlinkSync(sc); } catch (e) { } }
1609
+ }
1610
+ break;
1611
+ }
1612
+ }
1613
+ }
1614
+
1615
+ obj.webRtcCleanUp = function() {
1616
+ if (webRtcDesktop == null) return;
1617
+ if (webRtcDesktop.rtcchannel) {
1618
+ try { webRtcDesktop.rtcchannel.close(); } catch (e) { }
1619
+ try { webRtcDesktop.rtcchannel.removeAllListeners('data'); } catch (e) { }
1620
+ try { webRtcDesktop.rtcchannel.removeAllListeners('end'); } catch (e) { }
1621
+ delete webRtcDesktop.rtcchannel;
1622
+ }
1623
+ if (webRtcDesktop.webrtc) {
1624
+ try { webRtcDesktop.webrtc.close(); } catch (e) { }
1625
+ try { webRtcDesktop.webrtc.removeAllListeners('connected'); } catch (e) { }
1626
+ try { webRtcDesktop.webrtc.removeAllListeners('disconnected'); } catch (e) { }
1627
+ try { webRtcDesktop.webrtc.removeAllListeners('dataChannel'); } catch (e) { }
1628
+ delete webRtcDesktop.webrtc;
1629
+ }
1630
+ if (webRtcDesktop.kvm) {
1631
+ try { webRtcDesktop.kvm.end(); } catch (e) { }
1632
+ delete webRtcDesktop.kvm;
1633
+ }
1634
+ webRtcDesktop = null;
1635
+ }
1636
+
1637
+ obj.kvmSetData = function(x) {
1638
+ obj.osamtstack.IPS_KVMRedirectionSettingData_DataChannelWrite(Buffer.from(x).toString('base64'), function () { });
1639
+ }
1640
+
1641
+ return obj;
1642
+}
1643
+
1644
+//
1645
+// Module startup
1646
+//
1647
+
1648
+var xexports = null, mainMeshCore = null;
1649
+try { xexports = module.exports; } catch (e) { }
1650
+
1651
+if (xexports != null) {
1652
+ // If we are running within NodeJS, export the core
1653
+ module.exports.createMeshCore = createMeshCore;
1654
+} else {
1655
+ // If we are not running in NodeJS, launch the core
1656
+ mainMeshCore = createMeshCore();
1657
+ mainMeshCore.start(null);
1658
+}
agents/modules_meshcore_backup/process-manager.js
new
+100
@@ -0,0 +1,100 @@
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
+// JavaScript source code
18
+var GM = require('_GenericMarshal');
19
+
20
+function processManager() {
21
+ this._ObjectID = 'processManager';
22
+ switch (process.platform) {
23
+ case 'win32':
24
+ this._kernel32 = GM.CreateNativeProxy('kernel32.dll');
25
+ this._kernel32.CreateMethod('GetLastError');
26
+ this._kernel32.CreateMethod('CreateToolhelp32Snapshot');
27
+ this._kernel32.CreateMethod('Process32First');
28
+ this._kernel32.CreateMethod('Process32Next');
29
+ break;
30
+ case 'linux':
31
+ this._childProcess = require('child_process');
32
+ break;
33
+ default:
34
+ throw (process.platform + ' not supported');
35
+ }
36
+ this.getProcesses = function getProcesses(callback) {
37
+ switch (process.platform) {
38
+ default:
39
+ throw ('Enumerating processes on ' + process.platform + ' not supported');
40
+ case 'win32':
41
+ var retVal = {};
42
+ var h = this._kernel32.CreateToolhelp32Snapshot(2, 0);
43
+ var info = GM.CreateVariable(304);
44
+ info.toBuffer().writeUInt32LE(304, 0);
45
+ var nextProcess = this._kernel32.Process32First(h, info);
46
+ while (nextProcess.Val) {
47
+ retVal[info.Deref(8, 4).toBuffer().readUInt32LE(0)] = { cmd: info.Deref(GM.PointerSize == 4 ? 36 : 44, 260).String };
48
+ nextProcess = this._kernel32.Process32Next(h, info);
49
+ }
50
+ if (callback) { callback.apply(this, [retVal]); }
51
+ break;
52
+ case 'linux':
53
+ if (!this._psp) { this._psp = {}; }
54
+ var p = this._childProcess.execFile("/bin/ps", ["ps", "-uxa"], { type: this._childProcess.SpawnTypes.TERM });
55
+ this._psp[p.pid] = p;
56
+ p.Parent = this;
57
+ p.ps = '';
58
+ p.callback = callback;
59
+ p.args = [];
60
+ for (var i = 1; i < arguments.length; ++i) { p.args.push(arguments[i]); }
61
+ p.on('exit', function onGetProcesses() {
62
+ delete this.Parent._psp[this.pid];
63
+ var retVal = {}, lines = this.ps.split('\x0D\x0A'), key = {}, keyi = 0;
64
+ for (var i in lines) {
65
+ var tokens = lines[i].split(' ');
66
+ var tokenList = [];
67
+ for (var x in tokens) {
68
+ if (i == 0 && tokens[x]) { key[tokens[x]] = keyi++; }
69
+ if (i > 0 && tokens[x]) { tokenList.push(tokens[x]); }
70
+ }
71
+ if ((i > 0) && (tokenList[key.PID])) {
72
+ retVal[tokenList[key.PID]] = { user: tokenList[key.USER], cmd: tokenList[key.COMMAND] };
73
+ }
74
+ }
75
+ if (this.callback) {
76
+ this.args.unshift(retVal);
77
+ this.callback.apply(this.parent, this.args);
78
+ }
79
+ });
80
+ p.stdout.on('data', function (chunk) { this.parent.ps += chunk.toString(); });
81
+ break;
82
+ }
83
+ };
84
+ this.getProcessInfo = function getProcessInfo(pid) {
85
+ switch (process.platform) {
86
+ default:
87
+ throw ('getProcessInfo() not supported for ' + process.platform);
88
+ case 'linux':
89
+ var status = require('fs').readFileSync('/proc/' + pid + '/status'), info = {}, lines = status.toString().split('\n');
90
+ for (var i in lines) {
91
+ var tokens = lines[i].split(':');
92
+ if (tokens.length > 1) { tokens[1] = tokens[1].trim(); }
93
+ info[tokens[0]] = tokens[1];
94
+ }
95
+ return (info);
96
+ }
97
+ };
98
+}
99
+
100
+module.exports = new processManager();
\ No newline at end of file
agents/modules_meshcore_backup/smbios.js
new
+284
@@ -0,0 +1,284 @@
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
+try { Object.defineProperty(Array.prototype, "peek", { value: function () { return (this.length > 0 ? this[this.length - 1] : undefined); } }); } catch (e) { }
18
+try { Object.defineProperty(String.prototype, "replaceAll", { value: function replaceAll(oldVal, newVal) { return (this.split(oldVal).join(newVal)); } }); } catch (e) { }
19
+
20
+var RSMB = 1381190978;
21
+var memoryLocation = { 0x1: 'Other', 0x2: 'Unknown', 0x3: 'System Board', 0x4: 'ISA', 0x5: 'EISA', 0x6: 'PCI', 0x7: 'MCA', 0x8: 'PCMCIA', 0x9: 'Proprietary', 0xA: 'NuBus', 0xA0: 'PC-98/C20', 0xA1: 'PC-98/C24', 0xA2: 'PC-98/E', 0xA3: 'PC-98/LB' };
22
+var wakeReason = ['Reserved', 'Other', 'Unknown', 'APM Timer', 'Modem Ring', 'LAN', 'Power Switch', 'PCI', 'AC Power'];
23
+
24
+function SMBiosTables() {
25
+ this._ObjectID = 'SMBiosTable';
26
+ if (process.platform == 'win32') {
27
+ this._marshal = require('_GenericMarshal');
28
+ this._native = this._marshal.CreateNativeProxy("Kernel32.dll");
29
+
30
+ this._native.CreateMethod('EnumSystemFirmwareTables');
31
+ this._native.CreateMethod('GetSystemFirmwareTable');
32
+ }
33
+ if (process.platform == 'linux') {
34
+ this._canonicalizeData = function _canonicalizeData(data) {
35
+ var lines = data.toString().split('Header and Data:\x0A');
36
+ var MemoryStream = require('MemoryStream');
37
+ var ms = new MemoryStream();
38
+
39
+ for (var i = 1; i < lines.length; ++i) {
40
+ var tokens = lines[i].split('Strings:\x0A');
41
+ var header = tokens[0].split('\x0A\x0A')[0].replaceAll('\x0A', '').trim().replaceAll(' ', '').replaceAll('\x09', '');
42
+ ms.write(Buffer.from(header, 'hex'));
43
+ if (tokens.length > 1) {
44
+ var strings = tokens[1].split('\x0A\x0A')[0].split('\x0A');
45
+ var stringsFinal = [];
46
+ for (var strx in strings) {
47
+ var tmp = strings[strx].trim().replaceAll(' ', '').replaceAll('\x09', '');
48
+ if (!(tmp[0] == '"')) { stringsFinal.push(tmp); }
49
+ }
50
+ ms.write(Buffer.from(stringsFinal.join(''), 'hex'));
51
+ ms.write(Buffer.from('00', 'hex'));
52
+ }
53
+ else {
54
+ ms.write(Buffer.from('0000', 'hex'));
55
+ }
56
+ }
57
+ var retVal = ms.buffer;
58
+ retVal.ms = ms;
59
+ return (retVal);
60
+ };
61
+ }
62
+ this._parse = function _parse(SMData) {
63
+ var ret = {};
64
+ var pbyte;
65
+ var i = 0
66
+ var SMData;
67
+ var structcount = 0;
68
+
69
+ while (SMData && i < SMData.length) {
70
+ var SMtype = SMData[i];
71
+ var SMlength = SMData[i + 1];
72
+
73
+ if (!ret[SMtype]) { ret[SMtype] = []; }
74
+ ret[SMtype].push(SMData.slice(i + 4, i + SMlength));
75
+ if (process.platform == 'win32') { ret[SMtype].peek()._ext = pbyte; }
76
+ i += SMlength;
77
+
78
+ ret[SMtype].peek()._strings = [];
79
+
80
+ while (SMData[i] != 0) {
81
+ var strstart = i;
82
+
83
+ // Start of String, find end of string
84
+ while (SMData[i++] != 0);
85
+ ret[SMtype].peek()._strings.push(SMData.slice(strstart, i).toString().trim());
86
+ }
87
+ i += (ret[SMtype].peek()._strings.length == 0) ? 2 : 1;
88
+ ++structcount;
89
+ //console.log('End of Table[' + SMtype + ']: ' + i);
90
+ }
91
+ //console.log('Struct Count = ' + structcount);
92
+ return (ret);
93
+ };
94
+ this.get = function get(callback) {
95
+ if (process.platform == 'win32') {
96
+ var size = this._native.GetSystemFirmwareTable(RSMB, 0, 0, 0).Val;
97
+ //console.log('Table Size: ' + size);
98
+
99
+ var PtrSize = this._marshal.CreatePointer()._size;
100
+ var buffer = this._marshal.CreateVariable(size);
101
+ var written = this._native.GetSystemFirmwareTable(RSMB, 0, buffer, size).Val;
102
+ //console.log('Written Size: ' + written);
103
+
104
+ var rawBuffer = buffer.toBuffer();
105
+ var length = buffer.Deref(4, 4).toBuffer().readUInt32LE(0);
106
+
107
+ pbyte = buffer.Deref(8, length);
108
+ SMData = pbyte.toBuffer();
109
+
110
+ if (callback) { callback.apply(this, [this._parse(SMData)]); return; } else { return (this._parse(SMData)); }
111
+ }
112
+ if (process.platform == 'linux') {
113
+ var MemoryStream = require('MemoryStream');
114
+ this.child = require('child_process').execFile('/usr/sbin/dmidecode', ['dmidecode', '-u']);
115
+ this.child.SMBiosTable = this;
116
+ this.child.ms = new MemoryStream();
117
+ this.child.ms.callback = callback
118
+ this.child.ms.child = this.child;
119
+ this.child.stdout.on('data', function (buffer) { this.parent.ms.write(buffer); });
120
+ this.child.on('exit', function () { this.ms.end(); });
121
+ this.child.ms.on('end', function () {
122
+ //console.log('read ' + this.buffer.length + ' bytes');
123
+ if (this.buffer.length < 300) { // TODO: Trap error message better that this.
124
+ console.log('Not enough permission to read SMBiosTable');
125
+ if (this.callback) { this.callback.apply(this.child.SMBiosTable, []); }
126
+ }
127
+ else {
128
+ var SMData = this.child.SMBiosTable._canonicalizeData(this.buffer);
129
+ var j = this.child.SMBiosTable._parse(SMData);
130
+ if (this.callback) { this.callback.apply(this.child.SMBiosTable, [j]); }
131
+ }
132
+ });
133
+ return;
134
+ }
135
+ throw (process.platform + ' not supported');
136
+ };
137
+ this.parse = function parse(data) {
138
+ var r = {};
139
+ r.processorInfo = this.processorInfo(data);
140
+ r.memoryInfo = this.memoryInfo(data);
141
+ r.systemInfo = this.systemInfo(data);
142
+ r.systemSlots = this.systemInfo(data);
143
+ r.amtInfo = this.amtInfo(data);
144
+ return r;
145
+ }
146
+ this.processorInfo = function processorInfo(data) {
147
+ if (!data) { throw ('no data'); }
148
+ var ret = [];
149
+ var ptype = ['ERROR', 'Other', 'Unknown', 'CPU', 'ALU', 'DSP', 'GPU'];
150
+ var statusString = ['Unknown', 'Enabled', 'Disabled by user', 'Disabled by BIOS', 'Idle', 'Reserved', 'Reserved', 'Other'];
151
+ var cpuid = 0;
152
+ while (data[4] && data[4].length > 0) {
153
+ var p = data[4].pop();
154
+ var populated = p[20] & 0x40;
155
+ var status = p[20] & 0x07
156
+ if (populated) {
157
+ var j = { _ObjectID: 'SMBiosTables.processorInfo' };
158
+ j.Processor = ptype[p[1]];
159
+ j.MaxSpeed = p.readUInt16LE(16) + ' Mhz';
160
+ if (p[31]) { j.Cores = p[31]; }
161
+ if (p[33]) { j.Threads = p[33]; }
162
+ j.Populated = 1;
163
+ j.Status = statusString[status];
164
+ j.Socket = p._strings[p[0] - 1];
165
+ j.Manufacturer = p._strings[p[3] - 1];
166
+ j.Version = p._strings[p[12] - 1];
167
+ ret.push(j);
168
+ }
169
+ }
170
+ return (ret);
171
+ };
172
+ this.memoryInfo = function memoryInfo(data) {
173
+ if (!data) { throw ('no data'); }
174
+ var retVal = { _ObjectID: 'SMBiosTables.memoryInfo' };
175
+ if (data[16]) {
176
+ var m = data[16].peek();
177
+ retVal.location = memoryLocation[m[0]];
178
+ if ((retVal.maxCapacityKb = m.readUInt32LE(3)) == 0x80000000) {
179
+ retVal.maxCapacityKb = 'A really big number';
180
+ }
181
+ }
182
+ return (retVal);
183
+ };
184
+ this.systemInfo = function systemInfo(data) {
185
+ if (!data) { throw ('no data'); }
186
+ var retVal = { _ObjectID: 'SMBiosTables.systemInfo' };
187
+ if (data[1]) {
188
+ var si = data[1].peek();
189
+ retVal.uuid = si.slice(4, 20).toString('hex');
190
+ retVal.wakeReason = wakeReason[si[20]];
191
+ }
192
+ return (retVal);
193
+ };
194
+ this.systemSlots = function systemSlots(data) {
195
+ if (!data) { throw ('no data'); }
196
+ var retVal = [];
197
+ if (data[9]) {
198
+ while (data[9].length > 0) {
199
+ var ss = data[9].pop();
200
+ retVal.push({ name: ss._strings[ss[0] - 1] });
201
+ }
202
+ }
203
+ return (retVal);
204
+ };
205
+ this.amtInfo = function amtInfo(data) {
206
+ if (!data) { throw ('no data'); }
207
+ var retVal = { AMT: false };
208
+ if (data[130] && data[130].peek().slice(0, 4).toString() == '$AMT') {
209
+ var amt = data[130].peek();
210
+ retVal.AMT = amt[4] ? true : false;
211
+ if (retVal.AMT) {
212
+ retVal.enabled = amt[5] ? true : false;
213
+ retVal.storageRedirection = amt[6] ? true : false;
214
+ retVal.serialOverLan = amt[7] ? true : false;
215
+ retVal.kvm = amt[14] ? true : false;
216
+ if (data[131].peek() && data[131].peek().slice(52, 56).toString() == 'vPro') {
217
+ var settings = data[131].peek();
218
+ if (settings[0] & 0x04) { retVal.TXT = (settings[0] & 0x08) ? true : false; }
219
+ if (settings[0] & 0x10) { retVal.VMX = (settings[0] & 0x20) ? true : false; }
220
+ retVal.MEBX = settings.readUInt16LE(10).toString() + '.' + settings.readUInt16LE(8).toString() + '.' + settings.readUInt16LE(6).toString() + '.' + settings.readUInt16LE(4).toString();
221
+
222
+ var mecap = settings.slice(20, 32);
223
+ retVal.ManagementEngine = mecap.readUInt16LE(6).toString() + '.' + mecap.readUInt16LE(4).toString() + '.' + mecap.readUInt16LE(2).toString() + '.' + mecap.readUInt16LE(0).toString();
224
+
225
+ //var lan = settings.slice(36, 48);
226
+ //console.log(lan.toString('hex'));
227
+ //retVal.LAN = (lan.readUInt16LE(10) & 0x03).toString() + '/' + ((lan.readUInt16LE(10) & 0xF8) >> 3).toString();
228
+
229
+ //console.log(lan.readUInt16LE(3));
230
+ //retVal.WLAN = (lan.readUInt16LE(3) & 0x07).toString() + '/' + ((lan.readUInt16LE(3) & 0xF8) >> 3).toString() + '/' + (lan.readUInt16LE(3) >> 8).toString();
231
+ }
232
+ }
233
+ }
234
+ return (retVal);
235
+ };
236
+ this.smTableTypes = {
237
+ 0: 'BIOS information',
238
+ 1: 'System information',
239
+ 2: 'Baseboard (or Module) information',
240
+ 4: 'Processor information',
241
+ 5: 'memory controller information',
242
+ 6: 'Memory module information',
243
+ 7: 'Cache information',
244
+ 8: 'Port connector information',
245
+ 9: 'System slots',
246
+ 10: 'On board devices information',
247
+ 11: 'OEM strings',
248
+ 12: 'System configuration options',
249
+ 13: 'BIOS language information',
250
+ 14: 'Group associations',
251
+ 15: 'System event log',
252
+ 16: 'Physical memory array',
253
+ 17: 'Memory device',
254
+ 18: '32bit memory error information',
255
+ 19: 'Memory array mapped address',
256
+ 20: 'Memory device mapped address',
257
+ 21: 'Built-in pointing device',
258
+ 22: 'Portable battery',
259
+ 23: 'System reset',
260
+ 24: 'Hardware security',
261
+ 25: 'System power controls',
262
+ 26: 'Voltage probe',
263
+ 27: 'Cooling device',
264
+ 28: 'Temperature probe',
265
+ 29: 'Electrical current probe',
266
+ 30: 'Out-of-band remote access',
267
+ 31: 'Boot integrity services (BIS) entry point',
268
+ 32: 'System boot information',
269
+ 33: '64bit memory error information',
270
+ 34: 'Management device',
271
+ 35: 'Management device component',
272
+ 36: 'Management device threshold data',
273
+ 37: 'Memory channel',
274
+ 38: 'IPMI device information',
275
+ 39: 'System power supply',
276
+ 40: 'Additional information',
277
+ 41: 'Onboard devices extended information',
278
+ 42: 'Management controller host interface',
279
+ 126: 'Inactive',
280
+ 127: 'End-of-table'
281
+ }
282
+}
283
+
284
+module.exports = new SMBiosTables();
\ No newline at end of file
agents/modules_meshcore_backup/toaster.js
new
+72
@@ -0,0 +1,72 @@
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 toasters = {};
18
+
19
+function Toaster()
20
+{
21
+ this._ObjectID = 'Toaster';
22
+ this.Toast = function Toast(title, caption)
23
+ {
24
+ if (process.platform != 'win32') return;
25
+
26
+ var retVal = {};
27
+ var emitter = require('events').inherits(retVal);
28
+ emitter.createEvent('Clicked');
29
+ emitter.createEvent('Dismissed');
30
+
31
+ var session = require('user-sessions').Current();
32
+ for (var i in session)
33
+ {
34
+ console.log(session[i]);
35
+ }
36
+ try
37
+ {
38
+ console.log('Attempting Toast Mechanism 1');
39
+ retVal._child = require('ScriptContainer').Create({ processIsolation: true, sessionId: session.connected[0].SessionId });
40
+ }
41
+ catch (e) {
42
+ console.log(e);
43
+ console.log('Attempting Toast Mechanism 2');
44
+ retVal._child = require('ScriptContainer').Create({ processIsolation: true });
45
+ }
46
+ retVal._child.parent = retVal;
47
+
48
+ retVal._child.on('exit', function (code) { this.parent.emit('Dismissed'); delete this.parent._child; });
49
+ retVal._child.addModule('win-console', getJSModule('win-console'));
50
+ retVal._child.addModule('win-messagepump', getJSModule('win-messagepump'));
51
+
52
+ var str = "\
53
+ try{\
54
+ var toast = require('win-console');\
55
+ var balloon = toast.SetTrayIcon({ szInfo: '" + caption + "', szInfoTitle: '" + title + "', balloonOnly: true });\
56
+ balloon.on('ToastDismissed', function(){process.exit();});\
57
+ }\
58
+ catch(e)\
59
+ {\
60
+ require('ScriptContainer').send(e);\
61
+ }\
62
+ require('ScriptContainer').send('done');\
63
+ ";
64
+ retVal._child.ExecuteString(str);
65
+ toasters[retVal._hashCode()] = retVal;
66
+ retVal.on('Dismissed', function () { delete toasters[this._hashCode()]; });
67
+ console.log('Returning');
68
+ return (retVal);
69
+ };
70
+}
71
+
72
+module.exports = new Toaster();
\ No newline at end of file
agents/modules_meshcore_backup/user-sessions.js
new
+167
@@ -0,0 +1,167 @@
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
+function UserSessions()
18
+{
19
+ this._ObjectID = 'UserSessions';
20
+
21
+ if (process.platform == 'win32') {
22
+ this._marshal = require('_GenericMarshal');
23
+ this._kernel32 = this._marshal.CreateNativeProxy('Kernel32.dll');
24
+ this._kernel32.CreateMethod('GetLastError');
25
+ this._wts = this._marshal.CreateNativeProxy('Wtsapi32.dll');
26
+ this._wts.CreateMethod('WTSEnumerateSessionsA');
27
+ this._wts.CreateMethod('WTSQuerySessionInformationA');
28
+ this._wts.CreateMethod('WTSFreeMemory');
29
+ this.SessionStates = ['Active', 'Connected', 'ConnectQuery', 'Shadow', 'Disconnected', 'Idle', 'Listening', 'Reset', 'Down', 'Init'];
30
+ this.InfoClass =
31
+ {
32
+ 'WTSInitialProgram': 0,
33
+ 'WTSApplicationName': 1,
34
+ 'WTSWorkingDirectory': 2,
35
+ 'WTSOEMId': 3,
36
+ 'WTSSessionId': 4,
37
+ 'WTSUserName': 5,
38
+ 'WTSWinStationName': 6,
39
+ 'WTSDomainName': 7,
40
+ 'WTSConnectState': 8,
41
+ 'WTSClientBuildNumber': 9,
42
+ 'WTSClientName': 10,
43
+ 'WTSClientDirectory': 11,
44
+ 'WTSClientProductId': 12,
45
+ 'WTSClientHardwareId': 13,
46
+ 'WTSClientAddress': 14,
47
+ 'WTSClientDisplay': 15,
48
+ 'WTSClientProtocolType': 16,
49
+ 'WTSIdleTime': 17,
50
+ 'WTSLogonTime': 18,
51
+ 'WTSIncomingBytes': 19,
52
+ 'WTSOutgoingBytes': 20,
53
+ 'WTSIncomingFrames': 21,
54
+ 'WTSOutgoingFrames': 22,
55
+ 'WTSClientInfo': 23,
56
+ 'WTSSessionInfo': 24,
57
+ 'WTSSessionInfoEx': 25,
58
+ 'WTSConfigInfo': 26,
59
+ 'WTSValidationInfo': 27,
60
+ 'WTSSessionAddressV4': 28,
61
+ 'WTSIsRemoteSession': 29
62
+ };
63
+
64
+ this.getSessionAttribute = function getSessionAttribute(sessionId, attr)
65
+ {
66
+ var buffer = this._marshal.CreatePointer();
67
+ var bytesReturned = this._marshal.CreateVariable(4);
68
+
69
+ if (this._wts.WTSQuerySessionInformationA(0, sessionId, attr, buffer, bytesReturned).Val == 0)
70
+ {
71
+ throw ('Error calling WTSQuerySessionInformation: ' + this._kernel32.GetLastError.Val);
72
+ }
73
+
74
+ var retVal = buffer.Deref().String;
75
+
76
+ this._wts.WTSFreeMemory(buffer.Deref());
77
+ return (retVal);
78
+ };
79
+
80
+ this.Current = function Current()
81
+ {
82
+ var retVal = {};
83
+ var pinfo = this._marshal.CreatePointer();
84
+ var count = this._marshal.CreateVariable(4);
85
+ if (this._wts.WTSEnumerateSessionsA(0, 0, 1, pinfo, count).Val == 0)
86
+ {
87
+ throw ('Error calling WTSEnumerateSessionsA: ' + this._kernel32.GetLastError().Val);
88
+ }
89
+
90
+ for (var i = 0; i < count.toBuffer().readUInt32LE() ; ++i)
91
+ {
92
+ var info = pinfo.Deref().Deref(i * (this._marshal.PointerSize == 4 ? 12 : 24), this._marshal.PointerSize == 4 ? 12 : 24);
93
+ var j = { SessionId: info.toBuffer().readUInt32LE() };
94
+ j.StationName = info.Deref(this._marshal.PointerSize == 4 ? 4 : 8, this._marshal.PointerSize).Deref().String;
95
+ j.State = this.SessionStates[info.Deref(this._marshal.PointerSize == 4 ? 8 : 16, 4).toBuffer().readUInt32LE()];
96
+ if (j.State == 'Active') {
97
+ j.Username = this.getSessionAttribute(j.SessionId, this.InfoClass.WTSUserName);
98
+ j.Domain = this.getSessionAttribute(j.SessionId, this.InfoClass.WTSDomainName);
99
+ }
100
+ retVal[j.SessionId] = j;
101
+ }
102
+
103
+ this._wts.WTSFreeMemory(pinfo.Deref());
104
+
105
+ Object.defineProperty(retVal, 'connected', { value: showActiveOnly(retVal) });
106
+ return (retVal);
107
+ };
108
+ }
109
+ else
110
+ {
111
+ this.Current = function Current()
112
+ {
113
+ var retVal = {};
114
+ var emitterUtils = require('events').inherits(retVal);
115
+ emitterUtils.createEvent('logon');
116
+
117
+ retVal._child = require('child_process').execFile('/usr/bin/last', ['last', '-f', '/var/run/utmp']);
118
+ retVal._child.Parent = retVal;
119
+ retVal._child._txt = '';
120
+ retVal._child.on('exit', function (code)
121
+ {
122
+ var lines = this._txt.split('\n');
123
+ var sessions = [];
124
+ for(var i in lines)
125
+ {
126
+ if (lines[i])
127
+ {
128
+ console.log(getTokens(lines[i]));
129
+ var user = lines[i].substring(0, lines[i].indexOf(' '));
130
+ sessions.push(user);
131
+ }
132
+ }
133
+ sessions.pop();
134
+ console.log(sessions);
135
+ });
136
+ retVal._child.stdout.Parent = retVal._child;
137
+ retVal._child.stdout.on('data', function (chunk) { this.Parent._txt += chunk.toString(); });
138
+
139
+ return (retVal);
140
+ }
141
+ }
142
+}
143
+function showActiveOnly(source)
144
+{
145
+ var retVal = [];
146
+ for (var i in source)
147
+ {
148
+ if (source[i].State == 'Active' || source[i].State == 'Connected')
149
+ {
150
+ retVal.push(source[i]);
151
+ }
152
+ }
153
+ return (retVal);
154
+}
155
+function getTokens(str)
156
+{
157
+ var columns = [];
158
+ var i;
159
+
160
+ columns.push(str.substring(0, (i=str.indexOf(' '))));
161
+ while (str[++i] == ' ');
162
+ columns.push(str.substring(i, str.substring(i).indexOf(' ') + i));
163
+
164
+ return (columns);
165
+}
166
+
167
+module.exports = new UserSessions();
\ No newline at end of file
agents/modules_meshcore_backup/wifi-scanner-windows.js
new
+171
@@ -0,0 +1,171 @@
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
+
18
+function _Scan()
19
+{
20
+ var wlanInterfaces = this.Marshal.CreatePointer();
21
+ this.Native.WlanEnumInterfaces(this.Handle, 0, wlanInterfaces);
22
+
23
+ var count = wlanInterfaces.Deref().Deref(0, 4).toBuffer().readUInt32LE(0);
24
+
25
+ var info = wlanInterfaces.Deref().Deref(8, 532);
26
+ var iname = info.Deref(16, 512).AnsiString;
27
+
28
+ var istate;
29
+ switch (info.Deref(528, 4).toBuffer().readUInt32LE(0))
30
+ {
31
+ case 0:
32
+ istate = "NOT READY";
33
+ break;
34
+ case 1:
35
+ istate = "CONNECTED";
36
+ break;
37
+ case 2:
38
+ istate = "AD-HOC";
39
+ break;
40
+ case 3:
41
+ istate = "DISCONNECTING";
42
+ break;
43
+ case 4:
44
+ istate = "DISCONNECTED";
45
+ break;
46
+ case 5:
47
+ istate = "ASSOCIATING";
48
+ break;
49
+ case 6:
50
+ istate = "DISCOVERING";
51
+ break;
52
+ case 7:
53
+ istate = "AUTHENTICATING";
54
+ break;
55
+ default:
56
+ istate = "UNKNOWN";
57
+ break;
58
+ }
59
+
60
+ var iguid = info.Deref(0, 16);
61
+ if (this.Native.WlanScan(this.Handle, iguid, 0, 0, 0).Val == 0)
62
+ {
63
+ return (true);
64
+ }
65
+ else
66
+ {
67
+ return (false);
68
+ }
69
+}
70
+
71
+function AccessPoint(_ssid, _bssid, _rssi, _lq)
72
+{
73
+ this.ssid = _ssid;
74
+ this.bssid = _bssid;
75
+ this.rssi = _rssi;
76
+ this.lq = _lq;
77
+}
78
+AccessPoint.prototype.toString = function()
79
+{
80
+ return (this.ssid + " [" + this.bssid + "]: " + this.lq);
81
+}
82
+
83
+function OnNotify(NotificationData)
84
+{
85
+ var NotificationSource = NotificationData.Deref(0, 4).toBuffer().readUInt32LE(0);
86
+ var NotificationCode = NotificationData.Deref(4, 4).toBuffer().readUInt32LE(0);
87
+ var dataGuid = NotificationData.Deref(8, 16);
88
+
89
+ if ((NotificationSource & 0X00000008) && (NotificationCode == 7))
90
+ {
91
+ var bss = this.Parent.Marshal.CreatePointer();
92
+ var result = this.Parent.Native.GetBSSList(this.Parent.Handle, dataGuid, 0, 3, 0, 0, bss).Val;
93
+ if (result == 0)
94
+ {
95
+ var totalSize = bss.Deref().Deref(0, 4).toBuffer().readUInt32LE(0);
96
+ var numItems = bss.Deref().Deref(4, 4).toBuffer().readUInt32LE(0);
97
+ for (i = 0; i < numItems; ++i)
98
+ {
99
+ var item = bss.Deref().Deref(8 + (360 * i), 360);
100
+ var ssid = item.Deref(4, 32).String.trim();
101
+ var bssid = item.Deref(40, 6).HexString2;
102
+ var rssi = item.Deref(56, 4).toBuffer().readUInt32LE(0);
103
+ var lq = item.Deref(60, 4).toBuffer().readUInt32LE(0);
104
+
105
+ this.Parent.emit('Scan', new AccessPoint(ssid, bssid, rssi, lq));
106
+ }
107
+ }
108
+
109
+ }
110
+}
111
+
112
+function Wireless()
113
+{
114
+ var emitterUtils = require('events').inherits(this);
115
+
116
+ this.Marshal = require('_GenericMarshal');
117
+ this.Native = this.Marshal.CreateNativeProxy("wlanapi.dll");
118
+ this.Native.CreateMethod("WlanOpenHandle");
119
+ this.Native.CreateMethod("WlanGetNetworkBssList", "GetBSSList");
120
+ this.Native.CreateMethod("WlanRegisterNotification");
121
+ this.Native.CreateMethod("WlanEnumInterfaces");
122
+ this.Native.CreateMethod("WlanScan");
123
+ this.Native.CreateMethod("WlanQueryInterface");
124
+
125
+ var negotiated = this.Marshal.CreatePointer();
126
+ var h = this.Marshal.CreatePointer();
127
+
128
+ this.Native.WlanOpenHandle(2, 0, negotiated, h);
129
+ this.Handle = h.Deref();
130
+
131
+ this._NOTIFY_PROXY_OBJECT = this.Marshal.CreateCallbackProxy(OnNotify, 2);
132
+ this._NOTIFY_PROXY_OBJECT.Parent = this;
133
+ var PrevSource = this.Marshal.CreatePointer();
134
+ var result = this.Native.WlanRegisterNotification(this.Handle, 0X0000FFFF, 0, this._NOTIFY_PROXY_OBJECT.Callback, this._NOTIFY_PROXY_OBJECT.State, 0, PrevSource);
135
+
136
+ emitterUtils.createEvent('Scan');
137
+ emitterUtils.addMethod('Scan', _Scan);
138
+
139
+ this.GetConnectedNetwork = function ()
140
+ {
141
+ var interfaces = this.Marshal.CreatePointer();
142
+
143
+ console.log('Success = ' + this.Native.WlanEnumInterfaces(this.Handle, 0, interfaces).Val);
144
+ var count = interfaces.Deref().Deref(0, 4).toBuffer().readUInt32LE(0);
145
+ var info = interfaces.Deref().Deref(8, 532);
146
+ var iname = info.Deref(16, 512).AnsiString;
147
+ var istate = info.Deref(528, 4).toBuffer().readUInt32LE(0);
148
+ if(info.Deref(528, 4).toBuffer().readUInt32LE(0) == 1) // CONNECTED
149
+ {
150
+ var dataSize = this.Marshal.CreatePointer();
151
+ var pData = this.Marshal.CreatePointer();
152
+ var valueType = this.Marshal.CreatePointer();
153
+ var iguid = info.Deref(0, 16);
154
+ var retVal = this.Native.WlanQueryInterface(this.Handle, iguid, 7, 0, dataSize, pData, valueType).Val;
155
+ if (retVal == 0)
156
+ {
157
+ var associatedSSID = pData.Deref().Deref(524, 32).String;
158
+ var bssid = pData.Deref().Deref(560, 6).HexString;
159
+ var lq = pData.Deref().Deref(576, 4).toBuffer().readUInt32LE(0);
160
+
161
+ return (new AccessPoint(associatedSSID, bssid, 0, lq));
162
+ }
163
+ }
164
+ throw ("GetConnectedNetworks: FAILED (not associated to a network)");
165
+ };
166
+
167
+
168
+ return (this);
169
+}
170
+
171
+module.exports = new Wireless();
agents/modules_meshcore_backup/wifi-scanner.js
new
+126
@@ -0,0 +1,126 @@
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 MemoryStream = require('MemoryStream');
18
+var WindowsChildScript = 'var parent = require("ScriptContainer");var Wireless = require("wifi-scanner-windows");Wireless.on("Scan", function (ap) { parent.send(ap); });Wireless.Scan();';
19
+
20
+function AccessPoint(_ssid, _bssid, _lq)
21
+{
22
+ this.ssid = _ssid;
23
+ this.bssid = _bssid;
24
+ this.lq = _lq;
25
+}
26
+AccessPoint.prototype.toString = function ()
27
+{
28
+ return ("[" + this.bssid + "]: " + this.ssid + " (" + this.lq + ")");
29
+ //return (this.ssid + " [" + this.bssid + "]: " + this.lq);
30
+}
31
+
32
+function WiFiScanner()
33
+{
34
+ var emitterUtils = require('events').inherits(this);
35
+ emitterUtils.createEvent('accessPoint');
36
+
37
+ this.hasWireless = function ()
38
+ {
39
+ var retVal = false;
40
+ var interfaces = require('os').networkInterfaces();
41
+ for (var name in interfaces)
42
+ {
43
+ if (interfaces[name][0].type == 'wireless') { retVal = true; break; }
44
+ }
45
+ return (retVal);
46
+ };
47
+
48
+ this.Scan = function ()
49
+ {
50
+ if (process.platform == 'win32')
51
+ {
52
+ this.master = require('ScriptContainer').Create(15, ContainerPermissions.DEFAULT);
53
+ this.master.parent = this;
54
+ this.master.on('data', function (j) { this.parent.emit('accessPoint', new AccessPoint(j.ssid, j.bssid, j.lq)); });
55
+
56
+ this.master.addModule('wifi-scanner-windows', getJSModule('wifi-scanner-windows'));
57
+ this.master.ExecuteString(WindowsChildScript);
58
+ }
59
+ else if (process.platform == 'linux')
60
+ {
61
+ // Need to get the wireless interface name
62
+ var interfaces = require('os').networkInterfaces();
63
+ var wlan = null;
64
+ for (var i in interfaces)
65
+ {
66
+ if (interfaces[i][0].type == 'wireless')
67
+ {
68
+ wlan = i;
69
+ break;
70
+ }
71
+ }
72
+ if (wlan != null)
73
+ {
74
+ this.child = require('child_process').execFile('/sbin/iwlist', ['iwlist', wlan, 'scan']);
75
+ this.child.parent = this;
76
+ this.child.ms = new MemoryStream();
77
+ this.child.ms.parent = this.child;
78
+ this.child.stdout.on('data', function (buffer) { this.parent.ms.write(buffer); });
79
+ this.child.on('exit', function () { this.ms.end(); });
80
+ this.child.ms.on('end', function ()
81
+ {
82
+ var str = this.buffer.toString();
83
+ tokens = str.split(' - Address: ');
84
+ for (var block in tokens)
85
+ {
86
+ if (block == 0) continue;
87
+ var ln = tokens[block].split('\n');
88
+ var _bssid = ln[0];
89
+ var _lq;
90
+ var _ssid;
91
+
92
+ for (var lnblock in ln)
93
+ {
94
+ lnblock = ln[lnblock].trim();
95
+ lnblock = lnblock.trim();
96
+ if (lnblock.startsWith('ESSID:'))
97
+ {
98
+ _ssid = lnblock.slice(7, lnblock.length - 1);
99
+ if (_ssid == '<hidden>') { _ssid = ''; }
100
+ }
101
+ if (lnblock.startsWith('Signal level='))
102
+ {
103
+ _lq = lnblock.slice(13,lnblock.length-4);
104
+ }
105
+ else if (lnblock.startsWith('Quality='))
106
+ {
107
+ _lq = lnblock.slice(8, 10);
108
+ var scale = lnblock.slice(11, 13);
109
+ }
110
+ }
111
+ this.parent.parent.emit('accessPoint', new AccessPoint(_ssid, _bssid, _lq));
112
+ }
113
+ });
114
+ }
115
+ }
116
+ }
117
+}
118
+
119
+module.exports = WiFiScanner;
120
+
121
+
122
+
123
+
124
+
125
+
126
+
agents/modules_meshcore_backup/win-console.js
new
+164
@@ -0,0 +1,164 @@
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 TrayIconFlags =
18
+ {
19
+ NIF_MESSAGE: 0x00000001,
20
+ NIF_ICON: 0x00000002,
21
+ NIF_TIP: 0x00000004,
22
+ NIF_STATE: 0x00000008,
23
+ NIF_INFO: 0x00000010,
24
+ NIF_GUID: 0x00000020,
25
+ NIF_REALTIME: 0x00000040,
26
+ NIF_SHOWTIP: 0x00000080,
27
+
28
+ NIM_ADD: 0x00000000,
29
+ NIM_MODIFY: 0x00000001,
30
+ NIM_DELETE: 0x00000002,
31
+ NIM_SETFOCUS: 0x00000003,
32
+ NIM_SETVERSION: 0x00000004
33
+ };
34
+var NOTIFYICON_VERSION_4 = 4;
35
+var MessageTypes = { WM_APP: 0x8000, WM_USER: 0x0400 };
36
+function WindowsConsole()
37
+{
38
+ if (process.platform == 'win32')
39
+ {
40
+ this._ObjectID = 'WindowsConsole';
41
+ this._Marshal = require('_GenericMarshal');
42
+ this._kernel32 = this._Marshal.CreateNativeProxy("kernel32.dll");
43
+ this._user32 = this._Marshal.CreateNativeProxy("user32.dll");
44
+ this._kernel32.CreateMethod("GetConsoleWindow");
45
+ this._kernel32.CreateMethod('GetCurrentThread');
46
+ this._user32.CreateMethod("ShowWindow");
47
+ this._user32.CreateMethod("LoadImageA");
48
+ this._user32.CreateMethod({ method: 'GetMessageA', threadDispatch: 1 });
49
+ this._shell32 = this._Marshal.CreateNativeProxy('Shell32.dll');
50
+ this._shell32.CreateMethod('Shell_NotifyIconA');
51
+
52
+ this._handle = this._kernel32.GetConsoleWindow();
53
+ this.minimize = function () {
54
+ this._user32.ShowWindow(this._handle, 6);
55
+ };
56
+ this.restore = function () {
57
+ this._user32.ShowWindow(this._handle, 9);
58
+ };
59
+ this.hide = function () {
60
+ this._user32.ShowWindow(this._handle, 0);
61
+ };
62
+ this.show = function () {
63
+ this._user32.ShowWindow(this._handle, 5);
64
+ };
65
+
66
+
67
+ this._loadicon = function (imagePath) {
68
+ var h = this._user32.LoadImageA(0, this._Marshal.CreateVariable(imagePath), 1, 0, 0, 0x00000010 | 0x00008000 | 0x00000040); // LR_LOADFROMFILE | LR_SHARED | LR_DEFAULTSIZE
69
+ return (h);
70
+ };
71
+
72
+ this.SetTrayIcon = function SetTrayIcon(options)
73
+ {
74
+ var data = this._Marshal.CreateVariable(this._Marshal.PointerSize == 4 ? 508 : 528);
75
+ //console.log('struct size = ' + data._size);
76
+ //console.log('TryIcon, WM_MESSAGE filter = ' + options.filter);
77
+ data.toBuffer().writeUInt32LE(data._size, 0);
78
+
79
+ var trayType = TrayIconFlags.NIF_TIP | TrayIconFlags.NIF_MESSAGE
80
+ options.filter = MessageTypes.WM_APP + 1;
81
+ data.Deref(this._Marshal.PointerSize == 4 ? 16 : 24, 4).toBuffer().writeUInt32LE(options.filter);
82
+
83
+ if (!options.noBalloon) { trayType |= TrayIconFlags.NIF_INFO; }
84
+
85
+ if (options.icon)
86
+ {
87
+ trayType |= TrayIconFlags.NIF_ICON;
88
+ var hIcon = data.Deref(this._Marshal.PointerSize == 4 ? 20 : 32, this._Marshal.PointerSize);
89
+ options.icon.pointerBuffer().copy(hIcon.toBuffer());
90
+ }
91
+
92
+ data.Deref(this._Marshal.PointerSize * 2, 4).toBuffer().writeUInt32LE(1);
93
+ data.Deref(this._Marshal.PointerSize == 4 ? 12 : 20, 4).toBuffer().writeUInt32LE(trayType);
94
+ data.Deref(this._Marshal.PointerSize == 4 ? 416 : 432, 4).toBuffer().writeUInt32LE(NOTIFYICON_VERSION_4);
95
+
96
+ var szTip = data.Deref(this._Marshal.PointerSize == 4 ? 24 : 40, 128);
97
+ var szInfo = data.Deref(this._Marshal.PointerSize == 4 ? 160 : 176, 256);
98
+ var szInfoTitle = data.Deref(this._Marshal.PointerSize == 4 ? 420 : 436, 64);
99
+
100
+ if (options.szTip) { Buffer.from(options.szTip).copy(szTip.toBuffer()); }
101
+ if (options.szInfo) { Buffer.from(options.szInfo).copy(szInfo.toBuffer()); }
102
+ if (options.szInfoTitle) { Buffer.from(options.szInfoTitle).copy(szInfoTitle.toBuffer()); }
103
+
104
+
105
+ var MessagePump = require('win-messagepump');
106
+ retVal = { _ObjectID: 'WindowsConsole.TrayIcon', MessagePump: new MessagePump(options) };
107
+ var retValEvents = require('events').inherits(retVal);
108
+ retValEvents.createEvent('ToastClicked');
109
+ retValEvents.createEvent('IconHover');
110
+ retValEvents.createEvent('ToastDismissed');
111
+ retVal.Options = options;
112
+ retVal.MessagePump.TrayIcon = retVal;
113
+ retVal.MessagePump.NotifyData = data;
114
+ retVal.MessagePump.WindowsConsole = this;
115
+ retVal.MessagePump.on('exit', function onExit(code) { console.log('Pump Exited'); if (this.TrayIcon) { this.TrayIcon.remove(); } });
116
+ retVal.MessagePump.on('hwnd', function onHwnd(h)
117
+ {
118
+ //console.log('Got HWND');
119
+ options.hwnd = h;
120
+ h.pointerBuffer().copy(this.NotifyData.Deref(this.WindowsConsole._Marshal.PointerSize, this.WindowsConsole._Marshal.PointerSize).toBuffer());
121
+
122
+ if(this.WindowsConsole._shell32.Shell_NotifyIconA(TrayIconFlags.NIM_ADD, this.NotifyData).Val == 0)
123
+ {
124
+ // Something went wrong
125
+ }
126
+ });
127
+ retVal.MessagePump.on('message', function onWindowsMessage(msg)
128
+ {
129
+ if(msg.message == this.TrayIcon.Options.filter)
130
+ {
131
+ var handled = false;
132
+ if (msg.wparam == 1 && msg.lparam == 1029)
133
+ {
134
+ this.TrayIcon.emit('ToastClicked');
135
+ handled = true;
136
+ }
137
+ if (msg.wparam == 1 && msg.lparam == 512)
138
+ {
139
+ this.TrayIcon.emit('IconHover');
140
+ handled = true;
141
+ }
142
+ if (this.TrayIcon.Options.balloonOnly && msg.wparam == 1 && (msg.lparam == 1028 || msg.lparam == 1029))
143
+ {
144
+ this.TrayIcon.emit('ToastDismissed');
145
+ this.TrayIcon.remove();
146
+ handled = true;
147
+ }
148
+ if (!handled) { console.log(msg); }
149
+ }
150
+ });
151
+ retVal.remove = function remove()
152
+ {
153
+ this.MessagePump.WindowsConsole._shell32.Shell_NotifyIconA(TrayIconFlags.NIM_DELETE, this.MessagePump.NotifyData);
154
+ this.MessagePump.stop();
155
+ delete this.MessagePump.TrayIcon;
156
+ delete this.MessagePump;
157
+ };
158
+ return (retVal);
159
+
160
+ };
161
+ }
162
+}
163
+
164
+module.exports = new WindowsConsole();
\ No newline at end of file
agents/modules_meshcore_backup/win-messagepump.js
new
+122
@@ -0,0 +1,122 @@
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 WH_CALLWNDPROC = 4;
18
+var WM_QUIT = 0x0012;
19
+
20
+function WindowsMessagePump(options)
21
+{
22
+ this._ObjectID = 'WindowsMessagePump';
23
+ this._options = options;
24
+ var emitterUtils = require('events').inherits(this);
25
+ emitterUtils.createEvent('hwnd');
26
+ emitterUtils.createEvent('error');
27
+ emitterUtils.createEvent('message');
28
+ emitterUtils.createEvent('exit');
29
+
30
+ this._child = require('ScriptContainer').Create({ processIsolation: 0 });
31
+ this._child.MessagePump = this;
32
+ this._child.prependListener('~', function _childFinalizer() { this.MessagePump.emit('exit', 0); console.log('calling stop'); this.MessagePump.stop(); });
33
+ this._child.once('exit', function onExit(code) { this.MessagePump.emit('exit', code); });
34
+ this._child.once('ready', function onReady()
35
+ {
36
+ console.log('child ready');
37
+ var execString =
38
+ "var m = require('_GenericMarshal');\
39
+ var h = null;\
40
+ var k = m.CreateNativeProxy('Kernel32.dll');\
41
+ k.CreateMethod('GetLastError');\
42
+ k.CreateMethod('GetModuleHandleA');\
43
+ var u = m.CreateNativeProxy('User32.dll');\
44
+ u.CreateMethod('GetMessageA');\
45
+ u.CreateMethod('CreateWindowExA');\
46
+ u.CreateMethod('TranslateMessage');\
47
+ u.CreateMethod('DispatchMessageA');\
48
+ u.CreateMethod('RegisterClassExA');\
49
+ u.CreateMethod('DefWindowProcA');\
50
+ var wndclass = m.CreateVariable(m.PointerSize == 4 ? 48 : 80);\
51
+ wndclass.hinstance = k.GetModuleHandleA(0);\
52
+ wndclass.cname = m.CreateVariable('MainWWWClass');\
53
+ wndclass.wndproc = m.GetGenericGlobalCallback(4);\
54
+ wndclass.toBuffer().writeUInt32LE(wndclass._size);\
55
+ wndclass.cname.pointerBuffer().copy(wndclass.Deref(m.PointerSize == 4 ? 40 : 64, m.PointerSize).toBuffer());\
56
+ wndclass.wndproc.pointerBuffer().copy(wndclass.Deref(8, m.PointerSize).toBuffer());\
57
+ wndclass.hinstance.pointerBuffer().copy(wndclass.Deref(m.PointerSize == 4 ? 20 : 24, m.PointerSize).toBuffer());\
58
+ wndclass.wndproc.on('GlobalCallback', function onWndProc(xhwnd, xmsg, wparam, lparam)\
59
+ {\
60
+ if(h==null || h.Val == xhwnd.Val)\
61
+ {\
62
+ require('ScriptContainer').send({message: xmsg.Val, wparam: wparam.Val, lparam: lparam.Val});\
63
+ var retVal = u.DefWindowProcA(xhwnd, xmsg, wparam, lparam);\
64
+ return(retVal);\
65
+ }\
66
+ });\
67
+ u.RegisterClassExA(wndclass);\
68
+ h = u.CreateWindowExA(0x00000088, wndclass.cname, 0, 0x00800000, 0, 0, 100, 100, 0, 0, 0, 0);\
69
+ if(h.Val == 0)\
70
+ {\
71
+ require('ScriptContainer').send({error: 'Error Creating Hidden Window'});\
72
+ process.exit();\
73
+ }\
74
+ require('ScriptContainer').send({hwnd: h.pointerBuffer().toString('hex')});\
75
+ require('ScriptContainer').on('data', function onData(jmsg)\
76
+ {\
77
+ if(jmsg.listen)\
78
+ {\
79
+ var msg = m.CreateVariable(m.PointerSize == 4 ? 28 : 48);\
80
+ while(u.GetMessageA(msg, h, 0, 0).Val>0)\
81
+ {\
82
+ u.TranslateMessage(msg);\
83
+ u.DispatchMessageA(msg);\
84
+ }\
85
+ process.exit();\
86
+ }\
87
+ });";
88
+
89
+ this.ExecuteString(execString);
90
+ });
91
+ this._child.on('data', function onChildData(msg)
92
+ {
93
+ if (msg.hwnd)
94
+ {
95
+ var m = require('_GenericMarshal');
96
+ this._hwnd = m.CreatePointer(Buffer.from(msg.hwnd, 'hex'));
97
+ this.MessagePump.emit('hwnd', this._hwnd);
98
+ this.send({ listen: this.MessagePump._options.filter });
99
+ }
100
+ else if(msg.message)
101
+ {
102
+ this.MessagePump.emit('message', msg);
103
+ }
104
+ else
105
+ {
106
+ console.log('Received: ', msg);
107
+ }
108
+ });
109
+ this.stop = function stop()
110
+ {
111
+ if(this._child && this._child._hwnd)
112
+ {
113
+ console.log('posting WM_QUIT');
114
+ var marshal = require('_GenericMarshal');
115
+ var User32 = marshal.CreateNativeProxy('User32.dll');
116
+ User32.CreateMethod('PostMessageA');
117
+ User32.PostMessageA(this._child._hwnd, WM_QUIT, 0, 0);
118
+ }
119
+ };
120
+}
121
+
122
+module.exports = WindowsMessagePump;
agents/modules_meshcore_backup/win-registry.js
new
+167
@@ -0,0 +1,167 @@
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 KEY_QUERY_VALUE = 0x0001;
18
+var KEY_WRITE = 0x20006;
19
+
20
+var KEY_DATA_TYPES =
21
+ {
22
+ REG_NONE: 0,
23
+ REG_SZ: 1,
24
+ REG_EXPAND_SZ: 2,
25
+ REG_BINARY: 3,
26
+ REG_DWORD: 4,
27
+ REG_DWORD_BIG_ENDIAN: 5,
28
+ REG_LINK: 6,
29
+ REG_MULTI_SZ: 7,
30
+ REG_RESOURCE_LIST: 8,
31
+ REG_FULL_RESOURCE_DESCRIPTOR: 9,
32
+ REG_RESOURCE_REQUIREMENTS_LIST: 10,
33
+ REG_QWORD: 11
34
+ };
35
+
36
+function windows_registry()
37
+{
38
+ this._ObjectId = 'windows_registry';
39
+ this._marshal = require('_GenericMarshal');
40
+ this._AdvApi = this._marshal.CreateNativeProxy('Advapi32.dll');
41
+ this._AdvApi.CreateMethod('RegCreateKeyExA');
42
+ this._AdvApi.CreateMethod('RegOpenKeyExA');
43
+ this._AdvApi.CreateMethod('RegQueryValueExA');
44
+ this._AdvApi.CreateMethod('RegCloseKey');
45
+ this._AdvApi.CreateMethod('RegDeleteKeyA');
46
+ this._AdvApi.CreateMethod('RegDeleteValueA');
47
+ this._AdvApi.CreateMethod('RegSetValueExA');
48
+ this.HKEY = { Root: Buffer.from('80000000', 'hex').swap32(), CurrentUser: Buffer.from('80000001', 'hex').swap32(), LocalMachine: Buffer.from('80000002', 'hex').swap32(), Users: Buffer.from('80000003', 'hex').swap32() };
49
+
50
+ this.QueryKey = function QueryKey(hkey, path, key)
51
+ {
52
+ var h = this._marshal.CreatePointer();
53
+ var len = this._marshal.CreateVariable(4);
54
+ var valType = this._marshal.CreateVariable(4);
55
+ key = this._marshal.CreateVariable(key);
56
+ var HK = this._marshal.CreatePointer(hkey);
57
+ var retVal = null;
58
+
59
+ if (this._AdvApi.RegOpenKeyExA(HK, this._marshal.CreateVariable(path), 0, KEY_QUERY_VALUE, h).Val != 0)
60
+ {
61
+ throw ('Error Opening Registry Key: ' + path);
62
+ }
63
+
64
+ if(this._AdvApi.RegQueryValueExA(h.Deref(), key, 0, 0, 0, len).Val == 0)
65
+ {
66
+ var data = this._marshal.CreateVariable(len.toBuffer().readUInt32LE());
67
+ if (this._AdvApi.RegQueryValueExA(h.Deref(), key, 0, valType, data, len).Val == 0)
68
+ {
69
+ switch(valType.toBuffer().readUInt32LE())
70
+ {
71
+ case KEY_DATA_TYPES.REG_DWORD:
72
+ retVal = data.toBuffer().readUInt32LE();
73
+ break;
74
+ case KEY_DATA_TYPES.REG_DWORD_BIG_ENDIAN:
75
+ retVal = data.toBuffer().readUInt32BE();
76
+ break;
77
+ case KEY_DATA_TYPES.REG_SZ:
78
+ retVal = data.String;
79
+ break;
80
+ case KEY_DATA_TYPES.REG_BINARY:
81
+ default:
82
+ retVal = data.toBuffer();
83
+ retVal._data = data;
84
+ break;
85
+ }
86
+ }
87
+ }
88
+ else
89
+ {
90
+ this._AdvApi.RegCloseKey(h.Deref());
91
+ throw ('Not Found');
92
+ }
93
+ this._AdvApi.RegCloseKey(h.Deref());
94
+ return (retVal);
95
+ };
96
+ this.WriteKey = function WriteKey(hkey, path, key, value)
97
+ {
98
+ var result;
99
+ var h = this._marshal.CreatePointer();
100
+
101
+ if (this._AdvApi.RegCreateKeyExA(this._marshal.CreatePointer(hkey), this._marshal.CreateVariable(path), 0, 0, 0, KEY_WRITE, 0, h, 0).Val != 0)
102
+ {
103
+ throw ('Error Opening Registry Key: ' + path);
104
+ }
105
+
106
+ var data;
107
+ var dataType;
108
+
109
+ switch(typeof(value))
110
+ {
111
+ case 'boolean':
112
+ dataType = KEY_DATA_TYPES.REG_DWORD;
113
+ data = this._marshal.CreateVariable(4);
114
+ data.toBuffer().writeUInt32LE(value ? 1 : 0);
115
+ break;
116
+ case 'number':
117
+ dataType = KEY_DATA_TYPES.REG_DWORD;
118
+ data = this._marshal.CreateVariable(4);
119
+ data.toBuffer().writeUInt32LE(value);
120
+ break;
121
+ case 'string':
122
+ dataType = KEY_DATA_TYPES.REG_SZ;
123
+ data = this._marshal.CreateVariable(value);
124
+ break;
125
+ default:
126
+ dataType = KEY_DATA_TYPES.REG_BINARY;
127
+ data = this._marshal.CreateVariable(value.length);
128
+ value.copy(data.toBuffer());
129
+ break;
130
+ }
131
+
132
+ if(this._AdvApi.RegSetValueExA(h.Deref(), this._marshal.CreateVariable(key), 0, dataType, data, data._size).Val != 0)
133
+ {
134
+ this._AdvApi.RegCloseKey(h.Deref());
135
+ throw ('Error writing reg key: ' + key);
136
+ }
137
+ this._AdvApi.RegCloseKey(h.Deref());
138
+ };
139
+ this.DeleteKey = function DeleteKey(hkey, path, key)
140
+ {
141
+ if(!key)
142
+ {
143
+ if(this._AdvApi.RegDeleteKeyA(this._marshal.CreatePointer(hkey), this._marshal.CreateVariable(path)).Val != 0)
144
+ {
145
+ throw ('Error Deleting Key: ' + path);
146
+ }
147
+ }
148
+ else
149
+ {
150
+ var h = this._marshal.CreatePointer();
151
+ var result;
152
+ if (this._AdvApi.RegOpenKeyExA(this._marshal.CreatePointer(hkey), this._marshal.CreateVariable(path), 0, KEY_QUERY_VALUE | KEY_WRITE, h).Val != 0)
153
+ {
154
+ throw ('Error Opening Registry Key: ' + path);
155
+ }
156
+ if ((result = this._AdvApi.RegDeleteValueA(h.Deref(), this._marshal.CreateVariable(key)).Val) != 0)
157
+ {
158
+ this._AdvApi.RegCloseKey(h.Deref());
159
+ throw ('Error[' + result + '] Deleting Key: ' + path + '.' + key);
160
+ }
161
+ this._AdvApi.RegCloseKey(h.Deref());
162
+ }
163
+ };
164
+}
165
+
166
+module.exports = new windows_registry();
167
+
redirserver.js
+2
-2
@@ -71,7 +71,7 @@ module.exports.CreateRedirServer = function (parent, db, args, func) {
71
// Once the main web server is started, call this to hookup additional handlers
72
obj.hookMainWebServer = function (certs) {
73
obj.certificates = certs;
74
- for (var i = 0; i < parent.config.domains.length; i++) {
74
+ for (var i in parent.config.domains) {
75
if (parent.config.domains[i].dns != null) { continue; }
76
var url = parent.config.domains[i].url;
77
obj.app.post(url + "amtevents.ashx", obj.parent.webserver.handleAmtEventRequest);
@@ -82,7 +82,7 @@ module.exports.CreateRedirServer = function (parent, db, args, func) {
82
83
// Setup all HTTP redirection handlers
84
//obj.app.set("etag", false);
85
- for (var i = 0; i < parent.config.domains; i++) {
85
+ for (var i in parent.config.domains) {
86
if (parent.config.domains[i].dns != null) { continue; }
87
var url = parent.config.domains[i].url;
88
obj.app.get(url, performRedirection);
views/default.handlebars
+2
-2
@@ -927,7 +927,7 @@
927
928
// Poll the server, if it responds, refresh the page.
929
function serverPoll() {
930
- xdr = null;
930
+ var xdr = null;
931
try { xdr = new XDomainRequest(); } catch (e) { }
932
if (!xdr) xdr = new XMLHttpRequest();
933
xdr.open("HEAD", window.location.href);
@@ -2253,7 +2253,7 @@
2253
try {
2254
var loc = map_parseNodeLoc(nodes[i]);
2255
var feature = xxmap.markersSource.getFeatureById(nodes[i]._id);
2256
- if ((loc != null) && ((nodes[i].meshid == selectedMesh) || (selectedMesh == null))) { // Draw markers for devices with locations
2256
+ if ((typeof loc == 'object') && ((nodes[i].meshid == selectedMesh) || (selectedMesh == null))) { // Draw markers for devices with locations
2257
var lat = loc[0], lon = loc[1], type = loc[2];
2258
if (boundingBox == null) { boundingBox = [ lat, lon, lat, lon, 0 ]; } else { if (lat < boundingBox[0]) { boundingBox[0] = lat; } if (lon < boundingBox[1]) { boundingBox[1] = lon; } if (lat > boundingBox[2]) { boundingBox[2] = lat; } if (lon > boundingBox[3]) { boundingBox[3] = lon; } }
2259
if (feature == null) { addFeature(nodes[i]); boundingBox[4] = 1; } else { updateFeature(nodes[i], feature); feature.setStyle(markerStyle(nodes[i], loc[2])); } // Update Feature