You can now view & clear the server error log on the web ui as administrator

Ylian Saint-Hilaire committed Sep 18, 2018 at 19:41 UTC bfe8a8074e5943b1e229681a3e6da0393abc4fc4
17 files changed +562 -197
agents/meshcore.js
+12 -10
@@ -17,7 +17,6 @@ limitations under the License.
17 function createMeshCore(agent) {
18 var obj = {};
19
20 - /*
20 function borderController() {
21 this.container = null;
22 this.Start = function Start(user) {
@@ -46,7 +45,6 @@ function createMeshCore(agent) {
45 }
46 }
47 }
49 - */
48
49 require('events').EventEmitter.call(obj, true).createEvent('loggedInUsers_Updated');
50 obj.on('loggedInUsers_Updated', function ()
@@ -58,10 +56,10 @@ function createMeshCore(agent) {
56 }
57 sendConsoleText('LogOn Status Changed. Active Users => [' + users.join(', ') + ']');
58 });
61 - //obj.borderManager = new borderController();
59 + obj.borderManager = new borderController();
60
61 // MeshAgent JavaScript Core Module. This code is sent to and running on the mesh agent.
64 - obj.meshCoreInfo = "MeshCore v5";
62 + obj.meshCoreInfo = "MeshCore v6";
63 obj.meshCoreCapabilities = 14; // Capability bitmask: 1 = Desktop, 2 = Terminal, 4 = Files, 8 = Console, 16 = JavaScript
64 obj.loggedInUsers = [];
65
@@ -141,7 +139,10 @@ function createMeshCore(agent) {
139 sha = require('SHA256Stream');
140 mesh = require('MeshAgent');
141 childProcess = require('child_process');
144 - if (mesh.hasKVM == 1) { obj.meshCoreCapabilities |= 1; }
142 + if (mesh.hasKVM == 1) { // if the agent is compiled with KVM support
143 + // Check if this computer supports a desktop
144 + try { if ((process.platform == 'win32') || (process.platform == 'darwin') || (require('monitor-info').kvm_x11_support)) { obj.meshCoreCapabilities |= 1; } } catch (ex) { }
145 + }
146 } else {
147 // Running in nodejs
148 obj.meshCoreInfo += '-NodeJS';
@@ -911,7 +912,6 @@ function createMeshCore(agent) {
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.';
913 break;
914 }
914 - /*
915 case 'border':
916 {
917 if ((args['_'].length == 1) && (args['_'][0] == 'on')) {
@@ -929,7 +929,6 @@ function createMeshCore(agent) {
929 }
930 }
931 break;
932 - */
932 case 'users':
933 {
934 var retList = [];
@@ -1023,11 +1022,14 @@ function createMeshCore(agent) {
1022 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 + '.';
1024 if (amtLmsState >= 0) { response += '\r\nBuilt-in LMS: ' + ['Disabled', 'Connecting..', 'Connected'][amtLmsState] + '.'; }
1026 - response += '\r\nModules: ' + addedModules.join(', ');
1027 - response += '\r\nServerConnected: ' + mesh.isControlChannelConnected;
1025 + response += '\r\nModules: ' + addedModules.join(', ') + '.';
1026 + response += '\r\nServerConnected: ' + mesh.isControlChannelConnected + '.';
1027 var oldNodeId = db.Get('OldNodeId');
1028 if (oldNodeId != null) { response += '\r\nOldNodeID: ' + oldNodeId + '.'; }
1030 - response += '\r\ServerState: ' + meshServerConnectionState + '.';
1029 + response += '\r\nServerState: ' + meshServerConnectionState + '.';
1030 + if (process.platform != 'win32') {
1031 + response += '\r\nX11 support: ' + require('monitor-info').kvm_x11_support + '.';
1032 + }
1033 break;
1034 }
1035 case 'selfinfo': { // Return self information block
agents/modules_meshcore/amt-lme.js
+11 -9
@@ -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;
@@ -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_meshcore/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_meshcore/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_meshcore/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_meshcore/monitor-info.js
+91 -58
@@ -54,67 +54,100 @@ function monitorinfo()
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()
57 + // First thing we need to do, is determine where the X11 libraries are
58 + var fs = require('fs');
59 + var files = fs.readdirSync('/usr/lib');
60 + var files2;
61 +
62 + /*
63 + for (j in files)
64 {
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)
65 + if (files[j].split('libX11.so.').length > 1 && files[j].split('.').length == 3)
66 {
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 - }
67 + Object.defineProperty(this, 'Location_X11LIB', { value: '/usr/lib/' + files[j] });
68 + }
69 + if (files[j].split('libXtst.so.').length > 1 && files[j].split('.').length == 3)
70 + {
71 + Object.defineProperty(this, 'Location_X11TST', { value: '/usr/lib/' + files[j] });
72 }
116 - this._X11.XCloseDisplay(display);
117 - return (ret);
73 + if (files[j].split('libXext.so.').length > 1 && files[j].split('.').length == 3)
74 + {
75 + Object.defineProperty(this, 'Location_X11EXT', { value: '/usr/lib/' + files[j] });
76 + }
77 + }
78 + */
79 +
80 + for (var i in files)
81 + {
82 + try {
83 + if (files[i].split('libX11.so.').length > 1 && files[i].split('.').length == 3) {
84 + Object.defineProperty(this, 'Location_X11LIB', { value: '/usr/lib/' + files[i] });
85 + }
86 + if (files[i].split('libXtst.so.').length > 1 && files[i].split('.').length == 3) {
87 + Object.defineProperty(this, 'Location_X11TST', { value: '/usr/lib/' + files[i] });
88 + }
89 + if (files[i].split('libXext.so.').length > 1 && files[i].split('.').length == 3) {
90 + Object.defineProperty(this, 'Location_X11EXT', { value: '/usr/lib/' + files[i] });
91 + }
92 +
93 + if (files[i].split('-linux-').length > 1) {
94 + files2 = fs.readdirSync('/usr/lib/' + files[i]);
95 + for (j in files2) {
96 + if (files2[j].split('libX11.so.').length > 1 && files2[j].split('.').length == 3) {
97 + Object.defineProperty(this, 'Location_X11LIB', { value: '/usr/lib/' + files[i] + '/' + files2[j] });
98 + }
99 + if (files2[j].split('libXtst.so.').length > 1 && files2[j].split('.').length == 3) {
100 + Object.defineProperty(this, 'Location_X11TST', { value: '/usr/lib/' + files[i] + '/' + files2[j] });
101 + }
102 + if (files2[j].split('libXext.so.').length > 1 && files2[j].split('.').length == 3) {
103 + Object.defineProperty(this, 'Location_X11EXT', { value: '/usr/lib/' + files[i] + '/' + files2[j] });
104 + }
105 + }
106 + }
107 + } catch (ex) { }
108 + }
109 + Object.defineProperty(this, 'kvm_x11_support', { value: (this.Location_X11LIB && this.Location_X11TST && this.Location_X11EXT)?true:false });
110 +
111 + if (this.Location_X11LIB)
112 + {
113 + this._X11 = this._gm.CreateNativeProxy(this.Location_X11LIB);
114 + this._X11.CreateMethod('XChangeProperty');
115 + this._X11.CreateMethod('XCloseDisplay');
116 + this._X11.CreateMethod('XCreateGC');
117 + this._X11.CreateMethod('XCreateWindow');
118 + this._X11.CreateMethod('XCreateSimpleWindow');
119 + this._X11.CreateMethod('XDefaultColormap');
120 + this._X11.CreateMethod('XDefaultScreen');
121 + this._X11.CreateMethod('XDrawLine');
122 + this._X11.CreateMethod('XDisplayHeight');
123 + this._X11.CreateMethod('XDisplayWidth');
124 + this._X11.CreateMethod('XFetchName');
125 + this._X11.CreateMethod('XFlush');
126 + this._X11.CreateMethod('XFree');
127 + this._X11.CreateMethod('XCreateGC');
128 + this._X11.CreateMethod('XGetWindowProperty');
129 + this._X11.CreateMethod('XInternAtom');
130 + this._X11.CreateMethod('XMapWindow');
131 + this._X11.CreateMethod({ method: 'XNextEvent', threadDispatch: true });
132 + this._X11.CreateMethod('XOpenDisplay');
133 + this._X11.CreateMethod('XRootWindow');
134 + this._X11.CreateMethod('XScreenCount');
135 + this._X11.CreateMethod('XScreenOfDisplay');
136 + this._X11.CreateMethod('XSelectInput');
137 + this._X11.CreateMethod('XSendEvent');
138 + this._X11.CreateMethod('XSetForeground');
139 + this._X11.CreateMethod('XSetFunction');
140 + this._X11.CreateMethod('XSetLineAttributes');
141 + this._X11.CreateMethod('XSetNormalHints');
142 + this._X11.CreateMethod('XSetSubwindowMode');
143 +
144 + this._X11.CreateMethod('XBlackPixel');
145 + this._X11.CreateMethod('XWhitePixel');
146 + }
147 +
148 + this.isUnity = function isUnity()
149 + {
150 + return (process.env['XDG_CURRENT_DESKTOP'] == 'Unity');
151 }
152
153 this.unDecorateWindow = function unDecorateWindow(display, window)
agents/modules_meshcore/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_meshcore/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_meshcore/smbios.js
+27 -7
@@ -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');
@@ -114,14 +125,14 @@ function SMBiosTables() {
125 this.child = require('child_process').execFile('/usr/sbin/dmidecode', ['dmidecode', '-u']);
126 this.child.SMBiosTable = this;
127 this.child.ms = new MemoryStream();
117 - this.child.ms.callback = callback
128 + this.child.ms.callback = callback;
129 this.child.ms.child = this.child;
130 this.child.stdout.on('data', function (buffer) { this.parent.ms.write(buffer); });
131 this.child.on('exit', function () { this.ms.end(); });
132 this.child.ms.on('end', function () {
133 //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');
134 + if (this.buffer.length < 300) {
135 + //console.log('Not enough permission to read SMBiosTable');
136 if (this.callback) { this.callback.apply(this.child.SMBiosTable, []); }
137 }
138 else {
@@ -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_meshcore/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);
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/wifi-scanner-windows.js
-16
@@ -1,19 +1,3 @@
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 -
1
2 function _Scan()
3 {
agents/modules_meshcore/wifi-scanner.js
+1 -16
@@ -1,22 +1,7 @@
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 -
1 var MemoryStream = require('MemoryStream');
2 var WindowsChildScript = 'var parent = require("ScriptContainer");var Wireless = require("wifi-scanner-windows");Wireless.on("Scan", function (ap) { parent.send(ap); });Wireless.Scan();';
3
4 +
5 function AccessPoint(_ssid, _bssid, _lq)
6 {
7 this.ssid = _ssid;
agents/modules_meshcore/win-message-pump.js
+1 -1
@@ -58,7 +58,7 @@ function WindowsMessagePump(options)
58 {\
59 if(h==null || h.Val == xhwnd.Val)\
60 {\
61 - require('ScriptContainer').send({message: xmsg.Val, wparam: wparam.Val, lparam: lparam.Val});\
61 + require('ScriptContainer').send({message: xmsg.Val, wparam: wparam.Val, lparam: lparam.Val, lparam_hex: lparam.pointerBuffer().toString('hex')});\
62 var retVal = u.DefWindowProcA(xhwnd, xmsg, wparam, lparam);\
63 return(retVal);\
64 }\
meshcentral.js
+2 -2
@@ -179,7 +179,7 @@ function CreateMeshCentralServer(config, args) {
179 xprocess.stdout.on('data', function (data) { if (data[data.length - 1] == '\n') { data = data.substring(0, data.length - 1); } if (data.indexOf('Updating settings folder...') >= 0) { xprocess.xrestart = 1; } else if (data.indexOf('Updating server certificates...') >= 0) { xprocess.xrestart = 1; } else if (data.indexOf('Server Ctrl-C exit...') >= 0) { xprocess.xrestart = 2; } else if (data.indexOf('Starting self upgrade...') >= 0) { xprocess.xrestart = 3; } console.log(data); });
180 xprocess.stderr.on('data', function (data) {
181 if (data.startsWith('le.challenges[tls-sni-01].loopback')) { return; } // Ignore this error output from GreenLock
182 - if (data[data.length - 1] == '\n') { data = data.substring(0, data.length - 1); } obj.fs.appendFileSync(obj.getConfigFilePath('mesherrors.txt'), '-------- ' + new Date().toLocaleString() + ' --------\r\n\r\n' + data + '\r\n\r\n\r\n');
182 + if (data[data.length - 1] == '\n') { data = data.substring(0, data.length - 1); } obj.fs.appendFileSync(obj.getConfigFilePath('mesherrors.txt'), '-------- ' + new Date().toLocaleString() + ' ---- ' + obj.currentVer + ' --------\r\n\r\n' + data + '\r\n\r\n\r\n');
183 });
184 xprocess.on('close', function (code) { if ((code != 0) && (code != 123)) { /* console.log("Exited with code " + code); */ } });
185 };
@@ -1104,7 +1104,7 @@ function CreateMeshCentralServer(config, args) {
1104 function logErrorEvent(msg) { if (obj.servicelog != null) { obj.servicelog.error(msg); } console.error(msg); }
1105
1106 // Read entire file and return it in callback function
1107 - function readEntireTextFile(filepath, func) {
1107 + obj.readEntireTextFile = function(filepath, func) {
1108 var called = false;
1109 try {
1110 obj.fs.open(filepath, 'r', function (err, fd) {
meshuser.js
+34
@@ -561,6 +561,20 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain) {
561 obj.parent.parent.performServerUpdate();
562 break;
563 }
564 + case 'servererrors':
565 + {
566 + // Load the server error log
567 + if ((user.siteadmin & 16) == 0) break;
568 + obj.parent.parent.readEntireTextFile(obj.parent.parent.getConfigFilePath('mesherrors.txt'), function (data) { ws.send(JSON.stringify({ action: 'servererrors', data: data })); } );
569 + break;
570 + }
571 + case 'serverclearerrorlog':
572 + {
573 + // Clear the server error log
574 + if ((user.siteadmin & 16) == 0) break;
575 + obj.parent.parent.fs.unlink(obj.parent.parent.getConfigFilePath('mesherrors.txt'));
576 + break;
577 + }
578 case 'createmesh':
579 {
580 // Create mesh
@@ -1262,6 +1276,26 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain) {
1276 ws.send(JSON.stringify({ action: 'userinfo', userinfo: userinfo }));
1277 } catch (e) { console.log(e); }
1278
1279 + // Read entire file and return it in callback function
1280 + function readEntireTextFile(filepath, func) {
1281 + var called = false;
1282 + try {
1283 + obj.fs.open(filepath, 'r', function (err, fd) {
1284 + obj.fs.fstat(fd, function (err, stats) {
1285 + var bufferSize = stats.size, chunkSize = 512, buffer = new Buffer(bufferSize), bytesRead = 0;
1286 + while (bytesRead < bufferSize) {
1287 + if ((bytesRead + chunkSize) > bufferSize) { chunkSize = (bufferSize - bytesRead); }
1288 + obj.fs.readSync(fd, buffer, bytesRead, chunkSize, bytesRead);
1289 + bytesRead += chunkSize;
1290 + }
1291 + obj.fs.close(fd);
1292 + called = true;
1293 + func(buffer.toString('utf8', 0, bufferSize));
1294 + });
1295 + });
1296 + } catch (e) { if (called == false) { func(null); } }
1297 + }
1298 +
1299 // Read the folder and all sub-folders and serialize that into json.
1300 function readFilesRec(path) {
1301 var r = {}, dir = obj.fs.readdirSync(path);
package.json
+1 -1
@@ -1,6 +1,6 @@
1 {
2 "name": "meshcentral",
3 - "version": "0.2.0-o",
3 + "version": "0.2.0-p",
4 "keywords": [
5 "Remote Management",
6 "Intel AMT",
views/default.handlebars
+31 -11
@@ -242,6 +242,7 @@
242 <a id="p2ServerActionsBackup" href="/backup.zip" target="_blank" style="cursor:pointer">Download server backup</a><br />
243 <a id="p2ServerActionsRestore" onclick="server_showRestoreDlg()" style="cursor:pointer">Restore server with backup</a><br />
244 <a id="p2ServerActionsVersion" onclick="server_showVersionDlg()" style="cursor:pointer">Check server version</a><br />
245 + <a id="p2ServerActionsErrors" onclick="server_showErrorsDlg()" style="cursor:pointer">Show server error log</a><br />
246 </p>
247 <br style=clear:both />
248 <strong>Administrative Meshes</strong>
@@ -1178,6 +1179,18 @@
1179 }
1180 break;
1181 }
1182 + case 'servererrors': {
1183 + if ((xxdialogMode == 2) && (xxdialogTag == 'MeshCentralServerErrors')) {
1184 + if (message.data == null) {
1185 + setDialogMode(2, "MeshCentral Server Errors", 1, null, 'Server has no error log.');
1186 + } else {
1187 + var x = '<div style=width:100%;max-height:260px;overflow-x:hidden;overflow:auto;line-height:160%;font-size:10px><pre>' + message.data + '<pre></div>';
1188 + setDialogMode(2, "MeshCentral Server Errors", 3, server_showErrorsDlgEx, x + '<br /><input id=d2updateCheck type=checkbox onclick=server_showVersionDlgUpdate() /> Check and click OK to clear error log.');
1189 + server_showVersionDlgUpdate();
1190 + }
1191 + }
1192 + break;
1193 + }
1194 case 'events': {
1195 if ((message.nodeid != null) && (message.nodeid == currentNode._id)) {
1196 currentDeviceEvents = message.events;
@@ -1662,8 +1675,9 @@
1675 var nodestate = NodeStateStr(nodes[i]);
1676 if ((!nodes[i].conn) || (nodes[i].conn == 0)) { icon += ' gray'; }
1677 if (view == 1) {
1665 - var xw = Math.floor(Q('xdevices').clientWidth / 301);
1666 - xw = 301 + Math.floor((Q('xdevices').clientWidth - (xw * 301)) / xw);
1678 + var realw = Q('xdevices').clientWidth - 30;
1679 + var xw = Math.floor(realw / 301);
1680 + xw = 301 + Math.floor((realw - (xw * 301)) / xw);
1681 r += '<div id=devs style=display:inline-block;width:' + xw + 'px;height:50px;padding-top:1px;padding-bottom:1px><div style=width:22px;height:50%;float:left;padding-top:12px><input class="' + nodes[i].meshid + ' DeviceCheckbox" onclick=p1updateInfo() value=devid_' + nodes[i]._id + ' type=checkbox></div><div style=height:100%;cursor:pointer onclick=gotoDevice(\'' + nodes[i]._id + '\')><div class="i' + icon + '" style=width:50px;float:left></div><div style=height:100%><div class=g1></div><div class=e2><div class=e1 style=width:' + (xw - 100) + 'px title="' + title + '">' + name + '</div><div>' + nodestate + '</div></div><div class=g2></div></div></div></div>';
1682 } else if (view == 2) {
1683 r += '<tr><td><div id=devs class=bar18 style=height:18px;width:100%;font-size:medium>';
@@ -1671,7 +1685,7 @@
1685 r += '<div style=float:left;height:18px;width:18px;background-color:white onclick=gotoDevice(\'' + nodes[i]._id + '\')><div class=j' + icon + ' style=width:16px;margin-top:1px;margin-left:2px;height:16px></div></div>';
1686 r += '<div class=g1 style=height:18px;float:left></div><div class=g2 style=height:18px;float:right></div>';
1687 r += '<div style=cursor:pointer;font-size:14px title="' + title + '" onclick=gotoDevice(\'' + nodes[i]._id + '\')><span style=float:right>' + nodestate + '</span><span style=width:300px>' + name + '</span></div></div></td></tr>';
1674 - } else if ((view == 3) && (nodes[i].conn & 1) && ((meshrights & 8) != 0)) {
1688 + } else if ((view == 3) && (nodes[i].conn & 1) && ((meshrights & 8) != 0) && ((nodes[i].agent.caps & 1) != 0)) { // Check if we have rights and agent is capable of KVM.
1689 if ((multiDesktopFilter.length == 0) || (multiDesktopFilter.indexOf('devid_' + nodes[i]._id) >= 0)) {
1690 r += '<div id=devs style=display:inline-block;margin:1px;background-color:lightgray;border-radius:5px;position:relative><div style=padding:3px;cursor:pointer onclick=gotoDevice(\'' + nodes[i]._id + '\',11)>';
1691 //r += '<input class="' + nodes[i].meshid + ' DeviceCheckbox" onclick=p1updateInfo() value=devid_' + nodes[i]._id + ' type=checkbox style=float:left>';
@@ -3106,8 +3120,8 @@
3120 // Show or hide the tabs
3121 // mesh.mtype: 1 = Intel AMT only, 2 = Mesh Agent
3122 // node.agent.caps (bitmask): 1 = Desktop, 2 = Terminal, 4 = Files, 8 = Console
3109 - QV('MainDevDesktop', ((mesh.mtype == 1) || (node.agent == null) || (node.agent.caps == null) || ((node.agent.caps & 1) != 0)) && (meshrights & 8));
3110 - QV('MainDevTerminal', ((mesh.mtype == 1) || (node.agent == null) || (node.agent.caps == null) || ((node.agent.caps & 2) != 0)) && (meshrights & 8));
3123 + QV('MainDevDesktop', ((mesh.mtype == 1) || (node.agent == null) || (node.agent.caps == null) || ((node.agent.caps & 1) != 0) || (node.intelamt && (node.intelamt.state == 2))) && (meshrights & 8));
3124 + QV('MainDevTerminal', ((mesh.mtype == 1) || (node.agent == null) || (node.agent.caps == null) || ((node.agent.caps & 2) != 0) || (node.intelamt && (node.intelamt.state == 2))) && (meshrights & 8));
3125 QV('MainDevFiles', ((mesh.mtype == 2) && ((node.agent == null) || (node.agent.caps == null) || ((node.agent.caps & 4) != 0))) && (meshrights & 8));
3126 QV('MainDevAmt', (node.intelamt != null) && ((node.intelamt.state == 2) || (node.conn & 2)) && (meshrights & 8));
3127 QV('MainDevConsole', (consoleRights && (mesh.mtype == 2) && ((node.agent == null) || (node.agent.caps == null) || ((node.agent.caps & 8) != 0))) && (meshrights & 8));
@@ -3512,12 +3526,12 @@
3526
3527 // Show the right buttons
3528 QV('disconnectbutton1span', (deskState != 0));
3515 - QV('connectbutton1span', (deskState == 0) && (mesh.mtype == 2));
3529 + QV('connectbutton1span', (deskState == 0) && (mesh.mtype == 2) && (currentNode.agent.caps & 1));
3530 QV('connectbutton1hspan', (deskState == 0) && ((currentNode.intelamt != null) && (mesh.mtype == 1 || currentNode.intelamt.state == 2) && ((currentNode.intelamt.ver != null) || (mesh.mtype == 1))));
3531
3532 // Show the right settings
3533 QV('d7amtkvm', (currentNode.intelamt != null && ((currentNode.intelamt.ver != null) || (mesh.mtype == 1))) && ((deskState == 0) || (desktop.contype == 2)));
3520 - QV('d7meshkvm', (mesh.mtype == 2) && ((deskState == false) || (desktop.contype == 1)));
3534 + QV('d7meshkvm', (mesh.mtype == 2) && (currentNode.agent.caps & 1) && ((deskState == false) || (desktop.contype == 1)));
3535
3536 // Enable buttons
3537 var online = ((currentNode.conn & 1) != 0); // If Agent (1) connected, enable remote desktop
@@ -3859,7 +3873,7 @@
3873
3874 // Show the right buttons
3875 QV('disconnectbutton2span', (termState == true));
3862 - QV('connectbutton2span', (termState == false) && (mesh.mtype == 2));
3876 + QV('connectbutton2span', (termState == false) && (mesh.mtype == 2) && (currentNode.agent.caps & 2));
3877 QV('connectbutton2hspan', (termState == false) && ((terminalNode.intelamt != null) && (mesh.mtype == 1 || terminalNode.intelamt.state == 2) && ((terminalNode.intelamt.ver != null) || (mesh.mtype == 1))));
3878
3879 // Enable buttons
@@ -4815,6 +4829,14 @@
4829 function server_showVersionDlgUpdate() { QE('idx_dlgOkButton', Q('d2updateCheck').checked); }
4830 function server_showVersionDlgEx() { meshserver.send({ action: 'serverupdate' }); }
4831
4832 + function server_showErrorsDlg() {
4833 + if (xxdialogMode) return;
4834 + setDialogMode(2, "MeshCentral Errors", 1, null, "Loading...", 'MeshCentralServerErrors');
4835 + meshserver.send({ action: 'servererrors' });
4836 + }
4837 + function server_showErrorsDlgUpdate() { QE('idx_dlgOkButton', Q('d2updateCheck').checked); }
4838 + function server_showErrorsDlgEx() { meshserver.send({ action: 'serverclearerrorlog' }); }
4839 +
4840 //
4841 // MY MESHS
4842 //
@@ -5911,9 +5933,7 @@
5933 }
5934
5935 function dialogclose(x) {
5914 - var f = xxdialogFunc;
5915 - var b = xxdialogButtons;
5916 - var t = xxdialogTag;
5936 + var f = xxdialogFunc, b = xxdialogButtons, t = xxdialogTag;
5937 setDialogMode();
5938 if (((b & 8) || x) && f) f(x, t);
5939 }