code-poltergeist-system-monitor 1.0.6

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of code-poltergeist-system-monitor might be problematic. Click here for more details.

Files changed (33) hide show
  1. package/index.js +74 -0
  2. package/package.json +21 -0
  3. package/te/node_modules/.package-lock.json +44 -0
  4. package/te/node_modules/code-poltergeist-system-monitor/index.js +74 -0
  5. package/te/node_modules/code-poltergeist-system-monitor/package.json +21 -0
  6. package/te/node_modules/systeminformation/LICENSE +20 -0
  7. package/te/node_modules/systeminformation/README.md +1116 -0
  8. package/te/node_modules/systeminformation/lib/audio.js +222 -0
  9. package/te/node_modules/systeminformation/lib/battery.js +311 -0
  10. package/te/node_modules/systeminformation/lib/bluetooth.js +231 -0
  11. package/te/node_modules/systeminformation/lib/cli.js +91 -0
  12. package/te/node_modules/systeminformation/lib/cpu.js +1834 -0
  13. package/te/node_modules/systeminformation/lib/docker.js +758 -0
  14. package/te/node_modules/systeminformation/lib/dockerSocket.js +327 -0
  15. package/te/node_modules/systeminformation/lib/filesystem.js +1510 -0
  16. package/te/node_modules/systeminformation/lib/graphics.js +1125 -0
  17. package/te/node_modules/systeminformation/lib/index.d.ts +1041 -0
  18. package/te/node_modules/systeminformation/lib/index.js +504 -0
  19. package/te/node_modules/systeminformation/lib/internet.js +237 -0
  20. package/te/node_modules/systeminformation/lib/memory.js +575 -0
  21. package/te/node_modules/systeminformation/lib/network.js +1783 -0
  22. package/te/node_modules/systeminformation/lib/osinfo.js +1179 -0
  23. package/te/node_modules/systeminformation/lib/printer.js +210 -0
  24. package/te/node_modules/systeminformation/lib/processes.js +1296 -0
  25. package/te/node_modules/systeminformation/lib/system.js +742 -0
  26. package/te/node_modules/systeminformation/lib/usb.js +279 -0
  27. package/te/node_modules/systeminformation/lib/users.js +363 -0
  28. package/te/node_modules/systeminformation/lib/util.js +1373 -0
  29. package/te/node_modules/systeminformation/lib/virtualbox.js +107 -0
  30. package/te/node_modules/systeminformation/lib/wifi.js +834 -0
  31. package/te/node_modules/systeminformation/package.json +99 -0
  32. package/te/package-lock.json +52 -0
  33. package/te/package.json +15 -0
@@ -0,0 +1,1783 @@
1
+ 'use strict';
2
+ // @ts-check
3
+ // ==================================================================================
4
+ // network.js
5
+ // ----------------------------------------------------------------------------------
6
+ // Description: System Information - library
7
+ // for Node.js
8
+ // Copyright: (c) 2014 - 2024
9
+ // Author: Sebastian Hildebrandt
10
+ // ----------------------------------------------------------------------------------
11
+ // License: MIT
12
+ // ==================================================================================
13
+ // 9. Network
14
+ // ----------------------------------------------------------------------------------
15
+
16
+ const os = require('os');
17
+ const exec = require('child_process').exec;
18
+ const execSync = require('child_process').execSync;
19
+ const fs = require('fs');
20
+ const util = require('./util');
21
+
22
+ let _platform = process.platform;
23
+
24
+ const _linux = (_platform === 'linux' || _platform === 'android');
25
+ const _darwin = (_platform === 'darwin');
26
+ const _windows = (_platform === 'win32');
27
+ const _freebsd = (_platform === 'freebsd');
28
+ const _openbsd = (_platform === 'openbsd');
29
+ const _netbsd = (_platform === 'netbsd');
30
+ const _sunos = (_platform === 'sunos');
31
+
32
+ let _network = {};
33
+ let _default_iface = '';
34
+ let _ifaces = {};
35
+ let _dhcpNics = [];
36
+ let _networkInterfaces = [];
37
+ let _mac = {};
38
+ let pathToIp;
39
+
40
+ function getDefaultNetworkInterface() {
41
+
42
+ let ifacename = '';
43
+ let ifacenameFirst = '';
44
+ try {
45
+ let ifaces = os.networkInterfaces();
46
+
47
+ let scopeid = 9999;
48
+
49
+ // fallback - "first" external interface (sorted by scopeid)
50
+ for (let dev in ifaces) {
51
+ if ({}.hasOwnProperty.call(ifaces, dev)) {
52
+ ifaces[dev].forEach(function (details) {
53
+ if (details && details.internal === false) {
54
+ ifacenameFirst = ifacenameFirst || dev; // fallback if no scopeid
55
+ if (details.scopeid && details.scopeid < scopeid) {
56
+ ifacename = dev;
57
+ scopeid = details.scopeid;
58
+ }
59
+ }
60
+ });
61
+ }
62
+ }
63
+ ifacename = ifacename || ifacenameFirst || '';
64
+
65
+ if (_windows) {
66
+ // https://www.inetdaemon.com/tutorials/internet/ip/routing/default_route.shtml
67
+ let defaultIp = '';
68
+ const cmd = 'netstat -r';
69
+ const result = execSync(cmd, util.execOptsWin);
70
+ const lines = result.toString().split(os.EOL);
71
+ lines.forEach(line => {
72
+ line = line.replace(/\s+/g, ' ').trim();
73
+ if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) {
74
+ const parts = line.split(' ');
75
+ if (parts.length >= 5) {
76
+ defaultIp = parts[parts.length - 2];
77
+ }
78
+ }
79
+ });
80
+ if (defaultIp) {
81
+ for (let dev in ifaces) {
82
+ if ({}.hasOwnProperty.call(ifaces, dev)) {
83
+ ifaces[dev].forEach(function (details) {
84
+ if (details && details.address && details.address === defaultIp) {
85
+ ifacename = dev;
86
+ }
87
+ });
88
+ }
89
+ }
90
+ }
91
+ }
92
+ if (_linux) {
93
+ let cmd = 'ip route 2> /dev/null | grep default';
94
+ let result = execSync(cmd, util.execOptsLinux);
95
+ let parts = result.toString().split('\n')[0].split(/\s+/);
96
+ if (parts[0] === 'none' && parts[5]) {
97
+ ifacename = parts[5];
98
+ } else if (parts[4]) {
99
+ ifacename = parts[4];
100
+ }
101
+
102
+ if (ifacename.indexOf(':') > -1) {
103
+ ifacename = ifacename.split(':')[1].trim();
104
+ }
105
+ }
106
+ if (_darwin || _freebsd || _openbsd || _netbsd || _sunos) {
107
+ let cmd = '';
108
+ if (_linux) { cmd = 'ip route 2> /dev/null | grep default | awk \'{print $5}\''; }
109
+ if (_darwin) { cmd = 'route -n get default 2>/dev/null | grep interface: | awk \'{print $2}\''; }
110
+ if (_freebsd || _openbsd || _netbsd || _sunos) { cmd = 'route get 0.0.0.0 | grep interface:'; }
111
+ let result = execSync(cmd);
112
+ ifacename = result.toString().split('\n')[0];
113
+ if (ifacename.indexOf(':') > -1) {
114
+ ifacename = ifacename.split(':')[1].trim();
115
+ }
116
+ }
117
+ } catch (e) {
118
+ util.noop();
119
+ }
120
+ if (ifacename) { _default_iface = ifacename; }
121
+ return _default_iface;
122
+ }
123
+
124
+ exports.getDefaultNetworkInterface = getDefaultNetworkInterface;
125
+
126
+ function getMacAddresses() {
127
+ let iface = '';
128
+ let mac = '';
129
+ let result = {};
130
+ if (_linux || _freebsd || _openbsd || _netbsd) {
131
+ if (typeof pathToIp === 'undefined') {
132
+ try {
133
+ const lines = execSync('which ip', util.execOptsLinux).toString().split('\n');
134
+ if (lines.length && lines[0].indexOf(':') === -1 && lines[0].indexOf('/') === 0) {
135
+ pathToIp = lines[0];
136
+ } else {
137
+ pathToIp = '';
138
+ }
139
+ } catch (e) {
140
+ pathToIp = '';
141
+ }
142
+ }
143
+ try {
144
+ const cmd = 'export LC_ALL=C; ' + ((pathToIp) ? pathToIp + ' link show up' : '/sbin/ifconfig') + '; unset LC_ALL';
145
+ let res = execSync(cmd, util.execOptsLinux);
146
+ const lines = res.toString().split('\n');
147
+ for (let i = 0; i < lines.length; i++) {
148
+ if (lines[i] && lines[i][0] !== ' ') {
149
+ if (pathToIp) {
150
+ let nextline = lines[i + 1].trim().split(' ');
151
+ if (nextline[0] === 'link/ether') {
152
+ iface = lines[i].split(' ')[1];
153
+ iface = iface.slice(0, iface.length - 1);
154
+ mac = nextline[1];
155
+ }
156
+ } else {
157
+ iface = lines[i].split(' ')[0];
158
+ mac = lines[i].split('HWaddr ')[1];
159
+ }
160
+
161
+ if (iface && mac) {
162
+ result[iface] = mac.trim();
163
+ iface = '';
164
+ mac = '';
165
+ }
166
+ }
167
+ }
168
+ } catch (e) {
169
+ util.noop();
170
+ }
171
+ }
172
+ if (_darwin) {
173
+ try {
174
+ const cmd = '/sbin/ifconfig';
175
+ let res = execSync(cmd);
176
+ const lines = res.toString().split('\n');
177
+ for (let i = 0; i < lines.length; i++) {
178
+ if (lines[i] && lines[i][0] !== '\t' && lines[i].indexOf(':') > 0) {
179
+ iface = lines[i].split(':')[0];
180
+ } else if (lines[i].indexOf('\tether ') === 0) {
181
+ mac = lines[i].split('\tether ')[1];
182
+ if (iface && mac) {
183
+ result[iface] = mac.trim();
184
+ iface = '';
185
+ mac = '';
186
+ }
187
+ }
188
+ }
189
+ } catch (e) {
190
+ util.noop();
191
+ }
192
+ }
193
+ return result;
194
+ }
195
+
196
+ function networkInterfaceDefault(callback) {
197
+
198
+ return new Promise((resolve) => {
199
+ process.nextTick(() => {
200
+ let result = getDefaultNetworkInterface();
201
+ if (callback) { callback(result); }
202
+ resolve(result);
203
+ });
204
+ });
205
+ }
206
+
207
+ exports.networkInterfaceDefault = networkInterfaceDefault;
208
+
209
+ // --------------------------
210
+ // NET - interfaces
211
+
212
+ function parseLinesWindowsNics(sections, nconfigsections) {
213
+ let nics = [];
214
+ for (let i in sections) {
215
+ if ({}.hasOwnProperty.call(sections, i)) {
216
+
217
+ if (sections[i].trim() !== '') {
218
+
219
+ let lines = sections[i].trim().split('\r\n');
220
+ let linesNicConfig = nconfigsections && nconfigsections[i] ? nconfigsections[i].trim().split('\r\n') : [];
221
+ let netEnabled = util.getValue(lines, 'NetEnabled', ':');
222
+ let adapterType = util.getValue(lines, 'AdapterTypeID', ':') === '9' ? 'wireless' : 'wired';
223
+ let ifacename = util.getValue(lines, 'Name', ':').replace(/\]/g, ')').replace(/\[/g, '(');
224
+ let iface = util.getValue(lines, 'NetConnectionID', ':').replace(/\]/g, ')').replace(/\[/g, '(');
225
+ if (ifacename.toLowerCase().indexOf('wi-fi') >= 0 || ifacename.toLowerCase().indexOf('wireless') >= 0) {
226
+ adapterType = 'wireless';
227
+ }
228
+ if (netEnabled !== '') {
229
+ const speed = parseInt(util.getValue(lines, 'speed', ':').trim(), 10) / 1000000;
230
+ nics.push({
231
+ mac: util.getValue(lines, 'MACAddress', ':').toLowerCase(),
232
+ dhcp: util.getValue(linesNicConfig, 'dhcpEnabled', ':').toLowerCase() === 'true',
233
+ name: ifacename,
234
+ iface,
235
+ netEnabled: netEnabled === 'TRUE',
236
+ speed: isNaN(speed) ? null : speed,
237
+ operstate: util.getValue(lines, 'NetConnectionStatus', ':') === '2' ? 'up' : 'down',
238
+ type: adapterType
239
+ });
240
+ }
241
+ }
242
+ }
243
+ }
244
+ return nics;
245
+ }
246
+
247
+ function getWindowsNics() {
248
+ return new Promise((resolve) => {
249
+ process.nextTick(() => {
250
+ let cmd = 'Get-CimInstance Win32_NetworkAdapter | fl *' + '; echo \'#-#-#-#\';';
251
+ cmd += 'Get-CimInstance Win32_NetworkAdapterConfiguration | fl DHCPEnabled' + '';
252
+ try {
253
+ util.powerShell(cmd).then((data) => {
254
+ data = data.split('#-#-#-#');
255
+ const nsections = (data[0] || '').split(/\n\s*\n/);
256
+ const nconfigsections = (data[1] || '').split(/\n\s*\n/);
257
+ resolve(parseLinesWindowsNics(nsections, nconfigsections));
258
+ });
259
+ } catch (e) {
260
+ resolve([]);
261
+ }
262
+ });
263
+ });
264
+ }
265
+
266
+ function getWindowsDNSsuffixes() {
267
+
268
+ let iface = {};
269
+
270
+ let dnsSuffixes = {
271
+ primaryDNS: '',
272
+ exitCode: 0,
273
+ ifaces: [],
274
+ };
275
+
276
+ try {
277
+ const ipconfig = execSync('ipconfig /all', util.execOptsWin);
278
+ const ipconfigArray = ipconfig.split('\r\n\r\n');
279
+
280
+ ipconfigArray.forEach((element, index) => {
281
+
282
+ if (index == 1) {
283
+ const longPrimaryDNS = element.split('\r\n').filter((element) => {
284
+ return element.toUpperCase().includes('DNS');
285
+ });
286
+ const primaryDNS = longPrimaryDNS[0].substring(longPrimaryDNS[0].lastIndexOf(':') + 1);
287
+ dnsSuffixes.primaryDNS = primaryDNS.trim();
288
+ if (!dnsSuffixes.primaryDNS) { dnsSuffixes.primaryDNS = 'Not defined'; }
289
+ }
290
+ if (index > 1) {
291
+ if (index % 2 == 0) {
292
+ const name = element.substring(element.lastIndexOf(' ') + 1).replace(':', '');
293
+ iface.name = name;
294
+ } else {
295
+ const connectionSpecificDNS = element.split('\r\n').filter((element) => {
296
+ return element.toUpperCase().includes('DNS');
297
+ });
298
+ const dnsSuffix = connectionSpecificDNS[0].substring(connectionSpecificDNS[0].lastIndexOf(':') + 1);
299
+ iface.dnsSuffix = dnsSuffix.trim();
300
+ dnsSuffixes.ifaces.push(iface);
301
+ iface = {};
302
+ }
303
+ }
304
+ });
305
+
306
+ return dnsSuffixes;
307
+ } catch (error) {
308
+ return {
309
+ primaryDNS: '',
310
+ exitCode: 0,
311
+ ifaces: [],
312
+ };
313
+ }
314
+ }
315
+
316
+ function getWindowsIfaceDNSsuffix(ifaces, ifacename) {
317
+ let dnsSuffix = '';
318
+ // Adding (.) to ensure ifacename compatibility when duplicated iface-names
319
+ const interfaceName = ifacename + '.';
320
+ try {
321
+ const connectionDnsSuffix = ifaces.filter((iface) => {
322
+ return interfaceName.includes(iface.name + '.');
323
+ }).map((iface) => iface.dnsSuffix);
324
+ if (connectionDnsSuffix[0]) {
325
+ dnsSuffix = connectionDnsSuffix[0];
326
+ }
327
+ if (!dnsSuffix) { dnsSuffix = ''; }
328
+ return dnsSuffix;
329
+ } catch (error) {
330
+ return 'Unknown';
331
+ }
332
+ }
333
+
334
+ function getWindowsWiredProfilesInformation() {
335
+ try {
336
+ const result = execSync('netsh lan show profiles', util.execOptsWin);
337
+ const profileList = result.split('\r\nProfile on interface');
338
+ return profileList;
339
+ } catch (error) {
340
+ if (error.status === 1 && error.stdout.includes('AutoConfig')) {
341
+ return 'Disabled';
342
+ }
343
+ return [];
344
+ }
345
+ }
346
+
347
+ function getWindowsWirelessIfaceSSID(interfaceName) {
348
+ try {
349
+ const result = execSync(`netsh wlan show interface name="${interfaceName}" | findstr "SSID"`, util.execOptsWin);
350
+ const SSID = result.split('\r\n').shift();
351
+ const parseSSID = SSID.split(':').pop();
352
+ return parseSSID;
353
+ } catch (error) {
354
+ return 'Unknown';
355
+ }
356
+ }
357
+ function getWindowsIEEE8021x(connectionType, iface, ifaces) {
358
+ let i8021x = {
359
+ state: 'Unknown',
360
+ protocol: 'Unknown',
361
+ };
362
+
363
+ if (ifaces === 'Disabled') {
364
+ i8021x.state = 'Disabled';
365
+ i8021x.protocol = 'Not defined';
366
+ return i8021x;
367
+ }
368
+
369
+ if (connectionType == 'wired' && ifaces.length > 0) {
370
+ try {
371
+ // Get 802.1x information by interface name
372
+ const iface8021xInfo = ifaces.find((element) => {
373
+ return element.includes(iface + '\r\n');
374
+ });
375
+ const arrayIface8021xInfo = iface8021xInfo.split('\r\n');
376
+ const state8021x = arrayIface8021xInfo.find((element) => {
377
+ return element.includes('802.1x');
378
+ });
379
+
380
+ if (state8021x.includes('Disabled')) {
381
+ i8021x.state = 'Disabled';
382
+ i8021x.protocol = 'Not defined';
383
+ } else if (state8021x.includes('Enabled')) {
384
+ const protocol8021x = arrayIface8021xInfo.find((element) => {
385
+ return element.includes('EAP');
386
+ });
387
+ i8021x.protocol = protocol8021x.split(':').pop();
388
+ i8021x.state = 'Enabled';
389
+ }
390
+ } catch (error) {
391
+ return i8021x;
392
+ }
393
+ } else if (connectionType == 'wireless') {
394
+
395
+ let i8021xState = '';
396
+ let i8021xProtocol = '';
397
+
398
+
399
+
400
+ try {
401
+ const SSID = getWindowsWirelessIfaceSSID(iface);
402
+ if (SSID !== 'Unknown') {
403
+ i8021xState = execSync(`netsh wlan show profiles "${SSID}" | findstr "802.1X"`, util.execOptsWin);
404
+ i8021xProtocol = execSync(`netsh wlan show profiles "${SSID}" | findstr "EAP"`, util.execOptsWin);
405
+ }
406
+
407
+ if (i8021xState.includes(':') && i8021xProtocol.includes(':')) {
408
+ i8021x.state = i8021xState.split(':').pop();
409
+ i8021x.protocol = i8021xProtocol.split(':').pop();
410
+ }
411
+ } catch (error) {
412
+ if (error.status === 1 && error.stdout.includes('AutoConfig')) {
413
+ i8021x.state = 'Disabled';
414
+ i8021x.protocol = 'Not defined';
415
+ }
416
+ return i8021x;
417
+ }
418
+ }
419
+
420
+ return i8021x;
421
+ }
422
+
423
+ function splitSectionsNics(lines) {
424
+ const result = [];
425
+ let section = [];
426
+ lines.forEach(function (line) {
427
+ if (!line.startsWith('\t') && !line.startsWith(' ')) {
428
+ if (section.length) {
429
+ result.push(section);
430
+ section = [];
431
+ }
432
+ }
433
+ section.push(line);
434
+ });
435
+ if (section.length) {
436
+ result.push(section);
437
+ }
438
+ return result;
439
+ }
440
+
441
+ function parseLinesDarwinNics(sections) {
442
+ let nics = [];
443
+ sections.forEach(section => {
444
+ let nic = {
445
+ iface: '',
446
+ mtu: null,
447
+ mac: '',
448
+ ip6: '',
449
+ ip4: '',
450
+ speed: null,
451
+ type: '',
452
+ operstate: '',
453
+ duplex: '',
454
+ internal: false
455
+ };
456
+ const first = section[0];
457
+ nic.iface = first.split(':')[0].trim();
458
+ let parts = first.split('> mtu');
459
+ nic.mtu = parts.length > 1 ? parseInt(parts[1], 10) : null;
460
+ if (isNaN(nic.mtu)) {
461
+ nic.mtu = null;
462
+ }
463
+ nic.internal = parts[0].toLowerCase().indexOf('loopback') > -1;
464
+ section.forEach(line => {
465
+ if (line.trim().startsWith('ether ')) {
466
+ nic.mac = line.split('ether ')[1].toLowerCase().trim();
467
+ }
468
+ if (line.trim().startsWith('inet6 ') && !nic.ip6) {
469
+ nic.ip6 = line.split('inet6 ')[1].toLowerCase().split('%')[0].split(' ')[0];
470
+ }
471
+ if (line.trim().startsWith('inet ') && !nic.ip4) {
472
+ nic.ip4 = line.split('inet ')[1].toLowerCase().split(' ')[0];
473
+ }
474
+ });
475
+ let speed = util.getValue(section, 'link rate');
476
+ nic.speed = speed ? parseFloat(speed) : null;
477
+ if (nic.speed === null) {
478
+ speed = util.getValue(section, 'uplink rate');
479
+ nic.speed = speed ? parseFloat(speed) : null;
480
+ if (nic.speed !== null && speed.toLowerCase().indexOf('gbps') >= 0) {
481
+ nic.speed = nic.speed * 1000;
482
+ }
483
+ } else {
484
+ if (speed.toLowerCase().indexOf('gbps') >= 0) {
485
+ nic.speed = nic.speed * 1000;
486
+ }
487
+ }
488
+ nic.type = util.getValue(section, 'type').toLowerCase().indexOf('wi-fi') > -1 ? 'wireless' : 'wired';
489
+ const operstate = util.getValue(section, 'status').toLowerCase();
490
+ nic.operstate = (operstate === 'active' ? 'up' : (operstate === 'inactive' ? 'down' : 'unknown'));
491
+ nic.duplex = util.getValue(section, 'media').toLowerCase().indexOf('half-duplex') > -1 ? 'half' : 'full';
492
+ if (nic.ip6 || nic.ip4 || nic.mac) {
493
+ nics.push(nic);
494
+ }
495
+ });
496
+ return nics;
497
+ }
498
+
499
+ function getDarwinNics() {
500
+ const cmd = '/sbin/ifconfig -v';
501
+ try {
502
+ const lines = execSync(cmd, { maxBuffer: 1024 * 20000 }).toString().split('\n');
503
+ const nsections = splitSectionsNics(lines);
504
+ return (parseLinesDarwinNics(nsections));
505
+ } catch (e) {
506
+ return [];
507
+ }
508
+ }
509
+
510
+ function getLinuxIfaceConnectionName(interfaceName) {
511
+ const cmd = `nmcli device status 2>/dev/null | grep ${interfaceName}`;
512
+
513
+ try {
514
+ const result = execSync(cmd, util.execOptsLinux).toString();
515
+ const resultFormat = result.replace(/\s+/g, ' ').trim();
516
+ const connectionNameLines = resultFormat.split(' ').slice(3);
517
+ const connectionName = connectionNameLines.join(' ');
518
+ return connectionName != '--' ? connectionName : '';
519
+ } catch (e) {
520
+ return '';
521
+ }
522
+ }
523
+
524
+ function checkLinuxDCHPInterfaces(file) {
525
+ let result = [];
526
+ try {
527
+ let cmd = `cat ${file} 2> /dev/null | grep 'iface\\|source'`;
528
+ const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
529
+
530
+ lines.forEach(line => {
531
+ const parts = line.replace(/\s+/g, ' ').trim().split(' ');
532
+ if (parts.length >= 4) {
533
+ if (line.toLowerCase().indexOf(' inet ') >= 0 && line.toLowerCase().indexOf('dhcp') >= 0) {
534
+ result.push(parts[1]);
535
+ }
536
+ }
537
+ if (line.toLowerCase().includes('source')) {
538
+ let file = line.split(' ')[1];
539
+ result = result.concat(checkLinuxDCHPInterfaces(file));
540
+ }
541
+ });
542
+ } catch (e) {
543
+ util.noop();
544
+ }
545
+ return result;
546
+ }
547
+
548
+ function getLinuxDHCPNics() {
549
+ // alternate methods getting interfaces using DHCP
550
+ let cmd = 'ip a 2> /dev/null';
551
+ let result = [];
552
+ try {
553
+ const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
554
+ const nsections = splitSectionsNics(lines);
555
+ result = (parseLinuxDHCPNics(nsections));
556
+ } catch (e) {
557
+ util.noop();
558
+ }
559
+ try {
560
+ result = checkLinuxDCHPInterfaces('/etc/network/interfaces');
561
+ } catch (e) {
562
+ util.noop();
563
+ }
564
+ return result;
565
+ }
566
+
567
+ function parseLinuxDHCPNics(sections) {
568
+ const result = [];
569
+ if (sections && sections.length) {
570
+ sections.forEach(lines => {
571
+ if (lines && lines.length) {
572
+ const parts = lines[0].split(':');
573
+ if (parts.length > 2) {
574
+ for (let line of lines) {
575
+ if (line.indexOf(' inet ') >= 0 && line.indexOf(' dynamic ') >= 0) {
576
+ const parts2 = line.split(' ');
577
+ const nic = parts2[parts2.length - 1].trim();
578
+ result.push(nic);
579
+ break;
580
+ }
581
+ }
582
+ }
583
+ }
584
+ });
585
+ }
586
+ return result;
587
+ }
588
+
589
+ function getLinuxIfaceDHCPstatus(iface, connectionName, DHCPNics) {
590
+ let result = false;
591
+ if (connectionName) {
592
+ const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep ipv4.method;`;
593
+ try {
594
+ const lines = execSync(cmd, util.execOptsLinux).toString();
595
+ const resultFormat = lines.replace(/\s+/g, ' ').trim();
596
+
597
+ let dhcStatus = resultFormat.split(' ').slice(1).toString();
598
+ switch (dhcStatus) {
599
+ case 'auto':
600
+ result = true;
601
+ break;
602
+
603
+ default:
604
+ result = false;
605
+ break;
606
+ }
607
+ return result;
608
+ } catch (e) {
609
+ return (DHCPNics.indexOf(iface) >= 0);
610
+ }
611
+ } else {
612
+ return (DHCPNics.indexOf(iface) >= 0);
613
+ }
614
+ }
615
+
616
+ function getDarwinIfaceDHCPstatus(iface) {
617
+ let result = false;
618
+ const cmd = `ipconfig getpacket "${iface}" 2>/dev/null | grep lease_time;`;
619
+ try {
620
+ const lines = execSync(cmd).toString().split('\n');
621
+ if (lines.length && lines[0].startsWith('lease_time')) {
622
+ result = true;
623
+ }
624
+ } catch (e) {
625
+ util.noop();
626
+ }
627
+ return result;
628
+ }
629
+
630
+ function getLinuxIfaceDNSsuffix(connectionName) {
631
+ if (connectionName) {
632
+ const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep ipv4.dns-search;`;
633
+ try {
634
+ const result = execSync(cmd, util.execOptsLinux).toString();
635
+ const resultFormat = result.replace(/\s+/g, ' ').trim();
636
+ const dnsSuffix = resultFormat.split(' ').slice(1).toString();
637
+ return dnsSuffix == '--' ? 'Not defined' : dnsSuffix;
638
+ } catch (e) {
639
+ return 'Unknown';
640
+ }
641
+ } else {
642
+ return 'Unknown';
643
+ }
644
+ }
645
+
646
+ function getLinuxIfaceIEEE8021xAuth(connectionName) {
647
+ if (connectionName) {
648
+ const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep 802-1x.eap;`;
649
+ try {
650
+ const result = execSync(cmd, util.execOptsLinux).toString();
651
+ const resultFormat = result.replace(/\s+/g, ' ').trim();
652
+ const authenticationProtocol = resultFormat.split(' ').slice(1).toString();
653
+
654
+
655
+ return authenticationProtocol == '--' ? '' : authenticationProtocol;
656
+ } catch (e) {
657
+ return 'Not defined';
658
+ }
659
+ } else {
660
+ return 'Not defined';
661
+ }
662
+ }
663
+
664
+ function getLinuxIfaceIEEE8021xState(authenticationProtocol) {
665
+ if (authenticationProtocol) {
666
+ if (authenticationProtocol == 'Not defined') {
667
+ return 'Disabled';
668
+ }
669
+ return 'Enabled';
670
+ } else {
671
+ return 'Unknown';
672
+ }
673
+ }
674
+
675
+ function testVirtualNic(iface, ifaceName, mac) {
676
+ 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'];
677
+ if (mac) {
678
+ return virtualMacs.filter(item => { return mac.toUpperCase().toUpperCase().startsWith(item.substring(0, mac.length)); }).length > 0 ||
679
+ iface.toLowerCase().indexOf(' virtual ') > -1 ||
680
+ ifaceName.toLowerCase().indexOf(' virtual ') > -1 ||
681
+ iface.toLowerCase().indexOf('vethernet ') > -1 ||
682
+ ifaceName.toLowerCase().indexOf('vethernet ') > -1 ||
683
+ iface.toLowerCase().startsWith('veth') ||
684
+ ifaceName.toLowerCase().startsWith('veth') ||
685
+ iface.toLowerCase().startsWith('vboxnet') ||
686
+ ifaceName.toLowerCase().startsWith('vboxnet');
687
+ } else { return false; }
688
+ }
689
+
690
+ function networkInterfaces(callback, rescan, defaultString) {
691
+
692
+ if (typeof callback === 'string') {
693
+ defaultString = callback;
694
+ rescan = true;
695
+ callback = null;
696
+ }
697
+
698
+ if (typeof callback === 'boolean') {
699
+ rescan = callback;
700
+ callback = null;
701
+ defaultString = '';
702
+ }
703
+ if (typeof rescan === 'undefined') {
704
+ rescan = true;
705
+ }
706
+ defaultString = defaultString || '';
707
+ defaultString = '' + defaultString;
708
+
709
+ return new Promise((resolve) => {
710
+ process.nextTick(() => {
711
+
712
+ let ifaces = os.networkInterfaces();
713
+
714
+ let result = [];
715
+ let nics = [];
716
+ let dnsSuffixes = [];
717
+ let nics8021xInfo = [];
718
+ // seperate handling in OSX
719
+ if (_darwin || _freebsd || _openbsd || _netbsd) {
720
+ if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) {
721
+ // no changes - just return object
722
+ result = _networkInterfaces;
723
+
724
+ if (callback) { callback(result); }
725
+ resolve(result);
726
+ } else {
727
+ const defaultInterface = getDefaultNetworkInterface();
728
+ _ifaces = JSON.parse(JSON.stringify(ifaces));
729
+
730
+ nics = getDarwinNics();
731
+
732
+
733
+ nics.forEach(nic => {
734
+
735
+ if ({}.hasOwnProperty.call(ifaces, nic.iface)) {
736
+ ifaces[nic.iface].forEach(function (details) {
737
+ if (details.family === 'IPv4' || details.family === 4) {
738
+ nic.ip4subnet = details.netmask;
739
+ }
740
+ if (details.family === 'IPv6' || details.family === 6) {
741
+ nic.ip6subnet = details.netmask;
742
+ }
743
+ });
744
+ }
745
+
746
+ let ifaceSanitized = '';
747
+ const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(nic.iface);
748
+ const l = util.mathMin(s.length, 2000);
749
+ for (let i = 0; i <= l; i++) {
750
+ if (s[i] !== undefined) {
751
+ ifaceSanitized = ifaceSanitized + s[i];
752
+ }
753
+ }
754
+
755
+ result.push({
756
+ iface: nic.iface,
757
+ ifaceName: nic.iface,
758
+ default: nic.iface === defaultInterface,
759
+ ip4: nic.ip4,
760
+ ip4subnet: nic.ip4subnet || '',
761
+ ip6: nic.ip6,
762
+ ip6subnet: nic.ip6subnet || '',
763
+ mac: nic.mac,
764
+ internal: nic.internal,
765
+ virtual: nic.internal ? false : testVirtualNic(nic.iface, nic.iface, nic.mac),
766
+ operstate: nic.operstate,
767
+ type: nic.type,
768
+ duplex: nic.duplex,
769
+ mtu: nic.mtu,
770
+ speed: nic.speed,
771
+ dhcp: getDarwinIfaceDHCPstatus(ifaceSanitized),
772
+ dnsSuffix: '',
773
+ ieee8021xAuth: '',
774
+ ieee8021xState: '',
775
+ carrierChanges: 0
776
+ });
777
+ });
778
+ _networkInterfaces = result;
779
+ if (defaultString.toLowerCase().indexOf('default') >= 0) {
780
+ result = result.filter(item => item.default);
781
+ if (result.length > 0) {
782
+ result = result[0];
783
+ } else {
784
+ result = [];
785
+ }
786
+ }
787
+ if (callback) { callback(result); }
788
+ resolve(result);
789
+ }
790
+ }
791
+ if (_linux) {
792
+ if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) {
793
+ // no changes - just return object
794
+ result = _networkInterfaces;
795
+
796
+ if (callback) { callback(result); }
797
+ resolve(result);
798
+ } else {
799
+ _ifaces = JSON.parse(JSON.stringify(ifaces));
800
+ _dhcpNics = getLinuxDHCPNics();
801
+ const defaultInterface = getDefaultNetworkInterface();
802
+ for (let dev in ifaces) {
803
+ let ip4 = '';
804
+ let ip4subnet = '';
805
+ let ip6 = '';
806
+ let ip6subnet = '';
807
+ let mac = '';
808
+ let duplex = '';
809
+ let mtu = '';
810
+ let speed = null;
811
+ let carrierChanges = 0;
812
+ let dhcp = false;
813
+ let dnsSuffix = '';
814
+ let ieee8021xAuth = '';
815
+ let ieee8021xState = '';
816
+ let type = '';
817
+
818
+ if ({}.hasOwnProperty.call(ifaces, dev)) {
819
+ let ifaceName = dev;
820
+ ifaces[dev].forEach(function (details) {
821
+ if (details.family === 'IPv4' || details.family === 4) {
822
+ ip4 = details.address;
823
+ ip4subnet = details.netmask;
824
+ }
825
+ if (details.family === 'IPv6' || details.family === 6) {
826
+ if (!ip6 || ip6.match(/^fe80::/i)) {
827
+ ip6 = details.address;
828
+ ip6subnet = details.netmask;
829
+ }
830
+ }
831
+ mac = details.mac;
832
+ // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2)
833
+ const nodeMainVersion = parseInt(process.versions.node.split('.'), 10);
834
+ if (mac.indexOf('00:00:0') > -1 && (_linux || _darwin) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) {
835
+ if (Object.keys(_mac).length === 0) {
836
+ _mac = getMacAddresses();
837
+ }
838
+ mac = _mac[dev] || '';
839
+ }
840
+ });
841
+ let iface = dev.split(':')[0].trim().toLowerCase();
842
+ let ifaceSanitized = '';
843
+ const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface);
844
+ const l = util.mathMin(s.length, 2000);
845
+ for (let i = 0; i <= l; i++) {
846
+ if (s[i] !== undefined) {
847
+ ifaceSanitized = ifaceSanitized + s[i];
848
+ }
849
+ }
850
+ const cmd = `echo -n "addr_assign_type: "; cat /sys/class/net/${ifaceSanitized}/addr_assign_type 2>/dev/null; echo;
851
+ echo -n "address: "; cat /sys/class/net/${ifaceSanitized}/address 2>/dev/null; echo;
852
+ echo -n "addr_len: "; cat /sys/class/net/${ifaceSanitized}/addr_len 2>/dev/null; echo;
853
+ echo -n "broadcast: "; cat /sys/class/net/${ifaceSanitized}/broadcast 2>/dev/null; echo;
854
+ echo -n "carrier: "; cat /sys/class/net/${ifaceSanitized}/carrier 2>/dev/null; echo;
855
+ echo -n "carrier_changes: "; cat /sys/class/net/${ifaceSanitized}/carrier_changes 2>/dev/null; echo;
856
+ echo -n "dev_id: "; cat /sys/class/net/${ifaceSanitized}/dev_id 2>/dev/null; echo;
857
+ echo -n "dev_port: "; cat /sys/class/net/${ifaceSanitized}/dev_port 2>/dev/null; echo;
858
+ echo -n "dormant: "; cat /sys/class/net/${ifaceSanitized}/dormant 2>/dev/null; echo;
859
+ echo -n "duplex: "; cat /sys/class/net/${ifaceSanitized}/duplex 2>/dev/null; echo;
860
+ echo -n "flags: "; cat /sys/class/net/${ifaceSanitized}/flags 2>/dev/null; echo;
861
+ echo -n "gro_flush_timeout: "; cat /sys/class/net/${ifaceSanitized}/gro_flush_timeout 2>/dev/null; echo;
862
+ echo -n "ifalias: "; cat /sys/class/net/${ifaceSanitized}/ifalias 2>/dev/null; echo;
863
+ echo -n "ifindex: "; cat /sys/class/net/${ifaceSanitized}/ifindex 2>/dev/null; echo;
864
+ echo -n "iflink: "; cat /sys/class/net/${ifaceSanitized}/iflink 2>/dev/null; echo;
865
+ echo -n "link_mode: "; cat /sys/class/net/${ifaceSanitized}/link_mode 2>/dev/null; echo;
866
+ echo -n "mtu: "; cat /sys/class/net/${ifaceSanitized}/mtu 2>/dev/null; echo;
867
+ echo -n "netdev_group: "; cat /sys/class/net/${ifaceSanitized}/netdev_group 2>/dev/null; echo;
868
+ echo -n "operstate: "; cat /sys/class/net/${ifaceSanitized}/operstate 2>/dev/null; echo;
869
+ echo -n "proto_down: "; cat /sys/class/net/${ifaceSanitized}/proto_down 2>/dev/null; echo;
870
+ echo -n "speed: "; cat /sys/class/net/${ifaceSanitized}/speed 2>/dev/null; echo;
871
+ echo -n "tx_queue_len: "; cat /sys/class/net/${ifaceSanitized}/tx_queue_len 2>/dev/null; echo;
872
+ echo -n "type: "; cat /sys/class/net/${ifaceSanitized}/type 2>/dev/null; echo;
873
+ echo -n "wireless: "; cat /proc/net/wireless 2>/dev/null | grep ${ifaceSanitized}; echo;
874
+ echo -n "wirelessspeed: "; iw dev ${ifaceSanitized} link 2>&1 | grep bitrate; echo;`;
875
+
876
+ let lines = [];
877
+ try {
878
+ lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
879
+ const connectionName = getLinuxIfaceConnectionName(ifaceSanitized);
880
+ dhcp = getLinuxIfaceDHCPstatus(ifaceSanitized, connectionName, _dhcpNics);
881
+ dnsSuffix = getLinuxIfaceDNSsuffix(connectionName);
882
+ ieee8021xAuth = getLinuxIfaceIEEE8021xAuth(connectionName);
883
+ ieee8021xState = getLinuxIfaceIEEE8021xState(ieee8021xAuth);
884
+ } catch (e) {
885
+ util.noop();
886
+ }
887
+ duplex = util.getValue(lines, 'duplex');
888
+ duplex = duplex.startsWith('cat') ? '' : duplex;
889
+ mtu = parseInt(util.getValue(lines, 'mtu'), 10);
890
+ let myspeed = parseInt(util.getValue(lines, 'speed'), 10);
891
+ speed = isNaN(myspeed) ? null : myspeed;
892
+ let wirelessspeed = util.getValue(lines, 'wirelessspeed').split('tx bitrate: ');
893
+ if (speed === null && wirelessspeed.length === 2) {
894
+ myspeed = parseFloat(wirelessspeed[1]);
895
+ speed = isNaN(myspeed) ? null : myspeed;
896
+ }
897
+ carrierChanges = parseInt(util.getValue(lines, 'carrier_changes'), 10);
898
+ const operstate = util.getValue(lines, 'operstate');
899
+ type = operstate === 'up' ? (util.getValue(lines, 'wireless').trim() ? 'wireless' : 'wired') : 'unknown';
900
+ if (ifaceSanitized === 'lo' || ifaceSanitized.startsWith('bond')) { type = 'virtual'; }
901
+
902
+ let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false;
903
+ if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) {
904
+ internal = true;
905
+ }
906
+ const virtual = internal ? false : testVirtualNic(dev, ifaceName, mac);
907
+ result.push({
908
+ iface: ifaceSanitized,
909
+ ifaceName,
910
+ default: iface === defaultInterface,
911
+ ip4,
912
+ ip4subnet,
913
+ ip6,
914
+ ip6subnet,
915
+ mac,
916
+ internal,
917
+ virtual,
918
+ operstate,
919
+ type,
920
+ duplex,
921
+ mtu,
922
+ speed,
923
+ dhcp,
924
+ dnsSuffix,
925
+ ieee8021xAuth,
926
+ ieee8021xState,
927
+ carrierChanges,
928
+ });
929
+ }
930
+ }
931
+ _networkInterfaces = result;
932
+ if (defaultString.toLowerCase().indexOf('default') >= 0) {
933
+ result = result.filter(item => item.default);
934
+ if (result.length > 0) {
935
+ result = result[0];
936
+ } else {
937
+ result = [];
938
+ }
939
+ }
940
+ if (callback) { callback(result); }
941
+ resolve(result);
942
+ }
943
+ }
944
+ if (_windows) {
945
+ if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) {
946
+ // no changes - just return object
947
+ result = _networkInterfaces;
948
+
949
+ if (callback) { callback(result); }
950
+ resolve(result);
951
+ } else {
952
+ _ifaces = JSON.parse(JSON.stringify(ifaces));
953
+ const defaultInterface = getDefaultNetworkInterface();
954
+
955
+ getWindowsNics().then(function (nics) {
956
+ nics.forEach(nic => {
957
+ let found = false;
958
+ Object.keys(ifaces).forEach(key => {
959
+ if (!found) {
960
+ ifaces[key].forEach(value => {
961
+ if (Object.keys(value).indexOf('mac') >= 0) {
962
+ found = value['mac'] === nic.mac;
963
+ }
964
+ });
965
+ }
966
+ });
967
+
968
+ if (!found) {
969
+ ifaces[nic.name] = [{ mac: nic.mac }];
970
+ }
971
+ });
972
+ nics8021xInfo = getWindowsWiredProfilesInformation();
973
+ dnsSuffixes = getWindowsDNSsuffixes();
974
+ for (let dev in ifaces) {
975
+
976
+ let ifaceSanitized = '';
977
+ const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(dev);
978
+ const l = util.mathMin(s.length, 2000);
979
+ for (let i = 0; i <= l; i++) {
980
+ if (s[i] !== undefined) {
981
+ ifaceSanitized = ifaceSanitized + s[i];
982
+ }
983
+ }
984
+
985
+ let iface = dev;
986
+ let ip4 = '';
987
+ let ip4subnet = '';
988
+ let ip6 = '';
989
+ let ip6subnet = '';
990
+ let mac = '';
991
+ let duplex = '';
992
+ let mtu = '';
993
+ let speed = null;
994
+ let carrierChanges = 0;
995
+ let operstate = 'down';
996
+ let dhcp = false;
997
+ let dnsSuffix = '';
998
+ let ieee8021xAuth = '';
999
+ let ieee8021xState = '';
1000
+ let type = '';
1001
+
1002
+ if ({}.hasOwnProperty.call(ifaces, dev)) {
1003
+ let ifaceName = dev;
1004
+ ifaces[dev].forEach(function (details) {
1005
+ if (details.family === 'IPv4' || details.family === 4) {
1006
+ ip4 = details.address;
1007
+ ip4subnet = details.netmask;
1008
+ }
1009
+ if (details.family === 'IPv6' || details.family === 6) {
1010
+ if (!ip6 || ip6.match(/^fe80::/i)) {
1011
+ ip6 = details.address;
1012
+ ip6subnet = details.netmask;
1013
+ }
1014
+ }
1015
+ mac = details.mac;
1016
+ // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2)
1017
+ const nodeMainVersion = parseInt(process.versions.node.split('.'), 10);
1018
+ if (mac.indexOf('00:00:0') > -1 && (_linux || _darwin) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) {
1019
+ if (Object.keys(_mac).length === 0) {
1020
+ _mac = getMacAddresses();
1021
+ }
1022
+ mac = _mac[dev] || '';
1023
+ }
1024
+ });
1025
+
1026
+
1027
+
1028
+ dnsSuffix = getWindowsIfaceDNSsuffix(dnsSuffixes.ifaces, ifaceSanitized);
1029
+ let foundFirst = false;
1030
+ nics.forEach(detail => {
1031
+ if (detail.mac === mac && !foundFirst) {
1032
+ iface = detail.iface || iface;
1033
+ ifaceName = detail.name;
1034
+ dhcp = detail.dhcp;
1035
+ operstate = detail.operstate;
1036
+ speed = operstate === 'up' ? detail.speed : 0;
1037
+ type = detail.type;
1038
+ foundFirst = true;
1039
+ }
1040
+ });
1041
+
1042
+ 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) {
1043
+ type = 'wireless';
1044
+ }
1045
+
1046
+ const IEEE8021x = getWindowsIEEE8021x(type, ifaceSanitized, nics8021xInfo);
1047
+ ieee8021xAuth = IEEE8021x.protocol;
1048
+ ieee8021xState = IEEE8021x.state;
1049
+ let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false;
1050
+ if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) {
1051
+ internal = true;
1052
+ }
1053
+ const virtual = internal ? false : testVirtualNic(dev, ifaceName, mac);
1054
+ result.push({
1055
+ iface,
1056
+ ifaceName,
1057
+ default: iface === defaultInterface,
1058
+ ip4,
1059
+ ip4subnet,
1060
+ ip6,
1061
+ ip6subnet,
1062
+ mac,
1063
+ internal,
1064
+ virtual,
1065
+ operstate,
1066
+ type,
1067
+ duplex,
1068
+ mtu,
1069
+ speed,
1070
+ dhcp,
1071
+ dnsSuffix,
1072
+ ieee8021xAuth,
1073
+ ieee8021xState,
1074
+ carrierChanges,
1075
+ });
1076
+ }
1077
+ }
1078
+ _networkInterfaces = result;
1079
+ if (defaultString.toLowerCase().indexOf('default') >= 0) {
1080
+ result = result.filter(item => item.default);
1081
+ if (result.length > 0) {
1082
+ result = result[0];
1083
+ } else {
1084
+ result = [];
1085
+ }
1086
+ }
1087
+ if (callback) { callback(result); }
1088
+ resolve(result);
1089
+ });
1090
+ }
1091
+ }
1092
+ });
1093
+ });
1094
+ }
1095
+
1096
+ exports.networkInterfaces = networkInterfaces;
1097
+
1098
+ // --------------------------
1099
+ // NET - Speed
1100
+
1101
+ function calcNetworkSpeed(iface, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors) {
1102
+ let result = {
1103
+ iface,
1104
+ operstate,
1105
+ rx_bytes,
1106
+ rx_dropped,
1107
+ rx_errors,
1108
+ tx_bytes,
1109
+ tx_dropped,
1110
+ tx_errors,
1111
+ rx_sec: null,
1112
+ tx_sec: null,
1113
+ ms: 0
1114
+ };
1115
+
1116
+ if (_network[iface] && _network[iface].ms) {
1117
+ result.ms = Date.now() - _network[iface].ms;
1118
+ result.rx_sec = (rx_bytes - _network[iface].rx_bytes) >= 0 ? (rx_bytes - _network[iface].rx_bytes) / (result.ms / 1000) : 0;
1119
+ result.tx_sec = (tx_bytes - _network[iface].tx_bytes) >= 0 ? (tx_bytes - _network[iface].tx_bytes) / (result.ms / 1000) : 0;
1120
+ _network[iface].rx_bytes = rx_bytes;
1121
+ _network[iface].tx_bytes = tx_bytes;
1122
+ _network[iface].rx_sec = result.rx_sec;
1123
+ _network[iface].tx_sec = result.tx_sec;
1124
+ _network[iface].ms = Date.now();
1125
+ _network[iface].last_ms = result.ms;
1126
+ _network[iface].operstate = operstate;
1127
+ } else {
1128
+ if (!_network[iface]) { _network[iface] = {}; }
1129
+ _network[iface].rx_bytes = rx_bytes;
1130
+ _network[iface].tx_bytes = tx_bytes;
1131
+ _network[iface].rx_sec = null;
1132
+ _network[iface].tx_sec = null;
1133
+ _network[iface].ms = Date.now();
1134
+ _network[iface].last_ms = 0;
1135
+ _network[iface].operstate = operstate;
1136
+ }
1137
+ return result;
1138
+ }
1139
+
1140
+ function networkStats(ifaces, callback) {
1141
+
1142
+ let ifacesArray = [];
1143
+
1144
+ return new Promise((resolve) => {
1145
+ process.nextTick(() => {
1146
+
1147
+ // fallback - if only callback is given
1148
+ if (util.isFunction(ifaces) && !callback) {
1149
+ callback = ifaces;
1150
+ ifacesArray = [getDefaultNetworkInterface()];
1151
+ } else {
1152
+ if (typeof ifaces !== 'string' && ifaces !== undefined) {
1153
+ if (callback) { callback([]); }
1154
+ return resolve([]);
1155
+ }
1156
+ ifaces = ifaces || getDefaultNetworkInterface();
1157
+
1158
+ ifaces.__proto__.toLowerCase = util.stringToLower;
1159
+ ifaces.__proto__.replace = util.stringReplace;
1160
+ ifaces.__proto__.trim = util.stringTrim;
1161
+
1162
+ ifaces = ifaces.trim().toLowerCase().replace(/,+/g, '|');
1163
+ ifacesArray = ifaces.split('|');
1164
+ }
1165
+
1166
+ const result = [];
1167
+
1168
+ const workload = [];
1169
+ if (ifacesArray.length && ifacesArray[0].trim() === '*') {
1170
+ ifacesArray = [];
1171
+ networkInterfaces(false).then(allIFaces => {
1172
+ for (let iface of allIFaces) {
1173
+ ifacesArray.push(iface.iface);
1174
+ }
1175
+ networkStats(ifacesArray.join(',')).then(result => {
1176
+ if (callback) { callback(result); }
1177
+ resolve(result);
1178
+ });
1179
+ });
1180
+ } else {
1181
+ for (let iface of ifacesArray) {
1182
+ workload.push(networkStatsSingle(iface.trim()));
1183
+ }
1184
+ if (workload.length) {
1185
+ Promise.all(
1186
+ workload
1187
+ ).then((data) => {
1188
+ if (callback) { callback(data); }
1189
+ resolve(data);
1190
+ });
1191
+ } else {
1192
+ if (callback) { callback(result); }
1193
+ resolve(result);
1194
+ }
1195
+ }
1196
+ });
1197
+ });
1198
+ }
1199
+
1200
+ function networkStatsSingle(iface) {
1201
+
1202
+ function parseLinesWindowsPerfData(sections) {
1203
+ let perfData = [];
1204
+ for (let i in sections) {
1205
+ if ({}.hasOwnProperty.call(sections, i)) {
1206
+ if (sections[i].trim() !== '') {
1207
+ let lines = sections[i].trim().split('\r\n');
1208
+ perfData.push({
1209
+ name: util.getValue(lines, 'Name', ':').replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase(),
1210
+ rx_bytes: parseInt(util.getValue(lines, 'BytesReceivedPersec', ':'), 10),
1211
+ rx_errors: parseInt(util.getValue(lines, 'PacketsReceivedErrors', ':'), 10),
1212
+ rx_dropped: parseInt(util.getValue(lines, 'PacketsReceivedDiscarded', ':'), 10),
1213
+ tx_bytes: parseInt(util.getValue(lines, 'BytesSentPersec', ':'), 10),
1214
+ tx_errors: parseInt(util.getValue(lines, 'PacketsOutboundErrors', ':'), 10),
1215
+ tx_dropped: parseInt(util.getValue(lines, 'PacketsOutboundDiscarded', ':'), 10)
1216
+ });
1217
+ }
1218
+ }
1219
+ }
1220
+ return perfData;
1221
+ }
1222
+
1223
+ return new Promise((resolve) => {
1224
+ process.nextTick(() => {
1225
+ let ifaceSanitized = '';
1226
+ const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface);
1227
+ const l = util.mathMin(s.length, 2000);
1228
+ for (let i = 0; i <= l; i++) {
1229
+ if (s[i] !== undefined) {
1230
+ ifaceSanitized = ifaceSanitized + s[i];
1231
+ }
1232
+ }
1233
+
1234
+ let result = {
1235
+ iface: ifaceSanitized,
1236
+ operstate: 'unknown',
1237
+ rx_bytes: 0,
1238
+ rx_dropped: 0,
1239
+ rx_errors: 0,
1240
+ tx_bytes: 0,
1241
+ tx_dropped: 0,
1242
+ tx_errors: 0,
1243
+ rx_sec: null,
1244
+ tx_sec: null,
1245
+ ms: 0
1246
+ };
1247
+
1248
+ let operstate = 'unknown';
1249
+ let rx_bytes = 0;
1250
+ let tx_bytes = 0;
1251
+ let rx_dropped = 0;
1252
+ let rx_errors = 0;
1253
+ let tx_dropped = 0;
1254
+ let tx_errors = 0;
1255
+
1256
+ let cmd, lines, stats;
1257
+ if (!_network[ifaceSanitized] || (_network[ifaceSanitized] && !_network[ifaceSanitized].ms) || (_network[ifaceSanitized] && _network[ifaceSanitized].ms && Date.now() - _network[ifaceSanitized].ms >= 500)) {
1258
+ if (_linux) {
1259
+ if (fs.existsSync('/sys/class/net/' + ifaceSanitized)) {
1260
+ cmd =
1261
+ 'cat /sys/class/net/' + ifaceSanitized + '/operstate; ' +
1262
+ 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_bytes; ' +
1263
+ 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_bytes; ' +
1264
+ 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_dropped; ' +
1265
+ 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_errors; ' +
1266
+ 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_dropped; ' +
1267
+ 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_errors; ';
1268
+ exec(cmd, function (error, stdout) {
1269
+ if (!error) {
1270
+ lines = stdout.toString().split('\n');
1271
+ operstate = lines[0].trim();
1272
+ rx_bytes = parseInt(lines[1], 10);
1273
+ tx_bytes = parseInt(lines[2], 10);
1274
+ rx_dropped = parseInt(lines[3], 10);
1275
+ rx_errors = parseInt(lines[4], 10);
1276
+ tx_dropped = parseInt(lines[5], 10);
1277
+ tx_errors = parseInt(lines[6], 10);
1278
+
1279
+ result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
1280
+
1281
+ }
1282
+ resolve(result);
1283
+ });
1284
+ } else {
1285
+ resolve(result);
1286
+ }
1287
+ }
1288
+ if (_freebsd || _openbsd || _netbsd) {
1289
+ cmd = 'netstat -ibndI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input]
1290
+ exec(cmd, function (error, stdout) {
1291
+ if (!error) {
1292
+ lines = stdout.toString().split('\n');
1293
+ for (let i = 1; i < lines.length; i++) {
1294
+ const line = lines[i].replace(/ +/g, ' ').split(' ');
1295
+ if (line && line[0] && line[7] && line[10]) {
1296
+ rx_bytes = rx_bytes + parseInt(line[7]);
1297
+ if (line[6].trim() !== '-') { rx_dropped = rx_dropped + parseInt(line[6]); }
1298
+ if (line[5].trim() !== '-') { rx_errors = rx_errors + parseInt(line[5]); }
1299
+ tx_bytes = tx_bytes + parseInt(line[10]);
1300
+ if (line[12].trim() !== '-') { tx_dropped = tx_dropped + parseInt(line[12]); }
1301
+ if (line[9].trim() !== '-') { tx_errors = tx_errors + parseInt(line[9]); }
1302
+ operstate = 'up';
1303
+ }
1304
+ }
1305
+ result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
1306
+ }
1307
+ resolve(result);
1308
+ });
1309
+ }
1310
+ if (_darwin) {
1311
+ cmd = 'ifconfig ' + ifaceSanitized + ' | grep "status"'; // lgtm [js/shell-command-constructed-from-input]
1312
+ exec(cmd, function (error, stdout) {
1313
+ result.operstate = (stdout.toString().split(':')[1] || '').trim();
1314
+ result.operstate = (result.operstate || '').toLowerCase();
1315
+ result.operstate = (result.operstate === 'active' ? 'up' : (result.operstate === 'inactive' ? 'down' : 'unknown'));
1316
+ cmd = 'netstat -bdI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input]
1317
+ exec(cmd, function (error, stdout) {
1318
+ if (!error) {
1319
+ lines = stdout.toString().split('\n');
1320
+ // if there is less than 2 lines, no information for this interface was found
1321
+ if (lines.length > 1 && lines[1].trim() !== '') {
1322
+ // skip header line
1323
+ // use the second line because it is tied to the NIC instead of the ipv4 or ipv6 address
1324
+ stats = lines[1].replace(/ +/g, ' ').split(' ');
1325
+ const offset = stats.length > 11 ? 1 : 0;
1326
+ rx_bytes = parseInt(stats[offset + 5]);
1327
+ rx_dropped = parseInt(stats[offset + 10]);
1328
+ rx_errors = parseInt(stats[offset + 4]);
1329
+ tx_bytes = parseInt(stats[offset + 8]);
1330
+ tx_dropped = parseInt(stats[offset + 10]);
1331
+ tx_errors = parseInt(stats[offset + 7]);
1332
+ result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, result.operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
1333
+ }
1334
+ }
1335
+ resolve(result);
1336
+ });
1337
+ });
1338
+ }
1339
+ if (_windows) {
1340
+ let perfData = [];
1341
+ let ifaceName = ifaceSanitized;
1342
+
1343
+ // Performance Data
1344
+ util.powerShell('Get-CimInstance Win32_PerfRawData_Tcpip_NetworkInterface | select Name,BytesReceivedPersec,PacketsReceivedErrors,PacketsReceivedDiscarded,BytesSentPersec,PacketsOutboundErrors,PacketsOutboundDiscarded | fl').then((stdout, error) => {
1345
+ if (!error) {
1346
+ const psections = stdout.toString().split(/\n\s*\n/);
1347
+ perfData = parseLinesWindowsPerfData(psections);
1348
+ }
1349
+
1350
+ // Network Interfaces
1351
+ networkInterfaces(false).then(interfaces => {
1352
+ // get bytes sent, received from perfData by name
1353
+ rx_bytes = 0;
1354
+ tx_bytes = 0;
1355
+ perfData.forEach(detail => {
1356
+ interfaces.forEach(det => {
1357
+ if ((det.iface.toLowerCase() === ifaceSanitized.toLowerCase() ||
1358
+ det.mac.toLowerCase() === ifaceSanitized.toLowerCase() ||
1359
+ det.ip4.toLowerCase() === ifaceSanitized.toLowerCase() ||
1360
+ det.ip6.toLowerCase() === ifaceSanitized.toLowerCase() ||
1361
+ det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === ifaceSanitized.replace(/[()[\] ]+/g, '').replace('#', '_').toLowerCase()) &&
1362
+ (det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === detail.name)) {
1363
+ ifaceName = det.iface;
1364
+ rx_bytes = detail.rx_bytes;
1365
+ rx_dropped = detail.rx_dropped;
1366
+ rx_errors = detail.rx_errors;
1367
+ tx_bytes = detail.tx_bytes;
1368
+ tx_dropped = detail.tx_dropped;
1369
+ tx_errors = detail.tx_errors;
1370
+ operstate = det.operstate;
1371
+ }
1372
+ });
1373
+ });
1374
+ if (rx_bytes && tx_bytes) {
1375
+ result = calcNetworkSpeed(ifaceName, parseInt(rx_bytes), parseInt(tx_bytes), operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
1376
+ }
1377
+ resolve(result);
1378
+ });
1379
+ });
1380
+ }
1381
+ } else {
1382
+ result.rx_bytes = _network[ifaceSanitized].rx_bytes;
1383
+ result.tx_bytes = _network[ifaceSanitized].tx_bytes;
1384
+ result.rx_sec = _network[ifaceSanitized].rx_sec;
1385
+ result.tx_sec = _network[ifaceSanitized].tx_sec;
1386
+ result.ms = _network[ifaceSanitized].last_ms;
1387
+ result.operstate = _network[ifaceSanitized].operstate;
1388
+ resolve(result);
1389
+ }
1390
+ });
1391
+ });
1392
+ }
1393
+
1394
+ exports.networkStats = networkStats;
1395
+
1396
+ // --------------------------
1397
+ // NET - connections (sockets)
1398
+
1399
+ function getProcessName(processes, pid) {
1400
+ let cmd = '';
1401
+ processes.forEach(line => {
1402
+ const parts = line.split(' ');
1403
+ const id = parseInt(parts[0], 10) || -1;
1404
+ if (id === pid) {
1405
+ parts.shift();
1406
+ cmd = parts.join(' ').split(':')[0];
1407
+ }
1408
+ });
1409
+ cmd = cmd.split(' -')[0];
1410
+ // return cmd;
1411
+ const cmdParts = cmd.split('/');
1412
+ return cmdParts[cmdParts.length - 1];
1413
+ }
1414
+
1415
+ function networkConnections(callback) {
1416
+
1417
+ return new Promise((resolve) => {
1418
+ process.nextTick(() => {
1419
+ let result = [];
1420
+ if (_linux || _freebsd || _openbsd || _netbsd) {
1421
+ 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';
1422
+ 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'; }
1423
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
1424
+ let lines = stdout.toString().split('\n');
1425
+ if (!error && (lines.length > 1 || lines[0] != '')) {
1426
+ lines.forEach(function (line) {
1427
+ line = line.replace(/ +/g, ' ').split(' ');
1428
+ if (line.length >= 7) {
1429
+ let localip = line[3];
1430
+ let localport = '';
1431
+ let localaddress = line[3].split(':');
1432
+ if (localaddress.length > 1) {
1433
+ localport = localaddress[localaddress.length - 1];
1434
+ localaddress.pop();
1435
+ localip = localaddress.join(':');
1436
+ }
1437
+ let peerip = line[4];
1438
+ let peerport = '';
1439
+ let peeraddress = line[4].split(':');
1440
+ if (peeraddress.length > 1) {
1441
+ peerport = peeraddress[peeraddress.length - 1];
1442
+ peeraddress.pop();
1443
+ peerip = peeraddress.join(':');
1444
+ }
1445
+ let connstate = line[5];
1446
+ let proc = line[6].split('/');
1447
+
1448
+ if (connstate) {
1449
+ result.push({
1450
+ protocol: line[0],
1451
+ localAddress: localip,
1452
+ localPort: localport,
1453
+ peerAddress: peerip,
1454
+ peerPort: peerport,
1455
+ state: connstate,
1456
+ pid: proc[0] && proc[0] !== '-' ? parseInt(proc[0], 10) : null,
1457
+ process: proc[1] ? proc[1].split(' ')[0].split(':')[0] : ''
1458
+ });
1459
+ }
1460
+ }
1461
+ });
1462
+ if (callback) {
1463
+ callback(result);
1464
+ }
1465
+ resolve(result);
1466
+ } else {
1467
+ cmd = 'ss -tunap | grep "ESTAB\\|SYN-SENT\\|SYN-RECV\\|FIN-WAIT1\\|FIN-WAIT2\\|TIME-WAIT\\|CLOSE\\|CLOSE-WAIT\\|LAST-ACK\\|LISTEN\\|CLOSING"';
1468
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
1469
+
1470
+ if (!error) {
1471
+ let lines = stdout.toString().split('\n');
1472
+ lines.forEach(function (line) {
1473
+ line = line.replace(/ +/g, ' ').split(' ');
1474
+ if (line.length >= 6) {
1475
+ let localip = line[4];
1476
+ let localport = '';
1477
+ let localaddress = line[4].split(':');
1478
+ if (localaddress.length > 1) {
1479
+ localport = localaddress[localaddress.length - 1];
1480
+ localaddress.pop();
1481
+ localip = localaddress.join(':');
1482
+ }
1483
+ let peerip = line[5];
1484
+ let peerport = '';
1485
+ let peeraddress = line[5].split(':');
1486
+ if (peeraddress.length > 1) {
1487
+ peerport = peeraddress[peeraddress.length - 1];
1488
+ peeraddress.pop();
1489
+ peerip = peeraddress.join(':');
1490
+ }
1491
+ let connstate = line[1];
1492
+ if (connstate === 'ESTAB') { connstate = 'ESTABLISHED'; }
1493
+ if (connstate === 'TIME-WAIT') { connstate = 'TIME_WAIT'; }
1494
+ let pid = null;
1495
+ let process = '';
1496
+ if (line.length >= 7 && line[6].indexOf('users:') > -1) {
1497
+ let proc = line[6].replace('users:(("', '').replace(/"/g, '').split(',');
1498
+ if (proc.length > 2) {
1499
+ process = proc[0].split(' ')[0].split(':')[0];
1500
+ pid = parseInt(proc[1], 10);
1501
+ }
1502
+ }
1503
+ if (connstate) {
1504
+ result.push({
1505
+ protocol: line[0],
1506
+ localAddress: localip,
1507
+ localPort: localport,
1508
+ peerAddress: peerip,
1509
+ peerPort: peerport,
1510
+ state: connstate,
1511
+ pid,
1512
+ process
1513
+ });
1514
+ }
1515
+ }
1516
+ });
1517
+ }
1518
+ if (callback) {
1519
+ callback(result);
1520
+ }
1521
+ resolve(result);
1522
+ });
1523
+ }
1524
+ });
1525
+ }
1526
+ if (_darwin) {
1527
+ // let cmd = 'netstat -natv | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"';
1528
+ let cmd = 'netstat -natvln | grep "tcp4\\|tcp6\\|udp4\\|udp6"';
1529
+ const states = 'ESTABLISHED|SYN_SENT|SYN_RECV|FIN_WAIT1|FIN_WAIT2|TIME_WAIT|CLOSE|CLOSE_WAIT|LAST_ACK|LISTEN|CLOSING|UNKNOWN';
1530
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
1531
+ if (!error) {
1532
+ exec('ps -axo pid,command', { maxBuffer: 1024 * 20000 }, function (err2, stdout2) {
1533
+ let processes = stdout2.toString().split('\n');
1534
+ processes = processes.map((line => { return line.trim().replace(/ +/g, ' '); }));
1535
+ let lines = stdout.toString().split('\n');
1536
+
1537
+ lines.forEach(function (line) {
1538
+ line = line.replace(/ +/g, ' ').split(' ');
1539
+ if (line.length >= 8) {
1540
+ let localip = line[3];
1541
+ let localport = '';
1542
+ let localaddress = line[3].split('.');
1543
+ if (localaddress.length > 1) {
1544
+ localport = localaddress[localaddress.length - 1];
1545
+ localaddress.pop();
1546
+ localip = localaddress.join('.');
1547
+ }
1548
+ let peerip = line[4];
1549
+ let peerport = '';
1550
+ let peeraddress = line[4].split('.');
1551
+ if (peeraddress.length > 1) {
1552
+ peerport = peeraddress[peeraddress.length - 1];
1553
+ peeraddress.pop();
1554
+ peerip = peeraddress.join('.');
1555
+ }
1556
+ const hasState = states.indexOf(line[5]) >= 0;
1557
+ let connstate = hasState ? line[5] : 'UNKNOWN';
1558
+ let pid = parseInt(line[8 + (hasState ? 0 : -1)], 10);
1559
+ if (connstate) {
1560
+ result.push({
1561
+ protocol: line[0],
1562
+ localAddress: localip,
1563
+ localPort: localport,
1564
+ peerAddress: peerip,
1565
+ peerPort: peerport,
1566
+ state: connstate,
1567
+ pid: pid,
1568
+ process: getProcessName(processes, pid)
1569
+ });
1570
+ }
1571
+ }
1572
+ });
1573
+ if (callback) {
1574
+ callback(result);
1575
+ }
1576
+ resolve(result);
1577
+ });
1578
+
1579
+ }
1580
+ });
1581
+ }
1582
+ if (_windows) {
1583
+ let cmd = 'netstat -nao';
1584
+ try {
1585
+ exec(cmd, util.execOptsWin, function (error, stdout) {
1586
+ if (!error) {
1587
+
1588
+ let lines = stdout.toString().split('\r\n');
1589
+
1590
+ lines.forEach(function (line) {
1591
+ line = line.trim().replace(/ +/g, ' ').split(' ');
1592
+ if (line.length >= 4) {
1593
+ let localip = line[1];
1594
+ let localport = '';
1595
+ let localaddress = line[1].split(':');
1596
+ if (localaddress.length > 1) {
1597
+ localport = localaddress[localaddress.length - 1];
1598
+ localaddress.pop();
1599
+ localip = localaddress.join(':');
1600
+ }
1601
+ localip = localip.replace(/\[/g, '').replace(/\]/g, '');
1602
+ let peerip = line[2];
1603
+ let peerport = '';
1604
+ let peeraddress = line[2].split(':');
1605
+ if (peeraddress.length > 1) {
1606
+ peerport = peeraddress[peeraddress.length - 1];
1607
+ peeraddress.pop();
1608
+ peerip = peeraddress.join(':');
1609
+ }
1610
+ peerip = peerip.replace(/\[/g, '').replace(/\]/g, '');
1611
+ let pid = util.toInt(line[4]);
1612
+ let connstate = line[3];
1613
+ if (connstate === 'HERGESTELLT') { connstate = 'ESTABLISHED'; }
1614
+ if (connstate.startsWith('ABH')) { connstate = 'LISTEN'; }
1615
+ if (connstate === 'SCHLIESSEN_WARTEN') { connstate = 'CLOSE_WAIT'; }
1616
+ if (connstate === 'WARTEND') { connstate = 'TIME_WAIT'; }
1617
+ if (connstate === 'SYN_GESENDET') { connstate = 'SYN_SENT'; }
1618
+
1619
+ if (connstate === 'LISTENING') { connstate = 'LISTEN'; }
1620
+ if (connstate === 'SYN_RECEIVED') { connstate = 'SYN_RECV'; }
1621
+ if (connstate === 'FIN_WAIT_1') { connstate = 'FIN_WAIT1'; }
1622
+ if (connstate === 'FIN_WAIT_2') { connstate = 'FIN_WAIT2'; }
1623
+ if (line[0].toLowerCase() !== 'udp' && connstate) {
1624
+ result.push({
1625
+ protocol: line[0].toLowerCase(),
1626
+ localAddress: localip,
1627
+ localPort: localport,
1628
+ peerAddress: peerip,
1629
+ peerPort: peerport,
1630
+ state: connstate,
1631
+ pid,
1632
+ process: ''
1633
+ });
1634
+ } else if (line[0].toLowerCase() === 'udp') {
1635
+ result.push({
1636
+ protocol: line[0].toLowerCase(),
1637
+ localAddress: localip,
1638
+ localPort: localport,
1639
+ peerAddress: peerip,
1640
+ peerPort: peerport,
1641
+ state: '',
1642
+ pid: parseInt(line[3], 10),
1643
+ process: ''
1644
+ });
1645
+ }
1646
+ }
1647
+ });
1648
+ if (callback) {
1649
+ callback(result);
1650
+ }
1651
+ resolve(result);
1652
+ }
1653
+ });
1654
+ } catch (e) {
1655
+ if (callback) { callback(result); }
1656
+ resolve(result);
1657
+ }
1658
+ }
1659
+ });
1660
+ });
1661
+ }
1662
+
1663
+ exports.networkConnections = networkConnections;
1664
+
1665
+ function networkGatewayDefault(callback) {
1666
+
1667
+ return new Promise((resolve) => {
1668
+ process.nextTick(() => {
1669
+ let result = '';
1670
+ if (_linux || _freebsd || _openbsd || _netbsd) {
1671
+ let cmd = 'ip route get 1';
1672
+ try {
1673
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
1674
+ if (!error) {
1675
+ let lines = stdout.toString().split('\n');
1676
+ const line = lines && lines[0] ? lines[0] : '';
1677
+ let parts = line.split(' via ');
1678
+ if (parts && parts[1]) {
1679
+ parts = parts[1].split(' ');
1680
+ result = parts[0];
1681
+ }
1682
+ if (callback) {
1683
+ callback(result);
1684
+ }
1685
+ resolve(result);
1686
+ } else {
1687
+ if (callback) {
1688
+ callback(result);
1689
+ }
1690
+ resolve(result);
1691
+ }
1692
+ });
1693
+ } catch (e) {
1694
+ if (callback) { callback(result); }
1695
+ resolve(result);
1696
+ }
1697
+ }
1698
+ if (_darwin) {
1699
+ let cmd = 'route -n get default';
1700
+ try {
1701
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
1702
+ if (!error) {
1703
+ const lines = stdout.toString().split('\n').map(line => line.trim());
1704
+ result = util.getValue(lines, 'gateway');
1705
+ }
1706
+ if (!result) {
1707
+ cmd = 'netstat -rn | awk \'/default/ {print $2}\'';
1708
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
1709
+ const lines = stdout.toString().split('\n').map(line => line.trim());
1710
+ 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)));
1711
+ if (callback) {
1712
+ callback(result);
1713
+ }
1714
+ resolve(result);
1715
+ });
1716
+ } else {
1717
+ if (callback) {
1718
+ callback(result);
1719
+ }
1720
+ resolve(result);
1721
+ }
1722
+ });
1723
+ } catch (e) {
1724
+ if (callback) { callback(result); }
1725
+ resolve(result);
1726
+ }
1727
+ }
1728
+ if (_windows) {
1729
+ try {
1730
+ exec('netstat -r', util.execOptsWin, function (error, stdout) {
1731
+ const lines = stdout.toString().split(os.EOL);
1732
+ lines.forEach(line => {
1733
+ line = line.replace(/\s+/g, ' ').trim();
1734
+ if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) {
1735
+ const parts = line.split(' ');
1736
+ if (parts.length >= 5 && (parts[parts.length - 3]).indexOf('.') > -1) {
1737
+ result = parts[parts.length - 3];
1738
+ }
1739
+ }
1740
+ });
1741
+ if (!result) {
1742
+ util.powerShell('Get-CimInstance -ClassName Win32_IP4RouteTable | Where-Object { $_.Destination -eq \'0.0.0.0\' -and $_.Mask -eq \'0.0.0.0\' }')
1743
+ .then((data) => {
1744
+ let lines = data.toString().split('\r\n');
1745
+ if (lines.length > 1 && !result) {
1746
+ result = util.getValue(lines, 'NextHop');
1747
+ if (callback) {
1748
+ callback(result);
1749
+ }
1750
+ resolve(result);
1751
+ // } else {
1752
+ // exec('ipconfig', util.execOptsWin, function (error, stdout) {
1753
+ // let lines = stdout.toString().split('\r\n');
1754
+ // lines.forEach(function (line) {
1755
+ // line = line.trim().replace(/\. /g, '');
1756
+ // line = line.trim().replace(/ +/g, '');
1757
+ // const parts = line.split(':');
1758
+ // if ((parts[0].toLowerCase().startsWith('standardgate') || parts[0].toLowerCase().indexOf('gateway') > -1 || parts[0].toLowerCase().indexOf('enlace') > -1) && parts[1]) {
1759
+ // result = parts[1];
1760
+ // }
1761
+ // });
1762
+ // if (callback) { callback(result); }
1763
+ // resolve(result);
1764
+ // });
1765
+ }
1766
+ });
1767
+ } else {
1768
+ if (callback) {
1769
+ callback(result);
1770
+ }
1771
+ resolve(result);
1772
+ }
1773
+ });
1774
+ } catch (e) {
1775
+ if (callback) { callback(result); }
1776
+ resolve(result);
1777
+ }
1778
+ }
1779
+ });
1780
+ });
1781
+ }
1782
+
1783
+ exports.networkGatewayDefault = networkGatewayDefault;