Started work on hardware inventory support.

This commit is contained in:
Ylian Saint-Hilaire 2019-08-06 17:58:29 -07:00
parent 321f35ede8
commit bfd56a8a64
19 changed files with 1087 additions and 15 deletions

View File

@ -60,13 +60,16 @@
<Compile Include="agents\modules_meshcore\amt-wsman.js" />
<Compile Include="agents\modules_meshcore\amt-xml.js" />
<Compile Include="agents\modules_meshcore\amt.js" />
<Compile Include="agents\modules_meshcore\identifiers.js" />
<Compile Include="agents\modules_meshcore\linux-dbus.js" />
<Compile Include="agents\modules_meshcore\monitor-border.js" />
<Compile Include="agents\modules_meshcore\power-monitor.js" />
<Compile Include="agents\modules_meshcore\smbios.js" />
<Compile Include="agents\modules_meshcore\sysinfo.js" />
<Compile Include="agents\modules_meshcore\wifi-scanner-windows.js" />
<Compile Include="agents\modules_meshcore\wifi-scanner.js" />
<Compile Include="agents\modules_meshcore\win-console.js" />
<Compile Include="agents\modules_meshcore\win-info.js" />
<Compile Include="agents\modules_meshcore\win-terminal.js" />
<Compile Include="agents\modules_meshcore_min\amt-lme.min.js" />
<Compile Include="agents\modules_meshcore_min\amt-mei.min.js" />

View File

@ -822,6 +822,53 @@ function createMeshCore(agent)
sendConsoleText('getScript: ' + JSON.stringify(data));
break;
}
case 'sysinfo': {
// Fetch system information
if (process.platform != 'win32') break; // Remove this when Linux/MacOS support this.
try {
var results = { hardware: require('identifiers').get(), pendingReboot: require('win-info').pendingReboot() }; // Hardware & pending reboot
if (results.hardware.windows) {
var x = results.hardware.windows.osinfo;
try { delete x.FreePhysicalMemory; } catch (ex) { }
try { delete x.FreeSpaceInPagingFiles; } catch (ex) { }
try { delete x.FreeVirtualMemory; } catch (ex) { }
try { delete x.LocalDateTime; } catch (ex) { }
try { delete x.MaxProcessMemorySize; } catch (ex) { }
try { delete x.TotalVirtualMemorySize; } catch (ex) { }
try { delete x.TotalVisibleMemorySize; } catch (ex) { }
}
/*
if (process.platform == 'win32')
{
var defragResult = function (r)
{
if (typeof r == 'object') { results[this.callname] = r; }
if (this.callname == 'defrag')
{
var pr = require('win-info').installedApps(); // Installed apps
pr.callname = 'installedApps';
pr.sessionid = data.sessionid;
pr.then(defragResult, defragResult);
}
else
{
results.winpatches = require('win-info').qfe(); // Windows patches
results.hash = require('SHA384Stream').create().syncHash(JSON.stringify(results)).toString('hex');
if (data.hash != results.hash) { mesh.SendCommand({ "action": "sysinfo", "sessionid": this.sessionid, "data": results }); }
}
}
var pr = require('win-info').defrag({ volume: 'C:' }); // Defrag
pr.callname = 'defrag';
pr.sessionid = data.sessionid;
pr.then(defragResult, defragResult);
} else {
*/
results.hash = require('SHA384Stream').create().syncHash(JSON.stringify(results)).toString('hex');
if (data.hash != results.hash) { mesh.SendCommand({ "action": "sysinfo", "sessionid": this.sessionid, "data": results }); }
//}
} catch (ex) { }
break;
}
case 'ping': { mesh.SendCommand('{"action":"pong"}'); break; }
case 'pong': { break; }
default:
@ -1603,7 +1650,7 @@ function createMeshCore(agent)
var response = null;
switch (cmd) {
case 'help': { // Displays available commands
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.';
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.';
break;
}
/*
@ -1626,7 +1673,11 @@ function createMeshCore(agent)
break;
*/
case 'av':
if (process.platform == 'win32') { response = JSON.stringify(require('win-info').av()); } else { response = 'Not supported on the platform'; }
if (process.platform == 'win32') {
response = JSON.stringify(require('win-info').av(), null, 1);
} else {
response = 'Not supported on the platform';
}
break;
case 'log':
if (args['_'].length != 1) { response = 'Proper usage: log "sample text"'; } else { MeshServerLog(args['_'][0]); response = 'ok'; }
@ -1763,6 +1814,41 @@ function createMeshCore(agent)
}
break;
}
case 'cpuinfo': { // Return system information
// CPU & memory utilization
pr = require('sysinfo').cpuUtilization();
pr.sessionid = sessionid;
pr.then(function (data) {
sendConsoleText(JSON.stringify({ cpu: data, memory: require('sysinfo').memUtilization() }, null, 1), this.sessionid);
}, function (e) {
sendConsoleText(e);
});
break;
}
case 'sysinfo': { // Return system information
var results = { hardware: require('identifiers').get(), pendingReboot: require('win-info').pendingReboot() }; // Hardware && pending reboot
if (process.platform == 'win32') {
var defragResult = function (r) {
if (typeof r == 'object') { results[this.callname] = r; }
if (this.callname == 'defrag') {
var pr = require('win-info').installedApps(); // Installed apps
pr.sessionid = sessionid;
pr.callname = 'installedApps';
pr.then(defragResult, defragResult);
} else {
results.winpatches = require('win-info').qfe(); // Windows patches
sendConsoleText(JSON.stringify(results, null, 1), this.sessionid);
}
}
var pr = require('win-info').defrag({ volume: 'C:' }); // Defrag
pr.sessionid = sessionid;
pr.callname = 'defrag';
pr.then(defragResult, defragResult);
} else {
response = JSON.stringify(results, null, 1);
}
break;
}
case 'info': { // Return information about the agent and agent core module
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 + '.';
if (amt != null) { response += '\r\nBuilt-in LMS: ' + ['Disabled', 'Connecting..', 'Connected'][amt.lmsstate] + '.'; }
@ -2241,8 +2327,9 @@ function createMeshCore(agent)
if ((flags & 4) && (process.platform == 'win32')) {
// Update anti-virus information
var av;
try { av = require('win-info').av(); } catch (ex) { av = []; }
var av, pr;
try { av = require('win-info').av(); } catch (ex) { av = []; } // Antivirus
//if (process.platform == 'win32') { try { pr = require('win-info').pendingReboot(); } catch (ex) { pr = null; } } // Pending reboot
if ((meshCoreObj.av == null) || (JSON.stringify(meshCoreObj.av) != JSON.stringify(av))) { meshCoreObj.av = av; mesh.SendCommand(meshCoreObj); }
}
}

View File

@ -822,6 +822,53 @@ function createMeshCore(agent)
sendConsoleText('getScript: ' + JSON.stringify(data));
break;
}
case 'sysinfo': {
// Fetch system information
if (process.platform != 'win32') break; // Remove this when Linux/MacOS support this.
try {
var results = { hardware: require('identifiers').get(), pendingReboot: require('win-info').pendingReboot() }; // Hardware & pending reboot
if (results.hardware.windows) {
var x = results.hardware.windows.osinfo;
try { delete x.FreePhysicalMemory; } catch (ex) { }
try { delete x.FreeSpaceInPagingFiles; } catch (ex) { }
try { delete x.FreeVirtualMemory; } catch (ex) { }
try { delete x.LocalDateTime; } catch (ex) { }
try { delete x.MaxProcessMemorySize; } catch (ex) { }
try { delete x.TotalVirtualMemorySize; } catch (ex) { }
try { delete x.TotalVisibleMemorySize; } catch (ex) { }
}
/*
if (process.platform == 'win32')
{
var defragResult = function (r)
{
if (typeof r == 'object') { results[this.callname] = r; }
if (this.callname == 'defrag')
{
var pr = require('win-info').installedApps(); // Installed apps
pr.callname = 'installedApps';
pr.sessionid = data.sessionid;
pr.then(defragResult, defragResult);
}
else
{
results.winpatches = require('win-info').qfe(); // Windows patches
results.hash = require('SHA384Stream').create().syncHash(JSON.stringify(results)).toString('hex');
if (data.hash != results.hash) { mesh.SendCommand({ "action": "sysinfo", "sessionid": this.sessionid, "data": results }); }
}
}
var pr = require('win-info').defrag({ volume: 'C:' }); // Defrag
pr.callname = 'defrag';
pr.sessionid = data.sessionid;
pr.then(defragResult, defragResult);
} else {
*/
results.hash = require('SHA384Stream').create().syncHash(JSON.stringify(results)).toString('hex');
if (data.hash != results.hash) { mesh.SendCommand({ "action": "sysinfo", "sessionid": this.sessionid, "data": results }); }
//}
} catch (ex) { }
break;
}
case 'ping': { mesh.SendCommand('{"action":"pong"}'); break; }
case 'pong': { break; }
default:
@ -1603,7 +1650,7 @@ function createMeshCore(agent)
var response = null;
switch (cmd) {
case 'help': { // Displays available commands
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.';
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.';
break;
}
/*
@ -1626,7 +1673,11 @@ function createMeshCore(agent)
break;
*/
case 'av':
if (process.platform == 'win32') { response = JSON.stringify(require('win-info').av()); } else { response = 'Not supported on the platform'; }
if (process.platform == 'win32') {
response = JSON.stringify(require('win-info').av(), null, 1);
} else {
response = 'Not supported on the platform';
}
break;
case 'log':
if (args['_'].length != 1) { response = 'Proper usage: log "sample text"'; } else { MeshServerLog(args['_'][0]); response = 'ok'; }
@ -1763,6 +1814,41 @@ function createMeshCore(agent)
}
break;
}
case 'cpuinfo': { // Return system information
// CPU & memory utilization
pr = require('sysinfo').cpuUtilization();
pr.sessionid = sessionid;
pr.then(function (data) {
sendConsoleText(JSON.stringify({ cpu: data, memory: require('sysinfo').memUtilization() }, null, 1), this.sessionid);
}, function (e) {
sendConsoleText(e);
});
break;
}
case 'sysinfo': { // Return system information
var results = { hardware: require('identifiers').get(), pendingReboot: require('win-info').pendingReboot() }; // Hardware && pending reboot
if (process.platform == 'win32') {
var defragResult = function (r) {
if (typeof r == 'object') { results[this.callname] = r; }
if (this.callname == 'defrag') {
var pr = require('win-info').installedApps(); // Installed apps
pr.sessionid = sessionid;
pr.callname = 'installedApps';
pr.then(defragResult, defragResult);
} else {
results.winpatches = require('win-info').qfe(); // Windows patches
sendConsoleText(JSON.stringify(results, null, 1), this.sessionid);
}
}
var pr = require('win-info').defrag({ volume: 'C:' }); // Defrag
pr.sessionid = sessionid;
pr.callname = 'defrag';
pr.then(defragResult, defragResult);
} else {
response = JSON.stringify(results, null, 1);
}
break;
}
case 'info': { // Return information about the agent and agent core module
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 + '.';
if (amt != null) { response += '\r\nBuilt-in LMS: ' + ['Disabled', 'Connecting..', 'Connected'][amt.lmsstate] + '.'; }
@ -2241,8 +2327,9 @@ function createMeshCore(agent)
if ((flags & 4) && (process.platform == 'win32')) {
// Update anti-virus information
var av;
try { av = require('win-info').av(); } catch (ex) { av = []; }
var av, pr;
try { av = require('win-info').av(); } catch (ex) { av = []; } // Antivirus
//if (process.platform == 'win32') { try { pr = require('win-info').pendingReboot(); } catch (ex) { pr = null; } } // Pending reboot
if ((meshCoreObj.av == null) || (JSON.stringify(meshCoreObj.av) != JSON.stringify(av))) { meshCoreObj.av = av; mesh.SendCommand(meshCoreObj); }
}
}

View File

@ -0,0 +1,208 @@
/*
Copyright 2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
function trimIdentifiers(val)
{
for(var v in val)
{
if (!val[v] || val[v] == 'None' || val[v] == '') { delete val[v]; }
}
}
function linux_identifiers()
{
var identifiers = {};
var ret = {};
var values = {};
if (!require('fs').existsSync('/sys/class/dmi/id')) { throw ('this platform does not have DMI statistics'); }
var entries = require('fs').readdirSync('/sys/class/dmi/id');
for(var i in entries)
{
if (require('fs').statSync('/sys/class/dmi/id/' + entries[i]).isFile())
{
ret[entries[i]] = require('fs').readFileSync('/sys/class/dmi/id/' + entries[i]).toString().trim();
if (ret[entries[i]] == 'None') { delete ret[entries[i]];}
}
}
identifiers['bios_date'] = ret['bios_date'];
identifiers['bios_vendor'] = ret['bios_vendor'];
identifiers['bios_version'] = ret['bios_version'];
identifiers['board_name'] = ret['board_name'];
identifiers['board_serial'] = ret['board_serial'];
identifiers['board_vendor'] = ret['board_vendor'];
identifiers['board_version'] = ret['board_version'];
identifiers['product_uuid'] = ret['product_uuid'];
values.identifiers = identifiers;
values.linux = ret;
trimIdentifiers(values.identifiers);
return (values);
}
function windows_wmic_results(str)
{
var lines = str.trim().split('\r\n');
var keys = lines[0].split(',');
var i, key, keyval;
var tokens;
var result = [];
for (i = 1; i < lines.length; ++i)
{
var obj = {};
tokens = lines[i].split(',');
for (key = 0; key < keys.length; ++key)
{
if (tokens[key].trim())
{
obj[keys[key].trim()] = tokens[key].trim();
}
}
result.push(obj);
}
return (result);
}
function windows_identifiers()
{
var ret = { windows: {}}; values = {}; var items; var i; var item;
var child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'bios', 'get', '/VALUE']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.waitExit();
var items = child.stdout.str.split('\r\r\n');
for(i in items)
{
item = items[i].split('=');
values[item[0]] = item[1];
}
ret['identifiers'] = {};
ret['identifiers']['bios_date'] = values['ReleaseDate'];
ret['identifiers']['bios_vendor'] = values['Manufacturer'];
ret['identifiers']['bios_version'] = values['SMBIOSBIOSVersion'];
child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'BASEBOARD', 'get', '/VALUE']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.waitExit();
var items = child.stdout.str.split('\r\r\n');
for (i in items)
{
item = items[i].split('=');
values[item[0]] = item[1];
}
ret['identifiers']['board_name'] = values['Product'];
ret['identifiers']['board_serial'] = values['SerialNumber'];
ret['identifiers']['board_vendor'] = values['Manufacturer'];
ret['identifiers']['board_version'] = values['Version'];
child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'CSProduct', 'get', '/VALUE']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.waitExit();
var items = child.stdout.str.split('\r\r\n');
for (i in items)
{
item = items[i].split('=');
values[item[0]] = item[1];
}
ret['identifiers']['product_uuid'] = values['UUID'];
trimIdentifiers(ret.identifiers);
child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'MEMORYCHIP', 'LIST', '/FORMAT:CSV']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.waitExit();
ret.windows.memory = windows_wmic_results(child.stdout.str);
child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'OS', 'GET', '/FORMAT:CSV']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.waitExit();
ret.windows.osinfo = windows_wmic_results(child.stdout.str)[0];
child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'PARTITION', 'LIST', '/FORMAT:CSV']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.waitExit();
ret.windows.partitions = windows_wmic_results(child.stdout.str);
return (ret);
}
function macos_identifiers()
{
var ret = { identifiers: {} };
var child;
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep board-id | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
child.waitExit();
ret.identifiers.board_name = child.stdout.str.trim();
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformSerialNumber | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
child.waitExit();
ret.identifiers.board_serial = child.stdout.str.trim();
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep manufacturer | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
child.waitExit();
ret.identifiers.board_vendor = child.stdout.str.trim();
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep version | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
child.waitExit();
ret.identifiers.board_version = child.stdout.str.trim();
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformUUID | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
child.waitExit();
ret.identifiers.product_uuid = child.stdout.str.trim();
trimIdentifiers(ret.identifiers);
return (ret);
}
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;
}
// bios_date = BIOS->ReleaseDate
// bios_vendor = BIOS->Manufacturer
// bios_version = BIOS->SMBIOSBIOSVersion
// board_name = BASEBOARD->Product = ioreg/board-id
// board_serial = BASEBOARD->SerialNumber = ioreg/serial-number | ioreg/IOPlatformSerialNumber
// board_vendor = BASEBOARD->Manufacturer = ioreg/manufacturer
// board_version = BASEBOARD->Version

View File

@ -0,0 +1,230 @@
/*
Copyright 2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const PDH_FMT_LONG = 0x00000100;
const PDH_FMT_DOUBLE = 0x00000200;
var promise = require('promise');
if (process.platform == 'win32')
{
var GM = require('_GenericMarshal');
GM.kernel32 = GM.CreateNativeProxy('kernel32.dll');
GM.kernel32.CreateMethod('GlobalMemoryStatusEx');
GM.pdh = GM.CreateNativeProxy('pdh.dll');
GM.pdh.CreateMethod('PdhAddEnglishCounterA');
GM.pdh.CreateMethod('PdhCloseQuery');
GM.pdh.CreateMethod('PdhCollectQueryData');
GM.pdh.CreateMethod('PdhGetFormattedCounterValue');
GM.pdh.CreateMethod('PdhGetFormattedCounterArrayA');
GM.pdh.CreateMethod('PdhOpenQueryA');
GM.pdh.CreateMethod('PdhRemoveCounter');
}
function windows_cpuUtilization()
{
var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
p.counter = GM.CreateVariable(16);
p.cpu = GM.CreatePointer();
p.cpuTotal = GM.CreatePointer();
var err = 0;
if ((err = GM.pdh.PdhOpenQueryA(0, 0, p.cpu).Val) != 0) { p._rej(err); return; }
// This gets the CPU Utilization for each proc
if ((err = GM.pdh.PdhAddEnglishCounterA(p.cpu.Deref(), GM.CreateVariable('\\Processor(*)\\% Processor Time'), 0, p.cpuTotal).Val) != 0) { p._rej(err); return; }
if ((err = GM.pdh.PdhCollectQueryData(p.cpu.Deref()).Val != 0)) { p._rej(err); return; }
p._timeout = setTimeout(function (po)
{
var u = { cpus: [] };
var bufSize = GM.CreateVariable(4);
var itemCount = GM.CreateVariable(4);
var buffer, szName, item;
var e;
if ((e = GM.pdh.PdhCollectQueryData(po.cpu.Deref()).Val != 0)) { po._rej(e); return; }
if ((e = GM.pdh.PdhGetFormattedCounterArrayA(po.cpuTotal.Deref(), PDH_FMT_DOUBLE, bufSize, itemCount, 0).Val) == -2147481646)
{
buffer = GM.CreateVariable(bufSize.toBuffer().readUInt32LE());
}
else
{
po._rej(e);
return;
}
if ((e = GM.pdh.PdhGetFormattedCounterArrayA(po.cpuTotal.Deref(), PDH_FMT_DOUBLE, bufSize, itemCount, buffer).Val) != 0) { po._rej(e); return; }
for(var i=0;i<itemCount.toBuffer().readUInt32LE();++i)
{
item = buffer.Deref(i * 24, 24);
szName = item.Deref(0, GM.PointerSize).Deref();
if (szName.String == '_Total')
{
u.total = item.Deref(16, 8).toBuffer().readDoubleLE().toFixed(2);
}
else
{
u.cpus[parseInt(szName.String)] = item.Deref(16, 8).toBuffer().readDoubleLE().toFixed(2);
}
}
GM.pdh.PdhRemoveCounter(po.cpuTotal.Deref());
GM.pdh.PdhCloseQuery(po.cpu.Deref());
p._res(u);
}, 100, p);
return (p);
}
function windows_memUtilization()
{
var info = GM.CreateVariable(64);
info.Deref(0, 4).toBuffer().writeUInt32LE(64);
GM.kernel32.GlobalMemoryStatusEx(info);
var ret =
{
MemTotal: require('bignum').fromBuffer(info.Deref(8, 8).toBuffer(), { endian: 'little' }),
MemFree: require('bignum').fromBuffer(info.Deref(16, 8).toBuffer(), { endian: 'little' })
};
ret.percentFree = ((ret.MemFree.div(require('bignum')('1048576')).toNumber() / ret.MemTotal.div(require('bignum')('1048576')).toNumber()) * 100).toFixed(2);
ret.percentConsumed = ((ret.MemTotal.sub(ret.MemFree).div(require('bignum')('1048576')).toNumber() / ret.MemTotal.div(require('bignum')('1048576')).toNumber()) * 100).toFixed(2);
ret.MemTotal = ret.MemTotal.toString();
ret.MemFree = ret.MemFree.toString();
return (ret);
}
function linux_cpuUtilization()
{
var ret = { cpus: [] };
var info = require('fs').readFileSync('/proc/stat');
var lines = info.toString().split('\n');
var columns;
var x, y;
var sum, idle, utilization;
for (var i in lines)
{
columns = lines[i].split(' ');
if (!columns[0].startsWith('cpu')) { break; }
x = 0, sum = 0;
while (columns[++x] == '');
for (y = x; y < columns.length; ++y) { sum += parseInt(columns[y]); }
idle = parseInt(columns[3 + x]);
utilization = (100 - ((idle / sum) * 100)).toFixed(2);
if (!ret.total)
{
ret.total = utilization;
}
else
{
ret.cpus.push(utilization);
}
}
var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
p._res(ret);
return (p);
}
function linux_memUtilization()
{
var ret = {};
var info = require('fs').readFileSync('/proc/meminfo').toString().split('\n');
var tokens;
for(var i in info)
{
tokens = info[i].split(' ');
switch(tokens[0])
{
case 'MemTotal:':
ret.total = parseInt(tokens[tokens.length - 2]);
break;
case 'MemFree:':
ret.free = parseInt(tokens[tokens.length - 2]);
break;
}
}
ret.percentFree = ((ret.free / ret.total) * 100).toFixed(2);
ret.percentConsumed = (((ret.total - ret.free) / ret.total) * 100).toFixed(2);
return (ret);
}
function macos_cpuUtilization()
{
var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = '';
child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stdin.write('top -l 1 | grep -E "^CPU"\nexit\n');
child.waitExit();
var lines = child.stdout.str.split('\n');
if (lines[0].length > 0)
{
var usage = lines[0].split(':')[1];
var bdown = usage.split(',');
var tot = parseFloat(bdown[0].split('%')[0].trim()) + parseFloat(bdown[1].split('%')[0].trim());
ret._res({total: tot, cpus: []});
}
else
{
ret._rej('parse error');
}
return (ret);
}
function macos_memUtilization()
{
var mem = { };
var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = '';
child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stdin.write('top -l 1 | grep -E "^Phys"\nexit\n');
child.waitExit();
var lines = child.stdout.str.split('\n');
if (lines[0].length > 0)
{
var usage = lines[0].split(':')[1];
var bdown = usage.split(',');
mem.MemTotal = parseInt(bdown[0].trim().split(' ')[0]);
mem.MemFree = parseInt(bdown[1].trim().split(' ')[0]);
mem.percentFree = ((mem.MemFree / mem.MemTotal) * 100).toFixed(2);
mem.percentConsumed = (((mem.MemTotal - mem.MemFree)/ mem.MemTotal) * 100).toFixed(2);
return (mem);
}
else
{
throw ('Parse Error');
}
}
switch(process.platform)
{
case 'linux':
module.exports = { cpuUtilization: linux_cpuUtilization, memUtilization: linux_memUtilization };
break;
case 'win32':
module.exports = { cpuUtilization: windows_cpuUtilization, memUtilization: windows_memUtilization };
break;
case 'darwin':
module.exports = { cpuUtilization: macos_cpuUtilization, memUtilization: macos_memUtilization };
break;
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,208 @@
/*
Copyright 2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
function trimIdentifiers(val)
{
for(var v in val)
{
if (!val[v] || val[v] == 'None' || val[v] == '') { delete val[v]; }
}
}
function linux_identifiers()
{
var identifiers = {};
var ret = {};
var values = {};
if (!require('fs').existsSync('/sys/class/dmi/id')) { throw ('this platform does not have DMI statistics'); }
var entries = require('fs').readdirSync('/sys/class/dmi/id');
for(var i in entries)
{
if (require('fs').statSync('/sys/class/dmi/id/' + entries[i]).isFile())
{
ret[entries[i]] = require('fs').readFileSync('/sys/class/dmi/id/' + entries[i]).toString().trim();
if (ret[entries[i]] == 'None') { delete ret[entries[i]];}
}
}
identifiers['bios_date'] = ret['bios_date'];
identifiers['bios_vendor'] = ret['bios_vendor'];
identifiers['bios_version'] = ret['bios_version'];
identifiers['board_name'] = ret['board_name'];
identifiers['board_serial'] = ret['board_serial'];
identifiers['board_vendor'] = ret['board_vendor'];
identifiers['board_version'] = ret['board_version'];
identifiers['product_uuid'] = ret['product_uuid'];
values.identifiers = identifiers;
values.linux = ret;
trimIdentifiers(values.identifiers);
return (values);
}
function windows_wmic_results(str)
{
var lines = str.trim().split('\r\n');
var keys = lines[0].split(',');
var i, key, keyval;
var tokens;
var result = [];
for (i = 1; i < lines.length; ++i)
{
var obj = {};
tokens = lines[i].split(',');
for (key = 0; key < keys.length; ++key)
{
if (tokens[key].trim())
{
obj[keys[key].trim()] = tokens[key].trim();
}
}
result.push(obj);
}
return (result);
}
function windows_identifiers()
{
var ret = { windows: {}}; values = {}; var items; var i; var item;
var child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'bios', 'get', '/VALUE']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.waitExit();
var items = child.stdout.str.split('\r\r\n');
for(i in items)
{
item = items[i].split('=');
values[item[0]] = item[1];
}
ret['identifiers'] = {};
ret['identifiers']['bios_date'] = values['ReleaseDate'];
ret['identifiers']['bios_vendor'] = values['Manufacturer'];
ret['identifiers']['bios_version'] = values['SMBIOSBIOSVersion'];
child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'BASEBOARD', 'get', '/VALUE']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.waitExit();
var items = child.stdout.str.split('\r\r\n');
for (i in items)
{
item = items[i].split('=');
values[item[0]] = item[1];
}
ret['identifiers']['board_name'] = values['Product'];
ret['identifiers']['board_serial'] = values['SerialNumber'];
ret['identifiers']['board_vendor'] = values['Manufacturer'];
ret['identifiers']['board_version'] = values['Version'];
child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'CSProduct', 'get', '/VALUE']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.waitExit();
var items = child.stdout.str.split('\r\r\n');
for (i in items)
{
item = items[i].split('=');
values[item[0]] = item[1];
}
ret['identifiers']['product_uuid'] = values['UUID'];
trimIdentifiers(ret.identifiers);
child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'MEMORYCHIP', 'LIST', '/FORMAT:CSV']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.waitExit();
ret.windows.memory = windows_wmic_results(child.stdout.str);
child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'OS', 'GET', '/FORMAT:CSV']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.waitExit();
ret.windows.osinfo = windows_wmic_results(child.stdout.str)[0];
child = require('child_process').execFile(process.env['windir'] + '\\System32\\wbem\\wmic.exe', ['wmic', 'PARTITION', 'LIST', '/FORMAT:CSV']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.waitExit();
ret.windows.partitions = windows_wmic_results(child.stdout.str);
return (ret);
}
function macos_identifiers()
{
var ret = { identifiers: {} };
var child;
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep board-id | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
child.waitExit();
ret.identifiers.board_name = child.stdout.str.trim();
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformSerialNumber | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
child.waitExit();
ret.identifiers.board_serial = child.stdout.str.trim();
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep manufacturer | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
child.waitExit();
ret.identifiers.board_vendor = child.stdout.str.trim();
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep version | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
child.waitExit();
ret.identifiers.board_version = child.stdout.str.trim();
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformUUID | awk -F= \'{ split($2, res, "\\""); print res[2]; }\'\nexit\n');
child.waitExit();
ret.identifiers.product_uuid = child.stdout.str.trim();
trimIdentifiers(ret.identifiers);
return (ret);
}
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;
}
// bios_date = BIOS->ReleaseDate
// bios_vendor = BIOS->Manufacturer
// bios_version = BIOS->SMBIOSBIOSVersion
// board_name = BASEBOARD->Product = ioreg/board-id
// board_serial = BASEBOARD->SerialNumber = ioreg/serial-number | ioreg/IOPlatformSerialNumber
// board_vendor = BASEBOARD->Manufacturer = ioreg/manufacturer
// board_version = BASEBOARD->Version

View File

@ -0,0 +1,230 @@
/*
Copyright 2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const PDH_FMT_LONG = 0x00000100;
const PDH_FMT_DOUBLE = 0x00000200;
var promise = require('promise');
if (process.platform == 'win32')
{
var GM = require('_GenericMarshal');
GM.kernel32 = GM.CreateNativeProxy('kernel32.dll');
GM.kernel32.CreateMethod('GlobalMemoryStatusEx');
GM.pdh = GM.CreateNativeProxy('pdh.dll');
GM.pdh.CreateMethod('PdhAddEnglishCounterA');
GM.pdh.CreateMethod('PdhCloseQuery');
GM.pdh.CreateMethod('PdhCollectQueryData');
GM.pdh.CreateMethod('PdhGetFormattedCounterValue');
GM.pdh.CreateMethod('PdhGetFormattedCounterArrayA');
GM.pdh.CreateMethod('PdhOpenQueryA');
GM.pdh.CreateMethod('PdhRemoveCounter');
}
function windows_cpuUtilization()
{
var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
p.counter = GM.CreateVariable(16);
p.cpu = GM.CreatePointer();
p.cpuTotal = GM.CreatePointer();
var err = 0;
if ((err = GM.pdh.PdhOpenQueryA(0, 0, p.cpu).Val) != 0) { p._rej(err); return; }
// This gets the CPU Utilization for each proc
if ((err = GM.pdh.PdhAddEnglishCounterA(p.cpu.Deref(), GM.CreateVariable('\\Processor(*)\\% Processor Time'), 0, p.cpuTotal).Val) != 0) { p._rej(err); return; }
if ((err = GM.pdh.PdhCollectQueryData(p.cpu.Deref()).Val != 0)) { p._rej(err); return; }
p._timeout = setTimeout(function (po)
{
var u = { cpus: [] };
var bufSize = GM.CreateVariable(4);
var itemCount = GM.CreateVariable(4);
var buffer, szName, item;
var e;
if ((e = GM.pdh.PdhCollectQueryData(po.cpu.Deref()).Val != 0)) { po._rej(e); return; }
if ((e = GM.pdh.PdhGetFormattedCounterArrayA(po.cpuTotal.Deref(), PDH_FMT_DOUBLE, bufSize, itemCount, 0).Val) == -2147481646)
{
buffer = GM.CreateVariable(bufSize.toBuffer().readUInt32LE());
}
else
{
po._rej(e);
return;
}
if ((e = GM.pdh.PdhGetFormattedCounterArrayA(po.cpuTotal.Deref(), PDH_FMT_DOUBLE, bufSize, itemCount, buffer).Val) != 0) { po._rej(e); return; }
for(var i=0;i<itemCount.toBuffer().readUInt32LE();++i)
{
item = buffer.Deref(i * 24, 24);
szName = item.Deref(0, GM.PointerSize).Deref();
if (szName.String == '_Total')
{
u.total = item.Deref(16, 8).toBuffer().readDoubleLE();
}
else
{
u.cpus[parseInt(szName.String)] = item.Deref(16, 8).toBuffer().readDoubleLE();
}
}
GM.pdh.PdhRemoveCounter(po.cpuTotal.Deref());
GM.pdh.PdhCloseQuery(po.cpu.Deref());
p._res(u);
}, 100, p);
return (p);
}
function windows_memUtilization()
{
var info = GM.CreateVariable(64);
info.Deref(0, 4).toBuffer().writeUInt32LE(64);
GM.kernel32.GlobalMemoryStatusEx(info);
var ret =
{
MemTotal: require('bignum').fromBuffer(info.Deref(8, 8).toBuffer(), { endian: 'little' }),
MemFree: require('bignum').fromBuffer(info.Deref(16, 8).toBuffer(), { endian: 'little' })
};
ret.percentFree = ((ret.MemFree.div(require('bignum')('1048576')).toNumber() / ret.MemTotal.div(require('bignum')('1048576')).toNumber()) * 100);//.toFixed(2);
ret.percentConsumed = ((ret.MemTotal.sub(ret.MemFree).div(require('bignum')('1048576')).toNumber() / ret.MemTotal.div(require('bignum')('1048576')).toNumber()) * 100);//.toFixed(2);
ret.MemTotal = ret.MemTotal.toString();
ret.MemFree = ret.MemFree.toString();
return (ret);
}
function linux_cpuUtilization()
{
var ret = { cpus: [] };
var info = require('fs').readFileSync('/proc/stat');
var lines = info.toString().split('\n');
var columns;
var x, y;
var sum, idle, utilization;
for (var i in lines)
{
columns = lines[i].split(' ');
if (!columns[0].startsWith('cpu')) { break; }
x = 0, sum = 0;
while (columns[++x] == '');
for (y = x; y < columns.length; ++y) { sum += parseInt(columns[y]); }
idle = parseInt(columns[3 + x]);
utilization = (100 - ((idle / sum) * 100)); //.toFixed(2);
if (!ret.total)
{
ret.total = utilization;
}
else
{
ret.cpus.push(utilization);
}
}
var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });
p._res(ret);
return (p);
}
function linux_memUtilization()
{
var ret = {};
var info = require('fs').readFileSync('/proc/meminfo').toString().split('\n');
var tokens;
for(var i in info)
{
tokens = info[i].split(' ');
switch(tokens[0])
{
case 'MemTotal:':
ret.total = parseInt(tokens[tokens.length - 2]);
break;
case 'MemFree:':
ret.free = parseInt(tokens[tokens.length - 2]);
break;
}
}
ret.percentFree = ((ret.free / ret.total) * 100);//.toFixed(2);
ret.percentConsumed = (((ret.total - ret.free) / ret.total) * 100);//.toFixed(2);
return (ret);
}
function macos_cpuUtilization()
{
var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = '';
child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stdin.write('top -l 1 | grep -E "^CPU"\nexit\n');
child.waitExit();
var lines = child.stdout.str.split('\n');
if (lines[0].length > 0)
{
var usage = lines[0].split(':')[1];
var bdown = usage.split(',');
var tot = parseFloat(bdown[0].split('%')[0].trim()) + parseFloat(bdown[1].split('%')[0].trim());
ret._res({total: tot, cpus: []});
}
else
{
ret._rej('parse error');
}
return (ret);
}
function macos_memUtilization()
{
var mem = { };
var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = '';
child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stdin.write('top -l 1 | grep -E "^Phys"\nexit\n');
child.waitExit();
var lines = child.stdout.str.split('\n');
if (lines[0].length > 0)
{
var usage = lines[0].split(':')[1];
var bdown = usage.split(',');
mem.MemTotal = parseInt(bdown[0].trim().split(' ')[0]);
mem.MemFree = parseInt(bdown[1].trim().split(' ')[0]);
mem.percentFree = ((mem.MemFree / mem.MemTotal) * 100);//.toFixed(2);
mem.percentConsumed = (((mem.MemTotal - mem.MemFree) / mem.MemTotal) * 100);//.toFixed(2);
return (mem);
}
else
{
throw ('Parse Error');
}
}
switch(process.platform)
{
case 'linux':
module.exports = { cpuUtilization: linux_cpuUtilization, memUtilization: linux_memUtilization };
break;
case 'win32':
module.exports = { cpuUtilization: windows_cpuUtilization, memUtilization: windows_memUtilization };
break;
case 'darwin':
module.exports = { cpuUtilization: macos_cpuUtilization, memUtilization: macos_memUtilization };
break;
}

File diff suppressed because one or more lines are too long

View File

@ -1 +0,0 @@
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();

View File

@ -1 +0,0 @@
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;

View File

@ -1 +0,0 @@
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();

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

2
db.js
View File

@ -531,6 +531,7 @@ module.exports.CreateDB = function (parent, func) {
}
};
obj.GetAll = function (func) { obj.file.find({}).toArray(func); };
obj.GetHash = function (id, func) { obj.file.find({ _id: id }).project({ _id: 0, hash: 1 }).toArray(func); };
obj.GetAllTypeNoTypeField = function (type, domain, func) { obj.file.find({ type: type, domain: domain }).project({ type: 0 }).toArray(func); };
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); };
obj.GetAllType = function (type, func) { obj.file.find({ type: type }).toArray(func); };
@ -624,6 +625,7 @@ module.exports.CreateDB = function (parent, func) {
}
};
obj.GetAll = function (func) { obj.file.find({}, func); };
obj.GetHash = function (id, func) { obj.file.find({ _id: id }, { _id: 0, hash: 1 }, func); };
obj.GetAllTypeNoTypeField = function (type, domain, func) { obj.file.find({ type: type, domain: domain }, { type: 0 }, func); };
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); };
obj.GetAllType = function (type, func) { obj.file.find({ type: type }, func); };

View File

@ -64,6 +64,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
db.Remove('if' + obj.dbNodeKey); // Remove interface information
db.Remove('nt' + obj.dbNodeKey); // Remove notes
db.Remove('lc' + obj.dbNodeKey); // Remove last connect time
db.Remove('si' + obj.dbNodeKey); // Remove system information
db.RemoveSMBIOS(obj.dbNodeKey); // Remove SMBios data
db.RemoveAllNodeEvents(obj.dbNodeKey); // Remove all events for this node
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) {
try { obj.send(JSON.stringify({ action: 'amtPolicy', amtPolicy: completeIntelAmtPolicy(common.Clone(mesh.amt)) })); } catch (ex) { }
}
// Fetch system information
db.GetHash('si' + obj.dbNodeKey, function (err, results) {
if ((results != null) && (results.length == 1)) { obj.send(JSON.stringify({ action: 'sysinfo', hash: results[0].hash })); } else { obj.send(JSON.stringify({ action: 'sysinfo' })); }
});
// Do this if IP location is enabled on this domain TODO: Set IP location per device group?
if (domain.iplocation == true) {
// 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) {
}
break;
}
case 'sysinfo': {
//console.log('sysinfo', obj.nodeid, JSON.stringify(command.data.hash));
command.data._id = 'si' + obj.dbNodeKey;
db.Set(command.data); // Update system information in the database.
break;
}
case 'sysinfocheck': {
// Check system information update
db.GetHash('si' + obj.dbNodeKey, function (err, results) {
if ((results != null) && (results.length == 1)) { obj.send(JSON.stringify({ action: 'sysinfo', hash: results[0].hash })); } else { obj.send(JSON.stringify({ action: 'sysinfo' })); }
});
break;
}
default: {
parent.agentStats.unknownAgentActionCount++;
console.log('Unknown agent action (' + obj.remoteaddrport + '): ' + command.action + '.');

View File

@ -1937,6 +1937,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
db.Remove('if' + node._id); // Remove interface information
db.Remove('nt' + node._id); // Remove notes
db.Remove('lc' + node._id); // Remove last connect time
db.Remove('si' + node._id); // Remove system information
db.RemoveSMBIOS(node._id); // Remove SMBios data
db.RemoveAllNodeEvents(node._id); // Remove all events for this node
db.removeAllPowerEventsForNode(node._id); // Remove all power events for this node

View File

@ -1,6 +1,6 @@
{
"name": "meshcentral",
"version": "0.3.9-g",
"version": "0.3.9-h",
"keywords": [
"Remote Management",
"Intel AMT",
@ -39,6 +39,7 @@
"ipcheck": "^0.1.0",
"meshcentral": "*",
"minimist": "^1.2.0",
"mongojs": "^2.6.0",
"multiparty": "^4.2.1",
"nedb": "^1.8.0",
"node-forge": "^0.8.4",