diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f0f13c..7661d6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -90,6 +90,7 @@ For major (breaking) changes - **version 4, 3 and 2** - see end of page. | Version | Date | Comment | | ------- | ---------- | --------------------------------------------------------------------------------------------------- | +| 5.27.16 | 2025-12-23 | `cpuTemperature()` fix sensors parsingg AMD (linux) | | 5.27.15 | 2025-12-22 | Updated docs | | 5.27.14 | 2025-12-15 | `fsSize()` fix drive sanitation (windows) | | 5.27.13 | 2025-12-10 | `cpuCurrentSpeed()` fix hasOwnProperty | diff --git a/docs/history.html b/docs/history.html index 172e3fb..f2666b5 100644 --- a/docs/history.html +++ b/docs/history.html @@ -57,6 +57,11 @@ + + 5.27.16 + 2025-12-23 + cpuTemperature() fix sensor parsing for AMD (linux) + 5.27.15 2025-12-22 diff --git a/docs/index.html b/docs/index.html index 6b50884..a36f6e0 100644 --- a/docs/index.html +++ b/docs/index.html @@ -170,7 +170,7 @@
systeminformation
 
-
New Version: 5.27.15
+
New Version: 5.27.16
diff --git a/lib/cpu.js b/lib/cpu.js index 2ba497a..d7818b9 100644 --- a/lib/cpu.js +++ b/lib/cpu.js @@ -728,8 +728,8 @@ function getCpu() { result.flags = flags; result.virtualization = flags.indexOf('vmx') > -1 || flags.indexOf('svm') > -1; if (_darwin) { - exec('sysctl machdep.cpu hw.cpufrequency_max hw.cpufrequency_min hw.packages hw.physicalcpu_max hw.ncpu hw.tbfrequency hw.cpufamily hw.cpusubfamily', function (error, stdout) { - let lines = stdout.toString().split('\n'); + exec('sysctl machdep.cpu hw.cpufrequency_max hw.cpufrequency_min hw.packages hw.physicalcpu_max hw.ncpu hw.tbfrequency hw.cpufamily hw.cpusubfamily', (error, stdout) => { + const lines = stdout.toString().split('\n'); const modelline = util.getValue(lines, 'machdep.cpu.brand_string'); const modellineParts = modelline.split('@'); result.brand = modellineParts[0].trim(); @@ -759,12 +759,12 @@ function getCpu() { const performanceCores = clusters.filter((line) => line.indexOf('"P"') >= 0).length; result.efficiencyCores = efficiencyCores; result.performanceCores = performanceCores; - } catch (e) { + } catch { util.noop(); } } if (countProcessors) { - result.processors = parseInt(countProcessors) || 1; + result.processors = parseInt(countProcessors, 10) || 1; } if (countCores && countThreads) { result.cores = parseInt(countThreads) || util.cores(); @@ -782,7 +782,7 @@ function getCpu() { if (os.cpus()[0] && os.cpus()[0].model) { modelline = os.cpus()[0].model; } - exec('export LC_ALL=C; lscpu; echo -n "Governor: "; cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null; echo; unset LC_ALL', function (error, stdout) { + exec('export LC_ALL=C; lscpu; echo -n "Governor: "; cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null; echo; unset LC_ALL', (error, stdout) => { if (!error) { lines = stdout.toString().split('\n'); } @@ -866,7 +866,7 @@ function getCpu() { // socket type let lines2 = []; - exec('export LC_ALL=C; dmidecode –t 4 2>/dev/null | grep "Upgrade: Socket"; unset LC_ALL', function (error2, stdout2) { + exec('export LC_ALL=C; dmidecode –t 4 2>/dev/null | grep "Upgrade: Socket"; unset LC_ALL', (error2, stdout2) => { lines2 = stdout2.toString().split('\n'); if (lines2 && lines2.length) { result.socket = util.getValue(lines2, 'Upgrade').replace('Socket', '').trim() || result.socket; @@ -881,7 +881,7 @@ function getCpu() { if (os.cpus()[0] && os.cpus()[0].model) { modelline = os.cpus()[0].model; } - exec('export LC_ALL=C; dmidecode -t 4; dmidecode -t 7 unset LC_ALL', function (error, stdout) { + exec('export LC_ALL=C; dmidecode -t 4; dmidecode -t 7 unset LC_ALL', (error, stdout) => { let cache = []; if (!error) { const data = stdout.toString().split('# dmidecode'); @@ -1275,7 +1275,7 @@ function cpuTemperature(callback) { }); if (result.cores.length > 0) { result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length); - let maxtmp = Math.max.apply(Math, result.cores); + const maxtmp = Math.max.apply(Math, result.cores); result.max = maxtmp > result.main ? maxtmp : result.main; } else { if (result.main === null && tdieTemp !== null) { @@ -1283,6 +1283,9 @@ function cpuTemperature(callback) { result.max = tdieTemp; } } + if (result.main !== null && result.max === null) { + result.max = result.main; + } if (result.main !== null || result.max !== null) { if (callback) { callback(result); @@ -1358,27 +1361,25 @@ function cpuTemperature(callback) { }); } if (_darwin) { - let osxTemp = null; try { - osxTemp = require('osx-temperature-sensor'); - } catch (er) { - osxTemp = null; - } - if (osxTemp) { + const osxTemp = require('osx-temperature-sensor'); result = osxTemp.cpuTemperature(); - // round to 2 digits if (result.main) { + // round to 2 digits result.main = Math.round(result.main * 100) / 100; } if (result.max) { result.max = Math.round(result.max * 100) / 100; } - if (result.cores && result.cores.length) { + if (result?.cores.length) { for (let i = 0; i < result.cores.length; i++) { result.cores[i] = Math.round(result.cores[i] * 100) / 100; } } + } catch { + util.noop(); } + // add new macOS temperature library here if (callback) { callback(result); @@ -1441,7 +1442,7 @@ function cpuFlags(callback) { let result = ''; if (_windows) { try { - exec('reg query "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" /v FeatureSet', util.execOptsWin, function (error, stdout) { + exec('reg query "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" /v FeatureSet', util.execOptsWin, (error, stdout) => { if (!error) { let flag_hex = stdout.split('0x').pop().trim(); let flag_bin_unpadded = parseInt(flag_hex, 16).toString(2); @@ -1495,7 +1496,7 @@ function cpuFlags(callback) { } resolve(result); }); - } catch (e) { + } catch { if (callback) { callback(result); } @@ -1504,7 +1505,7 @@ function cpuFlags(callback) { } if (_linux) { try { - exec('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) { + exec('export LC_ALL=C; lscpu; unset LC_ALL', (error, stdout) => { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { @@ -1539,7 +1540,7 @@ function cpuFlags(callback) { } } if (_freebsd || _openbsd || _netbsd) { - exec('export LC_ALL=C; dmidecode -t 4 2>/dev/null; unset LC_ALL', function (error, stdout) { + exec('export LC_ALL=C; dmidecode -t 4 2>/dev/null; unset LC_ALL', (error, stdout) => { let flags = []; if (!error) { let parts = stdout.toString().split('\tFlags:'); @@ -1559,7 +1560,7 @@ function cpuFlags(callback) { }); } if (_darwin) { - exec('sysctl machdep.cpu.features', function (error, stdout) { + exec('sysctl machdep.cpu.features', (error, stdout) => { if (!error) { let lines = stdout.toString().split('\n'); if (lines.length > 0 && lines[0].indexOf('machdep.cpu.features:') !== -1) { @@ -1598,7 +1599,7 @@ function cpuCache(callback) { }; if (_linux) { try { - exec('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) { + exec('export LC_ALL=C; lscpu; unset LC_ALL', (error, stdout) => { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { @@ -1630,7 +1631,7 @@ function cpuCache(callback) { } } if (_freebsd || _openbsd || _netbsd) { - exec('export LC_ALL=C; dmidecode -t 7 2>/dev/null; unset LC_ALL', function (error, stdout) { + exec('export LC_ALL=C; dmidecode -t 7 2>/dev/null; unset LC_ALL', (error, stdout) => { let cache = []; if (!error) { const data = stdout.toString(); @@ -1661,7 +1662,7 @@ function cpuCache(callback) { }); } if (_darwin) { - exec('sysctl hw.l1icachesize hw.l1dcachesize hw.l2cachesize hw.l3cachesize', function (error, stdout) { + exec('sysctl hw.l1icachesize hw.l1dcachesize hw.l2cachesize hw.l3cachesize', (error, stdout) => { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { @@ -1788,7 +1789,7 @@ exports.cpuCache = cpuCache; function getLoad() { return new Promise((resolve) => { process.nextTick(() => { - let loads = os.loadavg().map(function (x) { + let loads = os.loadavg().map( (x) => { return x / util.cores(); }); let avgLoad = parseFloat(Math.max.apply(Math, loads).toFixed(2)); @@ -1883,9 +1884,9 @@ function getLoad() { cores[i].rawLoadSteal = _cpus[i].loadSteal; cores[i].rawLoadGuest = _cpus[i].loadGuest; } - let totalTick = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest + totalIdle; - let totalLoad = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest; - let currentTick = totalTick - _current_cpu.tick; + const totalTick = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest + totalIdle; + const totalLoad = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest; + const currentTick = totalTick - _current_cpu.tick; result = { avgLoad: avgLoad, currentLoad: ((totalLoad - _current_cpu.load) / currentTick) * 100, @@ -1935,7 +1936,7 @@ function getLoad() { rawCurrentLoadGuest: result.rawCurrentLoadGuest }; } else { - let cores = []; + const cores = []; for (let i = 0; i < _corecount; i++) { cores[i] = {}; cores[i].load = (_cpus[i].load / _cpus[i].currentTick) * 100; @@ -2010,7 +2011,7 @@ function getFullLoad() { let result = 0; - if (cpus && cpus.length) { + if (cpus?.length) { for (let i = 0, len = cpus.length; i < len; i++) { const cpu = cpus[i].times; totalUser += cpu.user; @@ -2019,7 +2020,7 @@ function getFullLoad() { totalIrq += cpu.irq; totalIdle += cpu.idle; } - let totalTicks = totalIdle + totalIrq + totalNice + totalSystem + totalUser; + const totalTicks = totalIdle + totalIrq + totalNice + totalSystem + totalUser; result = ((totalTicks - totalIdle) / totalTicks) * 100.0; } resolve(result); diff --git a/lib/network.js b/lib/network.js index 0614e57..70cd1b3 100644 --- a/lib/network.js +++ b/lib/network.js @@ -21,13 +21,13 @@ const util = require('./util'); let _platform = process.platform; -const _linux = (_platform === 'linux' || _platform === 'android'); -const _darwin = (_platform === 'darwin'); -const _windows = (_platform === 'win32'); -const _freebsd = (_platform === 'freebsd'); -const _openbsd = (_platform === 'openbsd'); -const _netbsd = (_platform === 'netbsd'); -const _sunos = (_platform === 'sunos'); +const _linux = _platform === 'linux' || _platform === 'android'; +const _darwin = _platform === 'darwin'; +const _windows = _platform === 'win32'; +const _freebsd = _platform === 'freebsd'; +const _openbsd = _platform === 'openbsd'; +const _netbsd = _platform === 'netbsd'; +const _sunos = _platform === 'sunos'; let _network = {}; let _default_iface = ''; @@ -38,7 +38,6 @@ let _mac = {}; let pathToIp; function getDefaultNetworkInterface() { - let ifacename = ''; let ifacenameFirst = ''; try { @@ -68,9 +67,9 @@ function getDefaultNetworkInterface() { const cmd = 'netstat -r'; const result = execSync(cmd, util.execOptsWin); const lines = result.toString().split(os.EOL); - lines.forEach(line => { + lines.forEach((line) => { line = line.replace(/\s+/g, ' ').trim(); - if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) { + if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !/[a-zA-Z]/.test(line)) { const parts = line.split(' '); if (parts.length >= 5) { defaultIp = parts[parts.length - 2]; @@ -105,9 +104,15 @@ function getDefaultNetworkInterface() { } if (_darwin || _freebsd || _openbsd || _netbsd || _sunos) { let cmd = ''; - if (_linux) { cmd = 'ip route 2> /dev/null | grep default | awk \'{print $5}\''; } - if (_darwin) { cmd = 'route -n get default 2>/dev/null | grep interface: | awk \'{print $2}\''; } - if (_freebsd || _openbsd || _netbsd || _sunos) { cmd = 'route get 0.0.0.0 | grep interface:'; } + if (_linux) { + cmd = "ip route 2> /dev/null | grep default | awk '{print $5}'"; + } + if (_darwin) { + cmd = "route -n get default 2>/dev/null | grep interface: | awk '{print $2}'"; + } + if (_freebsd || _openbsd || _netbsd || _sunos) { + cmd = 'route get 0.0.0.0 | grep interface:'; + } let result = execSync(cmd); ifacename = result.toString().split('\n')[0]; if (ifacename.indexOf(':') > -1) { @@ -117,7 +122,9 @@ function getDefaultNetworkInterface() { } catch (e) { util.noop(); } - if (ifacename) { _default_iface = ifacename; } + if (ifacename) { + _default_iface = ifacename; + } return _default_iface; } @@ -141,7 +148,7 @@ function getMacAddresses() { } } try { - const cmd = 'export LC_ALL=C; ' + ((pathToIp) ? pathToIp + ' link show up' : '/sbin/ifconfig') + '; unset LC_ALL'; + const cmd = 'export LC_ALL=C; ' + (pathToIp ? pathToIp + ' link show up' : '/sbin/ifconfig') + '; unset LC_ALL'; let res = execSync(cmd, util.execOptsLinux); const lines = res.toString().split('\n'); for (let i = 0; i < lines.length; i++) { @@ -194,11 +201,12 @@ function getMacAddresses() { } function networkInterfaceDefault(callback) { - return new Promise((resolve) => { process.nextTick(() => { let result = getDefaultNetworkInterface(); - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); }); }); @@ -214,9 +222,7 @@ function parseLinesWindowsNics(sections, nconfigsections) { for (let i in sections) { try { if ({}.hasOwnProperty.call(sections, i)) { - if (sections[i].trim() !== '') { - let lines = sections[i].trim().split('\r\n'); let linesNicConfig = null; try { @@ -256,7 +262,7 @@ function parseLinesWindowsNics(sections, nconfigsections) { function getWindowsNics() { return new Promise((resolve) => { process.nextTick(() => { - let cmd = 'Get-CimInstance Win32_NetworkAdapter | fl *' + '; echo \'#-#-#-#\';'; + let cmd = 'Get-CimInstance Win32_NetworkAdapter | fl *' + "; echo '#-#-#-#';"; cmd += 'Get-CimInstance Win32_NetworkAdapterConfiguration | fl DHCPEnabled' + ''; try { util.powerShell(cmd).then((data) => { @@ -273,13 +279,12 @@ function getWindowsNics() { } function getWindowsDNSsuffixes() { - let iface = {}; let dnsSuffixes = { primaryDNS: '', exitCode: 0, - ifaces: [], + ifaces: [] }; try { @@ -287,17 +292,18 @@ function getWindowsDNSsuffixes() { const ipconfigArray = ipconfig.split('\r\n\r\n'); ipconfigArray.forEach((element, index) => { - - if (index == 1) { + if (index === 1) { const longPrimaryDNS = element.split('\r\n').filter((element) => { return element.toUpperCase().includes('DNS'); }); const primaryDNS = longPrimaryDNS[0].substring(longPrimaryDNS[0].lastIndexOf(':') + 1); dnsSuffixes.primaryDNS = primaryDNS.trim(); - if (!dnsSuffixes.primaryDNS) { dnsSuffixes.primaryDNS = 'Not defined'; } + if (!dnsSuffixes.primaryDNS) { + dnsSuffixes.primaryDNS = 'Not defined'; + } } if (index > 1) { - if (index % 2 == 0) { + if (index % 2 === 0) { const name = element.substring(element.lastIndexOf(' ') + 1).replace(':', ''); iface.name = name; } else { @@ -317,7 +323,7 @@ function getWindowsDNSsuffixes() { return { primaryDNS: '', exitCode: 0, - ifaces: [], + ifaces: [] }; } } @@ -327,13 +333,17 @@ function getWindowsIfaceDNSsuffix(ifaces, ifacename) { // Adding (.) to ensure ifacename compatibility when duplicated iface-names const interfaceName = ifacename + '.'; try { - const connectionDnsSuffix = ifaces.filter((iface) => { - return interfaceName.includes(iface.name + '.'); - }).map((iface) => iface.dnsSuffix); + const connectionDnsSuffix = ifaces + .filter((iface) => { + return interfaceName.includes(iface.name + '.'); + }) + .map((iface) => iface.dnsSuffix); if (connectionDnsSuffix[0]) { dnsSuffix = connectionDnsSuffix[0]; } - if (!dnsSuffix) { dnsSuffix = ''; } + if (!dnsSuffix) { + dnsSuffix = ''; + } return dnsSuffix; } catch (error) { return 'Unknown'; @@ -366,7 +376,7 @@ function getWindowsWirelessIfaceSSID(interfaceName) { function getWindowsIEEE8021x(connectionType, iface, ifaces) { let i8021x = { state: 'Unknown', - protocol: 'Unknown', + protocol: 'Unknown' }; if (ifaces === 'Disabled') { @@ -375,7 +385,7 @@ function getWindowsIEEE8021x(connectionType, iface, ifaces) { return i8021x; } - if (connectionType == 'wired' && ifaces.length > 0) { + if (connectionType === 'wired' && ifaces.length > 0) { try { // Get 802.1x information by interface name const iface8021xInfo = ifaces.find((element) => { @@ -399,17 +409,13 @@ function getWindowsIEEE8021x(connectionType, iface, ifaces) { } catch (error) { return i8021x; } - } else if (connectionType == 'wireless') { - + } else if (connectionType === 'wireless') { let i8021xState = ''; let i8021xProtocol = ''; - - try { const SSID = getWindowsWirelessIfaceSSID(iface); if (SSID !== 'Unknown') { - let ifaceSanitized = ''; const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(SSID); const l = util.mathMin(s.length, 32); @@ -459,7 +465,7 @@ function splitSectionsNics(lines) { function parseLinesDarwinNics(sections) { let nics = []; - sections.forEach(section => { + sections.forEach((section) => { let nic = { iface: '', mtu: null, @@ -480,7 +486,7 @@ function parseLinesDarwinNics(sections) { nic.mtu = null; } nic.internal = parts[0].toLowerCase().indexOf('loopback') > -1; - section.forEach(line => { + section.forEach((line) => { if (line.trim().startsWith('ether ')) { nic.mac = line.split('ether ')[1].toLowerCase().trim(); } @@ -506,7 +512,7 @@ function parseLinesDarwinNics(sections) { } nic.type = util.getValue(section, 'type').toLowerCase().indexOf('wi-fi') > -1 ? 'wireless' : 'wired'; const operstate = util.getValue(section, 'status').toLowerCase(); - nic.operstate = (operstate === 'active' ? 'up' : (operstate === 'inactive' ? 'down' : 'unknown')); + nic.operstate = operstate === 'active' ? 'up' : operstate === 'inactive' ? 'down' : 'unknown'; nic.duplex = util.getValue(section, 'media').toLowerCase().indexOf('half-duplex') > -1 ? 'half' : 'full'; if (nic.ip6 || nic.ip4 || nic.mac) { nics.push(nic); @@ -518,9 +524,11 @@ function parseLinesDarwinNics(sections) { function getDarwinNics() { const cmd = '/sbin/ifconfig -v'; try { - const lines = execSync(cmd, { maxBuffer: 1024 * 20000 }).toString().split('\n'); + const lines = execSync(cmd, { maxBuffer: 1024 * 20000 }) + .toString() + .split('\n'); const nsections = splitSectionsNics(lines); - return (parseLinesDarwinNics(nsections)); + return parseLinesDarwinNics(nsections); } catch (e) { return []; } @@ -534,7 +542,7 @@ function getLinuxIfaceConnectionName(interfaceName) { const resultFormat = result.replace(/\s+/g, ' ').trim(); const connectionNameLines = resultFormat.split(' ').slice(3); const connectionName = connectionNameLines.join(' '); - return connectionName != '--' ? connectionName : ''; + return connectionName !== '--' ? connectionName : ''; } catch (e) { return ''; } @@ -543,10 +551,10 @@ function getLinuxIfaceConnectionName(interfaceName) { function checkLinuxDCHPInterfaces(file) { let result = []; try { - let cmd = `cat ${file} 2> /dev/null | grep 'iface\\|source'`; + const cmd = `cat ${file} 2> /dev/null | grep 'iface\\|source'`; const lines = execSync(cmd, util.execOptsLinux).toString().split('\n'); - lines.forEach(line => { + lines.forEach((line) => { const parts = line.replace(/\s+/g, ' ').trim().split(' '); if (parts.length >= 4) { if (line.toLowerCase().indexOf(' inet ') >= 0 && line.toLowerCase().indexOf('dhcp') >= 0) { @@ -571,7 +579,7 @@ function getLinuxDHCPNics() { try { const lines = execSync(cmd, util.execOptsLinux).toString().split('\n'); const nsections = splitSectionsNics(lines); - result = (parseLinuxDHCPNics(nsections)); + result = parseLinuxDHCPNics(nsections); } catch (e) { util.noop(); } @@ -586,7 +594,7 @@ function getLinuxDHCPNics() { function parseLinuxDHCPNics(sections) { const result = []; if (sections && sections.length) { - sections.forEach(lines => { + sections.forEach((lines) => { if (lines && lines.length) { const parts = lines[0].split(':'); if (parts.length > 2) { @@ -625,10 +633,10 @@ function getLinuxIfaceDHCPstatus(iface, connectionName, DHCPNics) { } return result; } catch (e) { - return (DHCPNics.indexOf(iface) >= 0); + return DHCPNics.indexOf(iface) >= 0; } } else { - return (DHCPNics.indexOf(iface) >= 0); + return DHCPNics.indexOf(iface) >= 0; } } @@ -653,7 +661,7 @@ function getLinuxIfaceDNSsuffix(connectionName) { const result = execSync(cmd, util.execOptsLinux).toString(); const resultFormat = result.replace(/\s+/g, ' ').trim(); const dnsSuffix = resultFormat.split(' ').slice(1).toString(); - return dnsSuffix == '--' ? 'Not defined' : dnsSuffix; + return dnsSuffix === '--' ? 'Not defined' : dnsSuffix; } catch (e) { return 'Unknown'; } @@ -670,8 +678,7 @@ function getLinuxIfaceIEEE8021xAuth(connectionName) { const resultFormat = result.replace(/\s+/g, ' ').trim(); const authenticationProtocol = resultFormat.split(' ').slice(1).toString(); - - return authenticationProtocol == '--' ? '' : authenticationProtocol; + return authenticationProtocol === '--' ? '' : authenticationProtocol; } catch (e) { return 'Not defined'; } @@ -682,7 +689,7 @@ function getLinuxIfaceIEEE8021xAuth(connectionName) { function getLinuxIfaceIEEE8021xState(authenticationProtocol) { if (authenticationProtocol) { - if (authenticationProtocol == 'Not defined') { + if (authenticationProtocol === 'Not defined') { return 'Disabled'; } return 'Enabled'; @@ -692,9 +699,35 @@ function getLinuxIfaceIEEE8021xState(authenticationProtocol) { } function testVirtualNic(iface, ifaceName, mac) { - const virtualMacs = ['00:00:00:00:00:00', '00:03:FF', '00:05:69', '00:0C:29', '00:0F:4B', '00:13:07', '00:13:BE', '00:15:5d', '00:16:3E', '00:1C:42', '00:21:F6', '00:24:0B', '00:50:56', '00:A0:B1', '00:E0:C8', '08:00:27', '0A:00:27', '18:92:2C', '16:DF:49', '3C:F3:92', '54:52:00', 'FC:15:97']; + const virtualMacs = [ + '00:00:00:00:00:00', + '00:03:FF', + '00:05:69', + '00:0C:29', + '00:0F:4B', + '00:13:07', + '00:13:BE', + '00:15:5d', + '00:16:3E', + '00:1C:42', + '00:21:F6', + '00:24:0B', + '00:50:56', + '00:A0:B1', + '00:E0:C8', + '08:00:27', + '0A:00:27', + '18:92:2C', + '16:DF:49', + '3C:F3:92', + '54:52:00', + 'FC:15:97' + ]; if (mac) { - return virtualMacs.filter(item => { return mac.toUpperCase().toUpperCase().startsWith(item.substring(0, mac.length)); }).length > 0 || + return ( + virtualMacs.filter((item) => { + return mac.toUpperCase().toUpperCase().startsWith(item.substring(0, mac.length)); + }).length > 0 || iface.toLowerCase().indexOf(' virtual ') > -1 || ifaceName.toLowerCase().indexOf(' virtual ') > -1 || iface.toLowerCase().indexOf('vethernet ') > -1 || @@ -702,12 +735,14 @@ function testVirtualNic(iface, ifaceName, mac) { iface.toLowerCase().startsWith('veth') || ifaceName.toLowerCase().startsWith('veth') || iface.toLowerCase().startsWith('vboxnet') || - ifaceName.toLowerCase().startsWith('vboxnet'); - } else { return false; } + ifaceName.toLowerCase().startsWith('vboxnet') + ); + } else { + return false; + } } function networkInterfaces(callback, rescan, defaultString) { - if (typeof callback === 'string') { defaultString = callback; rescan = true; @@ -727,7 +762,6 @@ function networkInterfaces(callback, rescan, defaultString) { return new Promise((resolve) => { process.nextTick(() => { - let ifaces = os.networkInterfaces(); let result = []; @@ -736,11 +770,13 @@ function networkInterfaces(callback, rescan, defaultString) { let nics8021xInfo = []; // seperate handling in OSX if (_darwin || _freebsd || _openbsd || _netbsd) { - if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) { + if (JSON.stringify(ifaces) === JSON.stringify(_ifaces) && !rescan) { // no changes - just return object result = _networkInterfaces; - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } else { const defaultInterface = getDefaultNetworkInterface(); @@ -748,9 +784,7 @@ function networkInterfaces(callback, rescan, defaultString) { nics = getDarwinNics(); - - nics.forEach(nic => { - + nics.forEach((nic) => { if ({}.hasOwnProperty.call(ifaces, nic.iface)) { ifaces[nic.iface].forEach(function (details) { if (details.family === 'IPv4' || details.family === 4) { @@ -796,23 +830,27 @@ function networkInterfaces(callback, rescan, defaultString) { }); _networkInterfaces = result; if (defaultString.toLowerCase().indexOf('default') >= 0) { - result = result.filter(item => item.default); + result = result.filter((item) => item.default); if (result.length > 0) { result = result[0]; } else { result = []; } } - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } } if (_linux) { - if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) { + if (JSON.stringify(ifaces) === JSON.stringify(_ifaces) && !rescan) { // no changes - just return object result = _networkInterfaces; - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } else { _ifaces = JSON.parse(JSON.stringify(ifaces)); @@ -850,7 +888,7 @@ function networkInterfaces(callback, rescan, defaultString) { mac = details.mac; // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2) const nodeMainVersion = parseInt(process.versions.node.split('.'), 10); - if (mac.indexOf('00:00:0') > -1 && (_linux || _darwin) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) { + if (mac.indexOf('00:00:0') > -1 && (_linux || _darwin) && !details.internal && nodeMainVersion >= 8 && nodeMainVersion <= 11) { if (Object.keys(_mac).length === 0) { _mac = getMacAddresses(); } @@ -900,7 +938,7 @@ function networkInterfaces(callback, rescan, defaultString) { dnsSuffix = getLinuxIfaceDNSsuffix(connectionName); ieee8021xAuth = getLinuxIfaceIEEE8021xAuth(connectionName); ieee8021xState = getLinuxIfaceIEEE8021xState(ieee8021xAuth); - } catch (e) { + } catch { util.noop(); } duplex = util.getValue(lines, 'duplex'); @@ -916,9 +954,11 @@ function networkInterfaces(callback, rescan, defaultString) { carrierChanges = parseInt(util.getValue(lines, 'carrier_changes'), 10); const operstate = util.getValue(lines, 'operstate'); type = operstate === 'up' ? (util.getValue(lines, 'wireless').trim() ? 'wireless' : 'wired') : 'unknown'; - if (ifaceSanitized === 'lo' || ifaceSanitized.startsWith('bond')) { type = 'virtual'; } + if (ifaceSanitized === 'lo' || ifaceSanitized.startsWith('bond')) { + type = 'virtual'; + } - let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false; + let internal = ifaces[dev] && ifaces[dev][0] ? ifaces[dev][0].internal : false; if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) { internal = true; } @@ -943,40 +983,44 @@ function networkInterfaces(callback, rescan, defaultString) { dnsSuffix, ieee8021xAuth, ieee8021xState, - carrierChanges, + carrierChanges }); } } _networkInterfaces = result; if (defaultString.toLowerCase().indexOf('default') >= 0) { - result = result.filter(item => item.default); + result = result.filter((item) => item.default); if (result.length > 0) { result = result[0]; } else { result = []; } } - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } } if (_windows) { - if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) { + if (JSON.stringify(ifaces) === JSON.stringify(_ifaces) && !rescan) { // no changes - just return object result = _networkInterfaces; - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } else { _ifaces = JSON.parse(JSON.stringify(ifaces)); const defaultInterface = getDefaultNetworkInterface(); getWindowsNics().then(function (nics) { - nics.forEach(nic => { + nics.forEach((nic) => { let found = false; - Object.keys(ifaces).forEach(key => { + Object.keys(ifaces).forEach((key) => { if (!found) { - ifaces[key].forEach(value => { + ifaces[key].forEach((value) => { if (Object.keys(value).indexOf('mac') >= 0) { found = value['mac'] === nic.mac; } @@ -991,7 +1035,6 @@ function networkInterfaces(callback, rescan, defaultString) { nics8021xInfo = getWindowsWiredProfilesInformation(); dnsSuffixes = getWindowsDNSsuffixes(); for (let dev in ifaces) { - let ifaceSanitized = ''; const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(dev); const l = util.mathMin(s.length, 2000); @@ -1034,7 +1077,7 @@ function networkInterfaces(callback, rescan, defaultString) { mac = details.mac; // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2) const nodeMainVersion = parseInt(process.versions.node.split('.'), 10); - if (mac.indexOf('00:00:0') > -1 && (_linux || _darwin) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) { + if (mac.indexOf('00:00:0') > -1 && (_linux || _darwin) && !details.internal && nodeMainVersion >= 8 && nodeMainVersion <= 11) { if (Object.keys(_mac).length === 0) { _mac = getMacAddresses(); } @@ -1042,11 +1085,9 @@ function networkInterfaces(callback, rescan, defaultString) { } }); - - dnsSuffix = getWindowsIfaceDNSsuffix(dnsSuffixes.ifaces, ifaceSanitized); let foundFirst = false; - nics.forEach(detail => { + nics.forEach((detail) => { if (detail.mac === mac && !foundFirst) { iface = detail.iface || iface; ifaceName = detail.name; @@ -1058,14 +1099,21 @@ function networkInterfaces(callback, rescan, defaultString) { } }); - if (dev.toLowerCase().indexOf('wlan') >= 0 || ifaceName.toLowerCase().indexOf('wlan') >= 0 || ifaceName.toLowerCase().indexOf('802.11n') >= 0 || ifaceName.toLowerCase().indexOf('wireless') >= 0 || ifaceName.toLowerCase().indexOf('wi-fi') >= 0 || ifaceName.toLowerCase().indexOf('wifi') >= 0) { + if ( + dev.toLowerCase().indexOf('wlan') >= 0 || + ifaceName.toLowerCase().indexOf('wlan') >= 0 || + ifaceName.toLowerCase().indexOf('802.11n') >= 0 || + ifaceName.toLowerCase().indexOf('wireless') >= 0 || + ifaceName.toLowerCase().indexOf('wi-fi') >= 0 || + ifaceName.toLowerCase().indexOf('wifi') >= 0 + ) { type = 'wireless'; } const IEEE8021x = getWindowsIEEE8021x(type, ifaceSanitized, nics8021xInfo); ieee8021xAuth = IEEE8021x.protocol; ieee8021xState = IEEE8021x.state; - let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false; + let internal = ifaces[dev] && ifaces[dev][0] ? ifaces[dev][0].internal : false; if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) { internal = true; } @@ -1090,20 +1138,22 @@ function networkInterfaces(callback, rescan, defaultString) { dnsSuffix, ieee8021xAuth, ieee8021xState, - carrierChanges, + carrierChanges }); } } _networkInterfaces = result; if (defaultString.toLowerCase().indexOf('default') >= 0) { - result = result.filter(item => item.default); + result = result.filter((item) => item.default); if (result.length > 0) { result = result[0]; } else { result = []; } } - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); }); } @@ -1134,8 +1184,8 @@ function calcNetworkSpeed(iface, rx_bytes, tx_bytes, operstate, rx_dropped, rx_e if (_network[iface] && _network[iface].ms) { result.ms = Date.now() - _network[iface].ms; - result.rx_sec = (rx_bytes - _network[iface].rx_bytes) >= 0 ? (rx_bytes - _network[iface].rx_bytes) / (result.ms / 1000) : 0; - result.tx_sec = (tx_bytes - _network[iface].tx_bytes) >= 0 ? (tx_bytes - _network[iface].tx_bytes) / (result.ms / 1000) : 0; + result.rx_sec = rx_bytes - _network[iface].rx_bytes >= 0 ? (rx_bytes - _network[iface].rx_bytes) / (result.ms / 1000) : 0; + result.tx_sec = tx_bytes - _network[iface].tx_bytes >= 0 ? (tx_bytes - _network[iface].tx_bytes) / (result.ms / 1000) : 0; _network[iface].rx_bytes = rx_bytes; _network[iface].tx_bytes = tx_bytes; _network[iface].rx_sec = result.rx_sec; @@ -1144,7 +1194,9 @@ function calcNetworkSpeed(iface, rx_bytes, tx_bytes, operstate, rx_dropped, rx_e _network[iface].last_ms = result.ms; _network[iface].operstate = operstate; } else { - if (!_network[iface]) { _network[iface] = {}; } + if (!_network[iface]) { + _network[iface] = {}; + } _network[iface].rx_bytes = rx_bytes; _network[iface].tx_bytes = tx_bytes; _network[iface].rx_sec = null; @@ -1157,19 +1209,19 @@ function calcNetworkSpeed(iface, rx_bytes, tx_bytes, operstate, rx_dropped, rx_e } function networkStats(ifaces, callback) { - let ifacesArray = []; return new Promise((resolve) => { process.nextTick(() => { - // fallback - if only callback is given if (util.isFunction(ifaces) && !callback) { callback = ifaces; ifacesArray = [getDefaultNetworkInterface()]; } else { if (typeof ifaces !== 'string' && ifaces !== undefined) { - if (callback) { callback([]); } + if (callback) { + callback([]); + } return resolve([]); } ifaces = ifaces || getDefaultNetworkInterface(); @@ -1195,12 +1247,14 @@ function networkStats(ifaces, callback) { const workload = []; if (ifacesArray.length && ifacesArray[0].trim() === '*') { ifacesArray = []; - networkInterfaces(false).then(allIFaces => { + networkInterfaces(false).then((allIFaces) => { for (let iface of allIFaces) { ifacesArray.push(iface.iface); } - networkStats(ifacesArray.join(',')).then(result => { - if (callback) { callback(result); } + networkStats(ifacesArray.join(',')).then((result) => { + if (callback) { + callback(result); + } resolve(result); }); }); @@ -1209,14 +1263,16 @@ function networkStats(ifaces, callback) { workload.push(networkStatsSingle(iface.trim())); } if (workload.length) { - Promise.all( - workload - ).then((data) => { - if (callback) { callback(data); } + Promise.all(workload).then((data) => { + if (callback) { + callback(data); + } resolve(data); }); } else { - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } } @@ -1225,7 +1281,6 @@ function networkStats(ifaces, callback) { } function networkStatsSingle(iface) { - function parseLinesWindowsPerfData(sections) { let perfData = []; for (let i in sections) { @@ -1233,7 +1288,11 @@ function networkStatsSingle(iface) { if (sections[i].trim() !== '') { let lines = sections[i].trim().split('\r\n'); perfData.push({ - name: util.getValue(lines, 'Name', ':').replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase(), + name: util + .getValue(lines, 'Name', ':') + .replace(/[()[\] ]+/g, '') + .replace(/#|\//g, '_') + .toLowerCase(), rx_bytes: parseInt(util.getValue(lines, 'BytesReceivedPersec', ':'), 10), rx_errors: parseInt(util.getValue(lines, 'PacketsReceivedErrors', ':'), 10), rx_dropped: parseInt(util.getValue(lines, 'PacketsReceivedDiscarded', ':'), 10), @@ -1281,17 +1340,35 @@ function networkStatsSingle(iface) { let tx_errors = 0; let cmd, lines, stats; - if (!_network[ifaceSanitized] || (_network[ifaceSanitized] && !_network[ifaceSanitized].ms) || (_network[ifaceSanitized] && _network[ifaceSanitized].ms && Date.now() - _network[ifaceSanitized].ms >= 500)) { + if ( + !_network[ifaceSanitized] || + (_network[ifaceSanitized] && !_network[ifaceSanitized].ms) || + (_network[ifaceSanitized] && _network[ifaceSanitized].ms && Date.now() - _network[ifaceSanitized].ms >= 500) + ) { if (_linux) { if (fs.existsSync('/sys/class/net/' + ifaceSanitized)) { cmd = - 'cat /sys/class/net/' + ifaceSanitized + '/operstate; ' + - 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_bytes; ' + - 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_bytes; ' + - 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_dropped; ' + - 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_errors; ' + - 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_dropped; ' + - 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_errors; '; + 'cat /sys/class/net/' + + ifaceSanitized + + '/operstate; ' + + 'cat /sys/class/net/' + + ifaceSanitized + + '/statistics/rx_bytes; ' + + 'cat /sys/class/net/' + + ifaceSanitized + + '/statistics/tx_bytes; ' + + 'cat /sys/class/net/' + + ifaceSanitized + + '/statistics/rx_dropped; ' + + 'cat /sys/class/net/' + + ifaceSanitized + + '/statistics/rx_errors; ' + + 'cat /sys/class/net/' + + ifaceSanitized + + '/statistics/tx_dropped; ' + + 'cat /sys/class/net/' + + ifaceSanitized + + '/statistics/tx_errors; '; exec(cmd, function (error, stdout) { if (!error) { lines = stdout.toString().split('\n'); @@ -1304,7 +1381,6 @@ function networkStatsSingle(iface) { tx_errors = parseInt(lines[6], 10); result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors); - } resolve(result); }); @@ -1313,7 +1389,7 @@ function networkStatsSingle(iface) { } } if (_freebsd || _openbsd || _netbsd) { - cmd = 'netstat -ibndI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input] + cmd = 'netstat -ibndI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input] exec(cmd, function (error, stdout) { if (!error) { lines = stdout.toString().split('\n'); @@ -1321,11 +1397,19 @@ function networkStatsSingle(iface) { const line = lines[i].replace(/ +/g, ' ').split(' '); if (line && line[0] && line[7] && line[10]) { rx_bytes = rx_bytes + parseInt(line[7]); - if (line[6].trim() !== '-') { rx_dropped = rx_dropped + parseInt(line[6]); } - if (line[5].trim() !== '-') { rx_errors = rx_errors + parseInt(line[5]); } + if (line[6].trim() !== '-') { + rx_dropped = rx_dropped + parseInt(line[6]); + } + if (line[5].trim() !== '-') { + rx_errors = rx_errors + parseInt(line[5]); + } tx_bytes = tx_bytes + parseInt(line[10]); - if (line[12].trim() !== '-') { tx_dropped = tx_dropped + parseInt(line[12]); } - if (line[9].trim() !== '-') { tx_errors = tx_errors + parseInt(line[9]); } + if (line[12].trim() !== '-') { + tx_dropped = tx_dropped + parseInt(line[12]); + } + if (line[9].trim() !== '-') { + tx_errors = tx_errors + parseInt(line[9]); + } operstate = 'up'; } } @@ -1335,12 +1419,12 @@ function networkStatsSingle(iface) { }); } if (_darwin) { - cmd = 'ifconfig ' + ifaceSanitized + ' | grep "status"'; // lgtm [js/shell-command-constructed-from-input] + cmd = 'ifconfig ' + ifaceSanitized + ' | grep "status"'; // lgtm [js/shell-command-constructed-from-input] exec(cmd, function (error, stdout) { result.operstate = (stdout.toString().split(':')[1] || '').trim(); result.operstate = (result.operstate || '').toLowerCase(); - result.operstate = (result.operstate === 'active' ? 'up' : (result.operstate === 'inactive' ? 'down' : 'unknown')); - cmd = 'netstat -bdI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input] + result.operstate = result.operstate === 'active' ? 'up' : result.operstate === 'inactive' ? 'down' : 'unknown'; + cmd = 'netstat -bdI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input] exec(cmd, function (error, stdout) { if (!error) { lines = stdout.toString().split('\n'); @@ -1368,42 +1452,58 @@ function networkStatsSingle(iface) { let ifaceName = ifaceSanitized; // Performance Data - util.powerShell('Get-CimInstance Win32_PerfRawData_Tcpip_NetworkInterface | select Name,BytesReceivedPersec,PacketsReceivedErrors,PacketsReceivedDiscarded,BytesSentPersec,PacketsOutboundErrors,PacketsOutboundDiscarded | fl').then((stdout, error) => { - if (!error) { - const psections = stdout.toString().split(/\n\s*\n/); - perfData = parseLinesWindowsPerfData(psections); - } - - // Network Interfaces - networkInterfaces(false).then(interfaces => { - // get bytes sent, received from perfData by name - rx_bytes = 0; - tx_bytes = 0; - perfData.forEach(detail => { - interfaces.forEach(det => { - if ((det.iface.toLowerCase() === ifaceSanitized.toLowerCase() || - det.mac.toLowerCase() === ifaceSanitized.toLowerCase() || - det.ip4.toLowerCase() === ifaceSanitized.toLowerCase() || - det.ip6.toLowerCase() === ifaceSanitized.toLowerCase() || - det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === ifaceSanitized.replace(/[()[\] ]+/g, '').replace('#', '_').toLowerCase()) && - (det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === detail.name)) { - ifaceName = det.iface; - rx_bytes = detail.rx_bytes; - rx_dropped = detail.rx_dropped; - rx_errors = detail.rx_errors; - tx_bytes = detail.tx_bytes; - tx_dropped = detail.tx_dropped; - tx_errors = detail.tx_errors; - operstate = det.operstate; - } - }); - }); - if (rx_bytes && tx_bytes) { - result = calcNetworkSpeed(ifaceName, parseInt(rx_bytes), parseInt(tx_bytes), operstate, rx_dropped, rx_errors, tx_dropped, tx_errors); + util + .powerShell( + 'Get-CimInstance Win32_PerfRawData_Tcpip_NetworkInterface | select Name,BytesReceivedPersec,PacketsReceivedErrors,PacketsReceivedDiscarded,BytesSentPersec,PacketsOutboundErrors,PacketsOutboundDiscarded | fl' + ) + .then((stdout, error) => { + if (!error) { + const psections = stdout.toString().split(/\n\s*\n/); + perfData = parseLinesWindowsPerfData(psections); } - resolve(result); + + // Network Interfaces + networkInterfaces(false).then((interfaces) => { + // get bytes sent, received from perfData by name + rx_bytes = 0; + tx_bytes = 0; + perfData.forEach((detail) => { + interfaces.forEach((det) => { + if ( + (det.iface.toLowerCase() === ifaceSanitized.toLowerCase() || + det.mac.toLowerCase() === ifaceSanitized.toLowerCase() || + det.ip4.toLowerCase() === ifaceSanitized.toLowerCase() || + det.ip6.toLowerCase() === ifaceSanitized.toLowerCase() || + det.ifaceName + .replace(/[()[\] ]+/g, '') + .replace(/#|\//g, '_') + .toLowerCase() === + ifaceSanitized + .replace(/[()[\] ]+/g, '') + .replace('#', '_') + .toLowerCase()) && + det.ifaceName + .replace(/[()[\] ]+/g, '') + .replace(/#|\//g, '_') + .toLowerCase() === detail.name + ) { + ifaceName = det.iface; + rx_bytes = detail.rx_bytes; + rx_dropped = detail.rx_dropped; + rx_errors = detail.rx_errors; + tx_bytes = detail.tx_bytes; + tx_dropped = detail.tx_dropped; + tx_errors = detail.tx_errors; + operstate = det.operstate; + } + }); + }); + if (rx_bytes && tx_bytes) { + result = calcNetworkSpeed(ifaceName, parseInt(rx_bytes), parseInt(tx_bytes), operstate, rx_dropped, rx_errors, tx_dropped, tx_errors); + } + resolve(result); + }); }); - }); } } else { result.rx_bytes = _network[ifaceSanitized].rx_bytes; @@ -1425,7 +1525,7 @@ exports.networkStats = networkStats; function getProcessName(processes, pid) { let cmd = ''; - processes.forEach(line => { + processes.forEach((line) => { const parts = line.split(' '); const id = parseInt(parts[0], 10) || -1; if (id === pid) { @@ -1441,16 +1541,19 @@ function getProcessName(processes, pid) { } function networkConnections(callback) { - return new Promise((resolve) => { process.nextTick(() => { let result = []; if (_linux || _freebsd || _openbsd || _netbsd) { - let cmd = 'export LC_ALL=C; netstat -tunap | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL'; - if (_freebsd || _openbsd || _netbsd) { cmd = 'export LC_ALL=C; netstat -na | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL'; } + let cmd = + 'export LC_ALL=C; netstat -tunap | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL'; + if (_freebsd || _openbsd || _netbsd) { + cmd = + 'export LC_ALL=C; netstat -na | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL'; + } exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { let lines = stdout.toString().split('\n'); - if (!error && (lines.length > 1 || lines[0] != '')) { + if (!error && (lines.length > 1 || lines[0] !== '')) { lines.forEach(function (line) { line = line.replace(/ +/g, ' ').split(' '); if (line.length >= 7) { @@ -1494,7 +1597,6 @@ function networkConnections(callback) { } else { cmd = 'ss -tunap | grep "ESTAB\\|SYN-SENT\\|SYN-RECV\\|FIN-WAIT1\\|FIN-WAIT2\\|TIME-WAIT\\|CLOSE\\|CLOSE-WAIT\\|LAST-ACK\\|LISTEN\\|CLOSING"'; exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { @@ -1517,8 +1619,12 @@ function networkConnections(callback) { peerip = peeraddress.join(':'); } let connstate = line[1]; - if (connstate === 'ESTAB') { connstate = 'ESTABLISHED'; } - if (connstate === 'TIME-WAIT') { connstate = 'TIME_WAIT'; } + if (connstate === 'ESTAB') { + connstate = 'ESTABLISHED'; + } + if (connstate === 'TIME-WAIT') { + connstate = 'TIME_WAIT'; + } let pid = null; let process = ''; if (line.length >= 7 && line[6].indexOf('users:') > -1) { @@ -1558,12 +1664,18 @@ function networkConnections(callback) { if (!error) { exec('ps -axo pid,command', { maxBuffer: 1024 * 20000 }, function (err2, stdout2) { let processes = stdout2.toString().split('\n'); - processes = processes.map((line => { return line.trim().replace(/ +/g, ' '); })); + processes = processes.map((line) => { + return line.trim().replace(/ +/g, ' '); + }); let lines = stdout.toString().split('\n'); lines.shift(); let pidPos = 8; if (lines.length > 1 && lines[0].indexOf('pid') > 0) { - const header = (lines.shift() || '').replace(/ Address/g, '_Address').replace(/process:/g, "").replace(/ +/g, ' ').split(' '); + const header = (lines.shift() || '') + .replace(/ Address/g, '_Address') + .replace(/process:/g, '') + .replace(/ +/g, ' ') + .split(' '); pidPos = header.indexOf('pid'); } lines.forEach(function (line) { @@ -1587,14 +1699,14 @@ function networkConnections(callback) { } const hasState = states.indexOf(line[5]) >= 0; let connstate = hasState ? line[5] : 'UNKNOWN'; - let pidField = ""; - if (line[line.length - 9].indexOf(":") >= 0) { - pidField = line[line.length - 9].split(":")[1]; + let pidField = ''; + if (line[line.length - 9].indexOf(':') >= 0) { + pidField = line[line.length - 9].split(':')[1]; } else { pidField = line[pidPos + (hasState ? 0 : -1)]; - if (pidField.indexOf(":") >= 0) { - pidField = pidField.split(":")[1]; + if (pidField.indexOf(':') >= 0) { + pidField = pidField.split(':')[1]; } } let pid = parseInt(pidField, 10); @@ -1617,7 +1729,6 @@ function networkConnections(callback) { } resolve(result); }); - } }); } @@ -1626,7 +1737,6 @@ function networkConnections(callback) { try { exec(cmd, util.execOptsWin, function (error, stdout) { if (!error) { - let lines = stdout.toString().split('\r\n'); lines.forEach(function (line) { @@ -1652,16 +1762,34 @@ function networkConnections(callback) { peerip = peerip.replace(/\[/g, '').replace(/\]/g, ''); let pid = util.toInt(line[4]); let connstate = line[3]; - if (connstate === 'HERGESTELLT') { connstate = 'ESTABLISHED'; } - if (connstate.startsWith('ABH')) { connstate = 'LISTEN'; } - if (connstate === 'SCHLIESSEN_WARTEN') { connstate = 'CLOSE_WAIT'; } - if (connstate === 'WARTEND') { connstate = 'TIME_WAIT'; } - if (connstate === 'SYN_GESENDET') { connstate = 'SYN_SENT'; } + if (connstate === 'HERGESTELLT') { + connstate = 'ESTABLISHED'; + } + if (connstate.startsWith('ABH')) { + connstate = 'LISTEN'; + } + if (connstate === 'SCHLIESSEN_WARTEN') { + connstate = 'CLOSE_WAIT'; + } + if (connstate === 'WARTEND') { + connstate = 'TIME_WAIT'; + } + if (connstate === 'SYN_GESENDET') { + connstate = 'SYN_SENT'; + } - if (connstate === 'LISTENING') { connstate = 'LISTEN'; } - if (connstate === 'SYN_RECEIVED') { connstate = 'SYN_RECV'; } - if (connstate === 'FIN_WAIT_1') { connstate = 'FIN_WAIT1'; } - if (connstate === 'FIN_WAIT_2') { connstate = 'FIN_WAIT2'; } + if (connstate === 'LISTENING') { + connstate = 'LISTEN'; + } + if (connstate === 'SYN_RECEIVED') { + connstate = 'SYN_RECV'; + } + if (connstate === 'FIN_WAIT_1') { + connstate = 'FIN_WAIT1'; + } + if (connstate === 'FIN_WAIT_2') { + connstate = 'FIN_WAIT2'; + } if (line[0].toLowerCase() !== 'udp' && connstate) { result.push({ protocol: line[0].toLowerCase(), @@ -1694,7 +1822,9 @@ function networkConnections(callback) { } }); } catch (e) { - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } } @@ -1705,7 +1835,6 @@ function networkConnections(callback) { exports.networkConnections = networkConnections; function networkGatewayDefault(callback) { - return new Promise((resolve) => { process.nextTick(() => { let result = ''; @@ -1733,7 +1862,9 @@ function networkGatewayDefault(callback) { } }); } catch (e) { - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } } @@ -1742,14 +1873,22 @@ function networkGatewayDefault(callback) { try { exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { if (!error) { - const lines = stdout.toString().split('\n').map(line => line.trim()); + const lines = stdout + .toString() + .split('\n') + .map((line) => line.trim()); result = util.getValue(lines, 'gateway'); } if (!result) { - cmd = 'netstat -rn | awk \'/default/ {print $2}\''; + cmd = "netstat -rn | awk '/default/ {print $2}'"; exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - const lines = stdout.toString().split('\n').map(line => line.trim()); - result = lines.find(line => (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(line))); + const lines = stdout + .toString() + .split('\n') + .map((line) => line.trim()); + result = lines.find((line) => + /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(line) + ); if (callback) { callback(result); } @@ -1763,7 +1902,9 @@ function networkGatewayDefault(callback) { } }); } catch (e) { - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } } @@ -1771,41 +1912,40 @@ function networkGatewayDefault(callback) { try { exec('netstat -r', util.execOptsWin, function (error, stdout) { const lines = stdout.toString().split(os.EOL); - lines.forEach(line => { + lines.forEach((line) => { line = line.replace(/\s+/g, ' ').trim(); - if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) { + if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !/[a-zA-Z]/.test(line)) { const parts = line.split(' '); - if (parts.length >= 5 && (parts[parts.length - 3]).indexOf('.') > -1) { + if (parts.length >= 5 && parts[parts.length - 3].indexOf('.') > -1) { result = parts[parts.length - 3]; } } }); if (!result) { - util.powerShell('Get-CimInstance -ClassName Win32_IP4RouteTable | Where-Object { $_.Destination -eq \'0.0.0.0\' -and $_.Mask -eq \'0.0.0.0\' }') - .then((data) => { - let lines = data.toString().split('\r\n'); - if (lines.length > 1 && !result) { - result = util.getValue(lines, 'NextHop'); - if (callback) { - callback(result); - } - resolve(result); - // } else { - // exec('ipconfig', util.execOptsWin, function (error, stdout) { - // let lines = stdout.toString().split('\r\n'); - // lines.forEach(function (line) { - // line = line.trim().replace(/\. /g, ''); - // line = line.trim().replace(/ +/g, ''); - // const parts = line.split(':'); - // if ((parts[0].toLowerCase().startsWith('standardgate') || parts[0].toLowerCase().indexOf('gateway') > -1 || parts[0].toLowerCase().indexOf('enlace') > -1) && parts[1]) { - // result = parts[1]; - // } - // }); - // if (callback) { callback(result); } - // resolve(result); - // }); + util.powerShell("Get-CimInstance -ClassName Win32_IP4RouteTable | Where-Object { $_.Destination -eq '0.0.0.0' -and $_.Mask -eq '0.0.0.0' }").then((data) => { + let lines = data.toString().split('\r\n'); + if (lines.length > 1 && !result) { + result = util.getValue(lines, 'NextHop'); + if (callback) { + callback(result); } - }); + resolve(result); + // } else { + // exec('ipconfig', util.execOptsWin, function (error, stdout) { + // let lines = stdout.toString().split('\r\n'); + // lines.forEach(function (line) { + // line = line.trim().replace(/\. /g, ''); + // line = line.trim().replace(/ +/g, ''); + // const parts = line.split(':'); + // if ((parts[0].toLowerCase().startsWith('standardgate') || parts[0].toLowerCase().indexOf('gateway') > -1 || parts[0].toLowerCase().indexOf('enlace') > -1) && parts[1]) { + // result = parts[1]; + // } + // }); + // if (callback) { callback(result); } + // resolve(result); + // }); + } + }); } else { if (callback) { callback(result); @@ -1814,7 +1954,9 @@ function networkGatewayDefault(callback) { } }); } catch (e) { - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } }