New MeshAgents, lots of bug fixes.
Ylian Saint-Hilaire committed
Sep 20, 2018 at 11:45 UTC
8dcd8938a6d408eca2b1a8934a3b96a286a93886
32 files changed
+546
-132
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/meshagent_arm
Binary files a/agents/meshagent_arm and b/agents/meshagent_arm differ
agents/meshagent_pi
Binary files a/agents/meshagent_pi and b/agents/meshagent_pi differ
agents/meshagent_pogo
Binary files a/agents/meshagent_pogo and b/agents/meshagent_pogo differ
agents/meshagent_poky
Binary files a/agents/meshagent_poky and b/agents/meshagent_poky differ
agents/meshagent_poky64
Binary files a/agents/meshagent_poky64 and b/agents/meshagent_poky64 differ
agents/meshagent_x86
Binary files a/agents/meshagent_x86 and b/agents/meshagent_x86 differ
agents/meshagent_x86-64
Binary files a/agents/meshagent_x86-64 and b/agents/meshagent_x86-64 differ
agents/meshagent_x86-64_nokvm
Binary files a/agents/meshagent_x86-64_nokvm and b/agents/meshagent_x86-64_nokvm differ
agents/meshagent_x86_nokvm
Binary files a/agents/meshagent_x86_nokvm and b/agents/meshagent_x86_nokvm differ
agents/meshcmd.js
+17
-1
@@ -96,7 +96,7 @@ function run(argv) {
96
//console.log('addedModules = ' + JSON.stringify(addedModules));
97
var actionpath = 'meshaction.txt';
98
if (args.actionfile != null) { actionpath = args.actionfile; }
99
- var actions = ['HELP', 'ROUTE', 'MICROLMS', 'AMTLOADWEBAPP', 'AMTLOADSMALLWEBAPP', 'AMTLOADLARGEWEBAPP', 'AMTCLEARWEBAPP', 'AMTSTORAGESTATE', 'AMTINFO', 'AMTVERSIONS', 'AMTHASHES', 'AMTSAVESTATE', 'AMTSCRIPT', 'AMTUUID', 'AMTCCM', 'AMTDEACTIVATE', 'SMBIOS', 'RAWSMBIOS', 'MESHCOMMANDER', 'AMTAUDITLOG', 'AMTPRESENCE'];
99
+ var actions = ['HELP', 'ROUTE', 'MICROLMS', 'AMTLOADWEBAPP', 'AMTLOADSMALLWEBAPP', 'AMTLOADLARGEWEBAPP', 'AMTCLEARWEBAPP', 'AMTSTORAGESTATE', 'AMTINFO', 'AMTINFODEBUG', 'AMTVERSIONS', 'AMTHASHES', 'AMTSAVESTATE', 'AMTSCRIPT', 'AMTUUID', 'AMTCCM', 'AMTDEACTIVATE', 'SMBIOS', 'RAWSMBIOS', 'MESHCOMMANDER', 'AMTAUDITLOG', 'AMTPRESENCE'];
100
101
// Load the action file
102
var actionfile = null;
@@ -372,6 +372,22 @@ function run(argv) {
372
console.log(str + '.');
373
exit(1);
374
});
375
+ } else if (settings.action == 'amtinfodebug') {
376
+ // Display Intel AMT version and activation state
377
+ mestate = {};
378
+ var amtMeiModule = require('amt-mei');
379
+ var amtMei = new amtMeiModule();
380
+ amtMei.on('error', function (e) { console.log('ERROR: ' + e); exit(1); return; });
381
+ amtMei.getVersion(function (result) { console.log('getVersion: ' + JSON.stringify(result)); });
382
+ amtMei.getProvisioningState(function (result) { console.log('getProvisioningState: ' + JSON.stringify(result)); });
383
+ amtMei.getProvisioningMode(function (result) { console.log('getProvisioningMode: ' + JSON.stringify(result)); });
384
+ amtMei.getEHBCState(function (result) { if (result) { console.log('getEHBCState: ' + JSON.stringify(result)); } });
385
+ amtMei.getControlMode(function (result) { if (result) { console.log('getControlMode: ' + JSON.stringify(result)); } });
386
+ amtMei.getMACAddresses(function (result) { if (result) { console.log('getMACAddresses: ' + JSON.stringify(result)); } });
387
+ amtMei.getLanInterfaceSettings(0, function (result) { console.log('getLanInterfaceSettings0: ' + JSON.stringify(result)); });
388
+ amtMei.getLanInterfaceSettings(1, function (result) { console.log('getLanInterfaceSettings1: ' + JSON.stringify(result)); });
389
+ amtMei.getUuid(function (result) { console.log('getUuid: ' + JSON.stringify(result)); });
390
+ amtMei.getDnsSuffix(function (result) { console.log('getDnsSuffix: ' + JSON.stringify(result)); });
391
} else if (settings.action == 'amtsavestate') {
392
// Save the entire state of Intel AMT info a JSON file
393
if ((settings.password == null) || (typeof settings.password != 'string') || (settings.password == '')) { console.log('No or invalid \"password\" specified, use --password [password].'); exit(1); return; }
agents/meshcore.js
+83
-31
@@ -14,9 +14,16 @@ See the License for the specific language governing permissions and
14
limitations under the License.
15
*/
16
17
+
18
+process.on('uncaughtException', function (ex) {
19
+ require('MeshAgent').SendCommand({ "action": "msg", "type": "console", "value": "uncaughtException1: " + ex });
20
+});
21
+
22
+
23
function createMeshCore(agent) {
24
var obj = {};
25
26
+ /*
27
function borderController() {
28
this.container = null;
29
this.Start = function Start(user) {
@@ -45,6 +52,7 @@ function createMeshCore(agent) {
52
}
53
}
54
}
55
+ */
56
57
require('events').EventEmitter.call(obj, true).createEvent('loggedInUsers_Updated');
58
obj.on('loggedInUsers_Updated', function ()
@@ -56,7 +64,7 @@ function createMeshCore(agent) {
64
}
65
sendConsoleText('LogOn Status Changed. Active Users => [' + users.join(', ') + ']');
66
});
59
- obj.borderManager = new borderController();
67
+ //obj.borderManager = new borderController();
68
69
// MeshAgent JavaScript Core Module. This code is sent to and running on the mesh agent.
70
obj.meshCoreInfo = "MeshCore v6";
@@ -82,6 +90,12 @@ function createMeshCore(agent) {
90
var networkMonitor = null;
91
var amtscanner = null;
92
var nextTunnelIndex = 1;
93
+
94
+ // Get the operating system description string
95
+ // *** THIS CAUSES AGENT TO BE UNSTABLE!!!
96
+ //obj.osDesc = null;
97
+ //try { require('os').name().then(function (v) { obj.osDesc = v; }); } catch (ex) { }
98
+ // *** THIS CAUSES AGENT TO BE UNSTABLE!!!
99
100
/*
101
var AMTScanner = require("AMTScanner");
@@ -120,7 +134,7 @@ function createMeshCore(agent) {
134
try {
135
var amtMeiLib = require('amt-mei');
136
amtMei = new amtMeiLib();
123
- amtMei.on('error', function (e) { amtMeiLib = null; amtMei = null; sendPeriodicServerUpdate(); });
137
+ amtMei.on('error', function (e) { amtMeiLib = null; amtMei = null; amtMeiConnected = -1; sendPeriodicServerUpdate(); });
138
amtMeiConnected = 2;
139
//amtMei.on('connect', function () { amtMeiConnected = 2; sendPeriodicServerUpdate(); });
140
} catch (e) { amtMeiLib = null; amtMei = null; amtMeiConnected = -1; }
@@ -909,9 +923,10 @@ function createMeshCore(agent) {
923
var response = null;
924
switch (cmd) {
925
case 'help': { // Displays available commands
912
- 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.';
926
+ response = 'Available commands: help, info, osinfo, 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, sendinfo, sendcaps.';
927
break;
928
}
929
+ /*
930
case 'border':
931
{
932
if ((args['_'].length == 1) && (args['_'][0] == 'on')) {
@@ -929,6 +944,7 @@ function createMeshCore(agent) {
944
}
945
}
946
break;
947
+ */
948
case 'users':
949
{
950
var retList = [];
@@ -1020,15 +1036,24 @@ function createMeshCore(agent) {
1036
break;
1037
}
1038
case 'info': { // Return information about the agent and agent core module
1023
- 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 + '.';
1039
+ response = 'Current Core: ' + obj.meshCoreInfo + '.\r\nAgent Time: ' + Date() + '.\r\nUser Rights: 0x' + rights.toString(16) + '.\r\nPlatform: ' + process.platform + '.\r\nCapabilities: ' + obj.meshCoreCapabilities + '.\r\nServer URL: ' + mesh.ServerUrl + '.';
1040
if (amtLmsState >= 0) { response += '\r\nBuilt-in LMS: ' + ['Disabled', 'Connecting..', 'Connected'][amtLmsState] + '.'; }
1041
+ //if (obj.osDesc) { response += '\r\nOS: ' + obj.osDesc + '.'; }
1042
response += '\r\nModules: ' + addedModules.join(', ') + '.';
1026
- response += '\r\nServerConnected: ' + mesh.isControlChannelConnected + '.';
1043
+ response += '\r\nServer Connection: ' + mesh.isControlChannelConnected + ', State: ' + meshServerConnectionState + '.';
1044
+ response += '\r\nLastInfo: ' + lastSelfInfo + '.';
1045
var oldNodeId = db.Get('OldNodeId');
1046
if (oldNodeId != null) { response += '\r\nOldNodeID: ' + oldNodeId + '.'; }
1029
- response += '\r\nServerState: ' + meshServerConnectionState + '.';
1030
- if (process.platform != 'win32') {
1031
- response += '\r\nX11 support: ' + require('monitor-info').kvm_x11_support + '.';
1047
+ if (process.platform != 'win32') { response += '\r\nX11 support: ' + require('monitor-info').kvm_x11_support + '.'; }
1048
+ break;
1049
+ }
1050
+ case 'osinfo': { // Return the operating system information
1051
+ var i = 1;
1052
+ if (args['_'].length > 0) { i = parseInt(args['_'][0]); response = 'Calling ' + i + ' times.'; }
1053
+ for (var j = 0; j < i; j++) {
1054
+ var pr = require('os').name();
1055
+ pr.sessionid = sessionid;
1056
+ pr.then(function (v) { sendConsoleText("OS: " + v, this.sessionid); });
1057
}
1058
break;
1059
}
@@ -1036,6 +1061,26 @@ function createMeshCore(agent) {
1061
buildSelfInfo(function (info) { sendConsoleText(objToString(info, 0, ' ', true), sessionid); });
1062
break;
1063
}
1064
+ case 'sendinfo': { // Send our information to the server
1065
+ buildSelfInfo(function (selfInfo) {
1066
+ lastSelfInfo = JSON.stringify(selfInfo);
1067
+ sendConsoleText('Sent: ' + lastSelfInfo);
1068
+ mesh.SendCommand(lastSelfInfo);
1069
+ });
1070
+ break;
1071
+ }
1072
+ case 'sendcaps': { // Send capability flags to the server
1073
+ if (args['_'].length == 0) {
1074
+ response = 'Proper usage: sendcaps (number)'; // Display correct command usage
1075
+ } else {
1076
+ var flags = 0;
1077
+ response = JSON.stringify(args);
1078
+ flags = { "action": "coreinfo", "value": obj.meshCoreInfo, "caps": parseInt(args['_'][0]) };
1079
+ mesh.SendCommand(flags);
1080
+ response = JSON.stringify(flags);
1081
+ }
1082
+ break;
1083
+ }
1084
case 'args': { // Displays parsed command arguments
1085
response = 'args ' + objToString(args, 0, ' ', true);
1086
break;
@@ -1345,15 +1390,17 @@ function createMeshCore(agent) {
1390
function buildSelfInfo(func) {
1391
getAmtInfo(function (meinfo) {
1392
var r = { "action": "coreinfo", "value": obj.meshCoreInfo, "caps": obj.meshCoreCapabilities };
1348
- if (meinfo != null) {
1349
- var intelamt = {}, p = false;
1350
- if (meinfo.Versions && meinfo.Versions.AMT) { intelamt.ver = meinfo.Versions.AMT; p = true; }
1351
- if (meinfo.ProvisioningState) { intelamt.state = meinfo.ProvisioningState; p = true; }
1352
- if (meinfo.Flags) { intelamt.flags = meinfo.Flags; p = true; }
1353
- if (meinfo.OsHostname) { intelamt.host = meinfo.OsHostname; p = true; }
1354
- if (meinfo.UUID) { intelamt.uuid = meinfo.UUID; p = true; }
1355
- if (p == true) { r.intelamt = intelamt }
1356
- }
1393
+ try {
1394
+ if (meinfo != null) {
1395
+ var intelamt = {}, p = false;
1396
+ if (meinfo.Versions && meinfo.Versions.AMT) { intelamt.ver = meinfo.Versions.AMT; p = true; }
1397
+ if (meinfo.ProvisioningState) { intelamt.state = meinfo.ProvisioningState; p = true; }
1398
+ if (meinfo.Flags) { intelamt.flags = meinfo.Flags; p = true; }
1399
+ if (meinfo.OsHostname) { intelamt.host = meinfo.OsHostname; p = true; }
1400
+ if (meinfo.UUID) { intelamt.uuid = meinfo.UUID; p = true; }
1401
+ if (p == true) { r.intelamt = intelamt }
1402
+ }
1403
+ } catch (ex) { }
1404
func(r);
1405
});
1406
}
@@ -1374,10 +1421,11 @@ function createMeshCore(agent) {
1421
// Called periodically to check if we need to send updates to the server
1422
function sendPeriodicServerUpdate(force) {
1423
if ((amtMeiConnected != 1) || (force == true)) { // If we are pending MEI connection, hold off on updating the server on self-info
1424
+ if (force == true) { lastSelfInfo = null; }
1425
// Update the self information data
1426
buildSelfInfo(function (selfInfo) {
1427
selfInfoStr = JSON.stringify(selfInfo);
1380
- if ((force == true) || (selfInfoStr != lastSelfInfo)) { mesh.SendCommand(selfInfo); lastSelfInfo = selfInfoStr; }
1428
+ if (selfInfoStr != lastSelfInfo) { mesh.SendCommand(selfInfo); lastSelfInfo = selfInfoStr; }
1429
});
1430
}
1431
@@ -1445,10 +1493,9 @@ function createMeshCore(agent) {
1493
} catch (e) { amtLmsState = -1; amtLms = null; }
1494
1495
// Check if the control channel is connected
1448
- if (mesh.isControlChannelConnected) {
1449
- sendPeriodicServerUpdate(true); // Send the server update
1450
- }
1496
+ if (mesh.isControlChannelConnected) { handleServerConnection(1); }
1497
1498
+ /*
1499
require('user-sessions').on('changed', function onUserSessionChanged()
1500
{
1501
require('user-sessions').enumerateUsers().then(function (users)
@@ -1461,6 +1508,7 @@ function createMeshCore(agent) {
1508
require('user-sessions').emit('changed');
1509
require('user-sessions').on('locked', function (user) { sendConsoleText('[' + (user.Domain ? user.Domain + '\\' : '') + user.Username + '] has LOCKED the desktop'); });
1510
require('user-sessions').on('unlocked', function (user) { sendConsoleText('[' + (user.Domain ? user.Domain + '\\' : '') + user.Username + '] has UNLOCKED the desktop'); });
1511
+ */
1512
//console.log('Stopping.');
1513
//process.exit();
1514
}
@@ -1733,14 +1781,18 @@ function createMeshCore(agent) {
1781
// Module startup
1782
//
1783
1736
-var xexports = null, mainMeshCore = null;
1737
-try { xexports = module.exports; } catch (e) { }
1784
+try {
1785
+ var xexports = null, mainMeshCore = null;
1786
+ try { xexports = module.exports; } catch (e) { }
1787
1739
-if (xexports != null) {
1740
- // If we are running within NodeJS, export the core
1741
- module.exports.createMeshCore = createMeshCore;
1742
-} else {
1743
- // If we are not running in NodeJS, launch the core
1744
- mainMeshCore = createMeshCore();
1745
- mainMeshCore.start(null);
1746
-}
1788
+ if (xexports != null) {
1789
+ // If we are running within NodeJS, export the core
1790
+ module.exports.createMeshCore = createMeshCore;
1791
+ } else {
1792
+ // If we are not running in NodeJS, launch the core
1793
+ mainMeshCore = createMeshCore();
1794
+ mainMeshCore.start(null);
1795
+ }
1796
+} catch (ex) {
1797
+ require('MeshAgent').SendCommand({ "action": "msg", "type": "console", "value": "uncaughtException2: " + ex });
1798
+}
\ No newline at end of file
agents/modules_meshcmd/amt-lme.js
+12
-10
@@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
14
limitations under the License.
15
*/
16
17
-
17
var MemoryStream = require('MemoryStream');
18
var lme_id = 0; // Our next channel identifier
19
var lme_port_offset = 0; // Debug: Set this to "-100" to bind to 16892 & 16893 and IN_ADDRANY. This is for LMS debugging.
@@ -38,6 +37,7 @@ var APF_CHANNEL_DATA = 94;
37
var APF_CHANNEL_CLOSE = 97;
38
var APF_PROTOCOLVERSION = 192;
39
40
+
41
function lme_object() {
42
this.ourId = ++lme_id;
43
this.amtId = -1;
@@ -266,7 +266,7 @@ function lme_heci(options) {
266
this.sockets[rChannelId].bufferedStream.emit('readable');
267
}
268
} else {
269
- //console.log('Unknown Recipient ID/' + rChannelId + ' for APF_CHANNEL_WINDOW_ADJUST');
269
+ console.log('Unknown Recipient ID/' + rChannelId + ' for APF_CHANNEL_WINDOW_ADJUST');
270
}
271
break;
272
case APF_CHANNEL_DATA:
@@ -379,14 +379,16 @@ function lme_heci(options) {
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);
382
+ /*
383
+ var buffer = Buffer.alloc(17);
384
+ buffer.writeUInt8(APF_CHANNEL_OPEN_FAILURE, 0);
385
+ buffer.writeUInt32BE(channelSender, 1); // Intel AMT sender channel
386
+ buffer.writeUInt32BE(2, 5); // Reason code
387
+ buffer.writeUInt32BE(0, 9); // Reserved
388
+ buffer.writeUInt32BE(0, 13); // Reserved
389
+ this.write(buffer);
390
+ console.log('Sent APF_CHANNEL_OPEN_FAILURE', channelSender);
391
+ */
392
393
break;
394
}
agents/modules_meshcmd/amt-wsman-duk.js
+2
-6
@@ -30,7 +30,6 @@ function CreateWsmanComm(/*host, port, user, pass, tls, extra*/)
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 = {};
33
34
if (arguments.length == 1 && typeof(arguments[0] == 'object'))
35
{
@@ -90,12 +89,9 @@ function CreateWsmanComm(/*host, port, user, pass, tls, extra*/)
89
}
90
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)); } };
91
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.
92
//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]); });
93
+ req.on('error', function (e) { obj.gotNextMessagesError({ status: 600 }, 'error', null, [postdata, callback, tag]); });
94
req.on('response', function (response) {
98
- response.reqid = this.reqid;
95
//console.log('Response: ' + response.statusCode);
96
if (response.statusCode != 200) {
97
//console.log('ERR:' + JSON.stringify(response));
@@ -103,7 +99,7 @@ function CreateWsmanComm(/*host, port, user, pass, tls, extra*/)
99
} else {
100
response.acc = '';
101
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]); });
102
+ response.on('end', function () { obj.gotNextMessages(response.acc, 'success', { status: response.statusCode }, [postdata, callback, tag]); });
103
}
104
});
105
agents/modules_meshcmd/amt-xml.js
+4
-2
@@ -14,6 +14,9 @@ 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
+
19
+
20
// Parse XML and return JSON
21
module.exports.ParseWsman = function (xml) {
22
try {
@@ -36,7 +39,7 @@ module.exports.ParseWsman = function (xml) {
39
}
40
return r;
41
} catch (e) {
39
- console.log("Unable to parse XML: " + xml);
42
+ console.error("Unable to parse XML: " + xml, e);
43
return null;
44
}
45
}
@@ -103,7 +106,6 @@ function _PutObjToBodyXml(resuri, putObj) {
106
}
107
108
// 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) { }
109
function _treeBuilder() {
110
this.tree = [];
111
this.push = function (element) { this.tree.push(element); };
agents/modules_meshcmd/amt.js
+7
-9
@@ -202,9 +202,6 @@ function AmtStackCreateService(wsmanStack) {
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); }
205
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); }
206
obj.AMT_AgentPresenceWatchdog_DeleteAllActions = function (callback_func, tag, pri, selectors) { obj.Exec("AMT_AgentPresenceWatchdog", "DeleteAllActions", {}, callback_func, tag, pri, selectors); }
207
obj.AMT_AgentPresenceWatchdogAction_GetActionEac = function (callback_func) { obj.Exec("AMT_AgentPresenceWatchdogAction", "GetActionEac", {}, callback_func); }
@@ -264,7 +261,7 @@ function AmtStackCreateService(wsmanStack) {
261
obj.AMT_MessageLog_FreezeLog = function (Freeze, callback_func) { obj.Exec("AMT_MessageLog", "FreezeLog", { "Freeze": Freeze }, callback_func); }
262
obj.AMT_PublicKeyManagementService_AddCRL = function (Url, SerialNumbers, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "AddCRL", { "Url": Url, "SerialNumbers": SerialNumbers }, callback_func); }
263
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); }
264
+ obj.AMT_PublicKeyManagementService_AddCertificate = function (CertificateBlob, callback_func, tag) { obj.Exec("AMT_PublicKeyManagementService", "AddCertificate", { "CertificateBlob": CertificateBlob }, callback_func, tag); }
265
obj.AMT_PublicKeyManagementService_AddTrustedRootCertificate = function (CertificateBlob, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "AddTrustedRootCertificate", { "CertificateBlob": CertificateBlob }, callback_func); }
266
obj.AMT_PublicKeyManagementService_AddKey = function (KeyBlob, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "AddKey", { "KeyBlob": KeyBlob }, callback_func); }
267
obj.AMT_PublicKeyManagementService_GeneratePKCS10Request = function (KeyPair, DNName, Usage, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "GeneratePKCS10Request", { "KeyPair": KeyPair, "DNName": DNName, "Usage": Usage }, callback_func); }
@@ -275,7 +272,7 @@ function AmtStackCreateService(wsmanStack) {
272
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); }
273
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); }
274
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); }
275
+ obj.AMT_SetupAndConfigurationService_CommitChanges = function (_method_dummy, callback_func, tag) { obj.Exec("AMT_SetupAndConfigurationService", "CommitChanges", { "_method_dummy": _method_dummy }, callback_func, tag); }
276
obj.AMT_SetupAndConfigurationService_Unprovision = function (ProvisioningMode, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "Unprovision", { "ProvisioningMode": ProvisioningMode }, callback_func); }
277
obj.AMT_SetupAndConfigurationService_PartialUnprovision = function (_method_dummy, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "PartialUnprovision", { "_method_dummy": _method_dummy }, callback_func); }
278
obj.AMT_SetupAndConfigurationService_ResetFlashWearOutProtection = function (_method_dummy, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "ResetFlashWearOutProtection", { "_method_dummy": _method_dummy }, callback_func); }
@@ -292,6 +289,7 @@ function AmtStackCreateService(wsmanStack) {
289
obj.AMT_SystemPowerScheme_SetPowerScheme = function (callback_func, schemeInstanceId, tag) { obj.Exec("AMT_SystemPowerScheme", "SetPowerScheme", {}, callback_func, tag, 0, { "InstanceID": schemeInstanceId }); }
290
obj.AMT_TimeSynchronizationService_GetLowAccuracyTimeSynch = function (callback_func, tag) { obj.Exec("AMT_TimeSynchronizationService", "GetLowAccuracyTimeSynch", {}, callback_func, tag); }
291
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); }
292
+ obj.AMT_TLSCredentialContext_Create = function AMT_TLSCredentialContext_Create(ElementInContext, ElementProvidingContext, callback_func, tag) { obj.Create("AMT_TLSCredentialContext", { "ElementInContext": ElementInContext, "ElementProvidingContext": ElementProvidingContext }, callback_func, tag); }
293
obj.AMT_UserInitiatedConnectionService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("AMT_UserInitiatedConnectionService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
294
obj.AMT_WebUIService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func, tag) { obj.Exec("AMT_WebUIService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func, tag); }
295
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); }
@@ -765,18 +763,18 @@ function AmtStackCreateService(wsmanStack) {
763
x['Initiator'] = 'KVM Default Port';
764
ptr = 5;
765
}
768
-
766
+
767
// Read timestamp
768
TimeStamp = ReadInt(e, ptr);
769
x['Time'] = new Date((TimeStamp + (t.getTimezoneOffset() * 60)) * 1000);
770
ptr += 4;
773
-
771
+
772
// Read network access
773
x['MCLocationType'] = e[ptr++];
774
var netlen = e[ptr++];
775
776
x['NetAddress'] = e.slice(ptr, ptr + netlen).toString();
779
-
777
+
778
// Read extended data
779
ptr += netlen;
780
var exlen = e[ptr++];
@@ -990,7 +988,7 @@ function AmtStackCreateService(wsmanStack) {
988
// Convert a byte array of SID into string
989
function GetSidString(sid) {
990
var r = "S-" + sid.charCodeAt(0) + "-" + sid.charCodeAt(7);
993
- for (var i = 2; i < (sid.length / 4) ; i++) r += "-" + ReadIntX(sid, i * 4);
991
+ for (var i = 2; i < (sid.length / 4); i++) r += "-" + ReadIntX(sid, i * 4);
992
return r;
993
}
994
agents/modules_meshcmd/process-manager.js
+71
-19
@@ -14,6 +14,7 @@ See the License for the specific language governing permissions and
14
limitations under the License.
15
*/
16
17
+
18
var GM = require('_GenericMarshal');
19
20
// Used on Windows and Linux to get information about running processes
@@ -21,7 +22,8 @@ function processManager() {
22
this._ObjectID = 'process-manager'; // Used for debugging, allows you to get the object type at runtime.
23
24
// Setup the platform specific calls.
24
- switch (process.platform) {
25
+ switch (process.platform)
26
+ {
27
case 'win32':
28
this._kernel32 = GM.CreateNativeProxy('kernel32.dll');
29
this._kernel32.CreateMethod('GetLastError');
@@ -30,17 +32,26 @@ function processManager() {
32
this._kernel32.CreateMethod('Process32Next');
33
break;
34
case 'linux':
35
+ case 'darwin':
36
this._childProcess = require('child_process');
37
break;
38
default:
39
throw (process.platform + ' not supported');
40
break;
41
}
39
-
42
+ this.enumerateProcesses = function enumerateProcesses()
43
+ {
44
+ var promise = require('promise');
45
+ var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
46
+ this.getProcesses(function (ps, prom) { prom._res(ps); }, ret);
47
+ return (ret);
48
+ }
49
// Return a object of: pid -> process information.
41
- this.getProcesses = function getProcesses(callback) {
42
- switch (process.platform) {
43
- default: // This is not a supported platform.
50
+ this.getProcesses = function getProcesses(callback)
51
+ {
52
+ switch(process.platform)
53
+ {
54
+ default:
55
throw ('Enumerating processes on ' + process.platform + ' not supported');
56
break;
57
case 'win32': // Windows processes
@@ -49,8 +60,9 @@ function processManager() {
60
var info = GM.CreateVariable(304);
61
info.toBuffer().writeUInt32LE(304, 0);
62
var nextProcess = this._kernel32.Process32First(h, info);
52
- while (nextProcess.Val) {
53
- retVal[info.Deref(8, 4).toBuffer().readUInt32LE(0)] = { cmd: info.Deref(GM.PointerSize == 4 ? 36 : 44, 260).String };
63
+ while (nextProcess.Val)
64
+ {
65
+ retVal[info.Deref(8, 4).toBuffer().readUInt32LE(0)] = { pid: info.Deref(8, 4).toBuffer().readUInt32LE(0), cmd: info.Deref(GM.PointerSize == 4 ? 36 : 44, 260).String };
66
nextProcess = this._kernel32.Process32Next(h, info);
67
}
68
if (callback) { callback.apply(this, [retVal]); }
@@ -64,40 +76,80 @@ function processManager() {
76
p.callback = callback;
77
p.args = [];
78
for (var i = 1; i < arguments.length; ++i) { p.args.push(arguments[i]); }
67
- p.on('exit', function onGetProcesses() {
68
- delete this.Parent._psp[this.pid];
79
+ p.on('exit', function onGetProcesses()
80
+ {
81
+ delete this.Parent._psp[this.pid];
82
var retVal = {}, lines = this.ps.split('\x0D\x0A'), key = {}, keyi = 0;
70
- for (var i in lines) {
83
+ for (var i in lines)
84
+ {
85
var tokens = lines[i].split(' ');
86
var tokenList = [];
73
- for (var x in tokens) {
87
+ for(var x in tokens)
88
+ {
89
if (i == 0 && tokens[x]) { key[tokens[x]] = keyi++; }
75
- if (i > 0 && tokens[x]) { tokenList.push(tokens[x]); }
90
+ if (i > 0 && tokens[x]) { tokenList.push(tokens[x]);}
91
}
92
if (i > 0) {
78
- if (tokenList[key.PID]) { retVal[tokenList[key.PID]] = { user: tokenList[key.USER], cmd: tokenList[key.COMMAND] }; }
93
+ if (tokenList[key.PID]) { retVal[tokenList[key.PID]] = { pid: key.PID, user: tokenList[key.USER], cmd: tokenList[key.COMMAND] }; }
94
}
95
}
81
- if (this.callback) {
96
+ if (this.callback)
97
+ {
98
this.args.unshift(retVal);
99
this.callback.apply(this.parent, this.args);
100
}
101
});
102
p.stdout.on('data', function (chunk) { this.parent.ps += chunk.toString(); });
103
break;
104
+ case 'darwin':
105
+ var promise = require('promise');
106
+ var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
107
+ p.pm = this;
108
+ p.callback = callback;
109
+ p.args = [];
110
+ for (var i = 1; i < arguments.length; ++i) { p.args.push(arguments[i]); }
111
+ p.child = this._childProcess.execFile("/bin/ps", ["ps", "-xa"]);
112
+ p.child.promise = p;
113
+ p.child.stdout.ps = '';
114
+ p.child.stdout.on('data', function (chunk) { this.ps += chunk.toString(); });
115
+ p.child.on('exit', function ()
116
+ {
117
+ var lines = this.stdout.ps.split('\n');
118
+ var pidX = lines[0].split('PID')[0].length + 3;
119
+ var cmdX = lines[0].split('CMD')[0].length;
120
+ var ret = {};
121
+ for (var i = 1; i < lines.length; ++i)
122
+ {
123
+ if (lines[i].length > 0)
124
+ {
125
+ ret[lines[i].substring(0, pidX).trim()] = { pid: lines[i].substring(0, pidX).trim(), cmd: lines[i].substring(cmdX) };
126
+ }
127
+ }
128
+ this.promise._res(ret);
129
+ });
130
+ p.then(function (ps)
131
+ {
132
+ this.args.unshift(ps);
133
+ this.callback.apply(this.pm, this.args);
134
+ });
135
+ break;
136
}
137
};
90
-
138
+
139
// Get information about a specific process on Linux
92
- this.getProcessInfo = function getProcessInfo(pid) {
93
- switch (process.platform) {
140
+ this.getProcessInfo = function getProcessInfo(pid)
141
+ {
142
+ switch(process.platform)
143
+ {
144
default:
145
throw ('getProcessInfo() not supported for ' + process.platform);
146
break;
147
case 'linux':
148
var status = require('fs').readFileSync('/proc/' + pid + '/status');
99
- var info = {}, lines = status.toString().split('\n');
100
- for (var i in lines) {
149
+ var info = {};
150
+ var lines = status.toString().split('\n');
151
+ for(var i in lines)
152
+ {
153
var tokens = lines[i].split(':');
154
if (tokens.length > 1) { tokens[1] = tokens[1].trim(); }
155
info[tokens[0]] = tokens[1];
agents/modules_meshcmd/promise.js
+28
-6
@@ -16,10 +16,32 @@ limitations under the License.
16
17
var refTable = {};
18
19
+function event_switcher_helper(desired_callee, target)
20
+{
21
+ this._ObjectID = 'event_switcher';
22
+ this.func = function func()
23
+ {
24
+ var args = [];
25
+ for(var i in arguments)
26
+ {
27
+ args.push(arguments[i]);
28
+ }
29
+ return (func.target.apply(func.desired, args));
30
+ };
31
+ this.func.desired = desired_callee;
32
+ this.func.target = target;
33
+ this.func.self = this;
34
+}
35
+function event_switcher(desired_callee, target)
36
+{
37
+ return (new event_switcher_helper(desired_callee, target));
38
+}
39
+
40
function Promise(promiseFunc)
41
{
42
this._ObjectID = 'promise';
22
- this._internal = { promise: this, func: promiseFunc, completed: false, errors: false, completedArgs: [] };
43
+ this.promise = this;
44
+ this._internal = { _ObjectID: 'promise.internal', promise: this, func: promiseFunc, completed: false, errors: false, completedArgs: [] };
45
require('events').EventEmitter.call(this._internal);
46
this._internal.on('_eventHook', function (eventName, eventCallback)
47
{
@@ -82,21 +104,21 @@ function Promise(promiseFunc)
104
};
105
this.catch = function(func)
106
{
85
- this._internal.once('settled', func);
107
+ this._internal.once('rejected', event_switcher(this, func).func);
108
}
109
this.finally = function (func)
110
{
89
- this._internal.once('settled', func);
111
+ this._internal.once('settled', event_switcher(this, func).func);
112
};
113
this.then = function (resolved, rejected)
114
{
93
- if (resolved) { this._internal.once('resolved', resolved); }
94
- if (rejected) { this._internal.once('rejected', rejected); }
115
+ if (resolved) { this._internal.once('resolved', event_switcher(this, resolved).func); }
116
+ if (rejected) { this._internal.once('rejected', event_switcher(this, rejected).func); }
117
118
var retVal = new Promise(function (r, j) { });
97
-
119
this._internal.once('resolved', retVal._internal.resolver);
120
this._internal.once('rejected', retVal._internal.rejector);
121
+ retVal.parentPromise = this;
122
return (retVal);
123
};
124
agents/modules_meshcmd/smbios.js
+24
-4
@@ -21,7 +21,18 @@ 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() {
24
+// Fill the left with zeros until the string is of a given length
25
+function zeroLeftPad(str, len)
26
+{
27
+ if ((len == null) && (typeof (len) != 'number')) { return null; }
28
+ if (str == null) str = ''; // If null, this is to generate zero leftpad string
29
+ var zlp = '';
30
+ for (var i = 0; i < len - str.length; i++) { zlp += '0'; }
31
+ return zlp + str;
32
+}
33
+
34
+function SMBiosTables()
35
+{
36
this._ObjectID = 'SMBiosTable';
37
if (process.platform == 'win32') {
38
this._marshal = require('_GenericMarshal');
@@ -181,12 +192,21 @@ function SMBiosTables() {
192
}
193
return (retVal);
194
};
184
- this.systemInfo = function systemInfo(data) {
195
+ this.systemInfo = function systemInfo(data)
196
+ {
197
if (!data) { throw ('no data'); }
198
var retVal = { _ObjectID: 'SMBiosTables.systemInfo' };
187
- if (data[1]) {
199
+ if (data[1])
200
+ {
201
var si = data[1].peek();
189
- retVal.uuid = si.slice(4, 20).toString('hex');
202
+ var uuid = si.slice(4, 20);
203
+
204
+ retVal.uuid = [zeroLeftPad(uuid.readUInt32LE(0).toString(16), 8),
205
+ zeroLeftPad(uuid.readUInt16LE(4).toString(16), 4),
206
+ zeroLeftPad(uuid.readUInt16LE(6).toString(16), 4),
207
+ zeroLeftPad(uuid.readUInt16BE(8).toString(16), 4),
208
+ zeroLeftPad(uuid.slice(10).toString('hex').toLowerCase(), 12)].join('-');
209
+
210
retVal.wakeReason = wakeReason[si[20]];
211
}
212
return (retVal);
agents/modules_meshcmd/user-sessions.js
+239
-24
@@ -17,6 +17,13 @@ limitations under the License.
17
var NOTIFY_FOR_THIS_SESSION = 0;
18
var NOTIFY_FOR_ALL_SESSIONS = 1;
19
var WM_WTSSESSION_CHANGE = 0x02B1;
20
+var WM_POWERBROADCAST = 0x218;
21
+var PBT_POWERSETTINGCHANGE = 0x8013;
22
+var PBT_APMSUSPEND = 0x4;
23
+var PBT_APMRESUMESUSPEND = 0x7;
24
+var PBT_APMRESUMEAUTOMATIC = 0x12;
25
+var PBT_APMPOWERSTATUSCHANGE = 0xA;
26
+
27
var WTS_CONSOLE_CONNECT = (0x1);
28
var WTS_CONSOLE_DISCONNECT = (0x2);
29
var WTS_REMOTE_CONNECT = (0x3);
@@ -29,6 +36,10 @@ var WTS_SESSION_REMOTE_CONTROL = (0x9);
36
var WTS_SESSION_CREATE = (0xA);
37
var WTS_SESSION_TERMINATE = (0xB);
38
39
+var GUID_ACDC_POWER_SOURCE;
40
+var GUID_BATTERY_PERCENTAGE_REMAINING;
41
+var GUID_CONSOLE_DISPLAY_STATE;
42
+
43
function UserSessions()
44
{
45
this._ObjectID = 'user-sessions';
@@ -49,7 +60,15 @@ function UserSessions()
60
{
61
p.__resolver(users);
62
};
52
- this.Current(p.__handler);
63
+ try
64
+ {
65
+ this.Current(p.__handler);
66
+ }
67
+ catch(e)
68
+ {
69
+ p.__rejector(e);
70
+ }
71
+ p.parent = this;
72
return (p);
73
}
74
@@ -65,6 +84,29 @@ function UserSessions()
84
this._wts.CreateMethod('WTSRegisterSessionNotification');
85
this._wts.CreateMethod('WTSUnRegisterSessionNotification');
86
this._wts.CreateMethod('WTSFreeMemory');
87
+ this._user32 = this._marshal.CreateNativeProxy('user32.dll');
88
+ this._user32.CreateMethod('RegisterPowerSettingNotification');
89
+ this._user32.CreateMethod('UnregisterPowerSettingNotification');
90
+ this._rpcrt = this._marshal.CreateNativeProxy('Rpcrt4.dll');
91
+ this._rpcrt.CreateMethod('UuidFromStringA');
92
+ this._rpcrt.StringToUUID = function StringToUUID(guid)
93
+ {
94
+ var retVal = StringToUUID.us._marshal.CreateVariable(16);
95
+ if(StringToUUID.us._rpcrt.UuidFromStringA(StringToUUID.us._marshal.CreateVariable(guid), retVal).Val == 0)
96
+ {
97
+ return (retVal);
98
+ }
99
+ else
100
+ {
101
+ throw ('Could not convert string to UUID');
102
+ }
103
+ }
104
+ this._rpcrt.StringToUUID.us = this;
105
+
106
+ GUID_ACDC_POWER_SOURCE = this._rpcrt.StringToUUID('5d3e9a59-e9D5-4b00-a6bd-ff34ff516548');
107
+ GUID_BATTERY_PERCENTAGE_REMAINING = this._rpcrt.StringToUUID('a7ad8041-b45a-4cae-87a3-eecbb468a9e1');
108
+ GUID_CONSOLE_DISPLAY_STATE = this._rpcrt.StringToUUID('6fe69556-704a-47a0-8f24-c28d936fda47');
109
+
110
this.SessionStates = ['Active', 'Connected', 'ConnectQuery', 'Shadow', 'Disconnected', 'Idle', 'Listening', 'Reset', 'Down', 'Init'];
111
this.InfoClass =
112
{
@@ -146,45 +188,112 @@ function UserSessions()
188
return (retVal);
189
};
190
149
- this._immediate = setImmediate(function (self)
191
+
192
+ // We need to spin up a message pump, and fetch a window handle
193
+ var message_pump = require('win-message-pump');
194
+ this._messagepump = new message_pump({ filter: WM_WTSSESSION_CHANGE }); this._messagepump.parent = this;
195
+ this._messagepump.on('exit', function (code) { this.parent._wts.WTSUnRegisterSessionNotification(this.parent.hwnd); });
196
+ this._messagepump.on('hwnd', function (h)
197
{
151
- if (self._serviceHooked) { return; } // If we were hooked by a service, we won't need to do anything further
198
+ this.parent.hwnd = h;
199
153
- // We need to spin up a message pump, and fetch a window handle
154
- var message_pump = require('win-message-pump');
155
- self._messagepump = new message_pump({ filter: WM_WTSSESSION_CHANGE });
156
- self._messagepump.on('exit', function (code) { self._wts.WTSUnRegisterSessionNotification(self.hwnd); });
157
- self._messagepump.on('hwnd', function (h)
158
- {
159
- self.hwnd = h;
160
- // Now that we have a window handle, we can register it to receive Windows Messages
161
- self._wts.WTSRegisterSessionNotification(self.hwnd, NOTIFY_FOR_ALL_SESSIONS);
162
- });
163
- self._messagepump.on('message', function (msg)
200
+ // Now that we have a window handle, we can register it to receive Windows Messages
201
+ this.parent._wts.WTSRegisterSessionNotification(this.parent.hwnd, NOTIFY_FOR_ALL_SESSIONS);
202
+ //this.parent._user32.ACDC_H = this.parent._user32.RegisterPowerSettingNotification(this.parent.hwnd, GUID_ACDC_POWER_SOURCE, 0);
203
+ //this.parent._user32.BATT_H = this.parent._user32.RegisterPowerSettingNotification(this.parent.hwnd, GUID_BATTERY_PERCENTAGE_REMAINING, 0);
204
+ //this.parent._user32.DISP_H = this.parent._user32.RegisterPowerSettingNotification(this.parent.hwnd, GUID_CONSOLE_DISPLAY_STATE, 0); // Windows 8+ only, THIS WILL BLOCK ON WIN7
205
+ });
206
+ this._messagepump.on('message', function (msg)
207
+ {
208
+ switch(msg.message)
209
{
165
- if (msg.message == WM_WTSSESSION_CHANGE)
166
- {
210
+ case WM_WTSSESSION_CHANGE:
211
switch(msg.wparam)
212
{
213
case WTS_SESSION_LOCK:
170
- self.enumerateUsers().then(function (users)
214
+ this.parent.enumerateUsers().then(function (users)
215
{
172
- if (users[msg.lparam]) { self.emit('locked', users[msg.lparam]); }
216
+ if (users[msg.lparam]) { this.parent.emit('locked', users[msg.lparam]); }
217
});
218
break;
219
case WTS_SESSION_UNLOCK:
176
- self.enumerateUsers().then(function (users)
220
+ this.parent.enumerateUsers().then(function (users)
221
{
178
- if (users[msg.lparam]) { self.emit('unlocked', users[msg.lparam]); }
222
+ if (users[msg.lparam]) { this.parent.emit('unlocked', users[msg.lparam]); }
223
});
224
break;
225
+ case WTS_SESSION_LOGON:
226
+ case WTS_SESSION_LOGOFF:
227
+ this.parent.emit('changed');
228
+ break;
229
}
182
- }
183
- });
184
- }, this);
230
+ break;
231
+ case WM_POWERBROADCAST:
232
+ switch(msg.wparam)
233
+ {
234
+ default:
235
+ console.log('WM_POWERBROADCAST [UNKNOWN wparam]: ' + msg.wparam);
236
+ break;
237
+ case PBT_APMSUSPEND:
238
+ require('power-monitor').emit('sx', 'SLEEP');
239
+ break;
240
+ case PBT_APMRESUMEAUTOMATIC:
241
+ require('power-monitor').emit('sx', 'RESUME_NON_INTERACTIVE');
242
+ break;
243
+ case PBT_APMRESUMESUSPEND:
244
+ require('power-monitor').emit('sx', 'RESUME_INTERACTIVE');
245
+ break;
246
+ case PBT_APMPOWERSTATUSCHANGE:
247
+ require('power-monitor').emit('changed');
248
+ break;
249
+ case PBT_POWERSETTINGCHANGE:
250
+ var lparam = this.parent._marshal.CreatePointer(Buffer.from(msg.lparam_hex, 'hex'));
251
+ var data = lparam.Deref(20, lparam.Deref(16, 4).toBuffer().readUInt32LE(0)).toBuffer();
252
+ switch(lparam.Deref(0, 16).toBuffer().toString('hex'))
253
+ {
254
+ case GUID_ACDC_POWER_SOURCE.Deref(0, 16).toBuffer().toString('hex'):
255
+ switch(data.readUInt32LE(0))
256
+ {
257
+ case 0:
258
+ require('power-monitor').emit('acdc', 'AC');
259
+ break;
260
+ case 1:
261
+ require('power-monitor').emit('acdc', 'BATTERY');
262
+ break;
263
+ case 2:
264
+ require('power-monitor').emit('acdc', 'HOT');
265
+ break;
266
+ }
267
+ break;
268
+ case GUID_BATTERY_PERCENTAGE_REMAINING.Deref(0, 16).toBuffer().toString('hex'):
269
+ require('power-monitor').emit('batteryLevel', data.readUInt32LE(0));
270
+ break;
271
+ case GUID_CONSOLE_DISPLAY_STATE.Deref(0, 16).toBuffer().toString('hex'):
272
+ switch(data.readUInt32LE(0))
273
+ {
274
+ case 0:
275
+ require('power-monitor').emit('display', 'OFF');
276
+ break;
277
+ case 1:
278
+ require('power-monitor').emit('display', 'ON');
279
+ break;
280
+ case 2:
281
+ require('power-monitor').emit('display', 'DIMMED');
282
+ break;
283
+ }
284
+ break;
285
+ }
286
+ break;
287
+ }
288
+ break;
289
+ default:
290
+ break;
291
+ }
292
+ });
293
}
186
- else
294
+ else if(process.platform == 'linux')
295
{
296
+ var dbus = require('linux-dbus');
297
this._linuxWatcher = require('fs').watch('/var/run/utmp');
298
this._linuxWatcher.user_session = this;
299
this._linuxWatcher.on('change', function (a, b)
@@ -336,6 +445,112 @@ function UserSessions()
445
446
return (retVal);
447
}
448
+ this._recheckLoggedInUsers = function _recheckLoggedInUsers()
449
+ {
450
+ this.enumerateUsers().then(function (u)
451
+ {
452
+
453
+ if (u.Active.length > 0)
454
+ {
455
+ // There is already a user logged in, so we can monitor DBUS for lock/unlock
456
+ if (this.parent._linux_lock_watcher != null && this.parent._linux_lock_watcher.uid != u.Active[0].uid)
457
+ {
458
+ delete this.parent._linux_lock_watcher;
459
+ }
460
+ this.parent._linux_lock_watcher = new dbus(process.env['XDG_CURRENT_DESKTOP'] == 'Unity' ? 'com.ubuntu.Upstart0_6' : 'org.gnome.ScreenSaver', u.Active[0].uid);
461
+ this.parent._linux_lock_watcher.user_session = this.parent;
462
+ this.parent._linux_lock_watcher.on('signal', function (s)
463
+ {
464
+ var p = this.user_session.enumerateUsers();
465
+ p.signalData = s.data[0];
466
+ p.then(function (u)
467
+ {
468
+ switch (this.signalData)
469
+ {
470
+ case true:
471
+ case 'desktop-lock':
472
+ this.parent.emit('locked', u.Active[0]);
473
+ break;
474
+ case false:
475
+ case 'desktop-unlock':
476
+ this.parent.emit('unlocked', u.Active[0]);
477
+ break;
478
+ }
479
+ });
480
+ });
481
+ }
482
+ else if (this.parent._linux_lock_watcher != null)
483
+ {
484
+ delete this.parent._linux_lock_watcher;
485
+ }
486
+ });
487
+
488
+ };
489
+ this.on('changed', this._recheckLoggedInUsers); // For linux Lock/Unlock monitoring, we need to watch for LogOn/LogOff, and keep track of the UID.
490
+
491
+
492
+ // First step, is to see if there is a user logged in:
493
+ this._recheckLoggedInUsers();
494
+ }
495
+ else if(process.platform == 'darwin')
496
+ {
497
+ this._idTable = function()
498
+ {
499
+ var table = {};
500
+ var child = require('child_process').execFile('/usr/bin/id', ['id']);
501
+ child.stdout.str = '';
502
+ child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
503
+ child.waitExit();
504
+
505
+ var lines = child.stdout.str.split('\n')[0].split(' ');
506
+ for (var i = 0; i < lines.length; ++i) {
507
+ var types = lines[i].split('=');
508
+ var tokens = types[1].split(',');
509
+ table[types[0]] = {};
510
+
511
+ for (var j in tokens) {
512
+ var idarr = tokens[j].split('(');
513
+ var id = idarr[0];
514
+ var name = idarr[1].substring(0, idarr[1].length - 1).trim();
515
+ table[types[0]][name] = id;
516
+ table[types[0]][id] = name;
517
+ }
518
+ }
519
+ return (table);
520
+ }
521
+ this.Current = function (cb)
522
+ {
523
+ var users = {};
524
+ var table = this._idTable();
525
+ var child = require('child_process').execFile('/usr/bin/last', ['last']);
526
+ child.stdout.str = '';
527
+ child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
528
+ child.waitExit();
529
+
530
+ var lines = child.stdout.str.split('\n');
531
+ for (var i = 0; i < lines.length && lines[i].length > 0; ++i)
532
+ {
533
+ if (!users[lines[i].split(' ')[0]])
534
+ {
535
+ try
536
+ {
537
+ users[lines[i].split(' ')[0]] = { Username: lines[i].split(' ')[0], State: lines[i].split('still logged in').length > 1 ? 'Active' : 'Inactive', uid: table.uid[lines[i].split(' ')[0]] };
538
+ }
539
+ catch(e)
540
+ {}
541
+ }
542
+ else
543
+ {
544
+ if(users[lines[i].split(' ')[0]].State != 'Active' && lines[i].split('still logged in').length > 1)
545
+ {
546
+ users[lines[i].split(' ')[0]].State = 'Active';
547
+ }
548
+ }
549
+ }
550
+
551
+ Object.defineProperty(users, 'Active', { value: showActiveOnly(users) });
552
+ if (cb) { cb.call(this, users); }
553
+ }
554
}
555
}
556
function showActiveOnly(source)
agents/modules_meshcore/power-monitor.js
new
+34
@@ -0,0 +1,34 @@
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 powerMonitor()
18
+{
19
+ this._ObjectID = 'power-monitor';
20
+ require('events').EventEmitter.call(this, true)
21
+ .createEvent('changed')
22
+ .createEvent('sx')
23
+ .createEvent('batteryLevel')
24
+ .createEvent('acdc')
25
+ .createEvent('display');
26
+
27
+ this._i = setImmediate(function (self)
28
+ {
29
+ require('user-sessions'); // This is needed because this is where the Windows Messages are processed for these events
30
+ delete self._i;
31
+ }, this);
32
+}
33
+
34
+module.exports = new powerMonitor();
\ No newline at end of file
agents/modules_meshcore/user-sessions.js
+3
-3
@@ -199,9 +199,9 @@ function UserSessions()
199
200
// Now that we have a window handle, we can register it to receive Windows Messages
201
this.parent._wts.WTSRegisterSessionNotification(this.parent.hwnd, NOTIFY_FOR_ALL_SESSIONS);
202
- this.parent._user32.ACDC_H = this.parent._user32.RegisterPowerSettingNotification(this.parent.hwnd, GUID_ACDC_POWER_SOURCE, 0);
203
- this.parent._user32.BATT_H = this.parent._user32.RegisterPowerSettingNotification(this.parent.hwnd, GUID_BATTERY_PERCENTAGE_REMAINING, 0);
204
- this.parent._user32.DISP_H = this.parent._user32.RegisterPowerSettingNotification(this.parent.hwnd, GUID_CONSOLE_DISPLAY_STATE, 0);
202
+ //this.parent._user32.ACDC_H = this.parent._user32.RegisterPowerSettingNotification(this.parent.hwnd, GUID_ACDC_POWER_SOURCE, 0);
203
+ //this.parent._user32.BATT_H = this.parent._user32.RegisterPowerSettingNotification(this.parent.hwnd, GUID_BATTERY_PERCENTAGE_REMAINING, 0);
204
+ //this.parent._user32.DISP_H = this.parent._user32.RegisterPowerSettingNotification(this.parent.hwnd, GUID_CONSOLE_DISPLAY_STATE, 0); // Windows 8+ only, THIS WILL BLOCK ON WIN7
205
});
206
this._messagepump.on('message', function (msg)
207
{
meshcentral.js
+10
-8
@@ -1087,14 +1087,16 @@ function CreateMeshCentralServer(config, args) {
1087
// Update server state. Writes a server state file.
1088
var meshServerState = {};
1089
obj.updateServerState = function (name, val) {
1090
- if ((name != null) && (val != null)) {
1091
- var changed = false;
1092
- if ((name != null) && (meshServerState[name] != val)) { if ((val == null) && (meshServerState[name] != null)) { delete meshServerState[name]; changed = true; } else { if (meshServerState[name] != val) { meshServerState[name] = val; changed = true; } } }
1093
- if (changed == false) return;
1094
- }
1095
- var r = 'time=' + Date.now() + '\r\n';
1096
- for (var i in meshServerState) { r += (i + '=' + meshServerState[i] + '\r\n'); }
1097
- obj.fs.writeFileSync(obj.getConfigFilePath('serverstate.txt'), r);
1090
+ try {
1091
+ if ((name != null) && (val != null)) {
1092
+ var changed = false;
1093
+ if ((name != null) && (meshServerState[name] != val)) { if ((val == null) && (meshServerState[name] != null)) { delete meshServerState[name]; changed = true; } else { if (meshServerState[name] != val) { meshServerState[name] = val; changed = true; } } }
1094
+ if (changed == false) return;
1095
+ }
1096
+ var r = 'time=' + Date.now() + '\r\n';
1097
+ for (var i in meshServerState) { r += (i + '=' + meshServerState[i] + '\r\n'); }
1098
+ obj.fs.writeFileSync(obj.getConfigFilePath('serverstate.txt'), r); // Try to write the server state, this may fail if we don't have permission.
1099
+ } catch (ex) { } // Do nothing since this is not a critical feature.
1100
};
1101
1102
// Logging funtions
package.json
+1
-1
@@ -1,6 +1,6 @@
1
{
2
"name": "meshcentral",
3
- "version": "0.2.0-q",
3
+ "version": "0.2.0-w",
4
"keywords": [
5
"Remote Management",
6
"Intel AMT",
public/scripts/amt-terminal-0.0.2.js
+4
-2
@@ -15,6 +15,7 @@ var CreateAmtRemoteTerminal = function (divid) {
15
// ###END###{Terminal-Enumation-All}
16
obj.fxEmulation = 0;
17
obj.lineFeed = '\r\n';
18
+ obj.debugmode = 0;
19
20
obj.width = 80; // 80 or 100
21
obj.height = 25; // 25 or 30
@@ -53,6 +54,7 @@ var CreateAmtRemoteTerminal = function (divid) {
54
obj.xxStateChange = function(newstate) { }
55
56
obj.ProcessData = function (str) {
57
+ if (obj.debugmode == 2) { console.log("TRecv(" + str.length + "): " + rstr2hex(str)); }
58
// ###BEGIN###{Terminal-Enumation-UTF8}
59
//str = decode_utf8(str);
60
// ###END###{Terminal-Enumation-UTF8}
@@ -480,8 +482,8 @@ var CreateAmtRemoteTerminal = function (divid) {
482
}
483
}
484
483
- obj.TermSendKeys = function(keys) { obj.parent.send(keys); }
484
- obj.TermSendKey = function(key) { obj.parent.send(String.fromCharCode(key)); }
485
+ obj.TermSendKeys = function (keys) { if (obj.debugmode == 2) { if (obj.debugmode == 2) { console.log("TSend(" + keys.length + "): " + rstr2hex(keys)); } } obj.parent.send(keys); }
486
+ obj.TermSendKey = function (key) { if (obj.debugmode == 2) { if (obj.debugmode == 2) { console.log("TSend(1): " + rstr2hex(String.fromCharCode(key))); } } obj.parent.send(String.fromCharCode(key)); }
487
488
function _TermMoveUp(linecount) {
489
var x, y;
views/default-mobile.handlebars
+5
-5
@@ -351,7 +351,7 @@
351
<div id=p10html2></div>
352
<div id=p10html3></div>
353
</div>
354
- <div id=p10desktop style="overflow-y:scroll;position:absolute;top:55px;bottom:0px;width:100%;display:none">
354
+ <div id=p10desktop style="overflow:hidden;position:absolute;top:55px;bottom:0px;width:100%;display:none">
355
<div id=deskarea1 style="position:absolute;top:0px;width:100%;height:25px">
356
<div style="padding-top:2px;padding-bottom:2px;background:#C0C0C0">
357
<div style="float:right;text-align:right">
@@ -1622,9 +1622,9 @@
1622
QV('p10desktop', currentDevicePanel == 1);
1623
QV('p10files', currentDevicePanel == 2);
1624
var menus = [];
1625
- if (currentDevicePanel != 0) { menus.push( { n:'General', f:'setupDeviceMenu(0)' } ); }
1626
- if (currentDevicePanel != 1) { menus.push( { n:'Desktop', f:'setupDeviceMenu(1)' } ); }
1627
- if ((currentDevicePanel != 2) && ((currentNode != null) && (currentNode.mtype == 2))) { menus.push( { n:'Files', f:'setupDeviceMenu(2)' } ); }
1625
+ if (currentDevicePanel != 0) { menus.push({ n: 'General', f: 'setupDeviceMenu(0)' }); }
1626
+ if ((currentDevicePanel != 1) && (currentNode != null) && ((currentNode.mtype == 1) || (currentNode.agent.caps & 1))) { menus.push({ n: 'Desktop', f: 'setupDeviceMenu(1)' }); }
1627
+ if ((currentDevicePanel != 2) && (currentNode != null) && ((currentNode.mtype == 2) && (currentNode.agent.caps & 4))) { menus.push({ n: 'Files', f: 'setupDeviceMenu(2)' }); }
1628
updateFooterMenu(menus);
1629
}
1630
@@ -2804,7 +2804,7 @@
2804
if (((b & 8) || x) && f) f(x, t);
2805
}
2806
2807
- function center() { QS('dialog').left = ((((getDocWidth() - 300) / 2)) + "px"); deskAdjust(); /*drawDeviceTimeline();*/ }
2807
+ function center() { QS('dialog').left = ((((getDocWidth() - 300) / 2)) + "px"); deskAdjust(); deskAdjust(); /*drawDeviceTimeline();*/ }
2808
function messagebox(t, m) { QH('id_dialogMessage', m); setDialogMode(1, t, 1); }
2809
function statusbox(t, m) { QH('id_dialogMessage', m); setDialogMode(1, t); }
2810
function getDocWidth() { if (window.innerWidth) return window.innerWidth; if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientWidth != 0) return document.documentElement.clientWidth; return document.getElementsByTagName('body')[0].clientWidth; }
views/default.handlebars
+2
-1
@@ -3949,6 +3949,7 @@
3949
if ((terminalNode.intelamt.user == null) || (terminalNode.intelamt.user == '')) { editDeviceAmtSettings(terminalNode._id, connectTerminal); return; }
3950
terminal = CreateAmtRedirect(CreateAmtRemoteTerminal('Term'));
3951
terminal.debugmode = debugmode;
3952
+ terminal.m.debugmode = debugmode;
3953
terminal.onStateChanged = onTerminalStateChange;
3954
terminal.Start(terminalNode._id, 16994, '*', '*', 0);
3955
terminal.contype = 2;
@@ -3958,7 +3959,7 @@
3959
terminal = CreateAgentRedirect(meshserver, CreateAmtRemoteTerminal('Term'), serverPublicNamePort);
3960
terminal.debugmode = debugmode;
3961
terminal.m.debugmode = debugmode;
3961
- terminal.m.lineFeed = ([1,2,3,4,21,22].indexOf(currentNode.agent.id) >= 0)?'\r\n':'\r'; // On windows, send \r\n, on Linux only \r
3962
+ terminal.m.lineFeed = ([1,2,3,4,21,22].indexOf(currentNode.agent.id) >= 0)?'\r\n':'\n'; // On windows, send \r\n, on Linux only \n
3963
terminal.attemptWebRTC = attemptWebRTC;
3964
terminal.onStateChanged = onTerminalStateChange;
3965
terminal.Start(terminalNode._id);