Started work on hardware inventory support.

Ylian Saint-Hilaire committed Aug 6, 2019 at 17:58 UTC bfd56a8a64d35bd23b22ac6a9e62cced2dd7315a
19 files changed +1087 -15
MeshCentralServer.njsproj
+3
@@ -60,13 +60,16 @@
60 <Compile Include="agents\modules_meshcore\amt-wsman.js" />
61 <Compile Include="agents\modules_meshcore\amt-xml.js" />
62 <Compile Include="agents\modules_meshcore\amt.js" />
63 + <Compile Include="agents\modules_meshcore\identifiers.js" />
64 <Compile Include="agents\modules_meshcore\linux-dbus.js" />
65 <Compile Include="agents\modules_meshcore\monitor-border.js" />
66 <Compile Include="agents\modules_meshcore\power-monitor.js" />
67 <Compile Include="agents\modules_meshcore\smbios.js" />
68 + <Compile Include="agents\modules_meshcore\sysinfo.js" />
69 <Compile Include="agents\modules_meshcore\wifi-scanner-windows.js" />
70 <Compile Include="agents\modules_meshcore\wifi-scanner.js" />
71 <Compile Include="agents\modules_meshcore\win-console.js" />
72 + <Compile Include="agents\modules_meshcore\win-info.js" />
73 <Compile Include="agents\modules_meshcore\win-terminal.js" />
74 <Compile Include="agents\modules_meshcore_min\amt-lme.min.js" />
75 <Compile Include="agents\modules_meshcore_min\amt-mei.min.js" />
agents/meshcore.js
+91 -4
@@ -822,6 +822,53 @@ function createMeshCore(agent)
822 sendConsoleText('getScript: ' + JSON.stringify(data));
823 break;
824 }
825 + case 'sysinfo': {
826 + // Fetch system information
827 + if (process.platform != 'win32') break; // Remove this when Linux/MacOS support this.
828 + try {
829 + var results = { hardware: require('identifiers').get(), pendingReboot: require('win-info').pendingReboot() }; // Hardware & pending reboot
830 + if (results.hardware.windows) {
831 + var x = results.hardware.windows.osinfo;
832 + try { delete x.FreePhysicalMemory; } catch (ex) { }
833 + try { delete x.FreeSpaceInPagingFiles; } catch (ex) { }
834 + try { delete x.FreeVirtualMemory; } catch (ex) { }
835 + try { delete x.LocalDateTime; } catch (ex) { }
836 + try { delete x.MaxProcessMemorySize; } catch (ex) { }
837 + try { delete x.TotalVirtualMemorySize; } catch (ex) { }
838 + try { delete x.TotalVisibleMemorySize; } catch (ex) { }
839 + }
840 + /*
841 + if (process.platform == 'win32')
842 + {
843 + var defragResult = function (r)
844 + {
845 + if (typeof r == 'object') { results[this.callname] = r; }
846 + if (this.callname == 'defrag')
847 + {
848 + var pr = require('win-info').installedApps(); // Installed apps
849 + pr.callname = 'installedApps';
850 + pr.sessionid = data.sessionid;
851 + pr.then(defragResult, defragResult);
852 + }
853 + else
854 + {
855 + results.winpatches = require('win-info').qfe(); // Windows patches
856 + results.hash = require('SHA384Stream').create().syncHash(JSON.stringify(results)).toString('hex');
857 + if (data.hash != results.hash) { mesh.SendCommand({ "action": "sysinfo", "sessionid": this.sessionid, "data": results }); }
858 + }
859 + }
860 + var pr = require('win-info').defrag({ volume: 'C:' }); // Defrag
861 + pr.callname = 'defrag';
862 + pr.sessionid = data.sessionid;
863 + pr.then(defragResult, defragResult);
864 + } else {
865 + */
866 + results.hash = require('SHA384Stream').create().syncHash(JSON.stringify(results)).toString('hex');
867 + if (data.hash != results.hash) { mesh.SendCommand({ "action": "sysinfo", "sessionid": this.sessionid, "data": results }); }
868 + //}
869 + } catch (ex) { }
870 + break;
871 + }
872 case 'ping': { mesh.SendCommand('{"action":"pong"}'); break; }
873 case 'pong': { break; }
874 default:
@@ -1603,7 +1650,7 @@ function createMeshCore(agent)
1650 var response = null;
1651 switch (cmd) {
1652 case 'help': { // Displays available commands
1606 - 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, sendcaps, openurl, amtreset, amtccm, amtacm,\r\namtdeactivate, amtpolicy, getscript, getclip, setclip, log, av.';
1653 + 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, sendcaps, openurl, amtreset, amtccm, amtacm,\r\namtdeactivate, amtpolicy, getscript, getclip, setclip, log, av, cpuinfo, sysinfo.';
1654 break;
1655 }
1656 /*
@@ -1626,7 +1673,11 @@ function createMeshCore(agent)
1673 break;
1674 */
1675 case 'av':
1629 - if (process.platform == 'win32') { response = JSON.stringify(require('win-info').av()); } else { response = 'Not supported on the platform'; }
1676 + if (process.platform == 'win32') {
1677 + response = JSON.stringify(require('win-info').av(), null, 1);
1678 + } else {
1679 + response = 'Not supported on the platform';
1680 + }
1681 break;
1682 case 'log':
1683 if (args['_'].length != 1) { response = 'Proper usage: log "sample text"'; } else { MeshServerLog(args['_'][0]); response = 'ok'; }
@@ -1763,6 +1814,41 @@ function createMeshCore(agent)
1814 }
1815 break;
1816 }
1817 + case 'cpuinfo': { // Return system information
1818 + // CPU & memory utilization
1819 + pr = require('sysinfo').cpuUtilization();
1820 + pr.sessionid = sessionid;
1821 + pr.then(function (data) {
1822 + sendConsoleText(JSON.stringify({ cpu: data, memory: require('sysinfo').memUtilization() }, null, 1), this.sessionid);
1823 + }, function (e) {
1824 + sendConsoleText(e);
1825 + });
1826 + break;
1827 + }
1828 + case 'sysinfo': { // Return system information
1829 + var results = { hardware: require('identifiers').get(), pendingReboot: require('win-info').pendingReboot() }; // Hardware && pending reboot
1830 + if (process.platform == 'win32') {
1831 + var defragResult = function (r) {
1832 + if (typeof r == 'object') { results[this.callname] = r; }
1833 + if (this.callname == 'defrag') {
1834 + var pr = require('win-info').installedApps(); // Installed apps
1835 + pr.sessionid = sessionid;
1836 + pr.callname = 'installedApps';
1837 + pr.then(defragResult, defragResult);
1838 + } else {
1839 + results.winpatches = require('win-info').qfe(); // Windows patches
1840 + sendConsoleText(JSON.stringify(results, null, 1), this.sessionid);
1841 + }
1842 + }
1843 + var pr = require('win-info').defrag({ volume: 'C:' }); // Defrag
1844 + pr.sessionid = sessionid;
1845 + pr.callname = 'defrag';
1846 + pr.then(defragResult, defragResult);
1847 + } else {
1848 + response = JSON.stringify(results, null, 1);
1849 + }
1850 + break;
1851 + }
1852 case 'info': { // Return information about the agent and agent core module
1853 response = 'Current Core: ' + meshCoreObj.value + '.\r\nAgent Time: ' + Date() + '.\r\nUser Rights: 0x' + rights.toString(16) + '.\r\nPlatform: ' + process.platform + '.\r\nCapabilities: ' + meshCoreObj.caps + '.\r\nServer URL: ' + mesh.ServerUrl + '.';
1854 if (amt != null) { response += '\r\nBuilt-in LMS: ' + ['Disabled', 'Connecting..', 'Connected'][amt.lmsstate] + '.'; }
@@ -2241,8 +2327,9 @@ function createMeshCore(agent)
2327
2328 if ((flags & 4) && (process.platform == 'win32')) {
2329 // Update anti-virus information
2244 - var av;
2245 - try { av = require('win-info').av(); } catch (ex) { av = []; }
2330 + var av, pr;
2331 + try { av = require('win-info').av(); } catch (ex) { av = []; } // Antivirus
2332 + //if (process.platform == 'win32') { try { pr = require('win-info').pendingReboot(); } catch (ex) { pr = null; } } // Pending reboot
2333 if ((meshCoreObj.av == null) || (JSON.stringify(meshCoreObj.av) != JSON.stringify(av))) { meshCoreObj.av = av; mesh.SendCommand(meshCoreObj); }
2334 }
2335 }
agents/meshcore.min.js
+91 -4
@@ -822,6 +822,53 @@ function createMeshCore(agent)
822 sendConsoleText('getScript: ' + JSON.stringify(data));
823 break;
824 }
825 + case 'sysinfo': {
826 + // Fetch system information
827 + if (process.platform != 'win32') break; // Remove this when Linux/MacOS support this.
828 + try {
829 + var results = { hardware: require('identifiers').get(), pendingReboot: require('win-info').pendingReboot() }; // Hardware & pending reboot
830 + if (results.hardware.windows) {
831 + var x = results.hardware.windows.osinfo;
832 + try { delete x.FreePhysicalMemory; } catch (ex) { }
833 + try { delete x.FreeSpaceInPagingFiles; } catch (ex) { }
834 + try { delete x.FreeVirtualMemory; } catch (ex) { }
835 + try { delete x.LocalDateTime; } catch (ex) { }
836 + try { delete x.MaxProcessMemorySize; } catch (ex) { }
837 + try { delete x.TotalVirtualMemorySize; } catch (ex) { }
838 + try { delete x.TotalVisibleMemorySize; } catch (ex) { }
839 + }
840 + /*
841 + if (process.platform == 'win32')
842 + {
843 + var defragResult = function (r)
844 + {
845 + if (typeof r == 'object') { results[this.callname] = r; }
846 + if (this.callname == 'defrag')
847 + {
848 + var pr = require('win-info').installedApps(); // Installed apps
849 + pr.callname = 'installedApps';
850 + pr.sessionid = data.sessionid;
851 + pr.then(defragResult, defragResult);
852 + }
853 + else
854 + {
855 + results.winpatches = require('win-info').qfe(); // Windows patches
856 + results.hash = require('SHA384Stream').create().syncHash(JSON.stringify(results)).toString('hex');
857 + if (data.hash != results.hash) { mesh.SendCommand({ "action": "sysinfo", "sessionid": this.sessionid, "data": results }); }
858 + }
859 + }
860 + var pr = require('win-info').defrag({ volume: 'C:' }); // Defrag
861 + pr.callname = 'defrag';
862 + pr.sessionid = data.sessionid;
863 + pr.then(defragResult, defragResult);
864 + } else {
865 + */
866 + results.hash = require('SHA384Stream').create().syncHash(JSON.stringify(results)).toString('hex');
867 + if (data.hash != results.hash) { mesh.SendCommand({ "action": "sysinfo", "sessionid": this.sessionid, "data": results }); }
868 + //}
869 + } catch (ex) { }
870 + break;
871 + }
872 case 'ping': { mesh.SendCommand('{"action":"pong"}'); break; }
873 case 'pong': { break; }
874 default:
@@ -1603,7 +1650,7 @@ function createMeshCore(agent)
1650 var response = null;
1651 switch (cmd) {
1652 case 'help': { // Displays available commands
1606 - 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, sendcaps, openurl, amtreset, amtccm, amtacm,\r\namtdeactivate, amtpolicy, getscript, getclip, setclip, log, av.';
1653 + 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, sendcaps, openurl, amtreset, amtccm, amtacm,\r\namtdeactivate, amtpolicy, getscript, getclip, setclip, log, av, cpuinfo, sysinfo.';
1654 break;
1655 }
1656 /*
@@ -1626,7 +1673,11 @@ function createMeshCore(agent)
1673 break;
1674 */
1675 case 'av':
1629 - if (process.platform == 'win32') { response = JSON.stringify(require('win-info').av()); } else { response = 'Not supported on the platform'; }
1676 + if (process.platform == 'win32') {
1677 + response = JSON.stringify(require('win-info').av(), null, 1);
1678 + } else {
1679 + response = 'Not supported on the platform';
1680 + }
1681 break;
1682 case 'log':
1683 if (args['_'].length != 1) { response = 'Proper usage: log "sample text"'; } else { MeshServerLog(args['_'][0]); response = 'ok'; }
@@ -1763,6 +1814,41 @@ function createMeshCore(agent)
1814 }
1815 break;
1816 }
1817 + case 'cpuinfo': { // Return system information
1818 + // CPU & memory utilization
1819 + pr = require('sysinfo').cpuUtilization();
1820 + pr.sessionid = sessionid;
1821 + pr.then(function (data) {
1822 + sendConsoleText(JSON.stringify({ cpu: data, memory: require('sysinfo').memUtilization() }, null, 1), this.sessionid);
1823 + }, function (e) {
1824 + sendConsoleText(e);
1825 + });
1826 + break;
1827 + }
1828 + case 'sysinfo': { // Return system information
1829 + var results = { hardware: require('identifiers').get(), pendingReboot: require('win-info').pendingReboot() }; // Hardware && pending reboot
1830 + if (process.platform == 'win32') {
1831 + var defragResult = function (r) {
1832 + if (typeof r == 'object') { results[this.callname] = r; }
1833 + if (this.callname == 'defrag') {
1834 + var pr = require('win-info').installedApps(); // Installed apps
1835 + pr.sessionid = sessionid;
1836 + pr.callname = 'installedApps';
1837 + pr.then(defragResult, defragResult);
1838 + } else {
1839 + results.winpatches = require('win-info').qfe(); // Windows patches
1840 + sendConsoleText(JSON.stringify(results, null, 1), this.sessionid);
1841 + }
1842 + }
1843 + var pr = require('win-info').defrag({ volume: 'C:' }); // Defrag
1844 + pr.sessionid = sessionid;
1845 + pr.callname = 'defrag';
1846 + pr.then(defragResult, defragResult);
1847 + } else {
1848 + response = JSON.stringify(results, null, 1);
1849 + }
1850 + break;
1851 + }
1852 case 'info': { // Return information about the agent and agent core module
1853 response = 'Current Core: ' + meshCoreObj.value + '.\r\nAgent Time: ' + Date() + '.\r\nUser Rights: 0x' + rights.toString(16) + '.\r\nPlatform: ' + process.platform + '.\r\nCapabilities: ' + meshCoreObj.caps + '.\r\nServer URL: ' + mesh.ServerUrl + '.';
1854 if (amt != null) { response += '\r\nBuilt-in LMS: ' + ['Disabled', 'Connecting..', 'Connected'][amt.lmsstate] + '.'; }
@@ -2241,8 +2327,9 @@ function createMeshCore(agent)
2327
2328 if ((flags & 4) && (process.platform == 'win32')) {
2329 // Update anti-virus information
2244 - var av;
2245 - try { av = require('win-info').av(); } catch (ex) { av = []; }
2330 + var av, pr;
2331 + try { av = require('win-info').av(); } catch (ex) { av = []; } // Antivirus
2332 + //if (process.platform == 'win32') { try { pr = require('win-info').pendingReboot(); } catch (ex) { pr = null; } } // Pending reboot
2333 if ((meshCoreObj.av == null) || (JSON.stringify(meshCoreObj.av) != JSON.stringify(av))) { meshCoreObj.av = av; mesh.SendCommand(meshCoreObj); }
2334 }
2335 }
agents/modules_meshcmd/identifiers.js new
+208
@@ -0,0 +1,208 @@
1 +/*
2 +Copyright 2019 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 trimIdentifiers(val)
18 +{
19 + for(var v in val)
20 + {
21 + if (!val[v] || val[v] == 'None' || val[v] == '') { delete val[v]; }
22 + }
23 +}
24 +
25 +function linux_identifiers()
26 +{
27 + var identifiers = {};
28 + var ret = {};
29 + var values = {};
30 + if (!require('fs').existsSync('/sys/class/dmi/id')) { throw ('this platform does not have DMI statistics'); }
31 + var entries = require('fs').readdirSync('/sys/class/dmi/id');
32 + for(var i in entries)
33 + {
34 + if (require('fs').statSync('/sys/class/dmi/id/' + entries[i]).isFile())
35 + {
36 + ret[entries[i]] = require('fs').readFileSync('/sys/class/dmi/id/' + entries[i]).toString().trim();
37 +
38 + if (ret[entries[i]] == 'None') { delete ret[entries[i]];}
39 + }
40 + }
41 + identifiers['bios_date'] = ret['bios_date'];
42 + identifiers['bios_vendor'] = ret['bios_vendor'];
43 + identifiers['bios_version'] = ret['bios_version'];
44 + identifiers['board_name'] = ret['board_name'];
45 + identifiers['board_serial'] = ret['board_serial'];
46 + identifiers['board_vendor'] = ret['board_vendor'];
47 + identifiers['board_version'] = ret['board_version'];
48 + identifiers['product_uuid'] = ret['product_uuid'];
49 +
50 + values.identifiers = identifiers;
51 + values.linux = ret;
52 + trimIdentifiers(values.identifiers);
53 + return (values);
54 +}
55 +
56 +function windows_wmic_results(str)
57 +{
58 + var lines = str.trim().split('\r\n');
59 + var keys = lines[0].split(',');
60 + var i, key, keyval;
61 + var tokens;
62 + var result = [];
63 +
64 + for (i = 1; i < lines.length; ++i)
65 + {
66 + var obj = {};
67 + tokens = lines[i].split(',');
68 + for (key = 0; key < keys.length; ++key)
69 + {
70 + if (tokens[key].trim())
71 + {
72 + obj[keys[key].trim()] = tokens[key].trim();
73 + }
74 + }
75 + result.push(obj);
76 + }
77 + return (result);
78 +}
79 +
80 +
81 +function windows_identifiers()
82 +{
83 + var ret = { windows: {}}; values = {}; var items; var i; var item;
84 + var child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'bios', 'get', '/VALUE']);
85 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
86 + child.waitExit();
87 +
88 + var items = child.stdout.str.split('\r\r\n');
89 + for(i in items)
90 + {
91 + item = items[i].split('=');
92 + values[item[0]] = item[1];
93 + }
94 +
95 + ret['identifiers'] = {};
96 + ret['identifiers']['bios_date'] = values['ReleaseDate'];
97 + ret['identifiers']['bios_vendor'] = values['Manufacturer'];
98 + ret['identifiers']['bios_version'] = values['SMBIOSBIOSVersion'];
99 +
100 + child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'BASEBOARD', 'get', '/VALUE']);
101 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
102 + child.waitExit();
103 +
104 + var items = child.stdout.str.split('\r\r\n');
105 + for (i in items)
106 + {
107 + item = items[i].split('=');
108 + values[item[0]] = item[1];
109 + }
110 + ret['identifiers']['board_name'] = values['Product'];
111 + ret['identifiers']['board_serial'] = values['SerialNumber'];
112 + ret['identifiers']['board_vendor'] = values['Manufacturer'];
113 + ret['identifiers']['board_version'] = values['Version'];
114 +
115 + child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'CSProduct', 'get', '/VALUE']);
116 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
117 + child.waitExit();
118 +
119 + var items = child.stdout.str.split('\r\r\n');
120 + for (i in items)
121 + {
122 + item = items[i].split('=');
123 + values[item[0]] = item[1];
124 + }
125 + ret['identifiers']['product_uuid'] = values['UUID'];
126 + trimIdentifiers(ret.identifiers);
127 +
128 + child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'MEMORYCHIP', 'LIST', '/FORMAT:CSV']);
129 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
130 + child.waitExit();
131 + ret.windows.memory = windows_wmic_results(child.stdout.str);
132 +
133 + child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'OS', 'GET', '/FORMAT:CSV']);
134 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
135 + child.waitExit();
136 + ret.windows.osinfo = windows_wmic_results(child.stdout.str)[0];
137 +
138 + child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'PARTITION', 'LIST', '/FORMAT:CSV']);
139 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
140 + child.waitExit();
141 + ret.windows.partitions = windows_wmic_results(child.stdout.str);
142 +
143 + return (ret);
144 +}
145 +function macos_identifiers()
146 +{
147 + var ret = { identifiers: {} };
148 + var child;
149 +
150 + child = require('child_process').execFile('/bin/sh', ['sh']);
151 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
152 + child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep board-id | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
153 + child.waitExit();
154 + ret.identifiers.board_name = child.stdout.str.trim();
155 +
156 + child = require('child_process').execFile('/bin/sh', ['sh']);
157 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
158 + child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformSerialNumber | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
159 + child.waitExit();
160 + ret.identifiers.board_serial = child.stdout.str.trim();
161 +
162 + child = require('child_process').execFile('/bin/sh', ['sh']);
163 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
164 + child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep manufacturer | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
165 + child.waitExit();
166 + ret.identifiers.board_vendor = child.stdout.str.trim();
167 +
168 + child = require('child_process').execFile('/bin/sh', ['sh']);
169 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
170 + child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep version | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
171 + child.waitExit();
172 + ret.identifiers.board_version = child.stdout.str.trim();
173 +
174 + child = require('child_process').execFile('/bin/sh', ['sh']);
175 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
176 + child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformUUID | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
177 + child.waitExit();
178 + ret.identifiers.product_uuid = child.stdout.str.trim();
179 +
180 + trimIdentifiers(ret.identifiers);
181 + return (ret);
182 +}
183 +
184 +switch(process.platform)
185 +{
186 + case 'linux':
187 + module.exports = { _ObjectID: 'identifiers', get: linux_identifiers };
188 + break;
189 + case 'win32':
190 + module.exports = { _ObjectID: 'identifiers', get: windows_identifiers };
191 + break;
192 + case 'darwin':
193 + module.exports = { _ObjectID: 'identifiers', get: macos_identifiers };
194 + break;
195 + default:
196 + module.exports = { get: function () { throw ('Unsupported Platform'); } };
197 + break;
198 +}
199 +
200 +
201 +// bios_date = BIOS->ReleaseDate
202 +// bios_vendor = BIOS->Manufacturer
203 +// bios_version = BIOS->SMBIOSBIOSVersion
204 +// board_name = BASEBOARD->Product = ioreg/board-id
205 +// board_serial = BASEBOARD->SerialNumber = ioreg/serial-number | ioreg/IOPlatformSerialNumber
206 +// board_vendor = BASEBOARD->Manufacturer = ioreg/manufacturer
207 +// board_version = BASEBOARD->Version
208 +
agents/modules_meshcmd/sysinfo.js new
+230
@@ -0,0 +1,230 @@
1 +/*
2 +Copyright 2019 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 +const PDH_FMT_LONG = 0x00000100;
18 +const PDH_FMT_DOUBLE = 0x00000200;
19 +
20 +var promise = require('promise');
21 +if (process.platform == 'win32')
22 +{
23 + var GM = require('_GenericMarshal');
24 + GM.kernel32 = GM.CreateNativeProxy('kernel32.dll');
25 + GM.kernel32.CreateMethod('GlobalMemoryStatusEx');
26 +
27 + GM.pdh = GM.CreateNativeProxy('pdh.dll');
28 + GM.pdh.CreateMethod('PdhAddEnglishCounterA');
29 + GM.pdh.CreateMethod('PdhCloseQuery');
30 + GM.pdh.CreateMethod('PdhCollectQueryData');
31 + GM.pdh.CreateMethod('PdhGetFormattedCounterValue');
32 + GM.pdh.CreateMethod('PdhGetFormattedCounterArrayA');
33 + GM.pdh.CreateMethod('PdhOpenQueryA');
34 + GM.pdh.CreateMethod('PdhRemoveCounter');
35 +}
36 +
37 +function windows_cpuUtilization()
38 +{
39 + var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
40 + p.counter = GM.CreateVariable(16);
41 + p.cpu = GM.CreatePointer();
42 + p.cpuTotal = GM.CreatePointer();
43 + var err = 0;
44 + if ((err = GM.pdh.PdhOpenQueryA(0, 0, p.cpu).Val) != 0) { p._rej(err); return; }
45 +
46 + // This gets the CPU Utilization for each proc
47 + if ((err = GM.pdh.PdhAddEnglishCounterA(p.cpu.Deref(), GM.CreateVariable('\\Processor(*)\\% Processor Time'), 0, p.cpuTotal).Val) != 0) { p._rej(err); return; }
48 +
49 + if ((err = GM.pdh.PdhCollectQueryData(p.cpu.Deref()).Val != 0)) { p._rej(err); return; }
50 + p._timeout = setTimeout(function (po)
51 + {
52 + var u = { cpus: [] };
53 + var bufSize = GM.CreateVariable(4);
54 + var itemCount = GM.CreateVariable(4);
55 + var buffer, szName, item;
56 + var e;
57 + if ((e = GM.pdh.PdhCollectQueryData(po.cpu.Deref()).Val != 0)) { po._rej(e); return; }
58 +
59 + if ((e = GM.pdh.PdhGetFormattedCounterArrayA(po.cpuTotal.Deref(), PDH_FMT_DOUBLE, bufSize, itemCount, 0).Val) == -2147481646)
60 + {
61 + buffer = GM.CreateVariable(bufSize.toBuffer().readUInt32LE());
62 + }
63 + else
64 + {
65 + po._rej(e);
66 + return;
67 + }
68 + if ((e = GM.pdh.PdhGetFormattedCounterArrayA(po.cpuTotal.Deref(), PDH_FMT_DOUBLE, bufSize, itemCount, buffer).Val) != 0) { po._rej(e); return; }
69 + for(var i=0;i<itemCount.toBuffer().readUInt32LE();++i)
70 + {
71 + item = buffer.Deref(i * 24, 24);
72 + szName = item.Deref(0, GM.PointerSize).Deref();
73 + if (szName.String == '_Total')
74 + {
75 + u.total = item.Deref(16, 8).toBuffer().readDoubleLE().toFixed(2);
76 + }
77 + else
78 + {
79 + u.cpus[parseInt(szName.String)] = item.Deref(16, 8).toBuffer().readDoubleLE().toFixed(2);
80 + }
81 + }
82 +
83 + GM.pdh.PdhRemoveCounter(po.cpuTotal.Deref());
84 + GM.pdh.PdhCloseQuery(po.cpu.Deref());
85 + p._res(u);
86 + }, 100, p);
87 +
88 + return (p);
89 +}
90 +function windows_memUtilization()
91 +{
92 + var info = GM.CreateVariable(64);
93 + info.Deref(0, 4).toBuffer().writeUInt32LE(64);
94 + GM.kernel32.GlobalMemoryStatusEx(info);
95 +
96 + var ret =
97 + {
98 + MemTotal: require('bignum').fromBuffer(info.Deref(8, 8).toBuffer(), { endian: 'little' }),
99 + MemFree: require('bignum').fromBuffer(info.Deref(16, 8).toBuffer(), { endian: 'little' })
100 + };
101 +
102 + ret.percentFree = ((ret.MemFree.div(require('bignum')('1048576')).toNumber() / ret.MemTotal.div(require('bignum')('1048576')).toNumber()) * 100).toFixed(2);
103 + ret.percentConsumed = ((ret.MemTotal.sub(ret.MemFree).div(require('bignum')('1048576')).toNumber() / ret.MemTotal.div(require('bignum')('1048576')).toNumber()) * 100).toFixed(2);
104 + ret.MemTotal = ret.MemTotal.toString();
105 + ret.MemFree = ret.MemFree.toString();
106 + return (ret);
107 +}
108 +
109 +function linux_cpuUtilization()
110 +{
111 + var ret = { cpus: [] };
112 + var info = require('fs').readFileSync('/proc/stat');
113 + var lines = info.toString().split('\n');
114 + var columns;
115 + var x, y;
116 + var sum, idle, utilization;
117 + for (var i in lines)
118 + {
119 + columns = lines[i].split(' ');
120 + if (!columns[0].startsWith('cpu')) { break; }
121 +
122 + x = 0, sum = 0;
123 + while (columns[++x] == '');
124 + for (y = x; y < columns.length; ++y) { sum += parseInt(columns[y]); }
125 + idle = parseInt(columns[3 + x]);
126 + utilization = (100 - ((idle / sum) * 100)).toFixed(2);
127 + if (!ret.total)
128 + {
129 + ret.total = utilization;
130 + }
131 + else
132 + {
133 + ret.cpus.push(utilization);
134 + }
135 + }
136 +
137 + var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
138 + p._res(ret);
139 + return (p);
140 +}
141 +function linux_memUtilization()
142 +{
143 + var ret = {};
144 +
145 + var info = require('fs').readFileSync('/proc/meminfo').toString().split('\n');
146 + var tokens;
147 + for(var i in info)
148 + {
149 + tokens = info[i].split(' ');
150 + switch(tokens[0])
151 + {
152 + case 'MemTotal:':
153 + ret.total = parseInt(tokens[tokens.length - 2]);
154 + break;
155 + case 'MemFree:':
156 + ret.free = parseInt(tokens[tokens.length - 2]);
157 + break;
158 + }
159 + }
160 + ret.percentFree = ((ret.free / ret.total) * 100).toFixed(2);
161 + ret.percentConsumed = (((ret.total - ret.free) / ret.total) * 100).toFixed(2);
162 + return (ret);
163 +}
164 +
165 +function macos_cpuUtilization()
166 +{
167 + var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
168 + var child = require('child_process').execFile('/bin/sh', ['sh']);
169 + child.stdout.str = '';
170 + child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
171 + child.stdin.write('top -l 1 | grep -E "^CPU"\nexit\n');
172 + child.waitExit();
173 +
174 + var lines = child.stdout.str.split('\n');
175 + if (lines[0].length > 0)
176 + {
177 + var usage = lines[0].split(':')[1];
178 + var bdown = usage.split(',');
179 +
180 + var tot = parseFloat(bdown[0].split('%')[0].trim()) + parseFloat(bdown[1].split('%')[0].trim());
181 + ret._res({total: tot, cpus: []});
182 + }
183 + else
184 + {
185 + ret._rej('parse error');
186 + }
187 +
188 + return (ret);
189 +}
190 +function macos_memUtilization()
191 +{
192 + var mem = { };
193 + var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
194 + var child = require('child_process').execFile('/bin/sh', ['sh']);
195 + child.stdout.str = '';
196 + child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
197 + child.stdin.write('top -l 1 | grep -E "^Phys"\nexit\n');
198 + child.waitExit();
199 +
200 + var lines = child.stdout.str.split('\n');
201 + if (lines[0].length > 0)
202 + {
203 + var usage = lines[0].split(':')[1];
204 + var bdown = usage.split(',');
205 +
206 + mem.MemTotal = parseInt(bdown[0].trim().split(' ')[0]);
207 + mem.MemFree = parseInt(bdown[1].trim().split(' ')[0]);
208 + mem.percentFree = ((mem.MemFree / mem.MemTotal) * 100).toFixed(2);
209 + mem.percentConsumed = (((mem.MemTotal - mem.MemFree)/ mem.MemTotal) * 100).toFixed(2);
210 + return (mem);
211 + }
212 + else
213 + {
214 + throw ('Parse Error');
215 + }
216 +}
217 +
218 +switch(process.platform)
219 +{
220 + case 'linux':
221 + module.exports = { cpuUtilization: linux_cpuUtilization, memUtilization: linux_memUtilization };
222 + break;
223 + case 'win32':
224 + module.exports = { cpuUtilization: windows_cpuUtilization, memUtilization: windows_memUtilization };
225 + break;
226 + case 'darwin':
227 + module.exports = { cpuUtilization: macos_cpuUtilization, memUtilization: macos_memUtilization };
228 + break;
229 +}
230 +
agents/modules_meshcmd_min/identifiers.min.js new
+1
@@ -0,0 +1 @@
1 +function trimIdentifiers(b){for(var a in b){if(!b[a]||b[a]=="None"||b[a]==""){delete b[a]}}}function linux_identifiers(){var c={};var d={};var e={};if(!require("fs").existsSync("/sys/class/dmi/id")){throw ("this platform does not have DMI statistics")}var a=require("fs").readdirSync("/sys/class/dmi/id");for(var b in a){if(require("fs").statSync("/sys/class/dmi/id/"+a[b]).isFile()){d[a[b]]=require("fs").readFileSync("/sys/class/dmi/id/"+a[b]).toString().trim();if(d[a[b]]=="None"){delete d[a[b]]}}}c.bios_date=d.bios_date;c.bios_vendor=d.bios_vendor;c.bios_version=d.bios_version;c.board_name=d.board_name;c.board_serial=d.board_serial;c.board_vendor=d.board_vendor;c.board_version=d.board_version;c.product_uuid=d.product_uuid;e.identifiers=c;e.linux=d;trimIdentifiers(e.identifiers);return(e)}function windows_wmic_results(h){var e=h.trim().split("\r\n");var c=e[0].split(",");var a,b,d;var j;var g=[];for(a=1;a<e.length;++a){var f={};j=e[a].split(",");for(b=0;b<c.length;++b){if(j[b].trim()){f[c[b].trim()]=j[b].trim()}}g.push(f)}return(g)}function windows_identifiers(){var e={windows:{}};values={};var d;var b;var c;var a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","bios","get","/VALUE"]);a.stdout.str="";a.stdout.on("data",function(f){this.str+=f.toString()});a.waitExit();var d=a.stdout.str.split("\r\r\n");for(b in d){c=d[b].split("=");values[c[0]]=c[1]}e.identifiers={};e.identifiers["bios_date"]=values.ReleaseDate;e.identifiers["bios_vendor"]=values.Manufacturer;e.identifiers["bios_version"]=values.SMBIOSBIOSVersion;a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","BASEBOARD","get","/VALUE"]);a.stdout.str="";a.stdout.on("data",function(f){this.str+=f.toString()});a.waitExit();var d=a.stdout.str.split("\r\r\n");for(b in d){c=d[b].split("=");values[c[0]]=c[1]}e.identifiers["board_name"]=values.Product;e.identifiers["board_serial"]=values.SerialNumber;e.identifiers["board_vendor"]=values.Manufacturer;e.identifiers["board_version"]=values.Version;a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","CSProduct","get","/VALUE"]);a.stdout.str="";a.stdout.on("data",function(f){this.str+=f.toString()});a.waitExit();var d=a.stdout.str.split("\r\r\n");for(b in d){c=d[b].split("=");values[c[0]]=c[1]}e.identifiers["product_uuid"]=values.UUID;trimIdentifiers(e.identifiers);a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","MEMORYCHIP","LIST","/FORMAT:CSV"]);a.stdout.str="";a.stdout.on("data",function(f){this.str+=f.toString()});a.waitExit();e.windows.memory=windows_wmic_results(a.stdout.str);a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","OS","GET","/FORMAT:CSV"]);a.stdout.str="";a.stdout.on("data",function(f){this.str+=f.toString()});a.waitExit();e.windows.osinfo=windows_wmic_results(a.stdout.str)[0];a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","PARTITION","LIST","/FORMAT:CSV"]);a.stdout.str="";a.stdout.on("data",function(f){this.str+=f.toString()});a.waitExit();e.windows.partitions=windows_wmic_results(a.stdout.str);return(e)}function macos_identifiers(){var b={identifiers:{}};var a;a=require("child_process").execFile("/bin/sh",["sh"]);a.stdout.str="";a.stdout.on("data",function(d){this.str+=d.toString()});a.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep board-id | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');a.waitExit();b.identifiers.board_name=a.stdout.str.trim();a=require("child_process").execFile("/bin/sh",["sh"]);a.stdout.str="";a.stdout.on("data",function(d){this.str+=d.toString()});a.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformSerialNumber | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');a.waitExit();b.identifiers.board_serial=a.stdout.str.trim();a=require("child_process").execFile("/bin/sh",["sh"]);a.stdout.str="";a.stdout.on("data",function(d){this.str+=d.toString()});a.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep manufacturer | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');a.waitExit();b.identifiers.board_vendor=a.stdout.str.trim();a=require("child_process").execFile("/bin/sh",["sh"]);a.stdout.str="";a.stdout.on("data",function(d){this.str+=d.toString()});a.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep version | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');a.waitExit();b.identifiers.board_version=a.stdout.str.trim();a=require("child_process").execFile("/bin/sh",["sh"]);a.stdout.str="";a.stdout.on("data",function(d){this.str+=d.toString()});a.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformUUID | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');a.waitExit();b.identifiers.product_uuid=a.stdout.str.trim();trimIdentifiers(b.identifiers);return(b)}switch(process.platform){case"linux":module.exports={_ObjectID:"identifiers",get:linux_identifiers};break;case"win32":module.exports={_ObjectID:"identifiers",get:windows_identifiers};break;case"darwin":module.exports={_ObjectID:"identifiers",get:macos_identifiers};break;default:module.exports={get:function(){throw ("Unsupported Platform")}};break};
\ No newline at end of file
agents/modules_meshcmd_min/user-sessions.min.js deleted
-1
@@ -1 +0,0 @@
1 -var NOTIFY_FOR_THIS_SESSION=0;var NOTIFY_FOR_ALL_SESSIONS=1;var WM_WTSSESSION_CHANGE=689;var WM_POWERBROADCAST=536;var PBT_POWERSETTINGCHANGE=32787;var PBT_APMSUSPEND=4;var PBT_APMRESUMESUSPEND=7;var PBT_APMRESUMEAUTOMATIC=18;var PBT_APMPOWERSTATUSCHANGE=10;var WTS_CONSOLE_CONNECT=(1);var WTS_CONSOLE_DISCONNECT=(2);var WTS_REMOTE_CONNECT=(3);var WTS_REMOTE_DISCONNECT=(4);var WTS_SESSION_LOGON=(5);var WTS_SESSION_LOGOFF=(6);var WTS_SESSION_LOCK=(7);var WTS_SESSION_UNLOCK=(8);var WTS_SESSION_REMOTE_CONTROL=(9);var WTS_SESSION_CREATE=(10);var WTS_SESSION_TERMINATE=(11);var GUID_ACDC_POWER_SOURCE;var GUID_BATTERY_PERCENTAGE_REMAINING;var GUID_CONSOLE_DISPLAY_STATE;function UserSessions(){this._ObjectID="user-sessions";require("events").EventEmitter.call(this,true).createEvent("changed").createEvent("locked").createEvent("unlocked");this.enumerateUsers=function h(){var s=require("promise");var r=new s(function(t,p){this.__resolver=t;this.__rejector=p});r.__handler=function o(p){r.__resolver(p)};try{this.Current(r.__handler)}catch(q){r.__rejector(q)}r.parent=this;return(r)};if(process.platform=="win32"){this._serviceHooked=false;this._marshal=require("_GenericMarshal");this._kernel32=this._marshal.CreateNativeProxy("Kernel32.dll");this._kernel32.CreateMethod("GetLastError");try{this._wts=this._marshal.CreateNativeProxy("Wtsapi32.dll");this._wts.CreateMethod("WTSEnumerateSessionsA");this._wts.CreateMethod("WTSQuerySessionInformationA");this._wts.CreateMethod("WTSRegisterSessionNotification");this._wts.CreateMethod("WTSUnRegisterSessionNotification");this._wts.CreateMethod("WTSFreeMemory")}catch(i){}this._advapi=this._marshal.CreateNativeProxy("Advapi32.dll");this._advapi.CreateMethod("AllocateAndInitializeSid");this._advapi.CreateMethod("CheckTokenMembership");this._advapi.CreateMethod("FreeSid");this._user32=this._marshal.CreateNativeProxy("user32.dll");this._user32.CreateMethod({method:"RegisterPowerSettingNotification",threadDispatch:1});this._user32.CreateMethod("UnregisterPowerSettingNotification");this._rpcrt=this._marshal.CreateNativeProxy("Rpcrt4.dll");this._rpcrt.CreateMethod("UuidFromStringA");this._rpcrt.StringToUUID=function n(o){var p=n.us._marshal.CreateVariable(16);if(n.us._rpcrt.UuidFromStringA(n.us._marshal.CreateVariable(o),p).Val==0){return(p)}else{throw ("Could not convert string to UUID")}};this._rpcrt.StringToUUID.us=this;GUID_ACDC_POWER_SOURCE=this._rpcrt.StringToUUID("5d3e9a59-e9D5-4b00-a6bd-ff34ff516548");GUID_BATTERY_PERCENTAGE_REMAINING=this._rpcrt.StringToUUID("a7ad8041-b45a-4cae-87a3-eecbb468a9e1");GUID_CONSOLE_DISPLAY_STATE=this._rpcrt.StringToUUID("6fe69556-704a-47a0-8f24-c28d936fda47");this.SessionStates=["Active","Connected","ConnectQuery","Shadow","Disconnected","Idle","Listening","Reset","Down","Init"];this.InfoClass={WTSInitialProgram:0,WTSApplicationName:1,WTSWorkingDirectory:2,WTSOEMId:3,WTSSessionId:4,WTSUserName:5,WTSWinStationName:6,WTSDomainName:7,WTSConnectState:8,WTSClientBuildNumber:9,WTSClientName:10,WTSClientDirectory:11,WTSClientProductId:12,WTSClientHardwareId:13,WTSClientAddress:14,WTSClientDisplay:15,WTSClientProtocolType:16,WTSIdleTime:17,WTSLogonTime:18,WTSIncomingBytes:19,WTSOutgoingBytes:20,WTSIncomingFrames:21,WTSOutgoingFrames:22,WTSClientInfo:23,WTSSessionInfo:24,WTSSessionInfoEx:25,WTSConfigInfo:26,WTSValidationInfo:27,WTSSessionAddressV4:28,WTSIsRemoteSession:29};this.isRoot=function k(){var r=this._marshal.CreateVariable(6);r.toBuffer().writeInt8(5,5);var p=this._marshal.CreatePointer();var o=false;if(this._advapi.AllocateAndInitializeSid(r,2,32,544,0,0,0,0,0,0,p).Val!=0){var q=this._marshal.CreateInteger();if(this._advapi.CheckTokenMembership(0,p.Deref(),q).Val!=0){if(q.toBuffer().readUInt32LE()!=0){o=true}}this._advapi.FreeSid(p.Deref())}return o};this.getSessionAttribute=function j(s,o){var p=this._marshal.CreatePointer();var q=this._marshal.CreateVariable(4);if(this._wts.WTSQuerySessionInformationA(0,s,o,p,q).Val==0){throw ("Error calling WTSQuerySessionInformation: "+this._kernel32.GetLastError.Val)}var r=p.Deref().String;this._wts.WTSFreeMemory(p.Deref());return(r)};this.Current=function f(o){var u={};var t=this._marshal.CreatePointer();var p=this._marshal.CreateVariable(4);if(this._wts.WTSEnumerateSessionsA(0,0,1,t,p).Val==0){throw ("Error calling WTSEnumerateSessionsA: "+this._kernel32.GetLastError().Val)}for(var q=0;q<p.toBuffer().readUInt32LE();++q){var r=t.Deref().Deref(q*(this._marshal.PointerSize==4?12:24),this._marshal.PointerSize==4?12:24);var s={SessionId:r.toBuffer().readUInt32LE()};s.StationName=r.Deref(this._marshal.PointerSize==4?4:8,this._marshal.PointerSize).Deref().String;s.State=this.SessionStates[r.Deref(this._marshal.PointerSize==4?8:16,4).toBuffer().readUInt32LE()];if(s.State=="Active"){s.Username=this.getSessionAttribute(s.SessionId,this.InfoClass.WTSUserName);s.Domain=this.getSessionAttribute(s.SessionId,this.InfoClass.WTSDomainName)}u[s.SessionId]=s}this._wts.WTSFreeMemory(t.Deref());Object.defineProperty(u,"Active",{value:showActiveOnly(u)});if(o){o(u)}return(u)};var l=require("win-message-pump");this._messagepump=new l({filter:WM_WTSSESSION_CHANGE});this._messagepump.parent=this;this._messagepump.on("exit",function(o){this.parent._wts.WTSUnRegisterSessionNotification(this.parent.hwnd)});this._messagepump.on("hwnd",function(o){this.parent.hwnd=o;this.immediate=setImmediate(function(p){if(p.parent._wts){p.parent._wts.WTSRegisterSessionNotification(p.parent.hwnd,NOTIFY_FOR_ALL_SESSIONS)}p.parent._user32.ACDC_H=p.parent._user32.RegisterPowerSettingNotification(p.parent.hwnd,GUID_ACDC_POWER_SOURCE,0);p.parent._user32.BATT_H=p.parent._user32.RegisterPowerSettingNotification(p.parent.hwnd,GUID_BATTERY_PERCENTAGE_REMAINING,0);p.parent._user32.DISP_H=p.parent._user32.RegisterPowerSettingNotification(p.parent.hwnd,GUID_CONSOLE_DISPLAY_STATE,0)},this)});this._messagepump.on("message",function(q){switch(q.message){case WM_WTSSESSION_CHANGE:switch(q.wparam){case WTS_SESSION_LOCK:this.parent.enumerateUsers().then(function(r){if(r[q.lparam]){this.parent.emit("locked",r[q.lparam])}});break;case WTS_SESSION_UNLOCK:this.parent.enumerateUsers().then(function(r){if(r[q.lparam]){this.parent.emit("unlocked",r[q.lparam])}});break;case WTS_SESSION_LOGON:case WTS_SESSION_LOGOFF:this.parent.emit("changed");break}break;case WM_POWERBROADCAST:switch(q.wparam){default:console.log("WM_POWERBROADCAST [UNKNOWN wparam]: "+q.wparam);break;case PBT_APMSUSPEND:require("power-monitor").emit("sx","SLEEP");break;case PBT_APMRESUMEAUTOMATIC:require("power-monitor").emit("sx","RESUME_NON_INTERACTIVE");break;case PBT_APMRESUMESUSPEND:require("power-monitor").emit("sx","RESUME_INTERACTIVE");break;case PBT_APMPOWERSTATUSCHANGE:require("power-monitor").emit("changed");break;case PBT_POWERSETTINGCHANGE:var p=this.parent._marshal.CreatePointer(Buffer.from(q.lparam_hex,"hex"));var o=p.Deref(20,p.Deref(16,4).toBuffer().readUInt32LE(0)).toBuffer();switch(p.Deref(0,16).toBuffer().toString("hex")){case GUID_ACDC_POWER_SOURCE.Deref(0,16).toBuffer().toString("hex"):switch(o.readUInt32LE(0)){case 0:require("power-monitor").emit("acdc","AC");break;case 1:require("power-monitor").emit("acdc","BATTERY");break;case 2:require("power-monitor").emit("acdc","HOT");break}break;case GUID_BATTERY_PERCENTAGE_REMAINING.Deref(0,16).toBuffer().toString("hex"):require("power-monitor").emit("batteryLevel",o.readUInt32LE(0));break;case GUID_CONSOLE_DISPLAY_STATE.Deref(0,16).toBuffer().toString("hex"):switch(o.readUInt32LE(0)){case 0:require("power-monitor").emit("display","OFF");break;case 1:require("power-monitor").emit("display","ON");break;case 2:require("power-monitor").emit("display","DIMMED");break}break}break}break;default:break}})}else{if(process.platform=="linux"){var g=require("linux-dbus");this._linuxWatcher=require("fs").watch("/var/run/utmp");this._linuxWatcher.user_session=this;this._linuxWatcher.on("change",function(o,p){this.user_session.emit("changed")});this._users=function d(){var o=require("child_process").execFile("/bin/sh",["sh"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("awk -F: '($3 >= 0) {printf \"%s:%s\\n\", $1, $3}' /etc/passwd\nexit\n");o.waitExit();var p=o.stdout.str.split("\n");var r={},s;for(var q in p){s=p[q].split(":");if(s[0]){r[s[0]]=s[1]}}return(r)};this._uids=function c(){var o=require("child_process").execFile("/bin/sh",["sh"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("awk -F: '($3 >= 0) {printf \"%s:%s\\n\", $1, $3}' /etc/passwd\nexit\n");o.waitExit();var p=o.stdout.str.split("\n");var r={},s;for(var q in p){s=p[q].split(":");if(s[0]){r[s[1]]=s[0]}}return(r)};this.Self=function m(){var q=require("promise");var o=new q(function(r,p){this.__resolver=r;this.__rejector=p;this.__child=require("child_process").execFile("/usr/bin/id",["id","-u"]);this.__child.promise=this;this.__child.stdout._txt="";this.__child.stdout.on("data",function(s){this._txt+=s.toString()});this.__child.on("exit",function(s){try{parseInt(this.stdout._txt)}catch(t){this.promise.__rejector("invalid uid");return}var u=parseInt(this.stdout._txt);this.promise.__resolver(u)})});return(o)};this.Current=function f(o){var p={};p._ObjectID="UserSession";Object.defineProperty(p,"_callback",{value:o});Object.defineProperty(p,"_child",{value:require("child_process").execFile("/usr/bin/last",["last","-f","/var/run/utmp"])});p._child.Parent=p;p._child._txt="";p._child.on("exit",function(q){var u=this._txt.split("\n");var A=[];var D={};for(var t in u){if(u[t]){var B=getTokens(u[t]);var z={Username:B[0],SessionId:B[1]};if(B[3].includes("still logged in")){z.State="Active"}else{z.LastActive=B[3]}A.push(z)}}A.pop();var C={};var y=[];for(var t in A){if(A[t].Username!="reboot"){D[A[t].SessionId]=A[t];if(C[A[t].Username]==null){C[A[t].Username]=-1}}}try{require("promise")}catch(r){Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(this.Parent._callback){this.Parent._callback.call(this.Parent,D)}return}var x=require("promise");for(var v in C){var w=new x(function(E,s){this.__username=v;this.__resolver=E;this.__rejector=s;this.__child=require("child_process").execFile("/usr/bin/id",["id","-u",v]);this.__child.promise=this;this.__child.stdout._txt="";this.__child.stdout.on("data",function(F){this._txt+=F.toString()});this.__child.on("exit",function(F){try{parseInt(this.stdout._txt)}catch(G){this.promise.__rejector("invalid uid");return}var H=parseInt(this.stdout._txt);this.promise.__resolver(H)})});y.push(w)}x.all(y).then(function(E){var F={};for(var s in E){F[E[s].__username]=E[s]._internal.completedArgs[0]}for(var s in D){D[s].uid=F[D[s].Username]}Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(p._callback){p._callback.call(p,D)}},function(s){Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(p._callback){p._callback.call(p,D)}})});p._child.stdout.Parent=p._child;p._child.stdout.on("data",function(q){this.Parent._txt+=q.toString()});return(p)};this._recheckLoggedInUsers=function a(){this.enumerateUsers().then(function(o){if(o.Active.length>0){if(this.parent._linux_lock_watcher!=null&&this.parent._linux_lock_watcher.uid!=o.Active[0].uid){delete this.parent._linux_lock_watcher}this.parent._linux_lock_watcher=new g(process.env.XDG_CURRENT_DESKTOP=="Unity"?"com.ubuntu.Upstart0_6":"org.gnome.ScreenSaver",o.Active[0].uid);this.parent._linux_lock_watcher.user_session=this.parent;this.parent._linux_lock_watcher.on("signal",function(r){var q=this.user_session.enumerateUsers();q.signalData=r.data[0];q.then(function(p){switch(this.signalData){case true:case"desktop-lock":this.parent.emit("locked",p.Active[0]);break;case false:case"desktop-unlock":this.parent.emit("unlocked",p.Active[0]);break}})})}else{if(this.parent._linux_lock_watcher!=null){delete this.parent._linux_lock_watcher}}})};this.on("changed",this._recheckLoggedInUsers);this._recheckLoggedInUsers()}else{if(process.platform=="darwin"){this._users=function(){var o=require("child_process").execFile("/usr/bin/dscl",["dscl",".","list","/Users","UniqueID"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("exit\n");o.waitExit();var q=o.stdout.str.split("\n");var r,p;var s={};for(p=0;p<q.length;++p){r=q[p].split(" ");if(r[0]){s[r[0]]=r[r.length-1]}}return(s)};this._uids=function(){var o=require("child_process").execFile("/usr/bin/dscl",["dscl",".","list","/Users","UniqueID"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("exit\n");o.waitExit();var q=o.stdout.str.split("\n");var r,p;var s={};for(p=0;p<q.length;++p){r=q[p].split(" ");if(r[0]){s[r[r.length-1]]=r[0]}}return(s)};this._idTable=function(){var v={};var o=require("child_process").execFile("/usr/bin/id",["id"]);o.stdout.str="";o.stdout.on("data",function(y){this.str+=y.toString()});o.waitExit();var t=o.stdout.str.split("\n")[0].split(" ");for(var p=0;p<t.length;++p){var x=t[p].split("=");var w=x[1].split(",");v[x[0]]={};for(var s in w){var r=w[s].split("(");var q=r[0];var u=r[1].substring(0,r[1].length-1).trim();v[x[0]][u]=q;v[x[0]][q]=u}}return(v)};this.Current=function(o){var u={};var t=this._idTable();var p=require("child_process").execFile("/usr/bin/last",["last"]);p.stdout.str="";p.stdout.on("data",function(v){this.str+=v.toString()});p.waitExit();var s=p.stdout.str.split("\n");for(var r=0;r<s.length&&s[r].length>0;++r){if(!u[s[r].split(" ")[0]]){try{u[s[r].split(" ")[0]]={Username:s[r].split(" ")[0],State:s[r].split("still logged in").length>1?"Active":"Inactive",uid:t.uid[s[r].split(" ")[0]]}}catch(q){}}else{if(u[s[r].split(" ")[0]].State!="Active"&&s[r].split("still logged in").length>1){u[s[r].split(" ")[0]].State="Active"}}}Object.defineProperty(u,"Active",{value:showActiveOnly(u)});if(o){o.call(this,u)}}}}}if(process.platform=="linux"||process.platform=="darwin"){this._self=function b(){var o=require("child_process").execFile("/usr/bin/id",["id","-u"]);o.stdout.str="";o.stdout.on("data",function(p){this.str+=p.toString()});o.waitExit();return(parseInt(o.stdout.str))};this.isRoot=function k(){return(this._self()==0)};this.consoleUid=function e(){var o=process.platform=="darwin"?"console":((process.env.DISPLAY)?process.env.DISPLAY:":0");var p=require("child_process").execFile("/bin/sh",["sh"]);p.stdout.str="";p.stdout.on("data",function(u){this.str+=u.toString()});p.stdin.write("who\nexit\n");p.waitExit();var s=p.stdout.str.split("\n");var t,q,r;for(q in s){t=s[q].split(" ");for(r=1;r<t.length;++r){if(t[r].length>0){return(parseInt(this._users()[t[0]]))}}}throw ("nobody logged into console")}}}function showActiveOnly(c){var b=[];var e={};var f=[];var d;for(var a in c){if(c[a].State=="Active"){b.push(c[a]);d=(c[a].Domain?(c[a].Domain+"\\"):"")+c[a].Username;if(!e[d]){e[d]=d}}}for(var a in e){f.push(a)}Object.defineProperty(b,"usernames",{value:f});return(b)}function getTokens(d){var a=[];var b;a.push(d.substring(0,(b=d.indexOf(" "))));while(d[++b]==" "){}a.push(d.substring(b,(b=d.substring(b).indexOf(" ")+b)));while(d[++b]==" "){}a.push(d.substring(b,(b=d.substring(b).indexOf(" ")+b)));while(d[++b]==" "){}var c=d.substring(b).trim();a.push(c);return(a)}module.exports=new UserSessions();
\ No newline at end of file
agents/modules_meshcore/identifiers.js new
+208
@@ -0,0 +1,208 @@
1 +/*
2 +Copyright 2019 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 trimIdentifiers(val)
18 +{
19 + for(var v in val)
20 + {
21 + if (!val[v] || val[v] == 'None' || val[v] == '') { delete val[v]; }
22 + }
23 +}
24 +
25 +function linux_identifiers()
26 +{
27 + var identifiers = {};
28 + var ret = {};
29 + var values = {};
30 + if (!require('fs').existsSync('/sys/class/dmi/id')) { throw ('this platform does not have DMI statistics'); }
31 + var entries = require('fs').readdirSync('/sys/class/dmi/id');
32 + for(var i in entries)
33 + {
34 + if (require('fs').statSync('/sys/class/dmi/id/' + entries[i]).isFile())
35 + {
36 + ret[entries[i]] = require('fs').readFileSync('/sys/class/dmi/id/' + entries[i]).toString().trim();
37 +
38 + if (ret[entries[i]] == 'None') { delete ret[entries[i]];}
39 + }
40 + }
41 + identifiers['bios_date'] = ret['bios_date'];
42 + identifiers['bios_vendor'] = ret['bios_vendor'];
43 + identifiers['bios_version'] = ret['bios_version'];
44 + identifiers['board_name'] = ret['board_name'];
45 + identifiers['board_serial'] = ret['board_serial'];
46 + identifiers['board_vendor'] = ret['board_vendor'];
47 + identifiers['board_version'] = ret['board_version'];
48 + identifiers['product_uuid'] = ret['product_uuid'];
49 +
50 + values.identifiers = identifiers;
51 + values.linux = ret;
52 + trimIdentifiers(values.identifiers);
53 + return (values);
54 +}
55 +
56 +function windows_wmic_results(str)
57 +{
58 + var lines = str.trim().split('\r\n');
59 + var keys = lines[0].split(',');
60 + var i, key, keyval;
61 + var tokens;
62 + var result = [];
63 +
64 + for (i = 1; i < lines.length; ++i)
65 + {
66 + var obj = {};
67 + tokens = lines[i].split(',');
68 + for (key = 0; key < keys.length; ++key)
69 + {
70 + if (tokens[key].trim())
71 + {
72 + obj[keys[key].trim()] = tokens[key].trim();
73 + }
74 + }
75 + result.push(obj);
76 + }
77 + return (result);
78 +}
79 +
80 +
81 +function windows_identifiers()
82 +{
83 + var ret = { windows: {}}; values = {}; var items; var i; var item;
84 + var child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'bios', 'get', '/VALUE']);
85 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
86 + child.waitExit();
87 +
88 + var items = child.stdout.str.split('\r\r\n');
89 + for(i in items)
90 + {
91 + item = items[i].split('=');
92 + values[item[0]] = item[1];
93 + }
94 +
95 + ret['identifiers'] = {};
96 + ret['identifiers']['bios_date'] = values['ReleaseDate'];
97 + ret['identifiers']['bios_vendor'] = values['Manufacturer'];
98 + ret['identifiers']['bios_version'] = values['SMBIOSBIOSVersion'];
99 +
100 + child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'BASEBOARD', 'get', '/VALUE']);
101 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
102 + child.waitExit();
103 +
104 + var items = child.stdout.str.split('\r\r\n');
105 + for (i in items)
106 + {
107 + item = items[i].split('=');
108 + values[item[0]] = item[1];
109 + }
110 + ret['identifiers']['board_name'] = values['Product'];
111 + ret['identifiers']['board_serial'] = values['SerialNumber'];
112 + ret['identifiers']['board_vendor'] = values['Manufacturer'];
113 + ret['identifiers']['board_version'] = values['Version'];
114 +
115 + child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'CSProduct', 'get', '/VALUE']);
116 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
117 + child.waitExit();
118 +
119 + var items = child.stdout.str.split('\r\r\n');
120 + for (i in items)
121 + {
122 + item = items[i].split('=');
123 + values[item[0]] = item[1];
124 + }
125 + ret['identifiers']['product_uuid'] = values['UUID'];
126 + trimIdentifiers(ret.identifiers);
127 +
128 + child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'MEMORYCHIP', 'LIST', '/FORMAT:CSV']);
129 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
130 + child.waitExit();
131 + ret.windows.memory = windows_wmic_results(child.stdout.str);
132 +
133 + child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'OS', 'GET', '/FORMAT:CSV']);
134 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
135 + child.waitExit();
136 + ret.windows.osinfo = windows_wmic_results(child.stdout.str)[0];
137 +
138 + child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'PARTITION', 'LIST', '/FORMAT:CSV']);
139 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
140 + child.waitExit();
141 + ret.windows.partitions = windows_wmic_results(child.stdout.str);
142 +
143 + return (ret);
144 +}
145 +function macos_identifiers()
146 +{
147 + var ret = { identifiers: {} };
148 + var child;
149 +
150 + child = require('child_process').execFile('/bin/sh', ['sh']);
151 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
152 + child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep board-id | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
153 + child.waitExit();
154 + ret.identifiers.board_name = child.stdout.str.trim();
155 +
156 + child = require('child_process').execFile('/bin/sh', ['sh']);
157 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
158 + child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformSerialNumber | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
159 + child.waitExit();
160 + ret.identifiers.board_serial = child.stdout.str.trim();
161 +
162 + child = require('child_process').execFile('/bin/sh', ['sh']);
163 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
164 + child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep manufacturer | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
165 + child.waitExit();
166 + ret.identifiers.board_vendor = child.stdout.str.trim();
167 +
168 + child = require('child_process').execFile('/bin/sh', ['sh']);
169 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
170 + child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep version | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
171 + child.waitExit();
172 + ret.identifiers.board_version = child.stdout.str.trim();
173 +
174 + child = require('child_process').execFile('/bin/sh', ['sh']);
175 + child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
176 + child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformUUID | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
177 + child.waitExit();
178 + ret.identifiers.product_uuid = child.stdout.str.trim();
179 +
180 + trimIdentifiers(ret.identifiers);
181 + return (ret);
182 +}
183 +
184 +switch(process.platform)
185 +{
186 + case 'linux':
187 + module.exports = { _ObjectID: 'identifiers', get: linux_identifiers };
188 + break;
189 + case 'win32':
190 + module.exports = { _ObjectID: 'identifiers', get: windows_identifiers };
191 + break;
192 + case 'darwin':
193 + module.exports = { _ObjectID: 'identifiers', get: macos_identifiers };
194 + break;
195 + default:
196 + module.exports = { get: function () { throw ('Unsupported Platform'); } };
197 + break;
198 +}
199 +
200 +
201 +// bios_date = BIOS->ReleaseDate
202 +// bios_vendor = BIOS->Manufacturer
203 +// bios_version = BIOS->SMBIOSBIOSVersion
204 +// board_name = BASEBOARD->Product = ioreg/board-id
205 +// board_serial = BASEBOARD->SerialNumber = ioreg/serial-number | ioreg/IOPlatformSerialNumber
206 +// board_vendor = BASEBOARD->Manufacturer = ioreg/manufacturer
207 +// board_version = BASEBOARD->Version
208 +
agents/modules_meshcore/sysinfo.js new
+230
@@ -0,0 +1,230 @@
1 +/*
2 +Copyright 2019 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 +const PDH_FMT_LONG = 0x00000100;
18 +const PDH_FMT_DOUBLE = 0x00000200;
19 +
20 +var promise = require('promise');
21 +if (process.platform == 'win32')
22 +{
23 + var GM = require('_GenericMarshal');
24 + GM.kernel32 = GM.CreateNativeProxy('kernel32.dll');
25 + GM.kernel32.CreateMethod('GlobalMemoryStatusEx');
26 +
27 + GM.pdh = GM.CreateNativeProxy('pdh.dll');
28 + GM.pdh.CreateMethod('PdhAddEnglishCounterA');
29 + GM.pdh.CreateMethod('PdhCloseQuery');
30 + GM.pdh.CreateMethod('PdhCollectQueryData');
31 + GM.pdh.CreateMethod('PdhGetFormattedCounterValue');
32 + GM.pdh.CreateMethod('PdhGetFormattedCounterArrayA');
33 + GM.pdh.CreateMethod('PdhOpenQueryA');
34 + GM.pdh.CreateMethod('PdhRemoveCounter');
35 +}
36 +
37 +function windows_cpuUtilization()
38 +{
39 + var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
40 + p.counter = GM.CreateVariable(16);
41 + p.cpu = GM.CreatePointer();
42 + p.cpuTotal = GM.CreatePointer();
43 + var err = 0;
44 + if ((err = GM.pdh.PdhOpenQueryA(0, 0, p.cpu).Val) != 0) { p._rej(err); return; }
45 +
46 + // This gets the CPU Utilization for each proc
47 + if ((err = GM.pdh.PdhAddEnglishCounterA(p.cpu.Deref(), GM.CreateVariable('\\Processor(*)\\% Processor Time'), 0, p.cpuTotal).Val) != 0) { p._rej(err); return; }
48 +
49 + if ((err = GM.pdh.PdhCollectQueryData(p.cpu.Deref()).Val != 0)) { p._rej(err); return; }
50 + p._timeout = setTimeout(function (po)
51 + {
52 + var u = { cpus: [] };
53 + var bufSize = GM.CreateVariable(4);
54 + var itemCount = GM.CreateVariable(4);
55 + var buffer, szName, item;
56 + var e;
57 + if ((e = GM.pdh.PdhCollectQueryData(po.cpu.Deref()).Val != 0)) { po._rej(e); return; }
58 +
59 + if ((e = GM.pdh.PdhGetFormattedCounterArrayA(po.cpuTotal.Deref(), PDH_FMT_DOUBLE, bufSize, itemCount, 0).Val) == -2147481646)
60 + {
61 + buffer = GM.CreateVariable(bufSize.toBuffer().readUInt32LE());
62 + }
63 + else
64 + {
65 + po._rej(e);
66 + return;
67 + }
68 + if ((e = GM.pdh.PdhGetFormattedCounterArrayA(po.cpuTotal.Deref(), PDH_FMT_DOUBLE, bufSize, itemCount, buffer).Val) != 0) { po._rej(e); return; }
69 + for(var i=0;i<itemCount.toBuffer().readUInt32LE();++i)
70 + {
71 + item = buffer.Deref(i * 24, 24);
72 + szName = item.Deref(0, GM.PointerSize).Deref();
73 + if (szName.String == '_Total')
74 + {
75 + u.total = item.Deref(16, 8).toBuffer().readDoubleLE();
76 + }
77 + else
78 + {
79 + u.cpus[parseInt(szName.String)] = item.Deref(16, 8).toBuffer().readDoubleLE();
80 + }
81 + }
82 +
83 + GM.pdh.PdhRemoveCounter(po.cpuTotal.Deref());
84 + GM.pdh.PdhCloseQuery(po.cpu.Deref());
85 + p._res(u);
86 + }, 100, p);
87 +
88 + return (p);
89 +}
90 +function windows_memUtilization()
91 +{
92 + var info = GM.CreateVariable(64);
93 + info.Deref(0, 4).toBuffer().writeUInt32LE(64);
94 + GM.kernel32.GlobalMemoryStatusEx(info);
95 +
96 + var ret =
97 + {
98 + MemTotal: require('bignum').fromBuffer(info.Deref(8, 8).toBuffer(), { endian: 'little' }),
99 + MemFree: require('bignum').fromBuffer(info.Deref(16, 8).toBuffer(), { endian: 'little' })
100 + };
101 +
102 + ret.percentFree = ((ret.MemFree.div(require('bignum')('1048576')).toNumber() / ret.MemTotal.div(require('bignum')('1048576')).toNumber()) * 100);//.toFixed(2);
103 + ret.percentConsumed = ((ret.MemTotal.sub(ret.MemFree).div(require('bignum')('1048576')).toNumber() / ret.MemTotal.div(require('bignum')('1048576')).toNumber()) * 100);//.toFixed(2);
104 + ret.MemTotal = ret.MemTotal.toString();
105 + ret.MemFree = ret.MemFree.toString();
106 + return (ret);
107 +}
108 +
109 +function linux_cpuUtilization()
110 +{
111 + var ret = { cpus: [] };
112 + var info = require('fs').readFileSync('/proc/stat');
113 + var lines = info.toString().split('\n');
114 + var columns;
115 + var x, y;
116 + var sum, idle, utilization;
117 + for (var i in lines)
118 + {
119 + columns = lines[i].split(' ');
120 + if (!columns[0].startsWith('cpu')) { break; }
121 +
122 + x = 0, sum = 0;
123 + while (columns[++x] == '');
124 + for (y = x; y < columns.length; ++y) { sum += parseInt(columns[y]); }
125 + idle = parseInt(columns[3 + x]);
126 + utilization = (100 - ((idle / sum) * 100)); //.toFixed(2);
127 + if (!ret.total)
128 + {
129 + ret.total = utilization;
130 + }
131 + else
132 + {
133 + ret.cpus.push(utilization);
134 + }
135 + }
136 +
137 + var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
138 + p._res(ret);
139 + return (p);
140 +}
141 +function linux_memUtilization()
142 +{
143 + var ret = {};
144 +
145 + var info = require('fs').readFileSync('/proc/meminfo').toString().split('\n');
146 + var tokens;
147 + for(var i in info)
148 + {
149 + tokens = info[i].split(' ');
150 + switch(tokens[0])
151 + {
152 + case 'MemTotal:':
153 + ret.total = parseInt(tokens[tokens.length - 2]);
154 + break;
155 + case 'MemFree:':
156 + ret.free = parseInt(tokens[tokens.length - 2]);
157 + break;
158 + }
159 + }
160 + ret.percentFree = ((ret.free / ret.total) * 100);//.toFixed(2);
161 + ret.percentConsumed = (((ret.total - ret.free) / ret.total) * 100);//.toFixed(2);
162 + return (ret);
163 +}
164 +
165 +function macos_cpuUtilization()
166 +{
167 + var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
168 + var child = require('child_process').execFile('/bin/sh', ['sh']);
169 + child.stdout.str = '';
170 + child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
171 + child.stdin.write('top -l 1 | grep -E "^CPU"\nexit\n');
172 + child.waitExit();
173 +
174 + var lines = child.stdout.str.split('\n');
175 + if (lines[0].length > 0)
176 + {
177 + var usage = lines[0].split(':')[1];
178 + var bdown = usage.split(',');
179 +
180 + var tot = parseFloat(bdown[0].split('%')[0].trim()) + parseFloat(bdown[1].split('%')[0].trim());
181 + ret._res({total: tot, cpus: []});
182 + }
183 + else
184 + {
185 + ret._rej('parse error');
186 + }
187 +
188 + return (ret);
189 +}
190 +function macos_memUtilization()
191 +{
192 + var mem = { };
193 + var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
194 + var child = require('child_process').execFile('/bin/sh', ['sh']);
195 + child.stdout.str = '';
196 + child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
197 + child.stdin.write('top -l 1 | grep -E "^Phys"\nexit\n');
198 + child.waitExit();
199 +
200 + var lines = child.stdout.str.split('\n');
201 + if (lines[0].length > 0)
202 + {
203 + var usage = lines[0].split(':')[1];
204 + var bdown = usage.split(',');
205 +
206 + mem.MemTotal = parseInt(bdown[0].trim().split(' ')[0]);
207 + mem.MemFree = parseInt(bdown[1].trim().split(' ')[0]);
208 + mem.percentFree = ((mem.MemFree / mem.MemTotal) * 100);//.toFixed(2);
209 + mem.percentConsumed = (((mem.MemTotal - mem.MemFree) / mem.MemTotal) * 100);//.toFixed(2);
210 + return (mem);
211 + }
212 + else
213 + {
214 + throw ('Parse Error');
215 + }
216 +}
217 +
218 +switch(process.platform)
219 +{
220 + case 'linux':
221 + module.exports = { cpuUtilization: linux_cpuUtilization, memUtilization: linux_memUtilization };
222 + break;
223 + case 'win32':
224 + module.exports = { cpuUtilization: windows_cpuUtilization, memUtilization: windows_memUtilization };
225 + break;
226 + case 'darwin':
227 + module.exports = { cpuUtilization: macos_cpuUtilization, memUtilization: macos_memUtilization };
228 + break;
229 +}
230 +
agents/modules_meshcore_min/identifiers.min.js new
+1
@@ -0,0 +1 @@
1 +function trimIdentifiers(b){for(var a in b){if(!b[a]||b[a]=="None"||b[a]==""){delete b[a]}}}function linux_identifiers(){var c={};var d={};var e={};if(!require("fs").existsSync("/sys/class/dmi/id")){throw ("this platform does not have DMI statistics")}var a=require("fs").readdirSync("/sys/class/dmi/id");for(var b in a){if(require("fs").statSync("/sys/class/dmi/id/"+a[b]).isFile()){d[a[b]]=require("fs").readFileSync("/sys/class/dmi/id/"+a[b]).toString().trim();if(d[a[b]]=="None"){delete d[a[b]]}}}c.bios_date=d.bios_date;c.bios_vendor=d.bios_vendor;c.bios_version=d.bios_version;c.board_name=d.board_name;c.board_serial=d.board_serial;c.board_vendor=d.board_vendor;c.board_version=d.board_version;c.product_uuid=d.product_uuid;e.identifiers=c;e.linux=d;trimIdentifiers(e.identifiers);return(e)}function windows_wmic_results(h){var e=h.trim().split("\r\n");var c=e[0].split(",");var a,b,d;var j;var g=[];for(a=1;a<e.length;++a){var f={};j=e[a].split(",");for(b=0;b<c.length;++b){if(j[b].trim()){f[c[b].trim()]=j[b].trim()}}g.push(f)}return(g)}function windows_identifiers(){var e={windows:{}};values={};var d;var b;var c;var a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","bios","get","/VALUE"]);a.stdout.str="";a.stdout.on("data",function(f){this.str+=f.toString()});a.waitExit();var d=a.stdout.str.split("\r\r\n");for(b in d){c=d[b].split("=");values[c[0]]=c[1]}e.identifiers={};e.identifiers["bios_date"]=values.ReleaseDate;e.identifiers["bios_vendor"]=values.Manufacturer;e.identifiers["bios_version"]=values.SMBIOSBIOSVersion;a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","BASEBOARD","get","/VALUE"]);a.stdout.str="";a.stdout.on("data",function(f){this.str+=f.toString()});a.waitExit();var d=a.stdout.str.split("\r\r\n");for(b in d){c=d[b].split("=");values[c[0]]=c[1]}e.identifiers["board_name"]=values.Product;e.identifiers["board_serial"]=values.SerialNumber;e.identifiers["board_vendor"]=values.Manufacturer;e.identifiers["board_version"]=values.Version;a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","CSProduct","get","/VALUE"]);a.stdout.str="";a.stdout.on("data",function(f){this.str+=f.toString()});a.waitExit();var d=a.stdout.str.split("\r\r\n");for(b in d){c=d[b].split("=");values[c[0]]=c[1]}e.identifiers["product_uuid"]=values.UUID;trimIdentifiers(e.identifiers);a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","MEMORYCHIP","LIST","/FORMAT:CSV"]);a.stdout.str="";a.stdout.on("data",function(f){this.str+=f.toString()});a.waitExit();e.windows.memory=windows_wmic_results(a.stdout.str);a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","OS","GET","/FORMAT:CSV"]);a.stdout.str="";a.stdout.on("data",function(f){this.str+=f.toString()});a.waitExit();e.windows.osinfo=windows_wmic_results(a.stdout.str)[0];a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","PARTITION","LIST","/FORMAT:CSV"]);a.stdout.str="";a.stdout.on("data",function(f){this.str+=f.toString()});a.waitExit();e.windows.partitions=windows_wmic_results(a.stdout.str);return(e)}function macos_identifiers(){var b={identifiers:{}};var a;a=require("child_process").execFile("/bin/sh",["sh"]);a.stdout.str="";a.stdout.on("data",function(d){this.str+=d.toString()});a.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep board-id | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');a.waitExit();b.identifiers.board_name=a.stdout.str.trim();a=require("child_process").execFile("/bin/sh",["sh"]);a.stdout.str="";a.stdout.on("data",function(d){this.str+=d.toString()});a.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformSerialNumber | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');a.waitExit();b.identifiers.board_serial=a.stdout.str.trim();a=require("child_process").execFile("/bin/sh",["sh"]);a.stdout.str="";a.stdout.on("data",function(d){this.str+=d.toString()});a.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep manufacturer | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');a.waitExit();b.identifiers.board_vendor=a.stdout.str.trim();a=require("child_process").execFile("/bin/sh",["sh"]);a.stdout.str="";a.stdout.on("data",function(d){this.str+=d.toString()});a.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep version | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');a.waitExit();b.identifiers.board_version=a.stdout.str.trim();a=require("child_process").execFile("/bin/sh",["sh"]);a.stdout.str="";a.stdout.on("data",function(d){this.str+=d.toString()});a.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformUUID | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');a.waitExit();b.identifiers.product_uuid=a.stdout.str.trim();trimIdentifiers(b.identifiers);return(b)}switch(process.platform){case"linux":module.exports={_ObjectID:"identifiers",get:linux_identifiers};break;case"win32":module.exports={_ObjectID:"identifiers",get:windows_identifiers};break;case"darwin":module.exports={_ObjectID:"identifiers",get:macos_identifiers};break;default:module.exports={get:function(){throw ("Unsupported Platform")}};break};
\ No newline at end of file
agents/modules_meshcore_min/wifi-scanner-windows.min.js deleted
-1
@@ -1 +0,0 @@
1 -function _Scan(){var f=this.Marshal.CreatePointer();this.Native.WlanEnumInterfaces(this.Handle,0,f);var a=f.Deref().Deref(0,4).toBuffer().readUInt32LE(0);var d=f.Deref().Deref(8,532);var c=d.Deref(16,512).AnsiString;var e;switch(d.Deref(528,4).toBuffer().readUInt32LE(0)){case 0:e="NOT READY";break;case 1:e="CONNECTED";break;case 2:e="AD-HOC";break;case 3:e="DISCONNECTING";break;case 4:e="DISCONNECTED";break;case 5:e="ASSOCIATING";break;case 6:e="DISCOVERING";break;case 7:e="AUTHENTICATING";break;default:e="UNKNOWN";break}var b=d.Deref(0,16);if(this.Native.WlanScan(this.Handle,b,0,0,0).Val==0){return(true)}else{return(false)}}function AccessPoint(d,a,c,b){this.ssid=d;this.bssid=a;this.rssi=c;this.lq=b}AccessPoint.prototype.toString=function(){return(this.ssid+" ["+this.bssid+"]: "+this.lq)};function OnNotify(g){var h=g.Deref(0,4).toBuffer().readUInt32LE(0);var f=g.Deref(4,4).toBuffer().readUInt32LE(0);var c=g.Deref(8,16);if((h&8)&&(f==7)){var a=this.Parent.Marshal.CreatePointer();var k=this.Parent.Native.GetBSSList(this.Parent.Handle,c,0,3,0,0,a).Val;if(k==0){var n=a.Deref().Deref(0,4).toBuffer().readUInt32LE(0);var j=a.Deref().Deref(4,4).toBuffer().readUInt32LE(0);for(i=0;i<j;++i){var d=a.Deref().Deref(8+(360*i),360);var m=d.Deref(4,32).String.trim();var b=d.Deref(40,6).HexString2;var l=d.Deref(56,4).toBuffer().readUInt32LE(0);var e=d.Deref(60,4).toBuffer().readUInt32LE(0);this.Parent.emit("Scan",new AccessPoint(m,b,l,e))}}}}function Wireless(){var a=require("events").inherits(this);this.Marshal=require("_GenericMarshal");this.Native=this.Marshal.CreateNativeProxy("wlanapi.dll");this.Native.CreateMethod("WlanOpenHandle");this.Native.CreateMethod("WlanGetNetworkBssList","GetBSSList");this.Native.CreateMethod("WlanRegisterNotification");this.Native.CreateMethod("WlanEnumInterfaces");this.Native.CreateMethod("WlanScan");this.Native.CreateMethod("WlanQueryInterface");var c=this.Marshal.CreatePointer();var b=this.Marshal.CreatePointer();this.Native.WlanOpenHandle(2,0,c,b);this.Handle=b.Deref();this._NOTIFY_PROXY_OBJECT=this.Marshal.CreateCallbackProxy(OnNotify,2);this._NOTIFY_PROXY_OBJECT.Parent=this;var d=this.Marshal.CreatePointer();var e=this.Native.WlanRegisterNotification(this.Handle,65535,0,this._NOTIFY_PROXY_OBJECT.Callback,this._NOTIFY_PROXY_OBJECT.State,0,d);a.createEvent("Scan");a.addMethod("Scan",_Scan);this.GetConnectedNetwork=function(){var n=this.Marshal.CreatePointer();console.log("Success = "+this.Native.WlanEnumInterfaces(this.Handle,0,n).Val);var h=n.Deref().Deref(0,4).toBuffer().readUInt32LE(0);var m=n.Deref().Deref(8,532);var l=m.Deref(16,512).AnsiString;var o=m.Deref(528,4).toBuffer().readUInt32LE(0);if(m.Deref(528,4).toBuffer().readUInt32LE(0)==1){var j=this.Marshal.CreatePointer();var q=this.Marshal.CreatePointer();var s=this.Marshal.CreatePointer();var k=m.Deref(0,16);var r=this.Native.WlanQueryInterface(this.Handle,k,7,0,j,q,s).Val;if(r==0){var f=q.Deref().Deref(524,32).String;var g=q.Deref().Deref(560,6).HexString;var p=q.Deref().Deref(576,4).toBuffer().readUInt32LE(0);return(new AccessPoint(f,g,0,p))}}throw ("GetConnectedNetworks: FAILED (not associated to a network)")};return(this)}module.exports=new Wireless();
\ No newline at end of file
agents/modules_meshcore_min/wifi-scanner.min.js deleted
-1
@@ -1 +0,0 @@
1 -var MemoryStream=require("MemoryStream");var WindowsChildScript='var parent = require("ScriptContainer");var Wireless = require("wifi-scanner-windows");Wireless.on("Scan", function (ap) { parent.send(ap); });Wireless.Scan();';function AccessPoint(c,a,b){this.ssid=c;this.bssid=a;this.lq=b}AccessPoint.prototype.toString=function(){return("["+this.bssid+"]: "+this.ssid+" ("+this.lq+")")};function WiFiScanner(){var a=require("events").inherits(this);a.createEvent("accessPoint");this.hasWireless=function(){var d=false;var b=require("os").networkInterfaces();for(var c in b){if(b[c][0].type=="wireless"){d=true;break}}return(d)};this.Scan=function(){if(process.platform=="win32"){this.master=require("ScriptContainer").Create(15,ContainerPermissions.DEFAULT);this.master.parent=this;this.master.on("data",function(e){this.parent.emit("accessPoint",new AccessPoint(e.ssid,e.bssid,e.lq))});this.master.addModule("wifi-scanner-windows",getJSModule("wifi-scanner-windows"));this.master.ExecuteString(WindowsChildScript)}else{if(process.platform=="linux"){var c=require("os").networkInterfaces();var d=null;for(var b in c){if(c[b][0].type=="wireless"){d=b;break}}if(d!=null){this.child=require("child_process").execFile("/sbin/iwlist",["iwlist",d,"scan"]);this.child.parent=this;this.child.ms=new MemoryStream();this.child.ms.parent=this.child;this.child.stdout.on("data",function(e){this.parent.ms.write(e)});this.child.on("exit",function(){this.ms.end()});this.child.ms.on("end",function(){var l=this.buffer.toString();tokens=l.split(" - Address: ");for(var h in tokens){if(h==0){continue}var i=tokens[h].split("\n");var e=i[0];var f;var g;for(var j in i){j=i[j].trim();j=j.trim();if(j.startsWith("ESSID:")){g=j.slice(7,j.length-1);if(g=="<hidden>"){g=""}}if(j.startsWith("Signal level=")){f=j.slice(13,j.length-4)}else{if(j.startsWith("Quality=")){f=j.slice(8,10);var k=j.slice(11,13)}}}this.parent.parent.emit("accessPoint",new AccessPoint(g,e,f))}})}}}}}module.exports=WiFiScanner;
\ No newline at end of file
agents/modules_meshcore_min/win-console.min.js deleted
-1
@@ -1 +0,0 @@
1 -var TrayIconFlags={NIF_MESSAGE:1,NIF_ICON:2,NIF_TIP:4,NIF_STATE:8,NIF_INFO:16,NIF_GUID:32,NIF_REALTIME:64,NIF_SHOWTIP:128,NIM_ADD:0,NIM_MODIFY:1,NIM_DELETE:2,NIM_SETFOCUS:3,NIM_SETVERSION:4};var NOTIFYICON_VERSION_4=4;var MessageTypes={WM_APP:32768,WM_USER:1024};function WindowsConsole(){if(process.platform=="win32"){this._ObjectID="win-console";this._Marshal=require("_GenericMarshal");this._kernel32=this._Marshal.CreateNativeProxy("kernel32.dll");this._user32=this._Marshal.CreateNativeProxy("user32.dll");this._kernel32.CreateMethod("GetConsoleWindow");this._kernel32.CreateMethod("GetCurrentThread");this._user32.CreateMethod("ShowWindow");this._user32.CreateMethod("LoadImageA");this._user32.CreateMethod({method:"GetMessageA",threadDispatch:1});this._shell32=this._Marshal.CreateNativeProxy("Shell32.dll");this._shell32.CreateMethod("Shell_NotifyIconA");this._handle=this._kernel32.GetConsoleWindow();this.minimize=function(){this._user32.ShowWindow(this._handle,6)};this.restore=function(){this._user32.ShowWindow(this._handle,9)};this.hide=function(){this._user32.ShowWindow(this._handle,0)};this.show=function(){this._user32.ShowWindow(this._handle,5)};this._loadicon=function(c){var b=this._user32.LoadImageA(0,this._Marshal.CreateVariable(c),1,0,0,16|32768|64);return(b)};this.SetTrayIcon=function a(h){var b=this._Marshal.CreateVariable(this._Marshal.PointerSize==4?508:528);b.toBuffer().writeUInt32LE(b._size,0);var n=TrayIconFlags.NIF_TIP|TrayIconFlags.NIF_MESSAGE;h.filter=MessageTypes.WM_APP+1;b.Deref(this._Marshal.PointerSize==4?16:24,4).toBuffer().writeUInt32LE(h.filter);if(!h.noBalloon){n|=TrayIconFlags.NIF_INFO}if(h.icon){n|=TrayIconFlags.NIF_ICON;var c=b.Deref(this._Marshal.PointerSize==4?20:32,this._Marshal.PointerSize);h.icon.pointerBuffer().copy(c.toBuffer())}b.Deref(this._Marshal.PointerSize*2,4).toBuffer().writeUInt32LE(1);b.Deref(this._Marshal.PointerSize==4?12:20,4).toBuffer().writeUInt32LE(n);b.Deref(this._Marshal.PointerSize==4?416:432,4).toBuffer().writeUInt32LE(NOTIFYICON_VERSION_4);var m=b.Deref(this._Marshal.PointerSize==4?24:40,128);var k=b.Deref(this._Marshal.PointerSize==4?160:176,256);var l=b.Deref(this._Marshal.PointerSize==4?420:436,64);if(h.szTip){Buffer.from(h.szTip).copy(m.toBuffer())}if(h.szInfo){Buffer.from(h.szInfo).copy(k.toBuffer())}if(h.szInfoTitle){Buffer.from(h.szInfoTitle).copy(l.toBuffer())}var d=require("win-message-pump");retVal={_ObjectID:"WindowsConsole.TrayIcon",MessagePump:new d(h)};var j=require("events").inherits(retVal);j.createEvent("ToastClicked");j.createEvent("IconHover");j.createEvent("ToastDismissed");retVal.Options=h;retVal.MessagePump.TrayIcon=retVal;retVal.MessagePump.NotifyData=b;retVal.MessagePump.WindowsConsole=this;retVal.MessagePump.on("exit",function e(o){console.log("Pump Exited");if(this.TrayIcon){this.TrayIcon.remove()}});retVal.MessagePump.on("hwnd",function f(o){h.hwnd=o;o.pointerBuffer().copy(this.NotifyData.Deref(this.WindowsConsole._Marshal.PointerSize,this.WindowsConsole._Marshal.PointerSize).toBuffer());if(this.WindowsConsole._shell32.Shell_NotifyIconA(TrayIconFlags.NIM_ADD,this.NotifyData).Val==0){}});retVal.MessagePump.on("message",function g(p){if(p.message==this.TrayIcon.Options.filter){var o=false;if(p.wparam==1&&p.lparam==1029){this.TrayIcon.emit("ToastClicked");o=true}if(p.wparam==1&&p.lparam==512){this.TrayIcon.emit("IconHover");o=true}if(this.TrayIcon.Options.balloonOnly&&p.wparam==1&&(p.lparam==1028||p.lparam==1029)){this.TrayIcon.emit("ToastDismissed");this.TrayIcon.remove();o=true}}});retVal.remove=function i(){this.MessagePump.WindowsConsole._shell32.Shell_NotifyIconA(TrayIconFlags.NIM_DELETE,this.MessagePump.NotifyData);this.MessagePump.stop();delete this.MessagePump.TrayIcon;delete this.MessagePump};return(retVal)}}}module.exports=new WindowsConsole();
\ No newline at end of file
agents/modules_meshcore_min/win-info.min.js deleted
-1
@@ -1 +0,0 @@
1 -var promise=require("promise");function qfe(){var a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","qfe","list","full","/FORMAT:CSV"]);a.stdout.str="";a.stdout.on("data",function(i){this.str+=i.toString()});a.stderr.str="";a.stderr.on("data",function(i){this.str+=i.toString()});a.waitExit();var e=a.stdout.str.trim().split("\r\n");var d=e[0].split(",");var b,c;var h;var g=[];for(b=1;b<e.length;++b){var f={};h=e[b].split(",");for(c=0;c<d.length;++c){if(h[c]){f[d[c]]=h[c]}}g.push(f)}return(g)}function av(){var a=require("child_process").execFile(process.env.windir+"\\System32\\wbem\\wmic.exe",["wmic","/Namespace:\\\\root\\SecurityCenter2","Path","AntiVirusProduct","get","/FORMAT:CSV"]);a.stdout.str="";a.stdout.on("data",function(i){this.str+=i.toString()});a.stderr.str="";a.stderr.on("data",function(i){this.str+=i.toString()});a.waitExit();var e=a.stdout.str.trim().split("\r\n");var d=e[0].split(",");var b,c;var j;var g=[];for(b=1;b<e.length;++b){var f={};var h={};j=e[b].split(",");for(c=0;c<d.length;++c){if(j[c]!=undefined){f[d[c].trim()]=j[c]}}h.product=f.displayName;h.updated=(parseInt(f.productState)&16)==0;h.enabled=(parseInt(f.productState)&4096)==4096;g.push(h)}return(g)}function defrag(a){var c=new promise(function(e,d){this._res=e;this._rej=d});var b="";switch(require("os").arch()){case"x64":if(require("_GenericMarshal").PointerSize==4){c._rej("Cannot defrag volume on 64 bit Windows from 32 bit application");return(c)}else{b=process.env.windir+"\\System32\\defrag.exe"}break;case"ia32":b=process.env.windir+"\\System32\\defrag.exe";break;default:c._rej(require("os").arch()+" not supported");return(c);break}c.child=require("child_process").execFile(process.env.windir+"\\System32\\defrag.exe",["defrag",a.volume+" /A"]);c.child.promise=c;c.child.promise.options=a;c.child.stdout.str="";c.child.stdout.on("data",function(d){this.str+=d.toString()});c.child.stderr.str="";c.child.stderr.on("data",function(d){this.str+=d.toString()});c.child.on("exit",function(d){var f=this.stdout.str.trim().split("\r\n");var g={volume:this.promise.options.volume};for(var e in f){var h=f[e].split("=");if(h.length==2){switch(h[0].trim().toLowerCase()){case"volume size":g.size=h[1];break;case"free space":g.free=h[1];break;case"total fragmented space":g.fragmented=h[1];break;case"largest free space size":g.largestFragment=h[1];break}}}this.promise._res(g)});return(c)}function regQuery(b,d,c){try{return(require("win-registry").QueryKey(b,d,c))}catch(a){return(null)}}function pendingReboot(){var c=null;var b=null;var a=require("win-registry").HKEY;if(regQuery(a.LocalMachine,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing","RebootPending")!=null){b="Component Based Servicing"}else{if(regQuery(a.LocalMachine,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate","RebootRequired")){b="Windows Update"}else{if((c=regQuery(a.LocalMachine,"SYSTEM\\CurrentControlSet\\Control\\Session Manager","PendingFileRenameOperations"))!=null&&c!=0&&c!=""){b="File Rename"}else{if(regQuery(a.LocalMachine,"SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName","ComputerName")!=regQuery(a.LocalMachine,"SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName","ComputerName")){b="System Rename"}}}}return(b)}function installedApps(){var b=require("promise");var c=new b(function(d,e){this._resolve=d;this._reject=e});var a=" var reg = require('win-registry'); var result = []; var val, tmp; var items = reg.QueryKey(reg.HKEY.LocalMachine, 'SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall'); for (var key in items.subkeys) { val = {}; try { val.name = reg.QueryKey(reg.HKEY.LocalMachine, 'SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\\\\' + items.subkeys[key], 'DisplayName'); } catch(e) { continue; } try { val.version = reg.QueryKey(reg.HKEY.LocalMachine, 'SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\\\\' + items.subkeys[key], 'DisplayVersion'); if (val.version == '') { delete val.version; } } catch(e) { } try { val.location = reg.QueryKey(reg.HKEY.LocalMachine, 'SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\\\\' + items.subkeys[key], 'InstallLocation'); if (val.location == '') { delete val.location; } } catch(e) { } result.push(val); } console.log(JSON.stringify(result,'', 1));process.exit();";c.child=require("child_process").execFile(process.execPath,[process.execPath.split("\\").pop().split(".exe")[0],'-exec "'+a+'"']);c.child.promise=c;c.child.stdout.str="";c.child.stdout.on("data",function(d){this.str+=d.toString()});c.child.on("exit",function(d){this.promise._resolve(JSON.parse(this.stdout.str.trim()))});return(c)}if(process.platform=="win32"){module.exports={qfe:qfe,av:av,defrag:defrag,pendingReboot:pendingReboot,installedApps:installedApps}}else{var not_supported=function(){throw (process.platform+" not supported")};module.exports={qfe:not_supported,av:not_supported,defrag:not_supported,pendingReboot:not_supported,installedApps:not_supported}};
\ No newline at end of file
agents/modules_meshcore_min/win-terminal.min.js deleted
-1
@@ -1 +0,0 @@
1 -var promise=require("promise");var duplex=require("stream").Duplex;var SW_HIDE=0;var SW_MINIMIZE=6;var STARTF_USESHOWWINDOW=1;var STD_INPUT_HANDLE=-10;var STD_OUTPUT_HANDLE=-11;var EVENT_CONSOLE_CARET=16385;var EVENT_CONSOLE_END_APPLICATION=16391;var WINEVENT_OUTOFCONTEXT=0;var WINEVENT_SKIPOWNPROCESS=2;var CREATE_NEW_PROCESS_GROUP=512;var EVENT_CONSOLE_UPDATE_REGION=16386;var EVENT_CONSOLE_UPDATE_SIMPLE=16387;var EVENT_CONSOLE_UPDATE_SCROLL=16388;var EVENT_CONSOLE_LAYOUT=16389;var EVENT_CONSOLE_START_APPLICATION=16390;var KEY_EVENT=1;var MAPVK_VK_TO_VSC=0;var WM_QUIT=18;var GM=require("_GenericMarshal");var si=GM.CreateVariable(GM.PointerSize==4?68:104);var pi=GM.CreateVariable(GM.PointerSize==4?16:24);si.Deref(0,4).toBuffer().writeUInt32LE(GM.PointerSize==4?68:104);si.Deref(GM.PointerSize==4?48:64,2).toBuffer().writeUInt16LE(SW_HIDE|SW_MINIMIZE);si.Deref(GM.PointerSize==4?44:60,4).toBuffer().writeUInt32LE(STARTF_USESHOWWINDOW);var MSG=GM.CreateVariable(GM.PointerSize==4?28:48);function windows_terminal(){this._ObjectID="windows_terminal";this._user32=GM.CreateNativeProxy("User32.dll");this._user32.CreateMethod("DispatchMessageA");this._user32.CreateMethod("GetMessageA");this._user32.CreateMethod("MapVirtualKeyA");this._user32.CreateMethod("PostThreadMessageA");this._user32.CreateMethod("SetWinEventHook");this._user32.CreateMethod("ShowWindow");this._user32.CreateMethod("TranslateMessage");this._user32.CreateMethod("UnhookWinEvent");this._user32.CreateMethod("VkKeyScanA");this._user32.terminal=this;this._kernel32=GM.CreateNativeProxy("Kernel32.dll");this._kernel32.CreateMethod("AllocConsole");this._kernel32.CreateMethod("CreateProcessA");this._kernel32.CreateMethod("CloseHandle");this._kernel32.CreateMethod("FillConsoleOutputAttribute");this._kernel32.CreateMethod("FillConsoleOutputCharacterA");this._kernel32.CreateMethod("GetConsoleScreenBufferInfo");this._kernel32.CreateMethod("GetConsoleWindow");this._kernel32.CreateMethod("GetLastError");this._kernel32.CreateMethod("GetStdHandle");this._kernel32.CreateMethod("GetThreadId");this._kernel32.CreateMethod("ReadConsoleOutputA");this._kernel32.CreateMethod("SetConsoleCursorPosition");this._kernel32.CreateMethod("SetConsoleScreenBufferSize");this._kernel32.CreateMethod("SetConsoleWindowInfo");this._kernel32.CreateMethod("TerminateProcess");this._kernel32.CreateMethod("WaitForSingleObject");this._kernel32.CreateMethod("WriteConsoleInputA");var b=0;var c=0;this._scrx=0;this._scry=0;this.SendCursorUpdate=function(){var g=GM.CreateVariable(22);if(this._kernel32.GetConsoleScreenBufferInfo(this._stdoutput,g).Val==0){return}if(g.Deref(4,2).toBuffer().readUInt16LE()!=this.currentX||g.Deref(6,2).toBuffer().readUInt16LE()!=this.currentY){this.currentX=g.Deref(4,2).toBuffer().readUInt16LE();this.currentY=g.Deref(6,2).toBuffer().readUInt16LE()}};this.ClearScreen=function(){var h=GM.CreateVariable(22);if(this._kernel32.GetConsoleScreenBufferInfo(this._stdoutput,h).Val==0){return}var i=GM.CreateVariable(4);var j=h.Deref(0,2).toBuffer().readUInt16LE(0)*h.Deref(2,2).toBuffer().readUInt16LE(0);var g=GM.CreateVariable(4);if(this._kernel32.FillConsoleOutputCharacterA(this._stdoutput,32,j,i.Deref(0,4).toBuffer().readUInt32LE(),g).Val==0){return}if(this._kernel32.GetConsoleScreenBufferInfo(this._stdoutput,h).Val==0){return}if(this._kernel32.FillConsoleOutputAttribute(this._stdoutput,h.Deref(8,2).toBuffer().readUInt16LE(0),j,i.Deref(0,4).toBuffer().readUInt32LE(),g).Val==0){return}this._kernel32.SetConsoleCursorPosition(this._stdoutput,i.Deref(0,4).toBuffer().readUInt32LE());var k=GM.CreateVariable(8);var l=h.Deref(10,8).toBuffer();k.Deref(4,2).toBuffer().writeUInt16LE(l.readUInt16LE(4)-l.readUInt16LE(0));k.Deref(6,2).toBuffer().writeUInt16LE(l.readUInt16LE(6)-l.readUInt16LE(2));this._kernel32.SetConsoleWindowInfo(this._stdoutput,1,k)};this.PowerShellCapable=function(){if(require("os").arch()=="x64"){return(require("fs").existsSync(process.env.windir+"\\SysWow64\\WindowsPowerShell\\v1.0\\powershell.exe"))}else{return(require("fs").existsSync(process.env.windir+"\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"))}};this.StartEx=function d(h,g,k){this.stopping=null;if(this._kernel32.GetConsoleWindow().Val==0){if(this._kernel32.AllocConsole().Val==0){throw ("AllocConsole failed with: "+this._kernel32.GetLastError().Val)}}this._stdinput=this._kernel32.GetStdHandle(STD_INPUT_HANDLE);this._stdoutput=this._kernel32.GetStdHandle(STD_OUTPUT_HANDLE);this._connected=false;var i=GM.CreateVariable(4);i.Deref(0,2).toBuffer().writeUInt16LE(h);i.Deref(2,2).toBuffer().writeUInt16LE(g);var j=GM.CreateVariable(8);j.Deref(4,2).toBuffer().writeUInt16LE(h-1);j.Deref(6,2).toBuffer().writeUInt16LE(g-1);if(this._kernel32.SetConsoleWindowInfo(this._stdoutput,1,j).Val==0){throw ("Failed to set Console Screen Size")}if(this._kernel32.SetConsoleScreenBufferSize(this._stdoutput,i.Deref(0,4).toBuffer().readUInt32LE()).Val==0){throw ("Failed to set Console Buffer Size")}this._user32.ShowWindow(this._kernel32.GetConsoleWindow().Val,SW_HIDE);this.ClearScreen();this._hookThread(k).then(function(){this.terminal.StartCommand(this.userArgs[0])},console.log);this._stream=new duplex({write:function(l,m){if(!this.terminal.connected){if(!this._promise.chunk){this._promise.chunk=[]}if(typeof(l)=="string"){this._promise.chunk.push(l)}else{this._promise.chunk.push(Buffer.alloc(l.length));l.copy(this._promise.chunk.peek())}this._promise.chunk.peek().flush=m;this._promise.then(function(){var n;while(this.chunk.length>0){n=this.chunk.shift();this.terminal._WriteBuffer(n);n.flush()}})}else{this.terminal._WriteBuffer(l);m()}return(true)},"final":function(l){var m=this.terminal._stop();m.__flush=l;m.then(function(){this.__flush()})}});this._stream.terminal=this;this._stream._promise=new promise(function(m,l){this._res=m;this._rej=l});this._stream._promise.terminal=this;return(this._stream)};this.Start=function d(h,g){return(this.StartEx(h,g,process.env.windir+"\\System32\\cmd.exe"))};this.StartPowerShell=function f(h,g){if(require("os").arch()=="x64"){return(this.StartEx(h,g,process.env.windir+"\\SysWow64\\WindowsPowerShell\\v1.0\\powershell.exe"))}else{return(this.StartEx(h,g,process.env.windir+"\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"))}};this._stop=function(){if(this.stopping){return(this.stopping)}this._ConsoleWinEventProc.removeAllListeners("GlobalCallback");this.stopping=new promise(function(i,h){this._res=i;this._rej=h});var g=this._kernel32.GetThreadId(this._user32.SetWinEventHook.async.thread()).Val;this._user32.PostThreadMessageA(g,WM_QUIT,0,0);this._stream.emit("end");return(this.stopping)};this._hookThread=function(){var i=new promise(function(k,j){this._res=k;this._rej=j});i.userArgs=[];for(var g in arguments){i.userArgs.push(arguments[g])}i.terminal=this;this._ConsoleWinEventProc=GM.GetGenericGlobalCallback(7);this._ConsoleWinEventProc.terminal=this;var h=this._user32.SetWinEventHook.async(EVENT_CONSOLE_CARET,EVENT_CONSOLE_END_APPLICATION,0,this._ConsoleWinEventProc,0,0,WINEVENT_OUTOFCONTEXT|WINEVENT_SKIPOWNPROCESS);h.ready=i;h.terminal=this;h.then(function(j){if(j.Val==0){this.ready._rej("Error calling SetWinEventHook")}else{this.terminal.hwinEventHook=j;this.ready._res();this.terminal._GetMessage()}});this._ConsoleWinEventProc.on("GlobalCallback",function(l,k,m,p,n,o,r){if(!this.terminal.hwinEventHook||this.terminal.hwinEventHook.Val!=l.Val){return}var j=null;switch(k.Val){case EVENT_CONSOLE_CARET:break;case EVENT_CONSOLE_UPDATE_REGION:if(!this.terminal.connected){this.terminal.connected=true;this.terminal._stream._promise._res()}if(this.terminal._scrollTimer==null){j=this.terminal._GetScreenBuffer(LOWORD(p.Val),HIWORD(p.Val),LOWORD(n.Val),HIWORD(n.Val));this.terminal._SendDataBuffer(j)}break;case EVENT_CONSOLE_UPDATE_SIMPLE:var q={data:[Buffer.alloc(1,LOWORD(n.Val))],attributes:[HIWORD(n.Val)],width:1,height:1,x:LOWORD(p.Val),y:HIWORD(p.Val)};this.terminal._SendDataBuffer(q);break;case EVENT_CONSOLE_UPDATE_SCROLL:this.terminal._SendScroll(p.Val,n.Val);break;case EVENT_CONSOLE_LAYOUT:break;case EVENT_CONSOLE_START_APPLICATION:break;case EVENT_CONSOLE_END_APPLICATION:if(p.Val==this.terminal._hProcessID){this.terminal._hProcess=null;this.terminal._stop().then(function(){console.log("STOPPED")})}break;default:console.log("Unknown event: "+k.Val);break}});return(i)};this._GetMessage=function(){if(this._user32.abort){console.log("aborting loop");return}this._user32.GetMessageA.async(this._user32.SetWinEventHook.async,MSG,0,0,0).then(function(g){if(g.Val!=0){if(g.Val==-1){}else{this.nativeProxy._user32.TranslateMessage.async(this.nativeProxy.user32.SetWinEventHook.async,MSG).then(function(){this.nativeProxy._user32.DispatchMessageA.async(this.nativeProxy.user32.SetWinEventHook.async,MSG).then(function(){this.nativeProxy.terminal._GetMessage()},console.log)},console.log)}}else{this.nativeProxy.UnhookWinEvent.async(this.nativeProxy.terminal._user32.SetWinEventHook.async,this.nativeProxy.terminal.hwinEventHook).then(function(){if(this.nativeProxy.terminal._hProcess==null){return}this.nativeProxy.terminal.stopping._res();if(this.nativeProxy.terminal._kernel32.TerminateProcess(this.nativeProxy.terminal._hProcess,1067).Val==0){var h=this.nativeProxy.terminal._kernel32.GetLastError().Val;console.log("Unable to kill Terminal Process, error: "+h)}this.nativeProxy.terminal.stopping=null},function(h){console.log("REJECTED_UnhookWinEvent: "+h)})}},function(g){console.log("REJECTED_GETMessage: "+g)})};this._WriteBuffer=function(g){for(var h=0;h<g.length;++h){if(typeof(g)=="string"){this._WriteCharacter(g.charCodeAt(h),false)}else{this._WriteCharacter(g[h],false)}}};this._WriteCharacter=function(i,g){var j=GM.CreateVariable(20);j.Deref(0,2).toBuffer().writeUInt16LE(KEY_EVENT);j.Deref(4,4).toBuffer().writeUInt16LE(1);j.Deref(16,4).toBuffer().writeUInt32LE(g);j.Deref(14,1).toBuffer()[0]=i;j.Deref(8,2).toBuffer().writeUInt16LE(1);j.Deref(10,2).toBuffer().writeUInt16LE(this._user32.VkKeyScanA(i).Val);j.Deref(12,2).toBuffer().writeUInt16LE(this._user32.MapVirtualKeyA(this._user32.VkKeyScanA(i).Val,MAPVK_VK_TO_VSC).Val);var h=GM.CreateVariable(4);if(this._kernel32.WriteConsoleInputA(this._stdinput,j,1,h).Val==0){return(false)}j.Deref(4,4).toBuffer().writeUInt16LE(0);return(this._kernel32.WriteConsoleInputA(this._stdinput,j,1,h).Val!=0)};this._GetScreenBuffer=function(t,u,g,h){var j=GM.CreateVariable(22);if(this._kernel32.GetConsoleScreenBufferInfo(this._stdoutput,j).Val==0){throw ("Error getting screen buffer info")}var o=j.Deref(14,2).toBuffer().readUInt16LE()-j.Deref(10,2).toBuffer().readUInt16LE()+1;var n=j.Deref(16,2).toBuffer().readUInt16LE()-j.Deref(12,2).toBuffer().readUInt16LE()+1;if(arguments[3]==null){t=0;u=0;g=o-1;h=n-1}else{if(this._scrx!=0){t+=this._scrx;g+=this._scrx}if(this._scry!=0){u+=this._scry;h+=this._scry}this._scrx=this._scry=0}var m=GM.CreateVariable((g-t+1)*(h-u+1)*4);var r=GM.CreateVariable(4);r.Deref(0,2).toBuffer().writeUInt16LE(g-t+1,0);r.Deref(2,2).toBuffer().writeUInt16LE(h-u+1,0);var s=GM.CreateVariable(4);s.Deref(0,2).toBuffer().writeUInt16LE(0,0);s.Deref(2,2).toBuffer().writeUInt16LE(0,0);var p=GM.CreateVariable(8);p.buffer=p.toBuffer();p.buffer.writeUInt16LE(t,0);p.buffer.writeUInt16LE(u,2);p.buffer.writeUInt16LE(g,4);p.buffer.writeUInt16LE(h,6);if(this._kernel32.ReadConsoleOutputA(this._stdoutput,m,r.Deref(0,4).toBuffer().readUInt32LE(),s.Deref(0,4).toBuffer().readUInt32LE(),p).Val==0){throw ("Unable to read Console Output")}var q={data:[],attributes:[],width:g-t+1,height:h-u+1,x:t,y:u};var w,z,k,i,v,l=g-t+1;for(z=0;z<=(h-u);++z){q.data.push(Buffer.alloc(l));q.attributes.push(Buffer.alloc(l));k=m.Deref(z*l*4,l*4).toBuffer();for(w=0;w<l;++w){q.data.peek()[w]=k[w*4];q.attributes.peek()[w]=k[2+(w*4)]}}return(q)};this._SendDataBuffer=function(h){var i,j,g;for(i=0;i<h.height;++i){j=h.data[i];g=h.attributes[i];j.s=j.toString();this._stream.push(TranslateLine(h.x+1,h.y+i+1,j,g))}};this._SendScroll=function a(h,j){if(this._scrollTimer){return}var l=GM.CreateVariable(22);if(this._kernel32.GetConsoleScreenBufferInfo(this._stdoutput,l).Val==0){throw ("Error getting screen buffer info")}var n=l.Deref(14,2).toBuffer().readUInt16LE()-l.Deref(10,2).toBuffer().readUInt16LE()+1;var m=l.Deref(16,2).toBuffer().readUInt16LE()-l.Deref(12,2).toBuffer().readUInt16LE()+1;this._stream.push(GetEsc("H",[m-1,0]));for(var k=0;k>m;++k){this._stream.push(Buffer.from("\r\n"))}var g=this._GetScreenBuffer(0,0,n-1,m-1);this._SendDataBuffer(g);this._scrollTimer=setTimeout(function(q,p,o){var i=q._GetScreenBuffer(0,0,p-1,o-1);q._SendDataBuffer(i);q._scrollTimer=null},250,this,n,m)};this.StartCommand=function e(g){if(this._kernel32.CreateProcessA(GM.CreateVariable(g),0,0,0,1,CREATE_NEW_PROCESS_GROUP,0,0,si,pi).Val==0){console.log("Error Spawning CMD");return}this._kernel32.CloseHandle(pi.Deref(GM.PointerSize,GM.PointerSize).Deref());this._hProcess=pi.Deref(0,GM.PointerSize).Deref();this._hProcessID=pi.Deref(GM.PointerSize==4?8:16,4).toBuffer().readUInt32LE()}}function LOWORD(a){return(a&65535)}function HIWORD(a){return((a>>16)&65535)}function GetEsc(b,a){return(Buffer.from("\x1B["+a.join(";")+b))}function MeshConsole(a){require("MeshAgent").SendCommand({action:"msg",type:"console",value:JSON.stringify(a)})}function TranslateLine(r,s,f,a){var m,l,e,q,j,c,n,k,d,p,h,b,g=[],o=[GetEsc("H",[s,r])];if(typeof a=="number"){a=[a]}for(m=0;m<f.length;m++){if(n!=a[m]){k=(a[m]&7);k=((k&1)<<2)+(k&2)+((k&4)>>2);d=(a[m]&112)>>4;d=((d&1)<<2)+(d&2)+((d&4)>>2);p=(a[m]&16384);h=(a[m]&8)>>3;b=(a[m]&128);if(p!=q){if(p!=0){g.push(7)}else{g.push(0);l=7;e=0;j=0;c=0}q=p}if(k!=l){g.push(k+30);l=k}if(d!=e){g.push(d+40);e=d}if(h!=j){g.push(2-h);j=h}if(b!=c){if(b==0){g.push(e+40)}else{g.push(e+100);c=b}}if(g.length>0){o.push(GetEsc("m",g));g=[]}n=a[m]}o.push(Buffer.from(String.fromCharCode(f[m])))}return Buffer.concat(o)}module.exports=new windows_terminal();
\ No newline at end of file
db.js
+2
@@ -531,6 +531,7 @@ module.exports.CreateDB = function (parent, func) {
531 }
532 };
533 obj.GetAll = function (func) { obj.file.find({}).toArray(func); };
534 + obj.GetHash = function (id, func) { obj.file.find({ _id: id }).project({ _id: 0, hash: 1 }).toArray(func); };
535 obj.GetAllTypeNoTypeField = function (type, domain, func) { obj.file.find({ type: type, domain: domain }).project({ type: 0 }).toArray(func); };
536 obj.GetAllTypeNoTypeFieldMeshFiltered = function (meshes, domain, type, id, func) { var x = { type: type, domain: domain, meshid: { $in: meshes } }; if (id) { x._id = id; } obj.file.find(x, { type: 0 }).toArray(func); };
537 obj.GetAllType = function (type, func) { obj.file.find({ type: type }).toArray(func); };
@@ -624,6 +625,7 @@ module.exports.CreateDB = function (parent, func) {
625 }
626 };
627 obj.GetAll = function (func) { obj.file.find({}, func); };
628 + obj.GetHash = function (id, func) { obj.file.find({ _id: id }, { _id: 0, hash: 1 }, func); };
629 obj.GetAllTypeNoTypeField = function (type, domain, func) { obj.file.find({ type: type, domain: domain }, { type: 0 }, func); };
630 obj.GetAllTypeNoTypeFieldMeshFiltered = function (meshes, domain, type, id, func) { var x = { type: type, domain: domain, meshid: { $in: meshes } }; if (id) { x._id = id; } obj.file.find(x, { type: 0 }, func); };
631 obj.GetAllType = function (type, func) { obj.file.find({ type: type }, func); };
meshagent.js
+19
@@ -64,6 +64,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
64 db.Remove('if' + obj.dbNodeKey); // Remove interface information
65 db.Remove('nt' + obj.dbNodeKey); // Remove notes
66 db.Remove('lc' + obj.dbNodeKey); // Remove last connect time
67 + db.Remove('si' + obj.dbNodeKey); // Remove system information
68 db.RemoveSMBIOS(obj.dbNodeKey); // Remove SMBios data
69 db.RemoveAllNodeEvents(obj.dbNodeKey); // Remove all events for this node
70 db.removeAllPowerEventsForNode(obj.dbNodeKey); // Remove all power events for this node
@@ -909,6 +910,11 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
910 try { obj.send(JSON.stringify({ action: 'amtPolicy', amtPolicy: completeIntelAmtPolicy(common.Clone(mesh.amt)) })); } catch (ex) { }
911 }
912
913 + // Fetch system information
914 + db.GetHash('si' + obj.dbNodeKey, function (err, results) {
915 + if ((results != null) && (results.length == 1)) { obj.send(JSON.stringify({ action: 'sysinfo', hash: results[0].hash })); } else { obj.send(JSON.stringify({ action: 'sysinfo' })); }
916 + });
917 +
918 // Do this if IP location is enabled on this domain TODO: Set IP location per device group?
919 if (domain.iplocation == true) {
920 // Check if we already have IP location information for this node
@@ -1298,6 +1304,19 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
1304 }
1305 break;
1306 }
1307 + case 'sysinfo': {
1308 + //console.log('sysinfo', obj.nodeid, JSON.stringify(command.data.hash));
1309 + command.data._id = 'si' + obj.dbNodeKey;
1310 + db.Set(command.data); // Update system information in the database.
1311 + break;
1312 + }
1313 + case 'sysinfocheck': {
1314 + // Check system information update
1315 + db.GetHash('si' + obj.dbNodeKey, function (err, results) {
1316 + if ((results != null) && (results.length == 1)) { obj.send(JSON.stringify({ action: 'sysinfo', hash: results[0].hash })); } else { obj.send(JSON.stringify({ action: 'sysinfo' })); }
1317 + });
1318 + break;
1319 + }
1320 default: {
1321 parent.agentStats.unknownAgentActionCount++;
1322 console.log('Unknown agent action (' + obj.remoteaddrport + '): ' + command.action + '.');
meshuser.js
+1
@@ -1937,6 +1937,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
1937 db.Remove('if' + node._id); // Remove interface information
1938 db.Remove('nt' + node._id); // Remove notes
1939 db.Remove('lc' + node._id); // Remove last connect time
1940 + db.Remove('si' + node._id); // Remove system information
1941 db.RemoveSMBIOS(node._id); // Remove SMBios data
1942 db.RemoveAllNodeEvents(node._id); // Remove all events for this node
1943 db.removeAllPowerEventsForNode(node._id); // Remove all power events for this node
package.json
+2 -1
@@ -1,6 +1,6 @@
1 {
2 "name": "meshcentral",
3 - "version": "0.3.9-g",
3 + "version": "0.3.9-h",
4 "keywords": [
5 "Remote Management",
6 "Intel AMT",
@@ -39,6 +39,7 @@
39 "ipcheck": "^0.1.0",
40 "meshcentral": "*",
41 "minimist": "^1.2.0",
42 + "mongojs": "^2.6.0",
43 "multiparty": "^4.2.1",
44 "nedb": "^1.8.0",
45 "node-forge": "^0.8.4",