forked from Ylianst/MeshAgent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoreModule.js
More file actions
6044 lines (5710 loc) · 463 KB
/
Copy pathCoreModule.js
File metadata and controls
6044 lines (5710 loc) · 463 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var addedModules = [];
try { addModule("computer-identifiers", "/*\r\nCopyright 2019-2021 Intel Corporation\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*/\r\n\r\nfunction trimIdentifiers(val)\r\n{\r\n for(var v in val)\r\n {\r\n if (!val[v] || val[v] == \'None\' || val[v] == \'\') { delete val[v]; }\r\n }\r\n}\r\nfunction trimResults(val)\r\n{\r\n var i, x;\r\n for (i = 0; i < val.length; ++i)\r\n {\r\n for (x in val[i])\r\n {\r\n if (x.startsWith(\'_\'))\r\n {\r\n delete val[i][x];\r\n }\r\n else\r\n {\r\n if (val[i][x] == null || val[i][x] == 0)\r\n {\r\n delete val[i][x];\r\n }\r\n }\r\n }\r\n }\r\n}\r\nfunction brief(headers, obj)\r\n{\r\n var i, x;\r\n for (x = 0; x < obj.length; ++x)\r\n {\r\n for (i in obj[x])\r\n {\r\n if (!headers.includes(i))\r\n {\r\n delete obj[x][i];\r\n }\r\n }\r\n }\r\n return (obj);\r\n}\r\n\r\nfunction dataHandler(c)\r\n{\r\n this.str += c.toString();\r\n}\r\n\r\nfunction linux_identifiers()\r\n{\r\n var identifiers = {};\r\n var ret = {};\r\n var values = {};\r\n\r\n if (!require(\'fs\').existsSync(\'/sys/class/dmi/id\')) { \r\n if (require(\'fs\').existsSync(\'/sys/firmware/devicetree/base/model\')) {\r\n if (require(\'fs\').readFileSync(\'/sys/firmware/devicetree/base/model\').toString().trim().startsWith(\'Raspberry\')) {\r\n identifiers[\'board_vendor\'] = \'Raspberry Pi\';\r\n identifiers[\'board_name\'] = require(\'fs\').readFileSync(\'/sys/firmware/devicetree/base/model\').toString().trim();\r\n identifiers[\'board_serial\'] = require(\'fs\').readFileSync(\'/sys/firmware/devicetree/base/serial-number\').toString().trim();\r\n const memorySlots = [];\r\n var child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', dataHandler);\r\n child.stdin.write(\'vcgencmd get_mem arm && vcgencmd get_mem gpu\\nexit\\n\');\r\n child.waitExit();\r\n try { \r\n const lines = child.stdout.str.trim().split(\'\\n\');\r\n if (lines.length == 2) {\r\n memorySlots.push({ Locator: \"ARM Memory\", Size: lines[0].split(\'=\')[1].trim() })\r\n memorySlots.push({ Locator: \"GPU Memory\", Size: lines[1].split(\'=\')[1].trim() })\r\n ret.memory = { Memory_Device: memorySlots };\r\n }\r\n } catch (xx) { }\r\n } else {\r\n throw(\'Unknown board\');\r\n }\r\n } else {\r\n throw (\'this platform does not have DMI statistics\');\r\n }\r\n } else {\r\n var entries = require(\'fs\').readdirSync(\'/sys/class/dmi/id\');\r\n for (var i in entries) {\r\n if (require(\'fs\').statSync(\'/sys/class/dmi/id/\' + entries[i]).isFile()) {\r\n try {\r\n ret[entries[i]] = require(\'fs\').readFileSync(\'/sys/class/dmi/id/\' + entries[i]).toString().trim();\r\n } catch(z) { }\r\n if (ret[entries[i]] == \'None\') { delete ret[entries[i]]; }\r\n }\r\n }\r\n entries = null;\r\n\r\n identifiers[\'bios_date\'] = ret[\'bios_date\'];\r\n identifiers[\'bios_vendor\'] = ret[\'bios_vendor\'];\r\n identifiers[\'bios_version\'] = ret[\'bios_version\'];\r\n identifiers[\'bios_serial\'] = ret[\'product_serial\'];\r\n identifiers[\'board_name\'] = ret[\'board_name\'];\r\n identifiers[\'board_serial\'] = ret[\'board_serial\'];\r\n identifiers[\'board_vendor\'] = ret[\'board_vendor\'];\r\n identifiers[\'board_version\'] = ret[\'board_version\'];\r\n identifiers[\'product_uuid\'] = ret[\'product_uuid\'];\r\n identifiers[\'product_name\'] = ret[\'product_name\'];\r\n }\r\n\r\n try {\r\n identifiers[\'bios_mode\'] = (require(\'fs\').statSync(\'/sys/firmware/efi\').isDirectory() ? \'UEFI\': \'Legacy\');\r\n } catch (ex) { identifiers[\'bios_mode\'] = \'Legacy\'; }\r\n\r\n var child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', dataHandler);\r\n child.stdin.write(\'cat /proc/cpuinfo | grep -i \"model name\" | \' + \"tr \'\\\\n\' \':\' | awk -F: \'{ print $2 }\'\\nexit\\n\");\r\n child.waitExit();\r\n identifiers[\'cpu_name\'] = child.stdout.str.trim();\r\n if (identifiers[\'cpu_name\'] == \"\") { // CPU BLANK, check lscpu instead\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', dataHandler);\r\n child.stdin.write(\'lscpu | grep -i \"model name\" | \' + \"tr \'\\\\n\' \':\' | awk -F: \'{ print $2 }\'\\nexit\\n\");\r\n child.waitExit();\r\n identifiers[\'cpu_name\'] = child.stdout.str.trim();\r\n }\r\n child = null;\r\n\r\n\r\n // Fetch GPU info\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', dataHandler);\r\n child.stdin.write(\"lspci | grep \' VGA \' | tr \'\\\\n\' \'`\' | awk \'{ a=split($0,lines\" + \',\"`\"); printf \"[\"; for(i=1;i<a;++i) { split(lines[i],gpu,\"r: \"); printf \"%s\\\\\"%s\\\\\"\", (i==1?\"\":\",\"),gpu[2]; } printf \"]\"; }\\\'\\nexit\\n\');\r\n child.waitExit();\r\n try { identifiers[\'gpu_name\'] = JSON.parse(child.stdout.str.trim()); } catch (xx) { }\r\n child = null;\r\n\r\n // Fetch Storage Info\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', dataHandler);\r\n child.stdin.write(\"lshw -class disk -disable network | tr \'\\\\n\' \'`\' | awk \'\" + \'{ len=split($0,lines,\"*\"); printf \"[\"; for(i=2;i<=len;++i) { model=\"\"; caption=\"\"; size=\"\"; clen=split(lines[i],item,\"`\"); for(j=2;j<clen;++j) { split(item[j],tokens,\":\"); split(tokens[1],key,\" \"); if(key[1]==\"description\") { caption=substr(tokens[2],2); } if(key[1]==\"product\") { model=substr(tokens[2],2); } if(key[1]==\"size\") { size=substr(tokens[2],2); } } if(model==\"\") { model=caption; } if(caption!=\"\" || model!=\"\") { printf \"%s{\\\\\"Caption\\\\\":\\\\\"%s\\\\\",\\\\\"Model\\\\\":\\\\\"%s\\\\\",\\\\\"Size\\\\\":\\\\\"%s\\\\\"}\",(i==2?\"\":\",\"),caption,model,size; } } printf \"]\"; }\\\'\\nexit\\n\');\r\n child.waitExit();\r\n try { identifiers[\'storage_devices\'] = JSON.parse(child.stdout.str.trim()); } catch (xx) { }\r\n child = null;\r\n\r\n // Fetch storage volumes using df\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', dataHandler);\r\n child.stdin.write(\'df -T | awk \\\'NR==1 || $1 ~ \".+\"{print $3, $4, $5, $7, $2}\\\' | awk \\\'NR>1 {printf \"{\\\\\"size\\\\\":\\\\\"%s\\\\\",\\\\\"used\\\\\":\\\\\"%s\\\\\",\\\\\"available\\\\\":\\\\\"%s\\\\\",\\\\\"mount_point\\\\\":\\\\\"%s\\\\\",\\\\\"type\\\\\":\\\\\"%s\\\\\"},\", $1, $2, $3, $4, $5}\\\' | sed \\\'$ s/,$//\\\' | awk \\\'BEGIN {printf \"[\"} {printf \"%s\", $0} END {printf \"]\"}\\\'\\nexit\\n\');\r\n child.waitExit();\r\n try { ret.volumes = JSON.parse(child.stdout.str.trim()); } catch (xx) { }\r\n child = null;\r\n\r\n values.identifiers = identifiers;\r\n values.linux = ret;\r\n trimIdentifiers(values.identifiers);\r\n\r\n var dmidecode = require(\'lib-finder\').findBinary(\'dmidecode\');\r\n if (dmidecode != null)\r\n {\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', dataHandler);\r\n child.stderr.str = \'\'; child.stderr.on(\'data\', dataHandler);\r\n child.stdin.write(dmidecode + \" -t memory | tr \'\\\\n\' \'`\' | \");\r\n child.stdin.write(\" awk \'{ \");\r\n child.stdin.write(\' printf(\"[\");\');\r\n child.stdin.write(\' comma=\"\";\');\r\n child.stdin.write(\' c=split($0, lines, \"``\");\');\r\n child.stdin.write(\' for(i=1;i<=c;++i)\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' d=split(lines[i], val, \"`\");\');\r\n child.stdin.write(\' split(val[1], tokens, \",\");\');\r\n child.stdin.write(\' split(tokens[2], dmitype, \" \");\');\r\n child.stdin.write(\' dmi = dmitype[3]+0; \');\r\n child.stdin.write(\' if(dmi == 5 || dmi == 6 || dmi == 16 || dmi == 17)\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' ccx=\"\";\');\r\n child.stdin.write(\' printf(\"%s{\\\\\"%s\\\\\": {\", comma, val[2]);\');\r\n child.stdin.write(\' for(j=3;j<d;++j)\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' sub(/^[ \\\\t]*/,\"\",val[j]);\');\r\n child.stdin.write(\' if(split(val[j],tmp,\":\")>1)\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' sub(/^[ \\\\t]*/,\"\",tmp[2]);\');\r\n child.stdin.write(\' gsub(/ /,\"\",tmp[1]);\');\r\n child.stdin.write(\' printf(\"%s\\\\\"%s\\\\\": \\\\\"%s\\\\\"\", ccx, tmp[1], tmp[2]);\');\r\n child.stdin.write(\' ccx=\",\";\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' printf(\"}}\");\');\r\n child.stdin.write(\' comma=\",\";\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' printf(\"]\");\');\r\n child.stdin.write(\"}\'\\nexit\\n\");\r\n child.waitExit();\r\n\r\n try\r\n {\r\n var j = JSON.parse(child.stdout.str);\r\n var i, key, key2;\r\n for (i = 0; i < j.length; ++i)\r\n {\r\n for (key in j[i])\r\n {\r\n delete j[i][key][\'ArrayHandle\'];\r\n delete j[i][key][\'ErrorInformationHandle\'];\r\n for (key2 in j[i][key])\r\n {\r\n if (j[i][key][key2] == \'Unknown\' || j[i][key][key2] == \'Not Specified\' || j[i][key][key2] == \'\')\r\n {\r\n delete j[i][key][key2];\r\n }\r\n }\r\n }\r\n }\r\n\r\n if(j.length > 0){\r\n var mem = {};\r\n for (i = 0; i < j.length; ++i)\r\n {\r\n for (key in j[i])\r\n {\r\n if (mem[key] == null) { mem[key] = []; }\r\n mem[key].push(j[i][key]);\r\n }\r\n }\r\n values.linux.memory = mem;\r\n }\r\n }\r\n catch (e)\r\n { }\r\n child = null;\r\n }\r\n\r\n var usbdevices = require(\'lib-finder\').findBinary(\'usb-devices\');\r\n if (usbdevices != null)\r\n {\r\n var child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', dataHandler);\r\n child.stderr.str = \'\'; child.stderr.on(\'data\', dataHandler);\r\n child.stdin.write(usbdevices + \" | tr \'\\\\n\' \'`\' | \");\r\n child.stdin.write(\" awk \'\");\r\n child.stdin.write(\'{\');\r\n child.stdin.write(\' comma=\"\";\');\r\n child.stdin.write(\' printf(\"[\");\');\r\n child.stdin.write(\' len=split($0, group, \"``\");\');\r\n child.stdin.write(\' for(i=1;i<=len;++i)\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' comma2=\"\";\');\r\n child.stdin.write(\' xlen=split(group[i], line, \"`\");\');\r\n child.stdin.write(\' scount=0;\');\r\n child.stdin.write(\' for(x=1;x<xlen;++x)\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' if(line[x] ~ \"^S:\")\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' ++scount;\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' if(scount>0)\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' printf(\"%s{\", comma); comma=\",\";\');\r\n child.stdin.write(\' for(x=1;x<xlen;++x)\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' if(line[x] ~ \"^T:\")\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' comma3=\"\";\');\r\n child.stdin.write(\' printf(\"%s\\\\\"hardware\\\\\": {\", comma2); comma2=\",\";\');\r\n child.stdin.write(\' sub(/^T:[ \\\\t]*/, \"\", line[x]);\');\r\n child.stdin.write(\' gsub(/= */, \"=\", line[x]);\');\r\n child.stdin.write(\' blen=split(line[x], tokens, \" \");\');\r\n child.stdin.write(\' for(y=1;y<blen;++y)\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' match(tokens[y],/=/);\');\r\n child.stdin.write(\' h=substr(tokens[y],1,RSTART-1);\');\r\n child.stdin.write(\' v=substr(tokens[y],RSTART+1);\');\r\n child.stdin.write(\' sub(/#/, \"\", h);\');\r\n child.stdin.write(\' printf(\"%s\\\\\"%s\\\\\": \\\\\"%s\\\\\"\", comma3, h, v); comma3=\",\";\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' printf(\"}\");\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' if(line[x] ~ \"^S:\")\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' sub(/^S:[ \\\\t]*/, \"\", line[x]);\');\r\n child.stdin.write(\' match(line[x], /=/);\');\r\n child.stdin.write(\' h=substr(line[x],1,RSTART-1);\');\r\n child.stdin.write(\' v=substr(line[x],RSTART+1);\');\r\n child.stdin.write(\' printf(\"%s\\\\\"%s\\\\\": \\\\\"%s\\\\\"\", comma2, h,v); comma2=\",\";\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' printf(\"}\");\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' printf(\"]\");\');\r\n child.stdin.write(\"}\'\\nexit\\n\");\r\n child.waitExit();\r\n\r\n try\r\n {\r\n values.linux.usb = JSON.parse(child.stdout.str);\r\n }\r\n catch(x)\r\n { }\r\n child = null;\r\n }\r\n\r\n var pcidevices = require(\'lib-finder\').findBinary(\'lspci\');\r\n if (pcidevices != null)\r\n {\r\n var child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', dataHandler);\r\n child.stderr.str = \'\'; child.stderr.on(\'data\', dataHandler);\r\n child.stdin.write(pcidevices + \" -m | tr \'\\\\n\' \'`\' | \");\r\n child.stdin.write(\" awk \'\");\r\n child.stdin.write(\'{\');\r\n child.stdin.write(\' printf(\"[\");\');\r\n child.stdin.write(\' comma=\"\";\');\r\n child.stdin.write(\' alen=split($0, lines, \"`\");\');\r\n child.stdin.write(\' for(a=1;a<alen;++a)\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' match(lines[a], / /);\');\r\n child.stdin.write(\' blen=split(lines[a], meta, \"\\\\\"\");\');\r\n child.stdin.write(\' bus=substr(lines[a], 1, RSTART);\');\r\n child.stdin.write(\' gsub(/ /, \"\", bus);\');\r\n child.stdin.write(\' printf(\"%s{\\\\\"bus\\\\\": \\\\\"%s\\\\\"\", comma, bus); comma=\",\";\');\r\n child.stdin.write(\' printf(\", \\\\\"device\\\\\": \\\\\"%s\\\\\"\", meta[2]);\');\r\n child.stdin.write(\' printf(\", \\\\\"manufacturer\\\\\": \\\\\"%s\\\\\"\", meta[4]);\');\r\n child.stdin.write(\' printf(\", \\\\\"description\\\\\": \\\\\"%s\\\\\"\", meta[6]);\');\r\n child.stdin.write(\' if(meta[8] != \"\")\');\r\n child.stdin.write(\' {\');\r\n child.stdin.write(\' printf(\", \\\\\"subsystem\\\\\": {\");\');\r\n child.stdin.write(\' printf(\"\\\\\"manufacturer\\\\\": \\\\\"%s\\\\\"\", meta[8]);\');\r\n child.stdin.write(\' printf(\", \\\\\"description\\\\\": \\\\\"%s\\\\\"\", meta[10]);\');\r\n child.stdin.write(\' printf(\"}\");\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' printf(\"}\");\');\r\n child.stdin.write(\' }\');\r\n child.stdin.write(\' printf(\"]\");\');\r\n child.stdin.write(\"}\'\\nexit\\n\");\r\n child.waitExit();\r\n\r\n try\r\n {\r\n values.linux.pci = JSON.parse(child.stdout.str);\r\n }\r\n catch (x)\r\n { }\r\n child = null;\r\n }\r\n\r\n // Linux Last Boot Up Time\r\n try {\r\n child = require(\'child_process\').execFile(\'/usr/bin/uptime\', [\'\', \'-s\']); // must include blank value at begining for some reason?\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stderr.on(\'data\', function () { });\r\n child.waitExit();\r\n var regex = /^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/;\r\n if (regex.test(child.stdout.str.trim())) {\r\n values.linux.LastBootUpTime = child.stdout.str.trim();\r\n } else {\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\'date -d \"@$(( $(date +%s) - $(awk \\\'{print int($1)}\\\' /proc/uptime) ))\" \"+%Y-%m-%d %H:%M:%S\"\\nexit\\n\');\r\n child.waitExit();\r\n if (regex.test(child.stdout.str.trim())) {\r\n values.linux.LastBootUpTime = child.stdout.str.trim();\r\n }\r\n }\r\n child = null;\r\n } catch (ex) { }\r\n\r\n // Linux TPM\r\n try {\r\n if (require(\'fs\').statSync(\'/sys/class/tpm/tpm0\').isDirectory()){\r\n values.tpm = {\r\n SpecVersion: require(\'fs\').readFileSync(\'/sys/class/tpm/tpm0/tpm_version_major\').toString().trim()\r\n }\r\n }\r\n } catch (ex) { }\r\n\r\n return (values);\r\n}\r\n\r\nfunction windows_wmic_results(str)\r\n{\r\n var lines = str.trim().split(\'\\r\\n\');\r\n var keys = lines[0].split(\',\');\r\n var i, key, keyval;\r\n var tokens;\r\n var result = [];\r\n\r\n console.log(\'Lines: \' + lines.length, \'Keys: \' + keys.length);\r\n\r\n for (i = 1; i < lines.length; ++i)\r\n {\r\n var obj = {};\r\n console.log(\'i: \' + i);\r\n tokens = lines[i].split(\',\');\r\n for (key = 0; key < keys.length; ++key)\r\n {\r\n var tmp = Buffer.from(tokens[key], \'binary\').toString();\r\n console.log(tokens[key], tmp);\r\n tokens[key] = tmp == null ? \'\' : tmp;\r\n if (tokens[key].trim())\r\n {\r\n obj[keys[key].trim()] = tokens[key].trim();\r\n }\r\n }\r\n delete obj.Node;\r\n result.push(obj);\r\n }\r\n return (result);\r\n}\r\n\r\nfunction windows_identifiers()\r\n{\r\n var ret = { windows: {} };\r\n var items, item, i;\r\n\r\n ret[\'identifiers\'] = {};\r\n\r\n var values = require(\'win-wmi\').query(\'ROOT\\\\CIMV2\', \"SELECT * FROM Win32_Bios\", [\'ReleaseDate\', \'Manufacturer\', \'SMBIOSBIOSVersion\', \'SerialNumber\']);\r\n if(values[0]){\r\n ret[\'identifiers\'][\'bios_date\'] = values[0][\'ReleaseDate\'];\r\n ret[\'identifiers\'][\'bios_vendor\'] = values[0][\'Manufacturer\'];\r\n ret[\'identifiers\'][\'bios_version\'] = values[0][\'SMBIOSBIOSVersion\'];\r\n ret[\'identifiers\'][\'bios_serial\'] = values[0][\'SerialNumber\'];\r\n }\r\n ret[\'identifiers\'][\'bios_mode\'] = \'Legacy\';\r\n\r\n values = require(\'win-wmi\').query(\'ROOT\\\\CIMV2\', \"SELECT * FROM Win32_BaseBoard\", [\'Product\', \'SerialNumber\', \'Manufacturer\', \'Version\']);\r\n if(values[0]){\r\n ret[\'identifiers\'][\'board_name\'] = values[0][\'Product\'];\r\n ret[\'identifiers\'][\'board_serial\'] = values[0][\'SerialNumber\'];\r\n ret[\'identifiers\'][\'board_vendor\'] = values[0][\'Manufacturer\'];\r\n ret[\'identifiers\'][\'board_version\'] = values[0][\'Version\'];\r\n }\r\n\r\n values = require(\'win-wmi\').query(\'ROOT\\\\CIMV2\', \"SELECT * FROM Win32_ComputerSystemProduct\", [\'UUID\', \'Name\']);\r\n if(values[0]){\r\n ret[\'identifiers\'][\'product_uuid\'] = values[0][\'UUID\'];\r\n ret[\'identifiers\'][\'product_name\'] = values[0][\'Name\'];\r\n trimIdentifiers(ret.identifiers);\r\n }\r\n\r\n values = require(\'win-wmi\').query(\'ROOT\\\\CIMV2\', \"SELECT * FROM Win32_PhysicalMemory\");\r\n if(values[0]){\r\n trimResults(values);\r\n ret.windows.memory = values;\r\n }\r\n\r\n values = require(\'win-wmi\').query(\'ROOT\\\\CIMV2\', \"SELECT * FROM Win32_OperatingSystem\");\r\n if(values[0]){\r\n trimResults(values);\r\n ret.windows.osinfo = values[0];\r\n }\r\n\r\n values = require(\'win-wmi\').query(\'ROOT\\\\CIMV2\', \"SELECT * FROM Win32_DiskPartition\");\r\n if(values[0]){\r\n trimResults(values);\r\n ret.windows.partitions = values;\r\n for (var i in values) {\r\n if (values[i].Description==\'GPT: System\') {\r\n ret[\'identifiers\'][\'bios_mode\'] = \'UEFI\';\r\n }\r\n }\r\n }\r\n\r\n values = require(\'win-wmi\').query(\'ROOT\\\\CIMV2\', \"SELECT * FROM Win32_Processor\", [\'Caption\', \'DeviceID\', \'Manufacturer\', \'MaxClockSpeed\', \'Name\', \'SocketDesignation\']);\r\n if(values[0]){\r\n ret.windows.cpu = values;\r\n }\r\n \r\n values = require(\'win-wmi\').query(\'ROOT\\\\CIMV2\', \"SELECT * FROM Win32_VideoController\", [\'Name\', \'CurrentHorizontalResolution\', \'CurrentVerticalResolution\']);\r\n if(values[0]){\r\n ret.windows.gpu = values;\r\n }\r\n\r\n values = require(\'win-wmi\').query(\'ROOT\\\\CIMV2\', \"SELECT * FROM Win32_DiskDrive\", [\'Caption\', \'DeviceID\', \'Model\', \'Partitions\', \'Size\', \'Status\']);\r\n if(values[0]){\r\n ret.windows.drives = values;\r\n }\r\n \r\n // Insert GPU names\r\n ret.identifiers.gpu_name = [];\r\n for (var gpuinfo in ret.windows.gpu)\r\n {\r\n if (ret.windows.gpu[gpuinfo].Name) { ret.identifiers.gpu_name.push(ret.windows.gpu[gpuinfo].Name); }\r\n }\r\n\r\n // Insert Storage Devices\r\n ret.identifiers.storage_devices = [];\r\n for (var dv in ret.windows.drives)\r\n {\r\n ret.identifiers.storage_devices.push({ Caption: ret.windows.drives[dv].Caption, Model: ret.windows.drives[dv].Model, Size: ret.windows.drives[dv].Size });\r\n }\r\n\r\n try { ret.identifiers.cpu_name = ret.windows.cpu[0].Name; } catch (x) { }\r\n\r\n // Windows TPM\r\n IntToStr = function (v) { return String.fromCharCode((v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF); };\r\n try {\r\n values = require(\'win-wmi\').query(\'ROOT\\\\CIMV2\\\\Security\\\\MicrosoftTpm\', \"SELECT * FROM Win32_Tpm\", [\'IsActivated_InitialValue\',\'IsEnabled_InitialValue\',\'IsOwned_InitialValue\',\'ManufacturerId\',\'ManufacturerVersion\',\'SpecVersion\']);\r\n if(values[0]) {\r\n ret.tpm = {\r\n SpecVersion: values[0].SpecVersion.split(\",\")[0],\r\n ManufacturerId: IntToStr(values[0].ManufacturerId).replace(/[^\\x00-\\x7F]/g, \"\"),\r\n ManufacturerVersion: values[0].ManufacturerVersion,\r\n IsActivated: values[0].IsActivated_InitialValue,\r\n IsEnabled: values[0].IsEnabled_InitialValue,\r\n IsOwned: values[0].IsOwned_InitialValue,\r\n }\r\n }\r\n } catch (ex) { }\r\n\r\n return (ret);\r\n}\r\nfunction macos_identifiers()\r\n{\r\n var ret = { identifiers: {}, darwin: {} };\r\n var child;\r\n\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\'ioreg -d2 -c IOPlatformExpertDevice | grep board-id | awk -F= \\\'{ split($2, res, \"\\\\\"\"); print res[2]; }\\\'\\nexit\\n\');\r\n child.waitExit();\r\n ret.identifiers.board_name = child.stdout.str.trim();\r\n\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\'ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformSerialNumber | awk -F= \\\'{ split($2, res, \"\\\\\"\"); print res[2]; }\\\'\\nexit\\n\');\r\n child.waitExit();\r\n ret.identifiers.board_serial = child.stdout.str.trim();\r\n\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\'ioreg -d2 -c IOPlatformExpertDevice | grep manufacturer | awk -F= \\\'{ split($2, res, \"\\\\\"\"); print res[2]; }\\\'\\nexit\\n\');\r\n child.waitExit();\r\n ret.identifiers.board_vendor = child.stdout.str.trim();\r\n\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\'ioreg -d2 -c IOPlatformExpertDevice | grep version | awk -F= \\\'{ split($2, res, \"\\\\\"\"); print res[2]; }\\\'\\nexit\\n\');\r\n child.waitExit();\r\n ret.identifiers.board_version = child.stdout.str.trim();\r\n\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\'ioreg -d2 -c IOPlatformExpertDevice | grep IOPlatformUUID | awk -F= \\\'{ split($2, res, \"\\\\\"\"); print res[2]; }\\\'\\nexit\\n\');\r\n child.waitExit();\r\n ret.identifiers.product_uuid = child.stdout.str.trim();\r\n\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\'sysctl -n machdep.cpu.brand_string\\nexit\\n\');\r\n child.waitExit();\r\n ret.identifiers.cpu_name = child.stdout.str.trim();\r\n\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\'system_profiler SPMemoryDataType\\nexit\\n\');\r\n child.waitExit();\r\n var lines = child.stdout.str.trim().split(\'\\n\');\r\n if(lines.length > 0) {\r\n const memorySlots = [];\r\n if(lines[2].trim().includes(\'Memory Slots:\')) { // OLD MACS WITH SLOTS\r\n var memorySlots1 = child.stdout.str.split(/\\n{2,}/).slice(3);\r\n memorySlots1.forEach(function(slot,index) {\r\n var lines = slot.split(\'\\n\');\r\n if(lines.length == 1){ // start here\r\n if(lines[0].trim()!=\'\'){\r\n var slotObj = { DeviceLocator: lines[0].trim().replace(/:$/, \'\') }; // Initialize name as an empty string\r\n var nextline = memorySlots1[index+1].split(\'\\n\');\r\n nextline.forEach(function(line) {\r\n if (line.trim() !== \'\') {\r\n var parts = line.split(\':\');\r\n var key = parts[0].trim();\r\n var value = parts[1].trim();\r\n value = (key == \'Part Number\' || key == \'Manufacturer\') ? hexToAscii(parts[1].trim()) : parts[1].trim();\r\n slotObj[key.replace(\' \',\'\')] = value; // Store attribute in the slot object\r\n }\r\n });\r\n memorySlots.push(slotObj);\r\n }\r\n }\r\n });\r\n } else { // NEW MACS WITHOUT SLOTS\r\n memorySlots.push({ DeviceLocator: \"Onboard Memory\", Size: lines[2].split(\":\")[1].trim(), PartNumber: lines[3].split(\":\")[1].trim(), Manufacturer: lines[4].split(\":\")[1].trim() })\r\n }\r\n ret.darwin.memory = memorySlots;\r\n }\r\n\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\'diskutil info -all\\nexit\\n\');\r\n child.waitExit();\r\n var sections = child.stdout.str.split(\'**********\\n\');\r\n if(sections.length > 0){\r\n var devices = [];\r\n for (var i = 0; i < sections.length; i++) {\r\n var lines = sections[i].split(\'\\n\');\r\n var deviceInfo = {};\r\n var wholeYes = false;\r\n var physicalYes = false;\r\n var oldmac = false;\r\n for (var j = 0; j < lines.length; j++) {\r\n var keyValue = lines[j].split(\':\');\r\n var key = keyValue[0].trim();\r\n var value = keyValue[1] ? keyValue[1].trim() : \'\';\r\n if (key === \'Virtual\') oldmac = true;\r\n if (key === \'Whole\' && value === \'Yes\') wholeYes = true;\r\n if (key === \'Virtual\' && value === \'No\') physicalYes = true;\r\n if(value && key === \'Device / Media Name\'){\r\n deviceInfo[\'Caption\'] = value;\r\n }\r\n if(value && key === \'Disk Size\'){\r\n deviceInfo[\'Size\'] = value.split(\' \')[0] + \' \' + value.split(\' \')[1];\r\n }\r\n }\r\n if (wholeYes) {\r\n if (oldmac) {\r\n if (physicalYes) devices.push(deviceInfo);\r\n } else {\r\n devices.push(deviceInfo);\r\n }\r\n }\r\n }\r\n ret.identifiers.storage_devices = devices;\r\n }\r\n\r\n // Fetch storage volumes using df\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', dataHandler);\r\n child.stdin.write(\'df -aHY | awk \\\'NR>1 {printf \"{\\\\\"size\\\\\":\\\\\"%s\\\\\",\\\\\"used\\\\\":\\\\\"%s\\\\\",\\\\\"available\\\\\":\\\\\"%s\\\\\",\\\\\"mount_point\\\\\":\\\\\"%s\\\\\",\\\\\"type\\\\\":\\\\\"%s\\\\\"},\", $3, $4, $5, $10, $2}\\\' | sed \\\'$ s/,$//\\\' | awk \\\'BEGIN {printf \"[\"} {printf \"%s\", $0} END {printf \"]\"}\\\'\\nexit\\n\');\r\n child.waitExit();\r\n try {\r\n ret.darwin.volumes = JSON.parse(child.stdout.str.trim());\r\n for (var index = 0; index < ret.darwin.volumes.length; index++) {\r\n if (ret.darwin.volumes[index].type == \'auto_home\'){\r\n ret.darwin.volumes.splice(index,1);\r\n }\r\n }\r\n if (ret.darwin.volumes.length == 0) { // not sonima OS so dont show type for now\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', dataHandler);\r\n child.stdin.write(\'df -aH | awk \\\'NR>1 {printf \"{\\\\\"size\\\\\":\\\\\"%s\\\\\",\\\\\"used\\\\\":\\\\\"%s\\\\\",\\\\\"available\\\\\":\\\\\"%s\\\\\",\\\\\"mount_point\\\\\":\\\\\"%s\\\\\"},\", $2, $3, $4, $9}\\\' | sed \\\'$ s/,$//\\\' | awk \\\'BEGIN {printf \"[\"} {printf \"%s\", $0} END {printf \"]\"}\\\'\\nexit\\n\');\r\n child.waitExit();\r\n try {\r\n ret.darwin.volumes = JSON.parse(child.stdout.str.trim());\r\n for (var index = 0; index < ret.darwin.volumes.length; index++) {\r\n if (ret.darwin.volumes[index].size == \'auto_home\'){\r\n ret.darwin.volumes.splice(index,1);\r\n }\r\n }\r\n } catch (xx) { }\r\n }\r\n } catch (xx) { }\r\n child = null;\r\n\r\n // MacOS Last Boot Up Time\r\n try {\r\n child = require(\'child_process\').execFile(\'/usr/sbin/sysctl\', [\'\', \'kern.boottime\']); // must include blank value at begining for some reason?\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stderr.on(\'data\', function () { });\r\n child.waitExit();\r\n const timestampMatch = /\\{ sec = (\\d+), usec = \\d+ \\}/.exec(child.stdout.str.trim());\r\n if (!ret.darwin) {\r\n ret.darwin = { LastBootUpTime: parseInt(timestampMatch[1]) };\r\n } else {\r\n ret.darwin.LastBootUpTime = parseInt(timestampMatch[1]);\r\n }\r\n child = null;\r\n } catch (ex) { }\r\n\r\n trimIdentifiers(ret.identifiers);\r\n\r\n child = null;\r\n return (ret);\r\n}\r\n\r\nfunction hexToAscii(hexString) {\r\n if(!hexString.startsWith(\'0x\')) return hexString.trim();\r\n hexString = hexString.startsWith(\'0x\') ? hexString.slice(2) : hexString;\r\n var str = \'\';\r\n for (var i = 0; i < hexString.length; i += 2) {\r\n var hexPair = hexString.substr(i, 2);\r\n str += String.fromCharCode(parseInt(hexPair, 16));\r\n }\r\n str = str.replace(/[\\u007F-\\uFFFF]/g, \'\'); // Remove characters from 0x0080 to 0xFFFF\r\n return str.trim();\r\n}\r\n\r\nfunction win_chassisType()\r\n{\r\n // needs to be replaced with win-wmi but due to bug in win-wmi it doesnt handle arrays correctly\r\n var child = require(\'child_process\').execFile(process.env[\'windir\'] + \'\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe\', [\'powershell\', \'-noprofile\', \'-nologo\', \'-command\', \'-\'], {});\r\n if (child == null) { return ([]); }\r\n child.descriptorMetadata = \'process-manager\';\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stderr.str = \'\'; child.stderr.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\'Get-WmiObject Win32_SystemEnclosure | Select-Object -ExpandProperty ChassisTypes\\r\\n\');\r\n child.stdin.write(\'exit\\r\\n\');\r\n child.waitExit();\r\n try {\r\n return (parseInt(child.stdout.str));\r\n } catch (e) {\r\n return (2); // unknown\r\n }\r\n}\r\n\r\nfunction win_systemType()\r\n{\r\n try {\r\n var tokens = require(\'win-wmi\').query(\'ROOT\\\\CIMV2\', \'SELECT PCSystemType FROM Win32_ComputerSystem\', [\'PCSystemType\']);\r\n if (tokens[0]) {\r\n return (parseInt(tokens[0][\'PCSystemType\']));\r\n } else {\r\n return (parseInt(1)); // default is desktop\r\n }\r\n } catch (ex) {\r\n return (parseInt(1)); // default is desktop\r\n }\r\n\r\n}\r\n\r\nfunction win_formFactor(chassistype)\r\n{\r\n var ret = \'DESKTOP\';\r\n switch (chassistype)\r\n {\r\n case 11: // Handheld\r\n case 30: // Tablet\r\n case 31: // Convertible\r\n case 32: // Detachable\r\n ret = \'TABLET\';\r\n break;\r\n case 9: // Laptop\r\n case 10: // Notebook\r\n case 14: // Sub Notebook\r\n ret = \'LAPTOP\';\r\n break;\r\n default:\r\n ret = win_systemType() == 2 ? \'MOBILE\' : \'DESKTOP\';\r\n break;\r\n }\r\n\r\n return (ret);\r\n}\r\n\r\nswitch(process.platform)\r\n{\r\n case \'linux\':\r\n module.exports = { _ObjectID: \'identifiers\', get: linux_identifiers };\r\n break;\r\n case \'win32\':\r\n module.exports = { _ObjectID: \'identifiers\', get: windows_identifiers, chassisType: win_chassisType, formFactor: win_formFactor, systemType: win_systemType };\r\n break;\r\n case \'darwin\':\r\n module.exports = { _ObjectID: \'identifiers\', get: macos_identifiers };\r\n break;\r\n default:\r\n module.exports = { get: function () { throw (\'Unsupported Platform\'); } };\r\n break;\r\n}\r\nmodule.exports.isDocker = function isDocker()\r\n{\r\n if (process.platform != \'linux\') { return (false); }\r\n\r\n var child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\"cat /proc/self/cgroup | tr \'\\n\' \'`\' | awk -F\'`\' \'{ split($1, res, \" + \'\"/\"); if(res[2]==\"docker\"){print \"1\";} }\\\'\\nexit\\n\');\r\n child.waitExit();\r\n return (child.stdout.str != \'\');\r\n};\r\nmodule.exports.isBatteryPowered = function isBatteryOperated()\r\n{\r\n var ret = false;\r\n switch(process.platform)\r\n {\r\n default:\r\n break;\r\n case \'linux\':\r\n var devices = require(\'fs\').readdirSync(\'/sys/class/power_supply\');\r\n for (var i in devices)\r\n {\r\n if (require(\'fs\').readFileSync(\'/sys/class/power_supply/\' + devices[i] + \'/type\').toString().trim() == \'Battery\')\r\n {\r\n ret = true;\r\n break;\r\n }\r\n }\r\n break;\r\n case \'win32\':\r\n var GM = require(\'_GenericMarshal\');\r\n var stats = GM.CreateVariable(12);\r\n var kernel32 = GM.CreateNativeProxy(\'Kernel32.dll\');\r\n kernel32.CreateMethod(\'GetSystemPowerStatus\');\r\n if (kernel32.GetSystemPowerStatus(stats).Val != 0)\r\n {\r\n if(stats.toBuffer()[1] != 128 && stats.toBuffer()[1] != 255)\r\n {\r\n ret = true;\r\n }\r\n else\r\n {\r\n // No Battery detected, so lets check if there is supposed to be one\r\n var formFactor = win_formFactor(win_chassisType());\r\n return (formFactor == \'LAPTOP\' || formFactor == \'TABLET\' || formFactor == \'MOBILE\');\r\n }\r\n }\r\n break;\r\n case \'darwin\':\r\n var child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function(c){ this.str += c.toString(); });\r\n child.stderr.str = \'\'; child.stderr.on(\'data\', function(c){ this.str += c.toString(); });\r\n child.stdin.write(\"pmset -g batt | tr \'\\\\n\' \'`\' | awk -F\'`\' \'{ if(NF>2) { print \\\"true\\\"; }}\'\\nexit\\n\");\r\n child.waitExit();\r\n if(child.stdout.str.trim() != \'\') { ret = true; }\r\n break;\r\n }\r\n return (ret);\r\n};\r\nmodule.exports.isVM = function isVM()\r\n{\r\n var ret = false;\r\n var id = this.get();\r\n if (id.linux && id.linux.sys_vendor)\r\n {\r\n switch (id.linux.sys_vendor)\r\n {\r\n case \'VMware, Inc.\':\r\n case \'QEMU\':\r\n case \'Xen\':\r\n ret = true;\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n if (id.identifiers.bios_vendor)\r\n {\r\n switch(id.identifiers.bios_vendor)\r\n {\r\n case \'VMware, Inc.\':\r\n case \'Xen\':\r\n case \'SeaBIOS\':\r\n case \'EFI Development Kit II / OVMF\':\r\n case \'Proxmox distribution of EDK II\':\r\n ret = true;\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n if (id.identifiers.board_vendor && id.identifiers.board_vendor == \'VMware, Inc.\') { ret = true; }\r\n if (id.identifiers.board_name)\r\n {\r\n switch (id.identifiers.board_name)\r\n {\r\n case \'VirtualBox\':\r\n case \'Virtual Machine\':\r\n ret = true;\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n\r\n if (process.platform == \'win32\' && !ret)\r\n {\r\n for(var i in id.identifiers.gpu_name)\r\n {\r\n if(id.identifiers.gpu_name[i].startsWith(\'VMware \'))\r\n {\r\n ret = true;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n\r\n if (!ret) { ret = this.isDocker(); }\r\n return (ret);\r\n};\r\n\r\n// bios_date = BIOS->ReleaseDate\r\n// bios_vendor = BIOS->Manufacturer\r\n// bios_version = BIOS->SMBIOSBIOSVersion\r\n// board_name = BASEBOARD->Product = ioreg/board-id\r\n// board_serial = BASEBOARD->SerialNumber = ioreg/serial-number | ioreg/IOPlatformSerialNumber\r\n// board_vendor = BASEBOARD->Manufacturer = ioreg/manufacturer\r\n// board_version = BASEBOARD->Version\r\n"); addedModules.push("computer-identifiers"); } catch (ex) { }
var coretranslations = JSON.parse('{\n \"en\": {\n \"allow\": \"Allow\",\n \"deny\": \"Deny\",\n \"autoAllowForFive\": \"Auto accept all connections for next 5 minutes\",\n \"terminalConsent\": \"{0} requesting remote terminal access. Grant access?\",\n \"desktopConsent\": \"{0} requesting remote desktop access. Grant access?\",\n \"fileConsent\": \"{0} requesting remote file Access. Grant access?\",\n \"terminalNotify\": \"{0} started a remote terminal session.\",\n \"desktopNotify\": \"{0} started a remote desktop session.\",\n \"fileNotify\": \"{0} started a remote file session.\",\n \"privacyBar\": \"Sharing desktop with: {0}\"\n },\n \"cs\": {\n \"allow\": \"Dovolit\",\n \"deny\": \"Odmítnout\",\n \"autoAllowForFive\": \"Automaticky přijímat všechna připojení na dalších 5 minut\",\n \"terminalConsent\": \"{0} žádá o vzdálený terminálový přístup. Přístup povolen?\",\n \"desktopConsent\": \"{0} žádá o přístup ke vzdálené ploše. Přístup povolen?\",\n \"fileConsent\": \"{0} požaduje vzdálený přístup k souboru. Přístup povolen?\",\n \"terminalNotify\": \"{0} zahájil relaci vzdáleného terminálu.\",\n \"desktopNotify\": \"{0} zahájil relaci vzdálené plochy.\",\n \"fileNotify\": \"{0} zahájil relaci vzdáleného souboru.\",\n \"privacyBar\": \"Sdílení plochy s: {0}\"\n },\n \"de\": {\n \"allow\": \"Erlauben\",\n \"deny\": \"Verweigern\",\n \"autoAllowForFive\": \"Alle Verbindungen für die nächsten 5 Minuten erlauben\",\n \"terminalConsent\": \"{0} erbittet Fern-Terminalzugriff. Zugang erlauben?\",\n \"desktopConsent\": \"{0} erbittet Fern-Desktopzugriff. Zugang erlauben?\",\n \"fileConsent\": \"{0} erbittet Fern-Dateizugriff. Zugang erlauben?\",\n \"terminalNotify\": \"{0} hat eine Fern-Terminalzugriff-Sitzung gestartet.\",\n \"desktopNotify\": \"{0} hat eine Fern-Desktopzugriff-Sitzung gestartet.\",\n \"fileNotify\": \"{0} hat eine Fern-Dateizugriff-Sitzung gestartet.\",\n \"privacyBar\": \"Teile desktop mit: {0}\"\n },\n \"es\": {\n \"allow\": \"Permitir\",\n \"deny\": \"Negar\",\n \"autoAllowForFive\": \"Aceptar automáticamente todas las conexiones durante los próximos 5 minutos\",\n \"terminalConsent\": \"{0} solicitando acceso a terminal remoto. ¿Autorizará el acceso?\",\n \"desktopConsent\": \"{0} solicita acceso a escritorio remoto. ¿Autorizará el acceso?\",\n \"fileConsent\": \"{0} solicita acceso remoto al archivo. ¿Autorizará el acceso?\",\n \"terminalNotify\": \"{0} inició una sesión de terminal remota.\",\n \"desktopNotify\": \"{0} inició una sesión de escritorio remoto.\",\n \"fileNotify\": \"{0} inició una sesión de archivo remoto.\",\n \"privacyBar\": \"Compartir escritorio con: {0}\"\n },\n \"fi\": {\n \"allow\": \"Sallia\",\n \"deny\": \"Kieltää\",\n \"autoAllowForFive\": \"Hyväksy automaattisesti kaikki yhteydet seuraavan 5 minuutin ajan\",\n \"terminalConsent\": \"{0} pyytää etäpäätteen käyttöoikeutta. Myönnetäänkö käyttöoikeus?\",\n \"desktopConsent\": \"{0} pyytää etätyöpöytäkäyttöä. Myönnetäänkö käyttöoikeus?\",\n \"fileConsent\": \"{0} pyytää etäkäyttöoikeutta tiedostoon. Myönnetäänkö käyttöoikeus?\",\n \"terminalNotify\": \"{0} aloitti etäpääteistunnon.\",\n \"desktopNotify\": \"{0} aloitti etätyöpöytäistunnon.\",\n \"fileNotify\": \"{0} aloitti etätiedostoistunnon.\",\n \"privacyBar\": \"Työpöytä jaetaan seuraavien kanssa: {0}\"\n },\n \"fr\": {\n \"allow\": \"Permettre\",\n \"deny\": \"Refuser\",\n \"autoAllowForFive\": \"Accepter automatiquement les connexions pendant les 5 prochaines minutes\",\n \"terminalConsent\": \"{0} demande(nt) d\'utilisation du terminal à distance. Autoriser l\'accès ?\",\n \"desktopConsent\": \"{0} demande(nt) l\'utilisation du bureau à distance. Autoriser l\'accès ?\",\n \"fileConsent\": \"{0} demande(nt) d\'accès à un fichier à distance. Autoriser l\'accès ?\",\n \"terminalNotify\": \"{0} a démarré une session de terminal distant.\",\n \"desktopNotify\": \"{0} a démarré une session de bureau à distance.\",\n \"fileNotify\": \"{0} a démarré une session de fichiers à distance.\",\n \"privacyBar\": \"Partage du bureau avec : {0}\"\n },\n \"hi\": {\n \"allow\": \"अनुमति\",\n \"deny\": \"मना\",\n \"autoAllowForFive\": \"अगले 5 मिनट के लिए सभी कनेक्शन स्वतः स्वीकार करें\",\n \"terminalConsent\": \"{0} दूरस्थ टर्मिनल पहुंच का अनुरोध कर रहा है। अनुदान पहुँच?\",\n \"desktopConsent\": \"{0} दूरस्थ डेस्कटॉप पहुंच का अनुरोध कर रहा है। अनुदान पहुँच?\",\n \"fileConsent\": \"{0} दूरस्थ फ़ाइल एक्सेस का अनुरोध करना। अनुदान पहुँच?\",\n \"terminalNotify\": \"{0} ने दूरस्थ टर्मिनल सत्र प्रारंभ किया।\",\n \"desktopNotify\": \"{0} ने दूरस्थ डेस्कटॉप सत्र प्रारंभ किया।\",\n \"fileNotify\": \"{0} ने दूरस्थ फ़ाइल सत्र प्रारंभ किया।\",\n \"privacyBar\": \"इसके साथ डेस्कटॉप साझा करना: {0}\"\n },\n \"it\": {\n \"allow\": \"Permettere\",\n \"deny\": \"Negare\",\n \"autoAllowForFive\": \"Accetta automaticamente tutte le connessioni per i prossimi 5 minuti\",\n \"terminalConsent\": \"{0} che richiede l\'accesso al terminale remoto. Concedere l\'accesso?\",\n \"desktopConsent\": \"{0} che richiede l\'accesso al desktop remoto. Concedere l\'accesso?\",\n \"fileConsent\": \"{0} che richiede l\'accesso al file remoto. Concedere l\'accesso?\",\n \"terminalNotify\": \"{0} ha avviato una sessione di terminale remoto.\",\n \"desktopNotify\": \"{0} ha avviato una sessione desktop remoto.\",\n \"fileNotify\": \"{0} ha avviato una sessione di file remota.\",\n \"privacyBar\": \"Condivisione del desktop con: {0}\"\n },\n \"ja\": {\n \"allow\": \"許可する\",\n \"deny\": \"拒否\",\n \"autoAllowForFive\": \"次の5分間はすべての接続を自動受け入れます\",\n \"terminalConsent\": \"{0}リモート端末アクセスを要求しています。アクセス許可?\",\n \"desktopConsent\": \"{0}リモートデスクトップアクセスを要求しています。アクセス許可?\",\n \"fileConsent\": \"{0}リモートファイルアクセスを要求しています。アクセス許可?\",\n \"terminalNotify\": \"{0}がリモートターミナルセッションを開始しました。\",\n \"desktopNotify\": \"{0}はリモートデスクトップセッションを開始しました。\",\n \"fileNotify\": \"{0}がリモートファイルセッションを開始しました。\",\n \"privacyBar\": \"デスクトップの共有:{0}\"\n },\n \"ko\": {\n \"allow\": \"허용하다\",\n \"deny\": \"거부\",\n \"terminalNotify\": \"{0}이(가) 원격 터미널 세션을 시작했습니다.\",\n \"desktopNotify\": \"{0}이(가) 원격 데스크톱 세션을 시작했습니다.\",\n \"fileNotify\": \"{0}이(가) 원격 파일 세션을 시작했습니다.\",\n \"privacyBar\": \"다음과 데스크톱 공유: {0}\",\n \"autoAllowForFive\": \"다음 5분 동안 모든 연결 자동 수락\",\n \"terminalConsent\": \"{0} 원격 터미널 액세스를 요청합니다. 액세스 권한을 부여하시겠습니까?\",\n \"desktopConsent\": \"{0} 원격 데스크톱 액세스를 요청합니다. 액세스 권한을 부여하시겠습니까?\",\n \"fileConsent\": \"{0}이(가) 원격 파일 액세스를 요청합니다. 액세스 권한을 부여하시겠습니까?\"\n },\n \"nl\": {\n \"allow\": \"Toestaan\",\n \"deny\": \"Weigeren\",\n \"autoAllowForFive\": \"Alle verbindingen automatisch accepteren voor de komende 5 minuten\",\n \"terminalConsent\": \"{0} verzoekt om toegang tot externe terminal.Toegang verlenen?\",\n \"desktopConsent\": \"{0} verzoekt om toegang tot extern bureaublad.Toegang verlenen?\",\n \"fileConsent\": \"{0} verzoekt om externe bestandstoegang.Toegang verlenen?\",\n \"terminalNotify\": \"{0} heeft een externe terminalsessie gestart.\",\n \"desktopNotify\": \"{0} heeft een extern bureaubladsessie gestart.\",\n \"fileNotify\": \"{0} heeft een externe bestandssessie gestart.\",\n \"privacyBar\": \"Bureaublad delen met: {0}\"\n },\n \"pt\": {\n \"allow\": \"Permitir\",\n \"deny\": \"Negar\",\n \"autoAllowForFive\": \"Aceita automaticamente todas as conexões pelos próximos 5 minutos\",\n \"terminalConsent\": \"{0} está a pedir acesso ao terminal remoto. Conceder acesso?\",\n \"desktopConsent\": \"{0} está a pedir acesso à área de trabalho remota. Conceder acesso?\",\n \"fileConsent\": \"{0} está a pedir acesso remoto aos ficheiros. Conceder acesso?\",\n \"terminalNotify\": \"{0} iniciou uma sessão de terminal remoto.\",\n \"desktopNotify\": \"{0} iniciou uma sessão de área de trabalho remota.\",\n \"fileNotify\": \"{0} iniciou uma sessão de ficheiro remoto.\",\n \"privacyBar\": \"Compartilhando área de trabalho com: {0}\"\n },\n \"ru\": {\n \"allow\": \"Разрешить\",\n \"deny\": \"Отказать\",\n \"autoAllowForFive\": \"Автоматически принимать все соединения в течение 5 минут\",\n \"terminalConsent\": \"{0} запрашивает удаленный доступ к терминалу. Разрешить доступ?\",\n \"desktopConsent\": \"{0} запрашивает удаленный доступ к рабочему столу. Разрешить доступ?\",\n \"fileConsent\": \"{0} запрашивает удаленный доступ к файлам. Разрешить доступ?\",\n \"terminalNotify\": \"{0} начал сеанс удаленного терминала.\",\n \"desktopNotify\": \"{0} начал сеанс удаленного рабочего стола.\",\n \"fileNotify\": \"{0} начал удаленный файловый сеанс.\",\n \"privacyBar\": \"Доступ к рабочему столу предоставлен: {0}\"\n },\n \"sv\": {\n \"allow\": \"Tillåta\",\n \"deny\": \"Förneka\",\n \"autoAllowForFive\": \"Acceptera alla anslutningar automatiskt under de kommande 5 minuterna\",\n \"terminalConsent\": \"{0} begär åtkomst till fjärrterminal. Ge tillgång?\",\n \"desktopConsent\": \"{0} begär åtkomst till fjärrskrivbord. Ge tillgång?\",\n \"fileConsent\": \"{0} begär fjärråtkomst till fil. Ge tillgång?\",\n \"terminalNotify\": \"{0} startade en fjärrterminalsession.\",\n \"desktopNotify\": \"{0} startade en fjärrskrivbordssession.\",\n \"fileNotify\": \"{0} startade en fjärrfilsession.\",\n \"privacyBar\": \"Dela skrivbord med: {0}\"\n },\n \"tr\": {\n \"allow\": \"İzin ver\",\n \"deny\": \"İnkar etmek\",\n \"autoAllowForFive\": \"Sonraki 5 dakika boyunca tüm bağlantıları otomatik olarak kabul et\",\n \"terminalConsent\": \"{0} uzak terminal erişimi istiyor. Erişim izni veriyor musunuz?\",\n \"desktopConsent\": \"{0} uzak masaüstü erişimi istiyor. Erişim izni veriyor musunuz?\",\n \"fileConsent\": \"{0} uzak dosya Erişimi istiyor. Erişim izni veriyor musunuz?\",\n \"terminalNotify\": \"{0} bir uzak terminal oturumu başlattı.\",\n \"desktopNotify\": \"{0} bir uzak masaüstü oturumu başlattı.\",\n \"fileNotify\": \"{0} bir uzak dosya oturumu başlattı.\",\n \"privacyBar\": \"Masaüstünü şu kişilerle paylaşma: {0}\"\n },\n \"zh-chs\": {\n \"allow\": \"允许\",\n \"deny\": \"否定\",\n \"autoAllowForFive\": \"在接下来的 5 分钟内自动接受所有连接\",\n \"terminalConsent\": \"{0} 请求远程终端访问。授予访问权限?\",\n \"desktopConsent\": \"{0} 请求远程桌面访问。授予访问权限?\",\n \"fileConsent\": \"{0} 请求远程文件访问。授予访问权限?\",\n \"terminalNotify\": \"{0} 启动了远程终端会话。\",\n \"desktopNotify\": \"{0} 启动了远程桌面会话。\",\n \"fileNotify\": \"{0} 启动了远程文件会话。\",\n \"privacyBar\": \"与:{0} 共享桌面\"\n },\n \"da\": {\n \"allow\": \"Tillad\",\n \"deny\": \"Afslå\",\n \"autoAllowForFive\": \"Accepter automatisk alle forbindelser i de næste 5 minutter\",\n \"terminalConsent\": \"{0} anmoder om ekstern terminaladgang. Give adgang?\",\n \"desktopConsent\": \"{0} anmoder om fjernskrivebordsadgang. Give adgang?\",\n \"fileConsent\": \"{0} anmoder om fjernadgang til fil. Give adgang?\",\n \"terminalNotify\": \"{0} startede en fjernterminalsession.\",\n \"desktopNotify\": \"{0} startede en fjernskrivebordssession.\",\n \"fileNotify\": \"{0} startede en ekstern filsession.\",\n \"privacyBar\": \"Deler skrivebordet med: {0}\"\n },\n \"pl\": {\n \"allow\": \"Zezwól\",\n \"deny\": \"Odrzucono\",\n \"autoAllowForFive\": \"Automatycznie akceptuj wszystkie połączenia przez następne 5 minut\",\n \"terminalConsent\": \"{0} prosi o zdalny dostęp do terminala. Przyznać dostęp?\",\n \"desktopConsent\": \"{0} prosi o zdalny dostęp do pulpitu. Przyznać dostęp?\",\n \"fileConsent\": \"{0} prosi o zdalny dostęp do plików. Przyznać dostęp?\",\n \"terminalNotify\": \"{0} rozpoczął sesję dostępu do terminala.\",\n \"desktopNotify\": \"{0} rozpoczął sesję dostępu do pulpitu.\",\n \"fileNotify\": \"{0} rozpoczął sesję dostępu do plików.\",\n \"privacyBar\": \"Współdzielenie pulpitu z: {0}\"\n },\n \"pt-br\": {\n \"allow\": \"Permitir\",\n \"deny\": \"Negar\",\n \"autoAllowForFive\": \"Aceitar todas conexões pelos próximos 5 minutos\",\n \"terminalConsent\": \"{0} está solicitando acesso ao terminal. Permitir?\",\n \"desktopConsent\": \"{0} está solicitando acesso a área de trabalho remota. Permitir?\",\n \"fileConsent\": \"{0} está solicitando acesso aos arquivos. Permitir?\",\n \"terminalNotify\": \"{0} iniciou uma sessão de terminal.\",\n \"desktopNotify\": \"{0} iniciou uma sessão de área de trabalho remota.\",\n \"fileNotify\": \"{0} {0} iniciou uma sessão de arquivos.\",\n \"privacyBar\": \"Compartilhando área de trabalho com: {0}\"\n },\n \"zh-cht\": {\n \"allow\": \"允許\",\n \"deny\": \"否定\",\n \"autoAllowForFive\": \"在接下來的 5 分鐘內自動接受所有連接\",\n \"terminalConsent\": \"{0} 請求遠程終端訪問。授予訪問權限?\",\n \"desktopConsent\": \"{0} 請求遠程桌面訪問。授予訪問權限?\",\n \"fileConsent\": \"{0} 請求遠程文件訪問。授予訪問權限?\",\n \"terminalNotify\": \"{0} 啟動了遠程終端會話。\",\n \"desktopNotify\": \"{0} 啟動了遠程桌面會話。\",\n \"fileNotify\": \"{0} 啟動了遠程文件會話。\",\n \"privacyBar\": \"與:{0} 共享桌面\"\n },\n \"bs\": {\n \"allow\": \"Dopustiti\",\n \"deny\": \"Deny\",\n \"autoAllowForFive\": \"Automatski prihvati sve veze u narednih 5 minuta\",\n \"terminalConsent\": \"{0} zahtijeva pristup udaljenom terminalu. Odobriti pristup?\",\n \"desktopConsent\": \"{0} zahtijeva pristup udaljenoj radnoj površini. Odobriti pristup?\",\n \"fileConsent\": \"{0} zahtijeva udaljeni pristup fajlu. Odobriti pristup?\",\n \"terminalNotify\": \"{0} je započeo sesiju udaljenog terminala.\",\n \"desktopNotify\": \"{0} je započeo sesiju udaljene radne površine.\",\n \"fileNotify\": \"{0} je započeo sesiju udaljenog fajla.\",\n \"privacyBar\": \"Dijeljenje radne površine sa: {0}\"\n },\n \"hu\": {\n \"allow\": \"Engedélyezés\",\n \"deny\": \"Elutasítás\",\n \"autoAllowForFive\": \"Csatlakozások automatikus elfogadása a következő 5 percben\",\n \"terminalConsent\": \"{0} távoli parancssor,terminál hozzáférést kér. Engedélyezi a hozzáférést?\",\n \"desktopConsent\": \"{0} távoli asztali hozzáférést kér. Engedélyezi a hozzáférést?\",\n \"fileConsent\": \"{0} távoli fájlhozzáférést kér. Engedélyezi a hozzáférést?\",\n \"terminalNotify\": \"{0} távoli parancssor munkamenetet indított.\",\n \"desktopNotify\": \"{0} távoli asztali munkamenetet indított.\",\n \"fileNotify\": \"{0} távoli fájlmunkamenetet indított.\",\n \"privacyBar\": \"Asztal megosztás aktív: {0} felhasználóval\"\n },\n \"ca\": {\n \"allow\": \"Permetre\",\n \"deny\": \"Negar\",\n \"autoAllowForFive\": \"Accepta automàticament totes les connexions durant els propers 5 minuts\",\n \"terminalConsent\": \"{0} sol·licitant accés al terminal remot. Accés garantit?\",\n \"desktopConsent\": \"{0} sol·licitant accés a l\'escriptori remot. Accés garantit?\",\n \"fileConsent\": \"{0} sol·licitant accés remot al fitxer. Accés garantit?\",\n \"terminalNotify\": \"{0} va iniciar una sessió de terminal remota.\",\n \"desktopNotify\": \"{0} va iniciar una sessió d\'escriptori remot.\",\n \"fileNotify\": \"{0} va iniciar una sessió de fitxer remota.\",\n \"privacyBar\": \"Compartint escriptori amb: {0}\"\n },\n \"uk\": {\n \"allow\": \"Дозволити\",\n \"deny\": \"Відмовити\",\n \"autoAllowForFive\": \"Автоматично приймати всі підключення впродовж наступних 5 хвилин\",\n \"terminalConsent\": \"{0} запитує доступ до віддаленого терміналу. Надати доступ?\",\n \"desktopConsent\": \"{0} запитує віддалений доступ до стільниці. Надати доступ?\",\n \"fileConsent\": \"{0} запитує віддалений доступ до файлу. Надати доступ?\",\n \"terminalNotify\": \"{0} почав сеанс віддаленого терміналу.\",\n \"desktopNotify\": \"{0} розпочав сеанс віддаленої стільниці.\",\n \"fileNotify\": \"{0} розпочав віддалений файловий сеанс.\",\n \"privacyBar\": \"Поширити доступ до стільниці з: {0}\"\n }\n}');
try { addModule("linux-dhcp", "/*\r\nCopyright 2021 Intel Corporation\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n\r\n* @description Mini DHCP Client Module, to fetch configuration data\r\n* @author Bryan Roe & Ylian Saint-Hilaire\r\n*/\r\n\r\n// DHCP Information\r\nif (Function.prototype.internal == null) { Object.defineProperty(Function.prototype, \'internal\', { get: function () { return (this); } }); }\r\nif (global._hide == null)\r\n{\r\n global._hide = function _hide(v)\r\n {\r\n if(v==null || (v!=null && typeof(v)==\'boolean\'))\r\n {\r\n var ret = _hide.currentObject;\r\n if (v) { _hide.currentObject = null; }\r\n return (ret);\r\n }\r\n else\r\n {\r\n _hide.currentObject = v;\r\n }\r\n }\r\n}\r\naddModule(\'promise2\', Buffer.from(\'LyoNCkNvcHlyaWdodCAyMDE4IEludGVsIENvcnBvcmF0aW9uDQoNCkxpY2Vuc2VkIHVuZGVyIHRoZSBBcGFjaGUgTGljZW5zZSwgVmVyc2lvbiAyLjAgKHRoZSAiTGljZW5zZSIpOw0KeW91IG1heSBub3QgdXNlIHRoaXMgZmlsZSBleGNlcHQgaW4gY29tcGxpYW5jZSB3aXRoIHRoZSBMaWNlbnNlLg0KWW91IG1heSBvYnRhaW4gYSBjb3B5IG9mIHRoZSBMaWNlbnNlIGF0DQoNCiAgICBodHRwOi8vd3d3LmFwYWNoZS5vcmcvbGljZW5zZXMvTElDRU5TRS0yLjANCg0KVW5sZXNzIHJlcXVpcmVkIGJ5IGFwcGxpY2FibGUgbGF3IG9yIGFncmVlZCB0byBpbiB3cml0aW5nLCBzb2Z0d2FyZQ0KZGlzdHJpYnV0ZWQgdW5kZXIgdGhlIExpY2Vuc2UgaXMgZGlzdHJpYnV0ZWQgb24gYW4gIkFTIElTIiBCQVNJUywNCldJVEhPVVQgV0FSUkFOVElFUyBPUiBDT05ESVRJT05TIE9GIEFOWSBLSU5ELCBlaXRoZXIgZXhwcmVzcyBvciBpbXBsaWVkLg0KU2VlIHRoZSBMaWNlbnNlIGZvciB0aGUgc3BlY2lmaWMgbGFuZ3VhZ2UgZ292ZXJuaW5nIHBlcm1pc3Npb25zIGFuZA0KbGltaXRhdGlvbnMgdW5kZXIgdGhlIExpY2Vuc2UuDQoqLw0KDQp2YXIgcmVmVGFibGUgPSB7fTsNCg0KZnVuY3Rpb24gcHJvbWlzZUluaXRpYWxpemVyKHIsaikNCnsNCiAgICB0aGlzLl9yZXMgPSByOw0KICAgIHRoaXMuX3JlaiA9IGo7DQp9DQoNCmZ1bmN0aW9uIGdldFJvb3RQcm9taXNlKG9iaikNCnsNCiAgICB3aGlsZShvYmoucGFyZW50UHJvbWlzZSkNCiAgICB7DQogICAgICAgIG9iaiA9IG9iai5wYXJlbnRQcm9taXNlOw0KICAgIH0NCiAgICByZXR1cm4gKG9iaik7DQp9DQoNCmZ1bmN0aW9uIGV2ZW50X3N3aXRjaGVyKGRlc2lyZWRfY2FsbGVlLCB0YXJnZXQpDQp7DQogICAgcmV0dXJuICh7IF9PYmplY3RJRDogJ2V2ZW50X3N3aXRjaGVyJywgZnVuYzogdGFyZ2V0LmJpbmQoZGVzaXJlZF9jYWxsZWUpIH0pOw0KfQ0KDQpmdW5jdGlvbiBldmVudF9mb3J3YXJkZXIoc291cmNlT2JqLCBzb3VyY2VOYW1lLCB0YXJnZXRPYmosIHRhcmdldE5hbWUpDQp7DQogICAgc291cmNlT2JqLm9uKHNvdXJjZU5hbWUsIHRhcmdldE9iai5lbWl0LmJpbmQodGFyZ2V0T2JqKSk7DQp9DQoNCg0KZnVuY3Rpb24gcmV0dXJuX3Jlc29sdmVkKCkNCnsNCiAgICB2YXIgcGFybXMgPSBbJ3Jlc29sdmVkJ107DQogICAgZm9yICh2YXIgYWkgaW4gYXJndW1lbnRzKQ0KICAgIHsNCiAgICAgICAgcGFybXMucHVzaChhcmd1bWVudHNbYWldKTsNCiAgICB9DQogICAgdGhpcy5fWFNMRi5lbWl0LmFwcGx5KHRoaXMuX1hTTEYsIHBhcm1zKTsNCn0NCmZ1bmN0aW9uIHJldHVybl9yZWplY3RlZCgpDQp7DQogICAgdGhpcy5fWFNMRi5wcm9taXNlLl9fY2hpbGRQcm9taXNlLl9yZWooZSk7DQp9DQpmdW5jdGlvbiBlbWl0cmVqZWN0KGEpDQp7DQogICAgcHJvY2Vzcy5lbWl0KCd1bmNhdWdodEV4Y2VwdGlvbicsICdwcm9taXNlLnVuY2F1Z2h0UmVqZWN0aW9uOiAnICsgSlNPTi5zdHJpbmdpZnkoYSkpOw0KfQ0KZnVuY3Rpb24gUHJvbWlzZShwcm9taXNlRnVuYykNCnsNCiAgICB0aGlzLl9PYmplY3RJRCA9ICdwcm9taXNlJzsNCiAgICB0aGlzLnByb21pc2UgPSB0aGlzOw0KICAgIHRoaXMuX2ludGVybmFsID0geyBfT2JqZWN0SUQ6ICdwcm9taXNlLmludGVybmFsJywgcHJvbWlzZTogdGhpcywgY29tcGxldGVkOiBmYWxzZSwgZXJyb3JzOiBmYWxzZSwgY29tcGxldGVkQXJnczogW10sIGludGVybmFsQ291bnQ6IDAsIF91cDogbnVsbCB9Ow0KICAgIHJlcXVpcmUoJ2V2ZW50cycpLkV2ZW50RW1pdHRlci5jYWxsKHRoaXMuX2ludGVybmFsKTsNCiAgICBPYmplY3QuZGVmaW5lUHJvcGVydHkodGhpcywgInBhcmVudFByb21pc2UiLA0KICAgICAgICB7DQogICAgICAgICAgICBnZXQ6IGZ1bmN0aW9uICgpIHsgcmV0dXJuICh0aGlzLl91cCk7IH0sDQogICAgICAgICAgICBzZXQ6IGZ1bmN0aW9uICh2YWx1ZSkNCiAgICAgICAgICAgIHsNCiAgICAgICAgICAgICAgICBpZiAodmFsdWUgIT0gbnVsbCAmJiB0aGlzLl91cCA9PSBudWxsKQ0KICAgICAgICAgICAgICAgIHsNCiAgICAgICAgICAgICAgICAgICAgLy8gV2UgYXJlIG5vIGxvbmdlciBhbiBvcnBoYW4NCiAgICAgICAgICAgICAgICAgICAgaWYgKHRoaXMuX2ludGVybmFsLnVuY2F1Z2h0ICE9IG51bGwpDQogICAgICAgICAgICAgICAgICAgIHsNCiAgICAgICAgICAgICAgICAgICAgICAgIGNsZWFySW1tZWRpYXRlKHRoaXMuX2ludGVybmFsLnVuY2F1Z2h0KTsNCiAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMuX2ludGVybmFsLnVuY2F1Z2h0ID0gbnVsbDsNCiAgICAgICAgICAgICAgICAgICAgfQ0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICB0aGlzLl91cCA9IHZhbHVlOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9KTsNCiAgICBPYmplY3QuZGVmaW5lUHJvcGVydHkodGhpcywgImRlc2NyaXB0b3JNZXRhZGF0YSIsDQogICAgICAgIHsNCiAgICAgICAgICAgIGdldDogZnVuY3Rpb24gKCkNCiAgICAgICAgICAgIHsNCiAgICAgICAgICAgICAgICByZXR1cm4gKHJlcXVpcmUoJ2V2ZW50cycpLmdldFByb3BlcnR5LmNhbGwodGhpcy5faW50ZXJuYWwsICc/X0ZpbmFsaXplckRlYnVnTWVzc2FnZScpKTsNCiAgICAgICAgICAgIH0sDQogICAgICAgICAgICBzZXQ6IGZ1bmN0aW9uICh2YWx1ZSkNCiAgICAgICAgICAgIHsNCiAgICAgICAgICAgICAgICByZXF1aXJlKCdldmVudHMnKS5zZXRQcm9wZXJ0eS5jYWxsKHRoaXMuX2ludGVybmFsLCAnP19GaW5hbGl6ZXJEZWJ1Z01lc3NhZ2UnLCB2YWx1ZSk7DQogICAgICAgICAgICB9DQogICAgICAgIH0pOw0KICAgIHRoaXMuX2ludGVybmFsLm9uKCd+JywgZnVuY3Rpb24gKCkNCiAgICB7DQogICAgICAgIHRoaXMuY29tcGxldGVkQXJncyA9IFtdOw0KICAgIH0pOw0KICAgIHRoaXMuX2ludGVybmFsLm9uKCduZXdMaXN0ZW5lcjInLCAoZnVuY3Rpb24gKGV2ZW50TmFtZSwgZXZlbnRDYWxsYmFjaykNCiAgICB7DQogICAgICAgIC8vY29uc29sZS5sb2coJ25ld0xpc3RlbmVyJywgZXZlbnROYW1lLCAnZXJyb3JzLycgKyB0aGlzLmVycm9ycyArICcgY29tcGxldGVkLycgKyB0aGlzLmNvbXBsZXRlZCk7DQogICAgICAgIHZhciByID0gbnVsbDsNCg0KICAgICAgICBpZiAoZXZlbnROYW1lID09ICdyZXNvbHZlZCcgJiYgIXRoaXMuZXJyb3JzICYmIHRoaXMuY29tcGxldGVkKQ0KICAgICAgICB7DQogICAgICAgICAgICByID0gZXZlbnRDYWxsYmFjay5hcHBseSh0aGlzLCB0aGlzLmNvbXBsZXRlZEFyZ3MpOw0KICAgICAgICAgICAgaWYociE9bnVsbCkNCiAgICAgICAgICAgIHsNCiAgICAgICAgICAgICAgICB0aGlzLmVtaXRfcmV0dXJuVmFsdWUoJ3Jlc29sdmVkJywgcik7DQogICAgICAgICAgICB9DQogICAgICAgICAgICB0cnkgeyB0aGlzLnJlbW92ZUFsbExpc3RlbmVycygncmVzb2x2ZWQnKTsgfSBjYXRjaCAoeCkgeyB9DQogICAgICAgICAgICB0cnkgeyB0aGlzLnJlbW92ZUFsbExpc3RlbmVycygncmVqZWN0ZWQnKTsgfSBjYXRjaCAoeCkgeyB9DQogICAgICAgIH0NCg0KICAgICAgICAvL2lmIChldmVudE5hbWUgPT0gJ3JlamVjdGVkJyAmJiAoZXZlbnRDYWxsYmFjay5pbnRlcm5hbCA9PSBudWxsIHx8IGV2ZW50Q2FsbGJhY2suaW50ZXJuYWwgPT0gZmFsc2UpKQ0KICAgICAgICBpZiAoZXZlbnROYW1lID09ICdyZWplY3RlZCcpDQogICAgICAgIHsNCiAgICAgICAgICAgIGlmICh0aGlzLnVuY2F1Z2h0ICE9IG51bGwpDQogICAgICAgICAgICB7DQogICAgICAgICAgICAgICAgY2xlYXJJbW1lZGlhdGUodGhpcy51bmNhdWdodCk7DQogICAgICAgICAgICAgICAgdGhpcy51bmNhdWdodCA9IG51bGw7DQogICAgICAgICAgICB9DQogICAgICAgICAgICBpZiAodGhpcy5wcm9taXNlKQ0KICAgICAgICAgICAgew0KICAgICAgICAgICAgICAgIHZhciBycCA9IGdldFJvb3RQcm9taXNlKHRoaXMucHJvbWlzZSk7DQogICAgICAgICAgICAgICAgcnAuX2ludGVybmFsLmV4dGVybmFsID0gdHJ1ZTsNCiAgICAgICAgICAgICAgICBpZiAocnAuX2ludGVybmFsLnVuY2F1Z2h0ICE9IG51bGwpDQogICAgICAgICAgICAgICAgew0KICAgICAgICAgICAgICAgICAgICBjbGVhckltbWVkaWF0ZShycC5faW50ZXJuYWwudW5jYXVnaHQpOw0KICAgICAgICAgICAgICAgICAgICBycC5faW50ZXJuYWwudW5jYXVnaHQgPSBudWxsOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgIH0NCiAgICAgICAgfQ0KDQogICAgICAgIGlmIChldmVudE5hbWUgPT0gJ3JlamVjdGVkJyAmJiB0aGlzLmVycm9ycyAmJiB0aGlzLmNvbXBsZXRlZCkNCiAgICAgICAgew0KICAgICAgICAgICAgZXZlbnRDYWxsYmFjay5hcHBseSh0aGlzLCB0aGlzLmNvbXBsZXRlZEFyZ3MpOw0KICAgICAgICAgICAgdHJ5IHsgdGhpcy5yZW1vdmVBbGxMaXN0ZW5lcnMoJ3Jlc29sdmVkJyk7IH0gY2F0Y2ggKHgpIHsgfQ0KICAgICAgICAgICAgdHJ5IHsgdGhpcy5yZW1vdmVBbGxMaXN0ZW5lcnMoJ3JlamVjdGVkJyk7IH0gY2F0Y2ggKHgpIHsgfQ0KICAgICAgICB9DQogICAgICAgIGlmIChldmVudE5hbWUgPT0gJ3NldHRsZWQnICYmIHRoaXMuY29tcGxldGVkKQ0KICAgICAgICB7DQogICAgICAgICAgICBldmVudENhbGxiYWNrLmFwcGx5KHRoaXMsIFtdKTsNCiAgICAgICAgfQ0KICAgIH0pLmludGVybmFsKTsNCiAgICB0aGlzLl9pbnRlcm5hbC5yZXNvbHZlciA9IGZ1bmN0aW9uIF9yZXNvbHZlcigpDQogICAgew0KICAgICAgICBpZiAodGhpcy5jb21wbGV0ZWQpIHsgcmV0dXJuOyB9DQogICAgICAgIHRoaXMuZXJyb3JzID0gZmFsc2U7DQogICAgICAgIHRoaXMuY29tcGxldGVkID0gdHJ1ZTsNCiAgICAgICAgdGhpcy5jb21wbGV0ZWRBcmdzID0gW107DQogICAgICAgIHZhciBhcmdzID0gWydyZXNvbHZlZCddOw0KICAgICAgICBpZiAodGhpcy5lbWl0X3JldHVyblZhbHVlICYmIHRoaXMuZW1pdF9yZXR1cm5WYWx1ZSgncmVzb2x2ZWQnKSAhPSBudWxsKQ0KICAgICAgICB7DQogICAgICAgICAgICB0aGlzLmNvbXBsZXRlZEFyZ3MucHVzaCh0aGlzLmVtaXRfcmV0dXJuVmFsdWUoJ3Jlc29sdmVkJykpOw0KICAgICAgICAgICAgYXJncy5wdXNoKHRoaXMuZW1pdF9yZXR1cm5WYWx1ZSgncmVzb2x2ZWQnKSk7DQogICAgICAgIH0NCiAgICAgICAgZWxzZQ0KICAgICAgICB7DQogICAgICAgICAgICBmb3IgKHZhciBhIGluIGFyZ3VtZW50cykNCiAgICAgICAgICAgIHsNCiAgICAgICAgICAgICAgICB0aGlzLmNvbXBsZXRlZEFyZ3MucHVzaChhcmd1bWVudHNbYV0pOw0KICAgICAgICAgICAgICAgIGFyZ3MucHVzaChhcmd1bWVudHNbYV0pOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9DQogICAgICAgIGlmIChhcmdzLmxlbmd0aCA9PSAyICYmIGFyZ3NbMV0hPW51bGwgJiYgdHlwZW9mKGFyZ3NbMV0pID09ICdvYmplY3QnICYmIGFyZ3NbMV0uX09iamVjdElEID09ICdwcm9taXNlJykNCiAgICAgICAgew0KICAgICAgICAgICAgdmFyIHByID0gZ2V0Um9vdFByb21pc2UodGhpcy5wcm9taXNlKTsNCiAgICAgICAgICAgIGFyZ3NbMV0uX1hTTEYgPSB0aGlzOw0KICAgICAgICAgICAgYXJnc1sxXS50aGVuKHJldHVybl9yZXNvbHZlZCwgcmV0dXJuX3JlamVjdGVkKTsNCiAgICAgICAgfQ0KICAgICAgICBlbHNlDQogICAgICAgIHsNCiAgICAgICAgICAgIHRoaXMuZW1pdC5hcHBseSh0aGlzLCBhcmdzKTsNCiAgICAgICAgICAgIHRoaXMuZW1pdCgnc2V0dGxlZCcpOw0KICAgICAgICB9DQogICAgfTsNCg0KICAgIHRoaXMuX2ludGVybmFsLnJlamVjdG9yID0gZnVuY3Rpb24gX3JlamVjdG9yKCkNCiAgICB7DQogICAgICAgIGlmICh0aGlzLmNvbXBsZXRlZCkgeyByZXR1cm47IH0NCiAgICAgICAgdGhpcy5lcnJvcnMgPSB0cnVlOw0KICAgICAgICB0aGlzLmNvbXBsZXRlZCA9IHRydWU7DQogICAgICAgIHRoaXMuY29tcGxldGVkQXJncyA9IFtdOw0KICAgICAgICB2YXIgYXJncyA9IFsncmVqZWN0ZWQnXTsNCiAgICAgICAgZm9yICh2YXIgYSBpbiBhcmd1bWVudHMpDQogICAgICAgIHsNCiAgICAgICAgICAgIHRoaXMuY29tcGxldGVkQXJncy5wdXNoKGFyZ3VtZW50c1thXSk7DQogICAgICAgICAgICBhcmdzLnB1c2goYXJndW1lbnRzW2FdKTsNCiAgICAgICAgfQ0KDQogICAgICAgIHZhciByID0gZ2V0Um9vdFByb21pc2UodGhpcy5wcm9taXNlKTsNCiAgICAgICAgaWYgKChyLl9pbnRlcm5hbC5leHRlcm5hbCA9PSBudWxsIHx8IHIuX2ludGVybmFsLmV4dGVybmFsID09IGZhbHNlKSAmJiByLl9pbnRlcm5hbC51bmNhdWdodCA9PSBudWxsKQ0KICAgICAgICB7DQogICAgICAgICAgICByLl9pbnRlcm5hbC51bmNhdWdodCA9IHNldEltbWVkaWF0ZShlbWl0cmVqZWN0LCBhcmd1bWVudHNbMF0pOw0KICAgICAgICB9DQoNCiAgICAgICAgdGhpcy5lbWl0LmFwcGx5KHRoaXMsIGFyZ3MpOw0KICAgICAgICB0aGlzLmVtaXQoJ3NldHRsZWQnKTsNCiAgICB9Ow0KDQogICAgdGhpcy5jYXRjaCA9IGZ1bmN0aW9uKGZ1bmMpDQogICAgew0KICAgICAgICB2YXIgcnQgPSBnZXRSb290UHJvbWlzZSh0aGlzKTsNCiAgICAgICAgaWYgKHJ0Ll9pbnRlcm5hbC51bmNhdWdodCAhPSBudWxsKSB7IGNsZWFySW1tZWRpYXRlKHJ0Ll9pbnRlcm5hbC51bmNhdWdodCk7IH0NCiAgICAgICAgdGhpcy5faW50ZXJuYWwub25jZSgncmVqZWN0ZWQnLCBldmVudF9zd2l0Y2hlcih0aGlzLCBmdW5jKS5mdW5jLmludGVybmFsKTsNCiAgICB9DQogICAgdGhpcy5maW5hbGx5ID0gZnVuY3Rpb24gKGZ1bmMpDQogICAgew0KICAgICAgICB0aGlzLl9pbnRlcm5hbC5vbmNlKCdzZXR0bGVkJywgZXZlbnRfc3dpdGNoZXIodGhpcywgZnVuYykuZnVuYy5pbnRlcm5hbCk7DQogICAgfTsNCiAgICB0aGlzLnRoZW4gPSBmdW5jdGlvbiAocmVzb2x2ZWQsIHJlamVjdGVkKQ0KICAgIHsNCiAgICAgICAgaWYgKHJlc29sdmVkKQ0KICAgICAgICB7DQogICAgICAgICAgICB0aGlzLl9pbnRlcm5hbC5vbmNlKCdyZXNvbHZlZCcsIGV2ZW50X3N3aXRjaGVyKHRoaXMsIHJlc29sdmVkKS5mdW5jLmludGVybmFsKTsNCiAgICAgICAgfQ0KICAgICAgICBpZiAocmVqZWN0ZWQpDQogICAgICAgIHsNCiAgICAgICAgICAgIGlmICh0aGlzLl9pbnRlcm5hbC5jb21wbGV0ZWQpDQogICAgICAgICAgICB7DQogICAgICAgICAgICAgICAgdmFyIHIgPSBnZXRSb290UHJvbWlzZSh0aGlzKTsNCiAgICAgICAgICAgICAgICBpZihyLl9pbnRlcm5hbC51bmNhdWdodCAhPSBudWxsKQ0KICAgICAgICAgICAgICAgIHsNCiAgICAgICAgICAgICAgICAgICAgY2xlYXJJbW1lZGlhdGUoci5faW50ZXJuYWwudW5jYXVnaHQpOw0KICAgICAgICAgICAgICAgIH0gICAgICAgICAgICAgICAgICAgIA0KICAgICAgICAgICAgfQ0KICAgICAgICAgICAgdGhpcy5faW50ZXJuYWwub25jZSgncmVqZWN0ZWQnLCBldmVudF9zd2l0Y2hlcih0aGlzLCByZWplY3RlZCkuZnVuYy5pbnRlcm5hbCk7DQogICAgICAgIH0NCiAgICAgICAgICANCiAgICAgICAgdmFyIHJldFZhbCA9IG5ldyBQcm9taXNlKHByb21pc2VJbml0aWFsaXplcik7DQogICAgICAgIHJldFZhbC5wYXJlbnRQcm9taXNlID0gdGhpczsNCg0KICAgICAgICBpZiAodGhpcy5faW50ZXJuYWwuY29tcGxldGVkKQ0KICAgICAgICB7DQogICAgICAgICAgICAvLyBUaGlzIHByb21pc2Ugd2FzIGFscmVhZHkgcmVzb2x2ZWQsIHNvIGxldHMgY2hlY2sgaWYgdGhlIGhhbmRsZXIgcmV0dXJuZWQgYSBwcm9taXNlDQogICAgICAgICAgICB2YXIgcnYgPSB0aGlzLl9pbnRlcm5hbC5lbWl0X3JldHVyblZhbHVlKCdyZXNvbHZlZCcpOw0KICAgICAgICAgICAgaWYocnYhPW51bGwpDQogICAgICAgICAgICB7DQogICAgICAgICAgICAgICAgaWYocnYuX09iamVjdElEID09ICdwcm9taXNlJykNCiAgICAgICAgICAgICAgICB7DQogICAgICAgICAgICAgICAgICAgIHJ2LnBhcmVudFByb21pc2UgPSB0aGlzOw0KICAgICAgICAgICAgICAgICAgICBydi5faW50ZXJuYWwub25jZSgncmVzb2x2ZWQnLCByZXRWYWwuX2ludGVybmFsLnJlc29sdmVyLmJpbmQocmV0VmFsLl9pbnRlcm5hbCkuaW50ZXJuYWwpOw0KICAgICAgICAgICAgICAgICAgICBydi5faW50ZXJuYWwub25jZSgncmVqZWN0ZWQnLCByZXRWYWwuX2ludGVybmFsLnJlamVjdG9yLmJpbmQocmV0VmFsLl9pbnRlcm5hbCkuaW50ZXJuYWwpOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICBlbHNlDQogICAgICAgICAgICAgICAgew0KICAgICAgICAgICAgICAgICAgICByZXRWYWwuX2ludGVybmFsLnJlc29sdmVyLmNhbGwocmV0VmFsLl9pbnRlcm5hbCwgcnYpOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgIH0NCiAgICAgICAgICAgIGVsc2UNCiAgICAgICAgICAgIHsNCiAgICAgICAgICAgICAgICB0aGlzLl9pbnRlcm5hbC5vbmNlKCdyZXNvbHZlZCcsIHJldFZhbC5faW50ZXJuYWwucmVzb2x2ZXIuYmluZChyZXRWYWwuX2ludGVybmFsKS5pbnRlcm5hbCk7DQogICAgICAgICAgICAgICAgdGhpcy5faW50ZXJuYWwub25jZSgncmVqZWN0ZWQnLCByZXRWYWwuX2ludGVybmFsLnJlamVjdG9yLmJpbmQocmV0VmFsLl9pbnRlcm5hbCkuaW50ZXJuYWwpOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9DQogICAgICAgIGVsc2UNCiAgICAgICAgew0KICAgICAgICAgICAgdGhpcy5faW50ZXJuYWwub25jZSgncmVzb2x2ZWQnLCByZXRWYWwuX2ludGVybmFsLnJlc29sdmVyLmJpbmQocmV0VmFsLl9pbnRlcm5hbCkuaW50ZXJuYWwpOw0KICAgICAgICAgICAgdGhpcy5faW50ZXJuYWwub25jZSgncmVqZWN0ZWQnLCByZXRWYWwuX2ludGVybmFsLnJlamVjdG9yLmJpbmQocmV0VmFsLl9pbnRlcm5hbCkuaW50ZXJuYWwpOw0KICAgICAgICB9DQoNCiAgICAgICAgdGhpcy5fX2NoaWxkUHJvbWlzZSA9IHJldFZhbDsNCiAgICAgICAgcmV0dXJuKHJldFZhbCk7DQogICAgfTsNCg0KICAgIHRyeQ0KICAgIHsNCiAgICAgICAgcHJvbWlzZUZ1bmMuY2FsbCh0aGlzLCB0aGlzLl9pbnRlcm5hbC5yZXNvbHZlci5iaW5kKHRoaXMuX2ludGVybmFsKSwgdGhpcy5faW50ZXJuYWwucmVqZWN0b3IuYmluZCh0aGlzLl9pbnRlcm5hbCkpOw0KICAgIH0NCiAgICBjYXRjaCAoZSkNCiAgICB7DQogICAgICAgIHRoaXMuX2ludGVybmFsLmVycm9ycyA9IHRydWU7DQogICAgICAgIHRoaXMuX2ludGVybmFsLmNvbXBsZXRlZCA9IHRydWU7DQogICAgICAgIHRoaXMuX2ludGVybmFsLmNvbXBsZXRlZEFyZ3MgPSBbZV07DQogICAgICAgIHRoaXMuX2ludGVybmFsLmVtaXQoJ3JlamVjdGVkJywgZSk7DQogICAgICAgIHRoaXMuX2ludGVybmFsLmVtaXQoJ3NldHRsZWQnKTsNCiAgICB9DQoNCiAgICBpZighdGhpcy5faW50ZXJuYWwuY29tcGxldGVkKQ0KICAgIHsNCiAgICAgICAgLy8gU2F2ZSByZWZlcmVuY2Ugb2YgdGhpcyBvYmplY3QNCiAgICAgICAgcmVmVGFibGVbdGhpcy5faW50ZXJuYWwuX2hhc2hDb2RlKCldID0gdGhpcy5faW50ZXJuYWw7DQogICAgICAgIHRoaXMuX2ludGVybmFsLm9uY2UoJ3NldHRsZWQnLCBmdW5jdGlvbiAoKQ0KICAgICAgICB7DQogICAgICAgICAgICBkZWxldGUgcmVmVGFibGVbdGhpcy5faGFzaENvZGUoKV07DQogICAgICAgIH0pOw0KICAgIH0NCiAgICBPYmplY3QuZGVmaW5lUHJvcGVydHkodGhpcywgImNvbXBsZXRlZCIsIHsNCiAgICAgICAgZ2V0OiBmdW5jdGlvbiAoKQ0KICAgICAgICB7DQogICAgICAgICAgICByZXR1cm4gKHRoaXMuX2ludGVybmFsLmNvbXBsZXRlZCk7DQogICAgICAgIH0NCiAgICB9KTsNCg0KICAgIHRoaXMuX2ludGVybmFsLm9uY2UoJ3NldHRsZWQnLCAoZnVuY3Rpb24gKCkNCiAgICB7DQogICAgICAgIGlmICh0aGlzLnVuY2F1Z2h0ICE9IG51bGwpDQogICAgICAgIHsNCiAgICAgICAgICAgIGNsZWFySW1tZWRpYXRlKHRoaXMudW5jYXVnaHQpOw0KICAgICAgICAgICAgdGhpcy51bmNhdWdodCA9IG51bGw7DQogICAgICAgIH0NCg0KICAgICAgICB2YXIgcnAgPSBnZXRSb290UHJvbWlzZSh0aGlzLnByb21pc2UpOw0KICAgICAgICBpZiAocnAgJiYgcnAuX2ludGVybmFsLnVuY2F1Z2h0KQ0KICAgICAgICB7DQogICAgICAgICAgICBjbGVhckltbWVkaWF0ZShycC5faW50ZXJuYWwudW5jYXVnaHQpOw0KICAgICAgICAgICAgcnAuX2ludGVybmFsLnVuY2F1Z2h0ID0gbnVsbDsNCiAgICAgICAgfQ0KDQogICAgICAgIGRlbGV0ZSB0aGlzLnByb21pc2UuX3VwOw0KICAgICAgICBkZWxldGUgdGhpcy5wcm9taXNlLl9fY2hpbGRQcm9taXNlOw0KICAgICAgICBkZWxldGUgdGhpcy5wcm9taXNlLnByb21pc2U7DQoNCiAgICAgICAgZGVsZXRlIHRoaXMuX3VwOw0KICAgICAgICBkZWxldGUgdGhpcy5fX2NoaWxkUHJvbWlzZTsNCiAgICAgICAgZGVsZXRlIHRoaXMucHJvbWlzZTsNCiAgICAgICAgdHJ5IHsgdGhpcy5yZW1vdmVBbGxMaXN0ZW5lcnMoJ3Jlc29sdmVkJyk7IH0gY2F0Y2ggKHgpIHsgfQ0KICAgICAgICB0cnkgeyB0aGlzLnJlbW92ZUFsbExpc3RlbmVycygncmVqZWN0ZWQnKTsgfSBjYXRjaCAoeCkgeyB9DQogICAgfSkuaW50ZXJuYWwpOw0KfQ0KDQpQcm9taXNlLnJlc29sdmUgPSBmdW5jdGlvbiByZXNvbHZlKCkNCnsNCiAgICB2YXIgcmV0VmFsID0gbmV3IFByb21pc2UoZnVuY3Rpb24gKHIsIGopIHsgfSk7DQogICAgdmFyIGFyZ3MgPSBbXTsNCiAgICBmb3IgKHZhciBpIGluIGFyZ3VtZW50cykNCiAgICB7DQogICAgICAgIGFyZ3MucHVzaChhcmd1bWVudHNbaV0pOw0KICAgIH0NCiAgICByZXRWYWwuX2ludGVybmFsLnJlc29sdmVyLmFwcGx5KHJldFZhbC5faW50ZXJuYWwsIGFyZ3MpOw0KICAgIHJldHVybiAocmV0VmFsKTsNCn07DQpQcm9taXNlLnJlamVjdCA9IGZ1bmN0aW9uIHJlamVjdCgpIHsNCiAgICB2YXIgcmV0VmFsID0gbmV3IFByb21pc2UoZnVuY3Rpb24gKHIsIGopIHsgfSk7DQogICAgdmFyIGFyZ3MgPSBbXTsNCiAgICBmb3IgKHZhciBpIGluIGFyZ3VtZW50cykgew0KICAgICAgICBhcmdzLnB1c2goYXJndW1lbnRzW2ldKTsNCiAgICB9DQogICAgcmV0VmFsLl9pbnRlcm5hbC5yZWplY3Rvci5hcHBseShyZXRWYWwuX2ludGVybmFsLCBhcmdzKTsNCiAgICByZXR1cm4gKHJldFZhbCk7DQp9Ow0KUHJvbWlzZS5hbGwgPSBmdW5jdGlvbiBhbGwocHJvbWlzZUxpc3QpDQp7DQogICAgdmFyIHJldCA9IG5ldyBQcm9taXNlKGZ1bmN0aW9uIChyZXMsIHJlaikNCiAgICB7DQogICAgICAgIHRoaXMuX19yZWplY3RvciA9IHJlajsNCiAgICAgICAgdGhpcy5fX3Jlc29sdmVyID0gcmVzOw0KICAgICAgICB0aGlzLl9fcHJvbWlzZUxpc3QgPSBwcm9taXNlTGlzdDsNCiAgICAgICAgdGhpcy5fX2RvbmUgPSBmYWxzZTsNCiAgICAgICAgdGhpcy5fX2NvdW50ID0gMDsNCiAgICB9KTsNCg0KICAgIGZvciAodmFyIGkgaW4gcHJvbWlzZUxpc3QpDQogICAgew0KICAgICAgICBwcm9taXNlTGlzdFtpXS50aGVuKGZ1bmN0aW9uICgpDQogICAgICAgIHsNCiAgICAgICAgICAgIC8vIFN1Y2Nlc3MNCiAgICAgICAgICAgIGlmKCsrcmV0Ll9fY291bnQgPT0gcmV0Ll9fcHJvbWlzZUxpc3QubGVuZ3RoKQ0KICAgICAgICAgICAgew0KICAgICAgICAgICAgICAgIHJldC5fX2RvbmUgPSB0cnVlOw0KICAgICAgICAgICAgICAgIHJldC5fX3Jlc29sdmVyKHJldC5fX3Byb21pc2VMaXN0KTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSwgZnVuY3Rpb24gKGFyZykNCiAgICAgICAgew0KICAgICAgICAgICAgLy8gRmFpbHVyZQ0KICAgICAgICAgICAgaWYoIXJldC5fX2RvbmUpDQogICAgICAgICAgICB7DQogICAgICAgICAgICAgICAgcmV0Ll9fZG9uZSA9IHRydWU7DQogICAgICAgICAgICAgICAgcmV0Ll9fcmVqZWN0b3IoYXJnKTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSk7DQogICAgfQ0KICAgIGlmIChwcm9taXNlTGlzdC5sZW5ndGggPT0gMCkNCiAgICB7DQogICAgICAgIHJldC5fX3Jlc29sdmVyKHByb21pc2VMaXN0KTsNCiAgICB9DQogICAgcmV0dXJuIChyZXQpOw0KfTsNCg0KbW9kdWxlLmV4cG9ydHMgPSBQcm9taXNlOw0KbW9kdWxlLmV4cG9ydHMuZXZlbnRfc3dpdGNoZXIgPSBldmVudF9zd2l0Y2hlcjsNCm1vZHVsZS5leHBvcnRzLmV2ZW50X2ZvcndhcmRlciA9IGV2ZW50X2ZvcndhcmRlcjsNCm1vZHVsZS5leHBvcnRzLmRlZmF1bHRJbml0ID0gZnVuY3Rpb24gZGVmYXVsdEluaXQocmVzLCByZWopIHsgdGhpcy5yZXNvbHZlID0gcmVzOyB0aGlzLnJlamVjdCA9IHJlajsgfQ==\', \'base64\').toString());\r\nvar promise = require(\'promise2\');\r\nfunction promise_default(res, rej)\r\n{\r\n this._res = res;\r\n this._rej = rej;\r\n}\r\n\r\n\r\nfunction buf2addr(buf)\r\n{\r\n return (buf[0] + \'.\' + buf[1] + \'.\' + buf[2] + \'.\' + buf[3]);\r\n}\r\nfunction parseDHCP(buffer)\r\n{\r\n var i;\r\n var packet = Buffer.alloc(buffer.length);\r\n for (i = 0; i < buffer.length; ++i) { packet[i] = buffer[i]; }\r\n\r\n var ret = { op: packet[0] == 0 ? \'REQ\' : \'RES\', hlen: packet[2] }; // OP Code\r\n ret.xid = packet.readUInt32BE(4); // Transaction ID\r\n ret.ciaddr = buf2addr(packet.slice(12, 16));\r\n ret.yiaddr = buf2addr(packet.slice(16, 20)); \r\n ret.siaddr = buf2addr(packet.slice(20, 24));\r\n ret.giaddr = buf2addr(packet.slice(24, 28));\r\n ret.chaddr = packet.slice(28, 28 + ret.hlen).toString(\'hex:\');\r\n if (packet[236] == 99 && packet[237] == 130 && packet[238] == 83 && packet[239] == 99)\r\n {\r\n // Magic Cookie Validated\r\n ret.magic = true;\r\n ret.options = {};\r\n\r\n i = 240;\r\n while(i<packet.length)\r\n {\r\n switch(packet[i])\r\n {\r\n case 0:\r\n i += 1;\r\n break;\r\n case 255:\r\n ret.options[255] = true;\r\n i += 2;\r\n break;\r\n default:\r\n ret.options[packet[i]] = packet.slice(i + 2, i + 2 + packet[i + 1]);\r\n switch(packet[i])\r\n {\r\n case 1: // Subnet Mask\r\n ret.options.subnetmask = buf2addr(ret.options[1]);\r\n delete ret.options[1];\r\n break;\r\n case 3: // Router\r\n ret.options.router = [];\r\n var ti = 0;\r\n while (ti < ret.options[3].length)\r\n {\r\n ret.options.router.push(buf2addr(ret.options[3].slice(ti, ti + 4)));\r\n ti += 4;\r\n }\r\n delete ret.options[3];\r\n break;\r\n case 6: // DNS\r\n ret.options.dns = buf2addr(ret.options[6]);\r\n delete ret.options[6];\r\n break;\r\n case 15: // Domain Name\r\n ret.options.domainname = ret.options[15].toString();\r\n delete ret.options[15];\r\n break;\r\n case 28: // Broadcast Address\r\n ret.options.broadcastaddr = buf2addr(ret.options[28]);\r\n delete ret.options[28];\r\n break;\r\n case 51: // Lease Time\r\n ret.options.lease = { raw: ret.options[51].readInt32BE() };\r\n delete ret.options[51];\r\n ret.options.lease.hours = Math.floor(ret.options.lease.raw / 3600);\r\n ret.options.lease.minutes = Math.floor((ret.options.lease.raw % 3600) / 60);\r\n ret.options.lease.seconds = (ret.options.lease.raw % 3600) % 60;\r\n break;\r\n case 53: // Message Type\r\n ret.options.messageType = ret.options[53][0];\r\n delete ret.options[53];\r\n break; \r\n case 54: // Server\r\n ret.options.server = buf2addr(ret.options[54]);\r\n delete ret.options[54];\r\n break;\r\n }\r\n i += (2 + packet[i + 1]);\r\n break;\r\n }\r\n }\r\n }\r\n\r\n\r\n return (ret);\r\n}\r\n\r\nfunction createPacket(messageType, data)\r\n{\r\n var b = Buffer.alloc(245);\r\n\r\n switch(messageType)\r\n {\r\n //case 0x02:\r\n //case 0x04:\r\n //case 0x05:\r\n //case 0x06:\r\n // b[0] = 0x00; // Reply\r\n // break;\r\n //case 0x01:\r\n //case 0x03:\r\n //case 0x07:\r\n case 0x08:\r\n b[0] = 0x01; // Request\r\n break;\r\n default:\r\n throw (\'DHCP(\' + messageType + \') NOT SUPPORTED\');\r\n break;\r\n }\r\n\r\n // Headers\r\n b[1] = 0x01; // Ethernet\r\n b[2] = 0x06; // HW Address Length\r\n b[3] = 0x00; // HOPS\r\n\r\n // Transaction ID\r\n var r = Buffer.alloc(4); r.randomFill();\r\n b.writeUInt32BE(r.readUInt32BE(), 4);\r\n b.writeUInt16BE(0x8000, 10);\r\n\r\n // Magic Cookie\r\n b[236] = 99;\r\n b[237] = 130;\r\n b[238] = 83;\r\n b[239] = 99;\r\n\r\n // DHCP Message Type\r\n b[240] = 53;\r\n b[241] = 1;\r\n b[242] = messageType;\r\n b[243] = 255;\r\n\r\n switch(messageType)\r\n {\r\n case 0x08:\r\n if (data.ciaddress == null) { throw (\'ciadress missing\'); }\r\n if (data.chaddress == null) { throw (\'chaddress missing\'); }\r\n\r\n // ciaddress\r\n var a = data.ciaddress.split(\'.\');\r\n var ci = parseInt(a[0]);\r\n ci = ci << 8;\r\n ci = ci | parseInt(a[1]);\r\n ci = ci << 8;\r\n ci = ci | parseInt(a[2]);\r\n ci = ci << 8;\r\n ci = ci | parseInt(a[3]);\r\n b.writeInt32BE(ci, 12);\r\n\r\n // chaddress\r\n var y = data.chaddress.split(\':\').join(\'\');\r\n y = Buffer.from(y, \'hex\');\r\n y.copy(b, 28);\r\n\r\n break;\r\n }\r\n\r\n return (b);\r\n}\r\n\r\nfunction raw(localAddress, port, buffer, handler)\r\n{\r\n var ret = new promise(promise_default);\r\n ret.socket = require(\'dgram\').createSocket({ type: \'udp4\' });\r\n try\r\n {\r\n ret.socket.bind({ address: localAddress, port: (port != null && port != 0) ? port : null });\r\n }\r\n catch (e)\r\n {\r\n ret._rej(\'Unable to bind to \' + localAddress);\r\n return (ret);\r\n }\r\n\r\n ret.socket.setBroadcast(true);\r\n ret.socket.setMulticastInterface(localAddress);\r\n ret.socket.setMulticastTTL(1);\r\n ret.socket.descriptorMetadata = \'DHCP (\' + localAddress + \')\';\r\n ret.socket.on(\'message\', handler.bind(ret));\r\n ret.socket.send(buffer, 67, \'255.255.255.255\');\r\n return (ret);\r\n}\r\n\r\nfunction info(interfaceName, port)\r\n{\r\n var f = require(\'os\').networkInterfaces();\r\n if (interfaceName.split(\':\').length == 6)\r\n {\r\n var newname = null;\r\n for(var n in f)\r\n {\r\n for (var nx in f[n])\r\n {\r\n if(f[n][nx].mac.toUpperCase() == interfaceName.toUpperCase())\r\n {\r\n newname = n;\r\n break;\r\n }\r\n }\r\n if(newname)\r\n {\r\n interfaceName = newname;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n\r\n if (f[interfaceName] != null)\r\n {\r\n var i;\r\n for(i=0;i<f[interfaceName].length;++i)\r\n {\r\n if(f[interfaceName][i].family == \'IPv4\' && f[interfaceName][i].mac != \'00:00:00:00:00:00\')\r\n {\r\n try\r\n {\r\n var b = createPacket(8, { ciaddress: f[interfaceName][i].address, chaddress: f[interfaceName][i].mac });\r\n _hide(raw(f[interfaceName][i].address, port, b, function infoHandler(msg)\r\n {\r\n try\r\n {\r\n var res = parseDHCP(msg);\r\n if (res.chaddr.toUpperCase() == this.hwaddr.toUpperCase() && res.options != null && res.options.lease != null)\r\n {\r\n clearTimeout(this.timeout);\r\n setImmediate(function (s) { try { s.removeAllListeners(\'message\'); } catch (x) { } }, this.socket); // Works around bug in older dgram.js\r\n this._res(res);\r\n }\r\n }\r\n catch(z)\r\n {\r\n }\r\n }));\r\n _hide().hwaddr = f[interfaceName][i].mac;\r\n _hide().timeout = setTimeout(function (x)\r\n {\r\n x.socket.removeAllListeners(\'message\');\r\n x._rej(\'timeout\');\r\n }, 2000, _hide());\r\n return (_hide(true));\r\n }\r\n catch(e)\r\n {\r\n var ret = new promise(promise_default);\r\n ret._rej(e);\r\n return (ret);\r\n }\r\n }\r\n }\r\n }\r\n\r\n var ret = new promise(promise_default);\r\n ret._rej(\'interface (\' + interfaceName + \') not found\');\r\n return (ret);\r\n}\r\n\r\nmodule.exports = \r\n {\r\n client: { info: info, raw: raw }, \r\n MESSAGE_TYPES: \r\n {\r\n DISCOVER: 1,\r\n OFFER: 2,\r\n REQUEST: 3,\r\n DECLINE: 4,\r\n ACK: 5,\r\n NACK: 6,\r\n RELEASE: 7,\r\n INFO: 8 \r\n } \r\n };\r\n\r\n"); addedModules.push("linux-dhcp"); } catch (ex) { }
try { addModule("monitor-border", "/*\r\nCopyright 2018-2021 Intel Corporation\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*/\r\n\r\nvar red = 0xFF;\r\nvar yellow = 0xFFFF;\r\nvar GXxor = 0x6; //\tsrc XOR dst\r\nvar GXclear = 0x0;\r\nvar ExposureMask = (1 << 15);\r\n\r\nfunction windows_monitorborder()\r\n{\r\n this._ObjectID = \'monitor-info\';\r\n var info = require(\'monitor-info\');\r\n var gm = require(\'_GenericMarshal\');\r\n var user32 = gm.CreateNativeProxy(\'user32.dll\');\r\n \r\n info.monitors = [];\r\n user32.CreateMethod(\'GetDC\');\r\n user32.CreateMethod(\'ReleaseDC\');\r\n user32.CreateMethod(\'FillRect\');\r\n user32.CreateMethod(\'InvalidateRect\');\r\n\r\n var gdi32 = gm.CreateNativeProxy(\'gdi32.dll\');\r\n gdi32.CreateMethod(\'CreateSolidBrush\');\r\n\r\n var redBrush = gdi32.CreateSolidBrush(red);\r\n var yellowBrush = gdi32.CreateSolidBrush(yellow);\r\n\r\n require(\'events\').EventEmitter.call(this);\r\n this.on(\'~\', function () { this.Stop(); });\r\n\r\n this.Stop = function Stop()\r\n {\r\n info.redInterval = null;\r\n\r\n var drawRect = gm.CreateVariable(16);\r\n var drawRectBuffer = drawRect.toBuffer();\r\n\r\n for (var i in info.monitors)\r\n {\r\n // Top\r\n drawRectBuffer.writeInt32LE(info.monitors[i].left, 0);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].top, 4);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].left + (info.monitors[i].right - info.monitors[i].left), 8);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].bottom - info.monitors[i].top, 12);\r\n user32.InvalidateRect(0, drawRect, 0);\r\n }\r\n }\r\n\r\n this.Start = function Start()\r\n {\r\n info.getInfo().then(function (mon)\r\n {\r\n var drawRect = gm.CreateVariable(16);\r\n\r\n info.monitors = mon;\r\n info.dc = user32.GetDC(0);\r\n info.state = 0;\r\n\r\n info.redInterval = setInterval(function ()\r\n {\r\n info.state = (info.state + 1) % 8;\r\n\r\n var drawRectBuffer = drawRect.toBuffer();\r\n for(var i in info.monitors)\r\n {\r\n drawRectBuffer.writeInt32LE(info.monitors[i].left, 0);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].top, 4);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].left + (info.monitors[i].right - info.monitors[i].left)/2, 8);\r\n drawRectBuffer.writeInt32LE(5, 12);\r\n user32.FillRect(info.dc, drawRect, (info.state == 0 || info.state == 4) ? yellowBrush : redBrush);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].left + (info.monitors[i].right - info.monitors[i].left) / 2, 0);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].top, 4);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].right, 8);\r\n drawRectBuffer.writeInt32LE(5, 12);\r\n user32.FillRect(info.dc, drawRect, (info.state == 1 || info.state == 5) ? yellowBrush : redBrush);\r\n\r\n\r\n drawRectBuffer.writeInt32LE(info.monitors[i].right - 5, 0);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].top, 4);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].right, 8);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].top + (info.monitors[i].bottom - info.monitors[i].top)/2, 12);\r\n user32.FillRect(info.dc, drawRect, (info.state == 2 || info.state == 6) ? yellowBrush : redBrush);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].right - 5, 0);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].top + (info.monitors[i].bottom - info.monitors[i].top) / 2, 4);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].right, 8);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].bottom, 12);\r\n user32.FillRect(info.dc, drawRect, (info.state == 3 || info.state == 7) ? yellowBrush : redBrush);\r\n\r\n\r\n drawRectBuffer.writeInt32LE(info.monitors[i].left + (info.monitors[i].right - info.monitors[i].left) / 2, 0);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].bottom - 5, 4);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].right, 8);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].bottom, 12);\r\n user32.FillRect(info.dc, drawRect, (info.state == 4 || info.state == 0) ? yellowBrush : redBrush);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].left, 0);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].bottom - 5, 4);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].left + (info.monitors[i].right - info.monitors[i].left) / 2, 8);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].bottom, 12);\r\n user32.FillRect(info.dc, drawRect, (info.state == 5 || info.state == 1) ? yellowBrush : redBrush);\r\n\r\n\r\n drawRectBuffer.writeInt32LE(info.monitors[i].left, 0);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].top + (info.monitors[i].bottom - info.monitors[i].top) / 2, 4);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].left + 5, 8);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].bottom, 12);\r\n user32.FillRect(info.dc, drawRect, (info.state == 6 || info.state == 2) ? yellowBrush : redBrush);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].left, 0);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].top, 4);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].left + 5, 8);\r\n drawRectBuffer.writeInt32LE(info.monitors[i].top + (info.monitors[i].bottom - info.monitors[i].top) / 2, 12);\r\n user32.FillRect(info.dc, drawRect, (info.state == 7 || info.state == 3) ? yellowBrush : redBrush);\r\n }\r\n }, 450);\r\n });\r\n }\r\n}\r\n\r\nfunction linux_monitorborder()\r\n{\r\n var self = this;\r\n this.displays = [];\r\n this._ObjectID = \'monitor-info\';\r\n this._info = require(\'monitor-info\');\r\n this._isUnity = this._info.isUnity();\r\n\r\n console.log(\'isUnity = \' + this._isUnity);\r\n\r\n require(\'events\').EventEmitter.call(this);\r\n this.on(\'~\', function () { this.Stop(); });\r\n\r\n this.Stop = function Stop()\r\n {\r\n this._timeout = null;\r\n if(!this._isUnity)\r\n {\r\n for(var i=0; i < this.displays.length; ++i)\r\n {\r\n if(this.displays[i].GC1 && this.displays[i].rootWindow)\r\n {\r\n self._info._X11.XSetFunction(self.displays[i].display, self.displays[i].GC1, GXclear);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, 0, self.displays[i].right, 0);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, self.displays[i].right, 0, self.displays[i].right, self.displays[i].bottom);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, self.displays[i].bottom, self.displays[i].right, self.displays[i].bottom);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, 0, 0, self.displays[i].bottom);\r\n\r\n this._info._X11.XFlush(this.displays[i].display);\r\n }\r\n }\r\n }\r\n }\r\n this.Start = function Start()\r\n {\r\n this._info.getInfo().then(function (mon)\r\n {\r\n self.displays = mon;\r\n console.log(mon.length + \' displays\');\r\n for(var i = 0; i<mon.length; ++i)\r\n {\r\n console.log(\'Width: \' + mon[i].right + \', Height: \' + mon[i].bottom);\r\n mon[i].rootWindow = self._info._X11.XRootWindow(mon[i].display, mon[i].screenId);\r\n\r\n if (self._isUnity)\r\n {\r\n // We are unity, so we have to fake the borders with borderless windows\r\n var white = self._info._X11.XWhitePixel(mon[i].display, mon[i].screenId).Val;\r\n\r\n // Top\r\n mon[i].window_top = self._info._X11.XCreateSimpleWindow(mon[i].display, mon[i].rootWindow, 0, 0, mon[i].right, 5, 0, white, white);\r\n mon[i].window_top.gc = self._info._X11.XCreateGC(mon[i].display, mon[i].window_top, 0, 0);\r\n self._info._X11.XSetLineAttributes(mon[i].display, mon[i].window_top.gc, 10, 0, 1, 1);\r\n self._info._X11.XSetSubwindowMode(mon[i].display, mon[i].window_top.gc, 1);\r\n self._info.unDecorateWindow(mon[i].display, mon[i].window_top);\r\n self._info.setWindowSizeHints(mon[i].display, mon[i].window_top, 0, 0, mon[i].right, 5);\r\n\r\n // Right\r\n mon[i].window_right = self._info._X11.XCreateSimpleWindow(mon[i].display, mon[i].rootWindow, mon[i].right - 5, 0, 5, mon[i].bottom, 0, white, white);\r\n mon[i].window_right.gc = self._info._X11.XCreateGC(mon[i].display, mon[i].window_right, 0, 0);\r\n self._info._X11.XSetLineAttributes(mon[i].display, mon[i].window_right.gc, 10, 0, 1, 1);\r\n self._info._X11.XSetSubwindowMode(mon[i].display, mon[i].window_right.gc, 1);\r\n self._info.unDecorateWindow(mon[i].display, mon[i].window_right);\r\n self._info.setWindowSizeHints(mon[i].display, mon[i].window_right, mon[i].right - 5, 0, 5, mon[i].bottom);\r\n\r\n // Left\r\n mon[i].window_left = self._info._X11.XCreateSimpleWindow(mon[i].display, mon[i].rootWindow, 0, 0, 5, mon[i].bottom, 0, white, white);\r\n mon[i].window_left.gc = self._info._X11.XCreateGC(mon[i].display, mon[i].window_left, 0, 0);\r\n self._info._X11.XSetLineAttributes(mon[i].display, mon[i].window_left.gc, 10, 0, 1, 1);\r\n self._info._X11.XSetSubwindowMode(mon[i].display, mon[i].window_left.gc, 1);\r\n self._info.unDecorateWindow(mon[i].display, mon[i].window_left);\r\n self._info.setWindowSizeHints(mon[i].display, mon[i].window_left, 0, 0, 5, mon[i].bottom);\r\n\r\n // Bottom\r\n mon[i].window_bottom = self._info._X11.XCreateSimpleWindow(mon[i].display, mon[i].rootWindow, 0, mon[i].bottom - 5, mon[i].right, 5, 0, white, white);\r\n mon[i].window_bottom.gc = self._info._X11.XCreateGC(mon[i].display, mon[i].window_bottom, 0, 0);\r\n self._info._X11.XSetLineAttributes(mon[i].display, mon[i].window_bottom.gc, 10, 0, 1, 1);\r\n self._info._X11.XSetSubwindowMode(mon[i].display, mon[i].window_bottom.gc, 1);\r\n self._info.unDecorateWindow(mon[i].display, mon[i].window_bottom);\r\n self._info.setWindowSizeHints(mon[i].display, mon[i].window_bottom, 0, mon[i].bottom - 5, mon[i].right, 5);\r\n\r\n self._info._X11.XMapWindow(mon[i].display, mon[i].window_top);\r\n self._info._X11.XMapWindow(mon[i].display, mon[i].window_right);\r\n self._info._X11.XMapWindow(mon[i].display, mon[i].window_left);\r\n self._info._X11.XMapWindow(mon[i].display, mon[i].window_bottom);\r\n\r\n self._info.setAlwaysOnTop(mon[i].display, mon[i].rootWindow, mon[i].window_top);\r\n self._info.hideWindowIcon(mon[i].display, mon[i].rootWindow, mon[i].window_top);\r\n self._info.setAlwaysOnTop(mon[i].display, mon[i].rootWindow, mon[i].window_right);\r\n self._info.hideWindowIcon(mon[i].display, mon[i].rootWindow, mon[i].window_right);\r\n self._info.setAlwaysOnTop(mon[i].display, mon[i].rootWindow, mon[i].window_left);\r\n self._info.hideWindowIcon(mon[i].display, mon[i].rootWindow, mon[i].window_left);\r\n self._info.setAlwaysOnTop(mon[i].display, mon[i].rootWindow, mon[i].window_bottom);\r\n self._info.hideWindowIcon(mon[i].display, mon[i].rootWindow, mon[i].window_bottom);\r\n\r\n self._info._X11.XFlush(mon[i].display);\r\n mon[i].borderState = 0;\r\n }\r\n else\r\n {\r\n // If we aren\'t unity, then we can just draw\r\n mon[i].GC1 = self._info._X11.XCreateGC(mon[i].display, mon[i].rootWindow, 0, 0);\r\n mon[i].borderState = 0;\r\n\r\n self._info._X11.XSetForeground(mon[i].display, mon[i].GC1, self._info._X11.XWhitePixel(mon[i].display, mon[i].screenId).Val); // White\r\n self._info._X11.XSetLineAttributes(mon[i].display, mon[i].GC1, 10, 0, 1, 1);\r\n self._info._X11.XSetSubwindowMode(mon[i].display, mon[i].GC1, 1);\r\n }\r\n }\r\n self._info._XEvent = self._info._gm.CreateVariable(192);\r\n self._timeout = setTimeout(self._isUnity ? self.unity_drawBorder : self.timeoutHandler, 250);\r\n });\r\n }\r\n\r\n this.timeoutHandler = function()\r\n {\r\n for (var i = 0; i < self.displays.length; ++i) {\r\n self.displays[i].borderState = (self.displays[i].borderState + 1) % 8;\r\n\r\n // Top\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 0 || self.displays[i].borderState == 4) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, 0, self.displays[i].right / 2, 0);\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 1 || self.displays[i].borderState == 5) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, self.displays[i].right / 2, 0, self.displays[i].right, 0);\r\n\r\n // Right\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 2 || self.displays[i].borderState == 6) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, self.displays[i].right, 0, self.displays[i].right, self.displays[i].bottom / 2);\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 3 || self.displays[i].borderState == 7) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, self.displays[i].right, self.displays[i].bottom / 2, self.displays[i].right, self.displays[i].bottom);\r\n\r\n // Bottom\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 5 || self.displays[i].borderState == 1) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, self.displays[i].bottom, self.displays[i].right / 2, self.displays[i].bottom);\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 4 || self.displays[i].borderState == 0) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, self.displays[i].right / 2, self.displays[i].bottom, self.displays[i].right, self.displays[i].bottom);\r\n\r\n // Left\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 7 || self.displays[i].borderState == 3) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, 0, 0, self.displays[i].bottom / 2);\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].GC1, (self.displays[i].borderState == 6 || self.displays[i].borderState == 2) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].rootWindow, self.displays[i].GC1, 0, self.displays[i].bottom / 2, 0, self.displays[i].bottom);\r\n\r\n\r\n self._info._X11.XFlush(self.displays[i].display);\r\n }\r\n self._timeout = setTimeout(self._isUnity ? self.unity_drawBorder : self.timeoutHandler, 400);\r\n }\r\n this.unity_drawBorder = function unity_drawBorder()\r\n {\r\n for (var i = 0; i < self.displays.length; ++i)\r\n {\r\n self.displays[i].borderState = (self.displays[i].borderState + 1) % 8;\r\n\r\n // Top\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_top.gc, (self.displays[i].borderState == 0 || self.displays[i].borderState == 4) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_top, self.displays[i].window_top.gc, 0, 0, self.displays[i].right / 2, 0);\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_top.gc, (self.displays[i].borderState == 1 || self.displays[i].borderState == 5) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_top, self.displays[i].window_top.gc, self.displays[i].right / 2, 0, self.displays[i].right, 0);\r\n self._info._X11.XFlush(self.displays[i].display);\r\n\r\n // Right\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_right.gc, (self.displays[i].borderState == 2 || self.displays[i].borderState == 6) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_right, self.displays[i].window_right.gc, 0, 0, 0, self.displays[i].bottom / 2);\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_right.gc, (self.displays[i].borderState == 3 || self.displays[i].borderState == 7) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_right, self.displays[i].window_right.gc, 0, self.displays[i].bottom / 2, 0, self.displays[i].bottom);\r\n self._info._X11.XFlush(self.displays[i].display);\r\n\r\n // Bottom\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_bottom.gc, (self.displays[i].borderState == 5 || self.displays[i].borderState == 1) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_bottom, self.displays[i].window_bottom.gc, 0, 0, self.displays[i].right / 2, 0);\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_bottom.gc, (self.displays[i].borderState == 4 || self.displays[i].borderState == 0) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_bottom, self.displays[i].window_bottom.gc, self.displays[i].right / 2, 0, self.displays[i].right, 0);\r\n self._info._X11.XFlush(self.displays[i].display);\r\n\r\n // Left\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_left.gc, (self.displays[i].borderState == 7 || self.displays[i].borderState == 3) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_left, self.displays[i].window_left.gc, 0, 0, 0, self.displays[i].bottom / 2);\r\n self._info._X11.XSetForeground(self.displays[i].display, self.displays[i].window_left.gc, (self.displays[i].borderState == 6 || self.displays[i].borderState == 2) ? 0xffff00 : 0xff0000);\r\n self._info._X11.XDrawLine(self.displays[i].display, self.displays[i].window_left, self.displays[i].window_left.gc, 0, self.displays[i].bottom / 2, 0, self.displays[i].bottom);\r\n self._info._X11.XFlush(self.displays[i].display);\r\n }\r\n self._timeout = setTimeout(self._isUnity ? self.unity_drawBorder : self.timeoutHandler, 400);\r\n }\r\n}\r\n\r\nswitch(process.platform)\r\n{\r\n case \'win32\':\r\n module.exports = new windows_monitorborder();\r\n break;\r\n case \'linux\':\r\n module.exports = new linux_monitorborder();\r\n break;\r\n default:\r\n break;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"); addedModules.push("monitor-border"); } catch (ex) { }
try { addModule("sysinfo", "/*\r\nCopyright 2019-2021 Intel Corporation\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*/\r\n\r\nvar PDH_FMT_LONG = 0x00000100;\r\nvar PDH_FMT_DOUBLE = 0x00000200;\r\n\r\nvar promise = require(\'promise\');\r\nif (process.platform == \'win32\')\r\n{\r\n var GM = require(\'_GenericMarshal\');\r\n GM.kernel32 = GM.CreateNativeProxy(\'kernel32.dll\');\r\n GM.kernel32.CreateMethod(\'GlobalMemoryStatusEx\');\r\n\r\n GM.pdh = GM.CreateNativeProxy(\'pdh.dll\');\r\n GM.pdh.CreateMethod(\'PdhAddEnglishCounterA\');\r\n GM.pdh.CreateMethod(\'PdhCloseQuery\');\r\n GM.pdh.CreateMethod(\'PdhCollectQueryData\');\r\n GM.pdh.CreateMethod(\'PdhGetFormattedCounterValue\');\r\n GM.pdh.CreateMethod(\'PdhGetFormattedCounterArrayA\');\r\n GM.pdh.CreateMethod(\'PdhOpenQueryA\');\r\n GM.pdh.CreateMethod(\'PdhRemoveCounter\');\r\n}\r\n\r\nfunction windows_cpuUtilization()\r\n{\r\n var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });\r\n p.counter = GM.CreateVariable(16);\r\n p.cpu = GM.CreatePointer();\r\n p.cpuTotal = GM.CreatePointer();\r\n var err = 0;\r\n if ((err = GM.pdh.PdhOpenQueryA(0, 0, p.cpu).Val) != 0) { p._rej(err); return; }\r\n\r\n // This gets the CPU Utilization for each proc\r\n if ((err = GM.pdh.PdhAddEnglishCounterA(p.cpu.Deref(), GM.CreateVariable(\'\\\\Processor(*)\\\\% Processor Time\'), 0, p.cpuTotal).Val) != 0) { p._rej(err); return; }\r\n\r\n if ((err = GM.pdh.PdhCollectQueryData(p.cpu.Deref()).Val != 0)) { p._rej(err); return; }\r\n p._timeout = setTimeout(function (po)\r\n {\r\n var u = { cpus: [] };\r\n var bufSize = GM.CreateVariable(4);\r\n var itemCount = GM.CreateVariable(4);\r\n var buffer, szName, item;\r\n var e;\r\n if ((e = GM.pdh.PdhCollectQueryData(po.cpu.Deref()).Val != 0)) { po._rej(e); return; }\r\n\r\n if ((e = GM.pdh.PdhGetFormattedCounterArrayA(po.cpuTotal.Deref(), PDH_FMT_DOUBLE, bufSize, itemCount, 0).Val) == -2147481646)\r\n {\r\n buffer = GM.CreateVariable(bufSize.toBuffer().readUInt32LE());\r\n }\r\n else\r\n {\r\n po._rej(e);\r\n return;\r\n }\r\n if ((e = GM.pdh.PdhGetFormattedCounterArrayA(po.cpuTotal.Deref(), PDH_FMT_DOUBLE, bufSize, itemCount, buffer).Val) != 0) { po._rej(e); return; }\r\n for(var i=0;i<itemCount.toBuffer().readUInt32LE();++i)\r\n {\r\n item = buffer.Deref(i * 24, 24);\r\n szName = item.Deref(0, GM.PointerSize).Deref();\r\n if (szName.String == \'_Total\')\r\n {\r\n u.total = item.Deref(16, 8).toBuffer().readDoubleLE();\r\n }\r\n else\r\n {\r\n u.cpus[parseInt(szName.String)] = item.Deref(16, 8).toBuffer().readDoubleLE();\r\n }\r\n }\r\n\r\n GM.pdh.PdhRemoveCounter(po.cpuTotal.Deref());\r\n GM.pdh.PdhCloseQuery(po.cpu.Deref());\r\n p._res(u);\r\n }, 100, p);\r\n\r\n return (p);\r\n}\r\nfunction windows_memUtilization()\r\n{\r\n var info = GM.CreateVariable(64);\r\n info.Deref(0, 4).toBuffer().writeUInt32LE(64);\r\n GM.kernel32.GlobalMemoryStatusEx(info);\r\n\r\n var ret =\r\n {\r\n MemTotal: require(\'bignum\').fromBuffer(info.Deref(8, 8).toBuffer(), { endian: \'little\' }),\r\n MemFree: require(\'bignum\').fromBuffer(info.Deref(16, 8).toBuffer(), { endian: \'little\' })\r\n };\r\n\r\n ret.percentFree = ((ret.MemFree.div(require(\'bignum\')(\'1048576\')).toNumber() / ret.MemTotal.div(require(\'bignum\')(\'1048576\')).toNumber()) * 100);//.toFixed(2);\r\n ret.percentConsumed = ((ret.MemTotal.sub(ret.MemFree).div(require(\'bignum\')(\'1048576\')).toNumber() / ret.MemTotal.div(require(\'bignum\')(\'1048576\')).toNumber()) * 100);//.toFixed(2);\r\n ret.MemTotal = ret.MemTotal.toString();\r\n ret.MemFree = ret.MemFree.toString();\r\n return (ret);\r\n}\r\n\r\nvar cpuLastIdle = [];\r\nvar cpuLastSum = [];\r\nfunction linux_cpuUtilization() {\r\n var ret = { cpus: [] };\r\n var info = require(\'fs\').readFileSync(\'/proc/stat\');\r\n var lines = info.toString().split(\'\\n\');\r\n var columns;\r\n var x, y;\r\n var cpuNo = 0;\r\n var currSum, currIdle, utilization;\r\n for (var i in lines) {\r\n columns = lines[i].split(\' \');\r\n if (!columns[0].startsWith(\'cpu\')) { break; }\r\n\r\n x = 0, currSum = 0;\r\n while (columns[++x] == \'\');\r\n for (y = x; y < columns.length; ++y) { currSum += parseInt(columns[y]); }\r\n currIdle = parseInt(columns[3 + x]);\r\n\r\n var diffIdle = currIdle - cpuLastIdle[cpuNo];\r\n var diffSum = currSum - cpuLastSum[cpuNo];\r\n\r\n utilization = (100 - ((diffIdle / diffSum) * 100));\r\n\r\n cpuLastSum[cpuNo] = currSum;\r\n cpuLastIdle[cpuNo] = currIdle;\r\n\r\n if (!ret.total) {\r\n ret.total = utilization;\r\n } else {\r\n ret.cpus.push(utilization);\r\n }\r\n ++cpuNo;\r\n }\r\n\r\n var p = new promise(function (res, rej) { this._res = res; this._rej = rej; });\r\n p._res(ret);\r\n return (p);\r\n}\r\nfunction linux_memUtilization()\r\n{\r\n var ret = {};\r\n\r\n var info = require(\'fs\').readFileSync(\'/proc/meminfo\').toString().split(\'\\n\');\r\n var tokens;\r\n for(var i in info)\r\n {\r\n tokens = info[i].split(\' \');\r\n switch(tokens[0])\r\n {\r\n case \'MemTotal:\':\r\n ret.total = parseInt(tokens[tokens.length - 2]);\r\n break;\r\n case \'MemAvailable:\':\r\n ret.free = parseInt(tokens[tokens.length - 2]);\r\n break;\r\n }\r\n }\r\n ret.percentFree = ((ret.free / ret.total) * 100);//.toFixed(2);\r\n ret.percentConsumed = (((ret.total - ret.free) / ret.total) * 100);//.toFixed(2);\r\n return (ret);\r\n}\r\n\r\nfunction macos_cpuUtilization()\r\n{\r\n var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });\r\n var child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\';\r\n child.stdout.on(\'data\', function (chunk) { this.str += chunk.toString(); });\r\n child.stdin.write(\'top -l 1 | grep -E \"^CPU\"\\nexit\\n\');\r\n child.waitExit();\r\n\r\n var lines = child.stdout.str.split(\'\\n\');\r\n if (lines[0].length > 0)\r\n {\r\n var usage = lines[0].split(\':\')[1];\r\n var bdown = usage.split(\',\');\r\n\r\n var tot = parseFloat(bdown[0].split(\'%\')[0].trim()) + parseFloat(bdown[1].split(\'%\')[0].trim());\r\n ret._res({total: tot, cpus: []});\r\n }\r\n else\r\n {\r\n ret._rej(\'parse error\');\r\n }\r\n\r\n return (ret);\r\n}\r\nfunction macos_memUtilization()\r\n{\r\n var mem = { };\r\n var ret = new promise(function (res, rej) { this._res = res; this._rej = rej; });\r\n var child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\';\r\n child.stdout.on(\'data\', function (chunk) { this.str += chunk.toString(); });\r\n child.stdin.write(\'top -l 1 | grep -E \"^Phys\"\\nexit\\n\');\r\n child.waitExit();\r\n\r\n var lines = child.stdout.str.split(\'\\n\');\r\n if (lines[0].length > 0)\r\n {\r\n var usage = lines[0].split(\':\')[1];\r\n var bdown = usage.split(\',\');\r\n if (bdown.length > 2){ // new style - PhysMem: 5750M used (1130M wired, 634M compressor), 1918M unused.\r\n mem.MemFree = parseInt(bdown[2].trim().split(\' \')[0]);\r\n } else { // old style - PhysMem: 6683M used (1606M wired), 9699M unused.\r\n mem.MemFree = parseInt(bdown[1].trim().split(\' \')[0]);\r\n }\r\n mem.MemUsed = parseInt(bdown[0].trim().split(\' \')[0]);\r\n mem.MemTotal = (mem.MemFree + mem.MemUsed);\r\n mem.percentFree = ((mem.MemFree / mem.MemTotal) * 100);//.toFixed(2);\r\n mem.percentConsumed = (((mem.MemTotal - mem.MemFree) / mem.MemTotal) * 100);//.toFixed(2);\r\n return (mem);\r\n }\r\n else\r\n {\r\n throw (\'Parse Error\');\r\n }\r\n}\r\n\r\nfunction windows_thermals()\r\n{\r\n var ret = [];\r\n try {\r\n ret = require(\'win-wmi\').query(\'ROOT\\\\WMI\', \'SELECT CurrentTemperature,InstanceName FROM MSAcpi_ThermalZoneTemperature\',[\'CurrentTemperature\',\'InstanceName\']);\r\n if (ret[0]) {\r\n for (var i = 0; i < ret.length; ++i) {\r\n ret[i][\'CurrentTemperature\'] = ((parseFloat(ret[i][\'CurrentTemperature\']) / 10) - 273.15).toFixed(2);\r\n }\r\n }\r\n } catch (ex) { }\r\n return (ret);\r\n}\r\n\r\nfunction linux_thermals()\r\n{\r\n var ret = [];\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stderr.str = \'\'; child.stderr.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\"for folder in /sys/class/thermal/thermal_zone*/; do [ -e \\\"$folder/temp\\\" ] && echo \\\"$(cat \\\"$folder/temp\\\"),$(cat \\\"$folder/type\\\")\\\"; done\\nexit\\n\");\r\n child.waitExit();\r\n if(child.stdout.str.trim()!=\'\')\r\n {\r\n var lines = child.stdout.str.trim().split(\'\\n\');\r\n for (var i = 0; i < lines.length; ++i)\r\n {\r\n var line = lines[i].trim().split(\',\');\r\n ret.push({CurrentTemperature: (parseFloat(line[0])/1000), InstanceName: line[1]});\r\n }\r\n }\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stderr.str = \'\'; child.stderr.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stdin.write(\"for mon in /sys/class/hwmon/hwmon*; do for label in \\\"$mon\\\"/temp*_label; do if [ -f $label ]; then echo $(cat \\\"$label\\\")___$(cat \\\"${label%_*}_input\\\"); fi; done; done;\\nexit\\n\");\r\n child.waitExit();\r\n if(child.stdout.str.trim()!=\'\')\r\n {\r\n var lines = child.stdout.str.trim().split(\'\\n\');\r\n for (var i = 0; i < lines.length; ++i)\r\n {\r\n var line = lines[i].trim().split(\'___\');\r\n ret.push({ CurrentTemperature: (parseFloat(line[1])/1000), InstanceName: line[0] });\r\n }\r\n }\r\n return (ret);\r\n}\r\n\r\nfunction macos_thermals()\r\n{\r\n var ret = [];\r\n var child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c) { this.str += c.toString(); });\r\n child.stderr.on(\'data\', function () { });\r\n child.stdin.write(\'powermetrics --help | grep SMC\\nexit\\n\');\r\n child.waitExit();\r\n if (child.stdout.str.trim() != \'\')\r\n {\r\n child = require(\'child_process\').execFile(\'/bin/sh\', [\'sh\']);\r\n child.stdout.str = \'\'; child.stdout.on(\'data\', function (c)\r\n {\r\n this.str += c.toString();\r\n var tokens = this.str.trim().split(\'\\n\');\r\n for (var i in tokens)\r\n {\r\n if (tokens[i].split(\' die temperature: \').length > 1)\r\n {\r\n ret.push({CurrentTemperature: tokens[i].split(\' \')[3], InstanceName: tokens[i].split(\' \')[0]});\r\n this.parent.kill();\r\n }\r\n }\r\n });\r\n child.stderr.on(\'data\', function (c) {\r\n if (c.toString().split(\'unable to get smc values\').length > 1) { // error getting sensors so just kill\r\n this.parent.kill();\r\n return;\r\n }\r\n });\r\n child.stdin.write(\'powermetrics -s smc -i 500 -n 1\\n\');\r\n child.waitExit(2000);\r\n }\r\n return (ret);\r\n}\r\n\r\nswitch(process.platform)\r\n{\r\n case \'linux\':\r\n module.exports = { cpuUtilization: linux_cpuUtilization, memUtilization: linux_memUtilization, thermals: linux_thermals };\r\n break;\r\n case \'win32\':\r\n module.exports = { cpuUtilization: windows_cpuUtilization, memUtilization: windows_memUtilization, thermals: windows_thermals };\r\n break;\r\n case \'darwin\':\r\n module.exports = { cpuUtilization: macos_cpuUtilization, memUtilization: macos_memUtilization, thermals: macos_thermals };\r\n break;\r\n}\r\n\r\n"); addedModules.push("sysinfo"); } catch (ex) { }
try { addModule("util-agentlog", "/*\r\nCopyright 2021 Intel Corporation\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*/\r\n\r\n\r\nfunction parseLine(entry)\r\n{\r\n var test = entry.match(/^\\[.*M\\]/);\r\n if (test == null)\r\n {\r\n test = entry.match(/\\[.+ => .+:[0-9]+\\]/);\r\n if (test != null)\r\n {\r\n // Windows Crash Entry\r\n var file = test[0].substring(1).match(/(?!.+ ).+(?=:)/);\r\n var line = test[0].match(/(?!:)[0-9]+(?=\\]$)/);\r\n var fn = test[0].match(/(?!\\[).+(?= =>)/);\r\n\r\n if (file != null) { this.results.peek().f = file[0].trim(); }\r\n if (line != null) { this.results.peek().l = line[0]; }\r\n if (fn != null) { this.results.peek().fn = fn[0]; }\r\n }\r\n else\r\n {\r\n test = entry.match(/^[\\.\\/].+\\(\\) \\[0x[0-9a-fA-F]+\\]$/);\r\n if (test != null)\r\n {\r\n // Linux Crash Stack with no symbols\r\n test = test[0].match(/(?!\\[)0x[0-9a-fA-F]+(?=\\]$)/);\r\n if (test != null)\r\n {\r\n if (this.results.peek().sx == null) { this.results.peek().sx = []; }\r\n this.results.peek().sx.unshift(test[0]);\r\n }\r\n }\r\n else\r\n {\r\n test = entry.match(/^\\[.+_[0-9a-fA-F]{16}\\]$/);\r\n if(test!=null)\r\n {\r\n // Linux Crash ID\r\n test = test[0].match(/(?!_)[0-9a-fA-F]{16}(?=\\]$)/);\r\n this.results.peek().h = test[0];\r\n }\r\n }\r\n\r\n test = entry.match(/(?!^=>)\\/+.+:[0-9]+$/);\r\n if(test!=null)\r\n {\r\n // Linux Crash Entry\r\n if (this.results.peek().s == null) { this.results.peek().s = []; }\r\n this.results.peek().s.unshift(test[0]);\r\n }\r\n \r\n }\r\n return;\r\n }\r\n test = test[0];\r\n\r\n var dd = test.substring(1, test.length -1);\r\n var c = dd.split(\' \');\r\n var t = c[1].split(\':\');\r\n if (c[2] == \'PM\') { t[0] = parseInt(t[0]) + 12; if (t[0] == 24) { t[0] = 0; } }\r\n\r\n var d = Date.parse(c[0] + \'T\' + t.join(\':\'));\r\n var msg = entry.substring(test.length).trim();\r\n var hash = msg.match(/^\\[[0-9a-fA-F]{16}\\]/);\r\n if (hash != null)\r\n {\r\n hash = hash[0].substring(1, hash[0].length - 1);\r\n msg = msg.substring(hash.length + 2).trim();\r\n }\r\n else\r\n {\r\n hash = msg.match(/^\\[\\]/);\r\n if(hash!=null)\r\n {\r\n msg = msg.substring(2).trim();\r\n hash = null;\r\n }\r\n }\r\n\r\n var log = { t: Math.floor(d / 1000), m: msg };\r\n if (hash != null) { log.h = hash; }\r\n\r\n // Check for File/Line in generic log entry\r\n test = msg.match(/^.+:[0-9]+ \\([0-9]+,[0-9]+\\)/);\r\n if (test != null)\r\n {\r\n log.m = log.m.substring(test[0].length).trim();\r\n log.f = test[0].match(/^.+(?=:[0-9]+)/)[0];\r\n log.l = test[0].match(/(?!:)[0-9]+(?= \\([0-9]+,[0-9]+\\)$)/)[0];\r\n }\r\n\r\n this.results.push(log);\r\n}\r\n\r\nfunction readLog_data(buffer)\r\n{\r\n var lines = buffer.toString();\r\n if (this.buffered != null) { lines = this.buffered + lines; }\r\n lines = lines.split(\'\\n\');\r\n var i;\r\n\r\n for (i = 0; i < (lines.length - 1) ; ++i)\r\n {\r\n parseLine.call(this, lines[i]);\r\n }\r\n\r\n if (lines.length == 1)\r\n {\r\n parseLine.call(this, lines[0]);\r\n this.buffered = null;\r\n }\r\n else\r\n {\r\n this.buffered = lines[lines.length - 1];\r\n }\r\n}\r\n\r\nfunction readLogEx(path)\r\n{\r\n var ret = [];\r\n try\r\n {\r\n var s = require(\'fs\').createReadStream(path);\r\n s.buffered = null;\r\n s.results = ret;\r\n s.on(\'data\', readLog_data);\r\n s.resume();\r\n if (s.buffered != null) { readLog_data.call(s, s.buffered); s.buffered = null; }\r\n s.removeAllListeners(\'data\');\r\n s = null;\r\n }\r\n catch(z)\r\n {\r\n }\r\n\r\n return (ret);\r\n}\r\n\r\nfunction readLog(criteria, path)\r\n{\r\n var objects = readLogEx(path == null ? (process.execPath.split(\'.exe\').join(\'\') + \'.log\') : path);\r\n var ret = [];\r\n\r\n if (typeof (criteria) == \'string\')\r\n {\r\n try\r\n {\r\n var dstring = Date.parse(criteria);\r\n criteria = Math.floor(dstring / 1000);\r\n }\r\n catch(z)\r\n {\r\n }\r\n }\r\n\r\n if (typeof (criteria) == \'number\')\r\n {\r\n if(criteria < 1000)\r\n {\r\n // Return the last xxx entries\r\n ret = objects.slice(objects.length - ((criteria > objects.length) ? objects.length : criteria));\r\n }\r\n else\r\n {\r\n // Return entries that are newer than xxx\r\n var i;\r\n for (i = 0; i < objects.length && objects[i].t <= criteria; ++i) { }\r\n ret = objects.slice(i);\r\n }\r\n }\r\n else\r\n {\r\n ret = objects;\r\n }\r\n\r\n return (ret);\r\n}\r\n\r\nmodule.exports = { read: readLog, readEx: readLogEx }\r\n\r\n"); addedModules.push("util-agentlog"); } catch (ex) { }
try { addModule("wifi-scanner-windows", "/*\r\nCopyright 2018-2021 Intel Corporation\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*/\r\n\r\nfunction _Scan()\r\n{\r\n var wlanInterfaces = this.Marshal.CreatePointer();\r\n this.Native.WlanEnumInterfaces(this.Handle, 0, wlanInterfaces);\r\n\r\n var count = wlanInterfaces.Deref().Deref(0, 4).toBuffer().readUInt32LE(0);\r\n\r\n var info = wlanInterfaces.Deref().Deref(8, 532);\r\n var iname = info.Deref(16, 512).AnsiString;\r\n\r\n var istate;\r\n switch (info.Deref(528, 4).toBuffer().readUInt32LE(0))\r\n {\r\n case 0:\r\n istate = \"NOT READY\";\r\n break;\r\n case 1:\r\n istate = \"CONNECTED\";\r\n break;\r\n case 2:\r\n istate = \"AD-HOC\";\r\n break;\r\n case 3:\r\n istate = \"DISCONNECTING\";\r\n break;\r\n case 4:\r\n istate = \"DISCONNECTED\";\r\n break;\r\n case 5:\r\n istate = \"ASSOCIATING\";\r\n break;\r\n case 6:\r\n istate = \"DISCOVERING\";\r\n break;\r\n case 7:\r\n istate = \"AUTHENTICATING\";\r\n break;\r\n default:\r\n istate = \"UNKNOWN\";\r\n break;\r\n }\r\n\r\n var iguid = info.Deref(0, 16);\r\n if (this.Native.WlanScan(this.Handle, iguid, 0, 0, 0).Val == 0)\r\n {\r\n return (true);\r\n }\r\n else\r\n {\r\n return (false);\r\n }\r\n}\r\n\r\nfunction AccessPoint(_ssid, _bssid, _rssi, _lq)\r\n{\r\n this.ssid = _ssid;\r\n this.bssid = _bssid;\r\n this.rssi = _rssi;\r\n this.lq = _lq;\r\n}\r\nAccessPoint.prototype.toString = function()\r\n{\r\n return (this.ssid + \" [\" + this.bssid + \"]: \" + this.lq);\r\n}\r\n\r\nfunction OnNotify(NotificationData)\r\n{\r\n var NotificationSource = NotificationData.Deref(0, 4).toBuffer().readUInt32LE(0);\r\n var NotificationCode = NotificationData.Deref(4, 4).toBuffer().readUInt32LE(0);\r\n var dataGuid = NotificationData.Deref(8, 16);\r\n\r\n if ((NotificationSource & 0X00000008) && (NotificationCode == 7))\r\n {\r\n var bss = this.Parent.Marshal.CreatePointer();\r\n var result = this.Parent.Native.GetBSSList(this.Parent.Handle, dataGuid, 0, 3, 0, 0, bss).Val;\r\n if (result == 0)\r\n {\r\n var totalSize = bss.Deref().Deref(0, 4).toBuffer().readUInt32LE(0);\r\n var numItems = bss.Deref().Deref(4, 4).toBuffer().readUInt32LE(0);\r\n for (i = 0; i < numItems; ++i)\r\n {\r\n var item = bss.Deref().Deref(8 + (360 * i), 360);\r\n var ssid = item.Deref(4, 32).String.trim();\r\n var bssid = item.Deref(40, 6).HexString2;\r\n var rssi = item.Deref(56, 4).toBuffer().readUInt32LE(0);\r\n var lq = item.Deref(60, 4).toBuffer().readUInt32LE(0);\r\n\r\n this.Parent.emit(\'Scan\', new AccessPoint(ssid, bssid, rssi, lq));\r\n }\r\n }\r\n\r\n }\r\n}\r\n\r\nfunction Wireless()\r\n{\r\n var emitterUtils = require(\'events\').inherits(this);\r\n\r\n this.Marshal = require(\'_GenericMarshal\');\r\n this.Native = this.Marshal.CreateNativeProxy(\"wlanapi.dll\");\r\n this.Native.CreateMethod(\"WlanOpenHandle\");\r\n this.Native.CreateMethod(\"WlanGetNetworkBssList\", \"GetBSSList\");\r\n this.Native.CreateMethod(\"WlanRegisterNotification\");\r\n this.Native.CreateMethod(\"WlanEnumInterfaces\");\r\n this.Native.CreateMethod(\"WlanScan\");\r\n this.Native.CreateMethod(\"WlanQueryInterface\");\r\n\r\n var negotiated = this.Marshal.CreatePointer();\r\n var h = this.Marshal.CreatePointer();\r\n\r\n this.Native.WlanOpenHandle(2, 0, negotiated, h);\r\n this.Handle = h.Deref();\r\n\r\n this._NOTIFY_PROXY_OBJECT = this.Marshal.CreateCallbackProxy(OnNotify, 2);\r\n this._NOTIFY_PROXY_OBJECT.Parent = this;\r\n var PrevSource = this.Marshal.CreatePointer();\r\n var result = this.Native.WlanRegisterNotification(this.Handle, 0X0000FFFF, 0, this._NOTIFY_PROXY_OBJECT.Callback, this._NOTIFY_PROXY_OBJECT.State, 0, PrevSource);\r\n\r\n emitterUtils.createEvent(\'Scan\');\r\n emitterUtils.addMethod(\'Scan\', _Scan);\r\n\r\n this.GetConnectedNetwork = function ()\r\n {\r\n var interfaces = this.Marshal.CreatePointer();\r\n\r\n console.log(\'Success = \' + this.Native.WlanEnumInterfaces(this.Handle, 0, interfaces).Val);\r\n var count = interfaces.Deref().Deref(0, 4).toBuffer().readUInt32LE(0);\r\n var info = interfaces.Deref().Deref(8, 532);\r\n var iname = info.Deref(16, 512).AnsiString;\r\n var istate = info.Deref(528, 4).toBuffer().readUInt32LE(0);\r\n if(info.Deref(528, 4).toBuffer().readUInt32LE(0) == 1) // CONNECTED\r\n {\r\n var dataSize = this.Marshal.CreatePointer();\r\n var pData = this.Marshal.CreatePointer();\r\n var valueType = this.Marshal.CreatePointer();\r\n var iguid = info.Deref(0, 16);\r\n var retVal = this.Native.WlanQueryInterface(this.Handle, iguid, 7, 0, dataSize, pData, valueType).Val;\r\n if (retVal == 0)\r\n {\r\n var associatedSSID = pData.Deref().Deref(524, 32).String;\r\n var bssid = pData.Deref().Deref(560, 6).HexString;\r\n var lq = pData.Deref().Deref(576, 4).toBuffer().readUInt32LE(0);\r\n\r\n return (new AccessPoint(associatedSSID, bssid, 0, lq));\r\n }\r\n }\r\n throw (\"GetConnectedNetworks: FAILED (not associated to a network)\");\r\n };\r\n\r\n\r\n return (this);\r\n}\r\n\r\nmodule.exports = new Wireless();\r\n"); addedModules.push("wifi-scanner-windows"); } catch (ex) { }
try { addModule("wifi-scanner", "/*\r\nCopyright 2018-2021 Intel Corporation\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*/\r\n\r\nvar MemoryStream = require(\'MemoryStream\');\r\nvar WindowsChildScript = \'var parent = require(\"ScriptContainer\");var Wireless = require(\"wifi-scanner-windows\");Wireless.on(\"Scan\", function (ap) { parent.send(ap); });Wireless.Scan();\';\r\n\r\n\r\nfunction AccessPoint(_ssid, _bssid, _lq)\r\n{\r\n this.ssid = _ssid;\r\n this.bssid = _bssid;\r\n this.lq = _lq;\r\n}\r\nAccessPoint.prototype.toString = function ()\r\n{\r\n return (\"[\" + this.bssid + \"]: \" + this.ssid + \" (\" + this.lq + \")\");\r\n //return (this.ssid + \" [\" + this.bssid + \"]: \" + this.lq);\r\n}\r\n\r\nfunction WiFiScanner()\r\n{\r\n var emitterUtils = require(\'events\').inherits(this);\r\n emitterUtils.createEvent(\'accessPoint\');\r\n\r\n this.hasWireless = function ()\r\n {\r\n var retVal = false;\r\n var interfaces = require(\'os\').networkInterfaces();\r\n for (var name in interfaces)\r\n {\r\n if (interfaces[name][0].type == \'wireless\') { retVal = true; break; }\r\n }\r\n return (retVal);\r\n };\r\n\r\n this.Scan = function ()\r\n {\r\n if (process.platform == \'win32\')\r\n {\r\n this.main = require(\'ScriptContainer\').Create(15, ContainerPermissions.DEFAULT);\r\n this.main.parent = this;\r\n this.main.on(\'data\', function (j) { this.parent.emit(\'accessPoint\', new AccessPoint(j.ssid, j.bssid, j.lq)); });\r\n\r\n this.main.addModule(\'wifi-scanner-windows\', getJSModule(\'wifi-scanner-windows\'));\r\n this.main.ExecuteString(WindowsChildScript);\r\n }\r\n else if (process.platform == \'linux\')\r\n {\r\n // Need to get the wireless interface name\r\n var interfaces = require(\'os\').networkInterfaces();\r\n var wlan = null;\r\n for (var i in interfaces)\r\n {\r\n if (interfaces[i][0].type == \'wireless\')\r\n {\r\n wlan = i;\r\n break;\r\n }\r\n }\r\n if (wlan != null)\r\n {\r\n this.child = require(\'child_process\').execFile(\'/sbin/iwlist\', [\'iwlist\', wlan, \'scan\']);\r\n this.child.parent = this;\r\n this.child.ms = new MemoryStream();\r\n this.child.ms.parent = this.child;\r\n this.child.stdout.on(\'data\', function (buffer) { this.parent.ms.write(buffer); });\r\n this.child.on(\'exit\', function () { this.ms.end(); });\r\n this.child.ms.on(\'end\', function ()\r\n {\r\n var str = this.buffer.toString();\r\n tokens = str.split(\' - Address: \');\r\n for (var block in tokens)\r\n {\r\n if (block == 0) continue;\r\n var ln = tokens[block].split(\'\\n\');\r\n var _bssid = ln[0];\r\n var _lq;\r\n var _ssid;\r\n\r\n for (var lnblock in ln)\r\n {\r\n lnblock = ln[lnblock].trim();\r\n lnblock = lnblock.trim();\r\n if (lnblock.startsWith(\'ESSID:\'))\r\n {\r\n _ssid = lnblock.slice(7, lnblock.length - 1);\r\n if (_ssid == \'<hidden>\') { _ssid = \'\'; }\r\n }\r\n if (lnblock.startsWith(\'Signal level=\'))\r\n {\r\n _lq = lnblock.slice(13,lnblock.length-4);\r\n }\r\n else if (lnblock.startsWith(\'Quality=\'))\r\n {\r\n _lq = lnblock.slice(8, 10);\r\n var scale = lnblock.slice(11, 13);\r\n }\r\n }\r\n this.parent.parent.emit(\'accessPoint\', new AccessPoint(_ssid, _bssid, _lq));\r\n }\r\n });\r\n }\r\n }\r\n }\r\n}\r\n\r\nmodule.exports = WiFiScanner;\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"); addedModules.push("wifi-scanner"); } catch (ex) { }
/*
Copyright 2018-2022 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
process.on('uncaughtException', function (ex) {
require('MeshAgent').SendCommand({ action: 'msg', type: 'console', value: "uncaughtException1: " + ex });
});
if (process.platform == 'win32' && require('user-sessions').getDomain == null) {
require('user-sessions').getDomain = function getDomain(uid) {
return (this.getSessionAttribute(uid, this.InfoClass.WTSDomainName));
};
}
var promise = require('promise');
// Mesh Rights
var MNG_ERROR = 65;
var MESHRIGHT_EDITMESH = 1;
var MESHRIGHT_MANAGEUSERS = 2;
var MESHRIGHT_MANAGECOMPUTERS = 4;
var MESHRIGHT_REMOTECONTROL = 8;
var MESHRIGHT_AGENTCONSOLE = 16;
var MESHRIGHT_SERVERFILES = 32;
var MESHRIGHT_WAKEDEVICE = 64;
var MESHRIGHT_SETNOTES = 128;
var MESHRIGHT_REMOTEVIEW = 256; // Remote View Only
var MESHRIGHT_NOTERMINAL = 512;
var MESHRIGHT_NOFILES = 1024;
var MESHRIGHT_NOAMT = 2048;
var MESHRIGHT_LIMITEDINPUT = 4096;
var MESHRIGHT_LIMITEVENTS = 8192;
var MESHRIGHT_CHATNOTIFY = 16384;
var MESHRIGHT_UNINSTALL = 32768;
var MESHRIGHT_NODESKTOP = 65536;
var pendingSetClip = false; // This is a temporary hack to prevent multiple setclips at the same time to stop the agent from crashing.
//
// This is a helper function used by the 32 bit Windows Agent, when running on 64 bit windows. It will check if the agent is already patched for this
// and will use this helper if it is not. This helper will inject 'sysnative' into the results when calling readdirSync() on %windir%.
//
function __readdirSync_fix(path)
{
var sysnative = false;
pathstr = require('fs')._fixwinpath(path);
if (pathstr.split('\\*').join('').toLowerCase() == process.env['windir'].toLowerCase()) { sysnative = true; }
var ret = require('fs').__readdirSync_old(path);
if (sysnative) { ret.push('sysnative'); }
return (ret);
}
if (process.platform == 'win32' && require('_GenericMarshal').PointerSize == 4 && require('os').arch() == 'x64')
{
if (require('fs').readdirSync.version == null)
{
//
// 32 Bit Windows Agent on 64 bit Windows has not been patched for sysnative issue, so lets use our own solution
//
require('fs').__readdirSync_old = require('fs').readdirSync;
require('fs').readdirSync = __readdirSync_fix;
}
}
function bcdOK() {
if (process.platform != 'win32') { return (false); }
if (require('os').arch() == 'x64') {
return (require('_GenericMarshal').PointerSize == 8);
}
return (true);
}
function getDomainInfo() {
var hostname = require('os').hostname();
var ret = { Name: hostname, Domain: "" };
switch (process.platform) {
case 'win32':
try {
ret = require('win-wmi').query('ROOT\\CIMV2', 'SELECT * FROM Win32_ComputerSystem', ['Name', 'Domain'])[0];
}
catch (x) {
}
break;
case 'linux':
var hasrealm = false;
try {
hasrealm = require('lib-finder').hasBinary('realm');
}
catch (x) {
}
if (hasrealm) {
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write("realm list | grep domain-name: | tr '\\n' '`' | ");
child.stdin.write("awk -F'`' '{ ");
child.stdin.write(' printf("[");');
child.stdin.write(' ST="";');
child.stdin.write(' for(i=1;i<NF;++i)');
child.stdin.write(' {');
child.stdin.write(' match($i,/domain-name: /);');
child.stdin.write(' printf("%s\\"%s\\"", ST, substr($i, RSTART+RLENGTH));');
child.stdin.write(' ST=",";');
child.stdin.write(' }');
child.stdin.write(' printf("]");');
child.stdin.write(" }'");
child.stdin.write('\nexit\n');
child.waitExit();
var names = [];
try {
names = JSON.parse(child.stdout.str);
}
catch (e) {
}
while (names.length > 0) {
if (hostname.endsWith('.' + names.peek())) {
ret = { Name: hostname.substring(0, hostname.length - names.peek().length - 1), Domain: names.peek() };
break;
}
names.pop();
}
}
break;
}
return (ret);
}
try {
Object.defineProperty(Array.prototype, 'findIndex', {
value: function (func) {
var i = 0;
for (i = 0; i < this.length; ++i) {
if (func(this[i], i, this)) {
return (i);
}
}
return (-1);
}
});
} catch (ex) { }
if (require('MeshAgent').ARCHID == null) {
var id = null;
switch (process.platform) {
case 'win32':
id = require('_GenericMarshal').PointerSize == 4 ? 3 : 4;
break;
case 'freebsd':
id = require('_GenericMarshal').PointerSize == 4 ? 31 : 30;
break;
case 'darwin':
try {
id = require('os').arch() == 'x64' ? 16 : 29;
} catch (ex) { id = 16; }
break;
}
if (id != null) { Object.defineProperty(require('MeshAgent'), 'ARCHID', { value: id }); }
}
function setDefaultCoreTranslation(obj, field, value) {
if (obj[field] == null || obj[field] == '') { obj[field] = value; }
}
function getCoreTranslation() {
var ret = {};
if (global.coretranslations != null) {
try {
var lang = require('util-language').current;
if (coretranslations[lang] == null) { lang = lang.split('-')[0]; }
if (coretranslations[lang] == null) { lang = 'en'; }
if (coretranslations[lang] != null) { ret = coretranslations[lang]; }
}
catch (ex) { }
}
setDefaultCoreTranslation(ret, 'allow', 'Allow');
setDefaultCoreTranslation(ret, 'deny', 'Deny');
setDefaultCoreTranslation(ret, 'autoAllowForFive', 'Auto accept all connections for next 5 minutes');
setDefaultCoreTranslation(ret, 'terminalConsent', '{0} requesting remote terminal access. Grant access?');
setDefaultCoreTranslation(ret, 'desktopConsent', '{0} requesting remote desktop access. Grant access?');
setDefaultCoreTranslation(ret, 'fileConsent', '{0} requesting remote file Access. Grant access?');
setDefaultCoreTranslation(ret, 'terminalNotify', '{0} started a remote terminal session.');
setDefaultCoreTranslation(ret, 'desktopNotify', '{0} started a remote desktop session.');
setDefaultCoreTranslation(ret, 'fileNotify', '{0} started a remote file session.');
setDefaultCoreTranslation(ret, 'privacyBar', 'Sharing desktop with: {0}');
return (ret);
}
var currentTranslation = getCoreTranslation();
try {
require('kvm-helper');
}
catch (e) {
var j =
{
users: function () {
var r = {};
require('user-sessions').Current(function (c) { r = c; });
if (process.platform != 'win32') {
for (var i in r) {
r[i].SessionId = r[i].uid;
}
}
return (r);
}
};
addModuleObject('kvm-helper', j);
}
function lockDesktop(uid) {
switch (process.platform) {
case 'linux':
if (uid != null) {
var name = require('user-sessions').getUsername(uid);
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stderr.str = ''; child.stderr.on('data', function (chunk) { this.str += chunk.toString(); });
child.stdin.write('loginctl show-user -p Sessions ' + name + " | awk '{");
child.stdin.write('gsub(/^Sessions=/,"",$0);');
child.stdin.write('cmd = sprintf("loginctl lock-session %s",$0);');
child.stdin.write('system(cmd);');
child.stdin.write("}'\nexit\n");
child.waitExit();
}
else {
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stderr.str = ''; child.stderr.on('data', function (chunk) { this.str += chunk.toString(); });
child.stdin.write('loginctl lock-sessions\nexit\n');
child.waitExit();
}
break;
case 'win32':
{
var options = { type: 1, uid: uid };
var child = require('child_process').execFile(process.env['windir'] + '\\system32\\cmd.exe', ['/c', 'RunDll32.exe user32.dll,LockWorkStation'], options);
child.waitExit();
}
break;
default:
break;
}
}
var writable = require('stream').Writable;
function destopLockHelper_pipe(httprequest) {
if (process.platform != 'linux' && process.platform != 'freebsd') { return; }
if (httprequest.unlockerHelper == null && httprequest.desktop != null && httprequest.desktop.kvm != null) {
httprequest.unlockerHelper = new writable(
{
'write': function (chunk, flush) {
if (chunk.readUInt16BE(0) == 65) {
delete this.request.autolock;
}
flush();
return (true);
},
'final': function (flush) {
flush();
}
});
httprequest.unlockerHelper.request = httprequest;
httprequest.desktop.kvm.pipe(httprequest.unlockerHelper);
}
}
var obj = { serverInfo: {} };
var agentFileHttpRequests = {}; // Currently active agent HTTPS GET requests from the server.
var agentFileHttpPendingRequests = []; // Pending HTTPS GET requests from the server.
var debugConsole = (global._MSH && (_MSH().debugConsole == 1));
var color_options =
{
background: (global._MSH != null) ? global._MSH().background : '0,54,105',
foreground: (global._MSH != null) ? global._MSH().foreground : '255,255,255'
};
if (process.platform == 'win32' && require('user-sessions').isRoot()) {
// Check the Agent Uninstall MetaData for correctness, as the installer may have written an incorrect value
try {
var writtenSize = 0, actualSize = Math.floor(require('fs').statSync(process.execPath).size / 1024);
var serviceName = (_MSH().serviceName ? _MSH().serviceName : (require('_agentNodeId').serviceName() ? require('_agentNodeId').serviceName() : 'Mesh Agent'));
try { writtenSize = require('win-registry').QueryKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\' + serviceName, 'EstimatedSize'); } catch (ex) { }
if (writtenSize != actualSize) { try { require('win-registry').WriteKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\' + serviceName, 'EstimatedSize', actualSize); } catch (ex) { } }
} catch (ex) { }
// Check to see if we are the Installed Mesh Agent Service, if we are, make sure we can run in Safe Mode
var svcname = process.platform == 'win32' ? 'Mesh Agent' : 'meshagent';
try {
svcname = require('MeshAgent').serviceName;
} catch (ex) { }
try {
var meshCheck = false;
try { meshCheck = require('service-manager').manager.getService(svcname).isMe(); } catch (ex) { }
if (meshCheck && require('win-bcd').isSafeModeService && !require('win-bcd').isSafeModeService(svcname)) { require('win-bcd').enableSafeModeService(svcname); }
} catch (ex) { }
// Check the Agent Uninstall MetaData for DisplayVersion and update if not the same and only on windows
if (process.platform == 'win32') {
try {
var writtenDisplayVersion = 0, actualDisplayVersion = process.versions.commitDate.toString();
var serviceName = (_MSH().serviceName ? _MSH().serviceName : (require('_agentNodeId').serviceName() ? require('_agentNodeId').serviceName() : 'Mesh Agent'));
try { writtenDisplayVersion = require('win-registry').QueryKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\' + serviceName, 'DisplayVersion'); } catch (ex) { }
if (writtenDisplayVersion != actualDisplayVersion) { try { require('win-registry').WriteKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\' + serviceName, 'DisplayVersion', actualDisplayVersion); } catch (ex) { } }
} catch (ex) { }
}
}
if (process.platform != 'win32') {
var ch = require('child_process');
ch._execFile = ch.execFile;
ch.execFile = function execFile(path, args, options) {
if (options && options.type && options.type == ch.SpawnTypes.TERM && options.env) {
options.env['TERM'] = 'xterm-256color';
}
return (this._execFile(path, args, options));
};
}
if (process.platform == 'darwin' && !process.versions) {
// This is an older MacOS Agent, so we'll need to check the service definition so that Auto-Update will function correctly
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = '';
child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stdin.write("cat /Library/LaunchDaemons/meshagent_osx64_LaunchDaemon.plist | tr '\n' '\.' | awk '{split($0, a, \"<key>KeepAlive</key>\"); split(a[2], b, \"<\"); split(b[2], c, \">\"); ");
child.stdin.write(" if(c[1]==\"dict\"){ split(a[2], d, \"</dict>\"); if(split(d[1], truval, \"<true/>\")>1) { split(truval[1], kn1, \"<key>\"); split(kn1[2], kn2, \"</key>\"); print kn2[1]; } }");
child.stdin.write(" else { split(c[1], ka, \"/\"); if(ka[1]==\"true\") {print \"ALWAYS\";} } }'\nexit\n");
child.waitExit();
if (child.stdout.str.trim() == 'Crashed') {
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = '';
child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stdin.write("launchctl list | grep 'meshagent' | awk '{ if($3==\"meshagent\"){print $1;}}'\nexit\n");
child.waitExit();
if (parseInt(child.stdout.str.trim()) == process.pid) {
// The currently running MeshAgent is us, so we can continue with the update
var plist = require('fs').readFileSync('/Library/LaunchDaemons/meshagent_osx64_LaunchDaemon.plist').toString();
var tokens = plist.split('<key>KeepAlive</key>');
if (tokens[1].split('>')[0].split('<')[1] == 'dict') {
var tmp = tokens[1].split('</dict>');
tmp.shift();
tokens[1] = '\n <true/>' + tmp.join('</dict>');
tokens = tokens.join('<key>KeepAlive</key>');
require('fs').writeFileSync('/Library/LaunchDaemons/meshagent_osx64_LaunchDaemon.plist', tokens);
var fix = '';
fix += ("function macosRepair()\n");
fix += ("{\n");
fix += (" var child = require('child_process').execFile('/bin/sh', ['sh']);\n");
fix += (" child.stdout.str = '';\n");
fix += (" child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });\n");
fix += (" child.stderr.on('data', function (chunk) { });\n");
fix += (" child.stdin.write('launchctl unload /Library/LaunchDaemons/meshagent_osx64_LaunchDaemon.plist\\n');\n");
fix += (" child.stdin.write('launchctl load /Library/LaunchDaemons/meshagent_osx64_LaunchDaemon.plist\\n');\n");
fix += (" child.stdin.write('rm /Library/LaunchDaemons/meshagentRepair.plist\\n');\n");
fix += (" child.stdin.write('rm " + process.cwd() + "/macosRepair.js\\n');\n");
fix += (" child.stdin.write('launchctl stop meshagentRepair\\nexit\\n');\n");
fix += (" child.waitExit();\n");
fix += ("}\n");
fix += ("macosRepair();\n");
fix += ("process.exit();\n");
require('fs').writeFileSync(process.cwd() + '/macosRepair.js', fix);
var plist = '<?xml version="1.0" encoding="UTF-8"?>\n';
plist += '<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n';
plist += '<plist version="1.0">\n';
plist += ' <dict>\n';
plist += ' <key>Label</key>\n';
plist += (' <string>meshagentRepair</string>\n');
plist += ' <key>ProgramArguments</key>\n';
plist += ' <array>\n';
plist += (' <string>' + process.execPath + '</string>\n');
plist += ' <string>macosRepair.js</string>\n';
plist += ' </array>\n';
plist += ' <key>WorkingDirectory</key>\n';
plist += (' <string>' + process.cwd() + '</string>\n');
plist += ' <key>RunAtLoad</key>\n';
plist += ' <true/>\n';
plist += ' </dict>\n';
plist += '</plist>';
require('fs').writeFileSync('/Library/LaunchDaemons/meshagentRepair.plist', plist);
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = '';
child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });
child.stdin.write("launchctl load /Library/LaunchDaemons/meshagentRepair.plist\nexit\n");
child.waitExit();
}
}
}
}
// Add an Intel AMT event to the log
function addAmtEvent(msg) {
if (obj.amtevents == null) { obj.amtevents = []; }
var d = new Date(), e = zeroPad(d.getHours(), 2) + ':' + zeroPad(d.getMinutes(), 2) + ':' + zeroPad(d.getSeconds(), 2) + ', ' + msg;
obj.amtevents.push(e);
if (obj.amtevents.length > 100) { obj.amtevents.splice(0, obj.amtevents.length - 100); }
if (obj.showamtevent) { require('MeshAgent').SendCommand({ action: 'msg', type: 'console', value: e }); }
}
function zeroPad(num, size) { var s = '000000000' + num; return s.substr(s.length - size); }
// Create Secure IPC for Diagnostic Agent Communications
obj.DAIPC = require('net').createServer();
if (process.platform != 'win32') { try { require('fs').unlinkSync(process.cwd() + '/DAIPC'); } catch (ex) { } }
obj.DAIPC.IPCPATH = process.platform == 'win32' ? ('\\\\.\\pipe\\' + require('_agentNodeId')() + '-DAIPC') : (process.cwd() + '/DAIPC');
try { obj.DAIPC.listen({ path: obj.DAIPC.IPCPATH, writableAll: true, maxConnections: 5 }); } catch (ex) { }
obj.DAIPC._daipc = [];
obj.DAIPC.on('connection', function (c) {
c._send = function (j) {
var data = JSON.stringify(j);
var packet = Buffer.alloc(data.length + 4);
packet.writeUInt32LE(data.length + 4, 0);
Buffer.from(data).copy(packet, 4);
this.write(packet);
};
this._daipc.push(c);
c.parent = this;
c.on('end', function () { removeRegisteredApp(this); });
c.on('data', function (chunk) {
if (chunk.length < 4) { this.unshift(chunk); return; }
var len = chunk.readUInt32LE(0);
if (len > 8192) { removeRegisteredApp(this); this.end(); return; }
if (chunk.length < len) { this.unshift(chunk); return; }
var data = chunk.slice(4, len);
try { data = JSON.parse(data.toString()); } catch (ex) { }
if ((data == null) || (typeof data.cmd != 'string')) return;
try {
switch (data.cmd) {
case 'requesthelp':
if (this._registered == null) return;
sendConsoleText('Request Help (' + this._registered + '): ' + data.value);
var help = {};
help[this._registered] = data.value;
try { mesh.SendCommand({ action: 'sessions', type: 'help', value: help }); } catch (ex) { }
MeshServerLogEx(98, [this._registered, data.value], "Help Requested, user: " + this._registered + ", details: " + data.value, null);
break;
case 'cancelhelp':
if (this._registered == null) return;
sendConsoleText('Cancel Help (' + this._registered + ')');
try { mesh.SendCommand({ action: 'sessions', type: 'help', value: {} }); } catch (ex) { }
break;
case 'register':
if (typeof data.value == 'string') {
this._registered = data.value;
var apps = {};
apps[data.value] = 1;
try { mesh.SendCommand({ action: 'sessions', type: 'app', value: apps }); } catch (ex) { }
this._send({ cmd: 'serverstate', value: meshServerConnectionState, url: require('MeshAgent').ConnectedServer, amt: (amt != null) });
}
break;
case 'query':
switch (data.value) {
case 'connection':
data.result = require('MeshAgent').ConnectedServer;
this._send(data);
break;
case 'descriptors':
require('ChainViewer').getSnapshot().then(function (f) {
this.tag.payload.result = f;
this.tag.ipc._send(this.tag.payload);
}).parentPromise.tag = { ipc: this, payload: data };
break;
case 'timerinfo':
data.result = require('ChainViewer').getTimerInfo();
this._send(data);
break;
}
break;
case 'amtstate':
if (amt == null) return;
var func = function amtStateFunc(state) { if (state != null) { amtStateFunc.pipe._send({ cmd: 'amtstate', value: state }); } }
func.pipe = this;
amt.getMeiState(11, func);
break;
case 'sessions':
this._send({ cmd: 'sessions', sessions: tunnelUserCount });
break;
case 'meshToolInfo':
try { mesh.SendCommand({ action: 'meshToolInfo', name: data.name, hash: data.hash, cookie: data.cookie ? true : false, pipe: true }); } catch (ex) { }
break;
case 'getUserImage':
try { mesh.SendCommand({ action: 'getUserImage', userid: data.userid, pipe: true }); } catch (ex) { }
break;
case 'console':
if (debugConsole) {
var args = splitArgs(data.value);
processConsoleCommand(args[0].toLowerCase(), parseArgs(args), 0, 'pipe');
}
break;
}
}
catch (ex) { removeRegisteredApp(this); this.end(); return; }
});
});
// Send current sessions to registered apps
function broadcastSessionsToRegisteredApps(x) {
var p = {}, i;
for (i = 0; sendAgentMessage.messages != null && i < sendAgentMessage.messages.length; ++i) {
p[i] = sendAgentMessage.messages[i];
}
tunnelUserCount.msg = p;
broadcastToRegisteredApps({ cmd: 'sessions', sessions: tunnelUserCount });
tunnelUserCount.msg = {};
}
// Send this object to all registered local applications
function broadcastToRegisteredApps(x) {
if ((obj.DAIPC == null) || (obj.DAIPC._daipc == null)) return;
for (var i in obj.DAIPC._daipc) {
if (obj.DAIPC._daipc[i]._registered != null) { obj.DAIPC._daipc[i]._send(x); }
}
}
// Send this object to a specific registered local applications
function sendToRegisteredApp(appid, x) {
if ((obj.DAIPC == null) || (obj.DAIPC._daipc == null)) return;
for (var i in obj.DAIPC._daipc) { if (obj.DAIPC._daipc[i]._registered == appid) { obj.DAIPC._daipc[i]._send(x); } }
}
// Send list of registered apps to the server
function updateRegisteredAppsToServer() {
if ((obj.DAIPC == null) || (obj.DAIPC._daipc == null)) return;
var apps = {};
for (var i in obj.DAIPC._daipc) { if (apps[obj.DAIPC._daipc[i]._registered] == null) { apps[obj.DAIPC._daipc[i]._registered] = 1; } else { apps[obj.DAIPC._daipc[i]._registered]++; } }
try { mesh.SendCommand({ action: 'sessions', type: 'app', value: apps }); } catch (ex) { }
}
// Remove a registered app
function removeRegisteredApp(pipe) {
for (var i = obj.DAIPC._daipc.length - 1; i >= 0; i--) { if (obj.DAIPC._daipc[i] === pipe) { obj.DAIPC._daipc.splice(i, 1); } }
if (pipe._registered != null) updateRegisteredAppsToServer();
}
function diagnosticAgent_uninstall() {
require('service-manager').manager.uninstallService('meshagentDiagnostic');
require('task-scheduler').delete('meshagentDiagnostic/periodicStart'); // TODO: Using "delete" here breaks the minifier since this is a reserved keyword
}
function diagnosticAgent_installCheck(install) {
try {
var diag = require('service-manager').manager.getService('meshagentDiagnostic');
return (diag);
} catch (ex) { }
if (!install) { return null; }
var svc = null;
try {
require('service-manager').manager.installService(
{
name: 'meshagentDiagnostic',
displayName: "Mesh Agent Diagnostic Service",
description: "Mesh Agent Diagnostic Service",
servicePath: process.execPath,
parameters: ['-recovery']
//files: [{ newName: 'diagnostic.js', _buffer: Buffer.from('LyoNCkNvcHlyaWdodCAyMDE5IEludGVsIENvcnBvcmF0aW9uDQoNCkxpY2Vuc2VkIHVuZGVyIHRoZSBBcGFjaGUgTGljZW5zZSwgVmVyc2lvbiAyLjAgKHRoZSAiTGljZW5zZSIpOw0KeW91IG1heSBub3QgdXNlIHRoaXMgZmlsZSBleGNlcHQgaW4gY29tcGxpYW5jZSB3aXRoIHRoZSBMaWNlbnNlLg0KWW91IG1heSBvYnRhaW4gYSBjb3B5IG9mIHRoZSBMaWNlbnNlIGF0DQoNCiAgICBodHRwOi8vd3d3LmFwYWNoZS5vcmcvbGljZW5zZXMvTElDRU5TRS0yLjANCg0KVW5sZXNzIHJlcXVpcmVkIGJ5IGFwcGxpY2FibGUgbGF3IG9yIGFncmVlZCB0byBpbiB3cml0aW5nLCBzb2Z0d2FyZQ0KZGlzdHJpYnV0ZWQgdW5kZXIgdGhlIExpY2Vuc2UgaXMgZGlzdHJpYnV0ZWQgb24gYW4gIkFTIElTIiBCQVNJUywNCldJVEhPVVQgV0FSUkFOVElFUyBPUiBDT05ESVRJT05TIE9GIEFOWSBLSU5ELCBlaXRoZXIgZXhwcmVzcyBvciBpbXBsaWVkLg0KU2VlIHRoZSBMaWNlbnNlIGZvciB0aGUgc3BlY2lmaWMgbGFuZ3VhZ2UgZ292ZXJuaW5nIHBlcm1pc3Npb25zIGFuZA0KbGltaXRhdGlvbnMgdW5kZXIgdGhlIExpY2Vuc2UuDQoqLw0KDQp2YXIgaG9zdCA9IHJlcXVpcmUoJ3NlcnZpY2UtaG9zdCcpLmNyZWF0ZSgnbWVzaGFnZW50RGlhZ25vc3RpYycpOw0KdmFyIFJlY292ZXJ5QWdlbnQgPSByZXF1aXJlKCdNZXNoQWdlbnQnKTsNCg0KaG9zdC5vbignc2VydmljZVN0YXJ0JywgZnVuY3Rpb24gKCkNCnsNCiAgICBjb25zb2xlLnNldERlc3RpbmF0aW9uKGNvbnNvbGUuRGVzdGluYXRpb25zLkxPR0ZJTEUpOw0KICAgIGhvc3Quc3RvcCA9IGZ1bmN0aW9uKCkNCiAgICB7DQogICAgICAgIHJlcXVpcmUoJ3NlcnZpY2UtbWFuYWdlcicpLm1hbmFnZXIuZ2V0U2VydmljZSgnbWVzaGFnZW50RGlhZ25vc3RpYycpLnN0b3AoKTsNCiAgICB9DQogICAgUmVjb3ZlcnlBZ2VudC5vbignQ29ubmVjdGVkJywgZnVuY3Rpb24gKHN0YXR1cykNCiAgICB7DQogICAgICAgIGlmIChzdGF0dXMgPT0gMCkNCiAgICAgICAgew0KICAgICAgICAgICAgY29uc29sZS5sb2coJ0RpYWdub3N0aWMgQWdlbnQ6IFNlcnZlciBjb25uZWN0aW9uIGxvc3QuLi4nKTsNCiAgICAgICAgICAgIHJldHVybjsNCiAgICAgICAgfQ0KICAgICAgICBjb25zb2xlLmxvZygnRGlhZ25vc3RpYyBBZ2VudDogQ29ubmVjdGlvbiBFc3RhYmxpc2hlZCB3aXRoIFNlcnZlcicpOw0KICAgICAgICBzdGFydCgpOw0KICAgIH0pOw0KfSk7DQpob3N0Lm9uKCdub3JtYWxTdGFydCcsIGZ1bmN0aW9uICgpDQp7DQogICAgaG9zdC5zdG9wID0gZnVuY3Rpb24gKCkNCiAgICB7DQogICAgICAgIHByb2Nlc3MuZXhpdCgpOw0KICAgIH0NCiAgICBjb25zb2xlLmxvZygnTm9uIFNlcnZpY2UgTW9kZScpOw0KICAgIFJlY292ZXJ5QWdlbnQub24oJ0Nvbm5lY3RlZCcsIGZ1bmN0aW9uIChzdGF0dXMpDQogICAgew0KICAgICAgICBpZiAoc3RhdHVzID09IDApDQogICAgICAgIHsNCiAgICAgICAgICAgIGNvbnNvbGUubG9nKCdEaWFnbm9zdGljIEFnZW50OiBTZXJ2ZXIgY29ubmVjdGlvbiBsb3N0Li4uJyk7DQogICAgICAgICAgICByZXR1cm47DQogICAgICAgIH0NCiAgICAgICAgY29uc29sZS5sb2coJ0RpYWdub3N0aWMgQWdlbnQ6IENvbm5lY3Rpb24gRXN0YWJsaXNoZWQgd2l0aCBTZXJ2ZXInKTsNCiAgICAgICAgc3RhcnQoKTsNCiAgICB9KTsNCn0pOw0KaG9zdC5vbignc2VydmljZVN0b3AnLCBmdW5jdGlvbiAoKSB7IHByb2Nlc3MuZXhpdCgpOyB9KTsNCmhvc3QucnVuKCk7DQoNCg0KZnVuY3Rpb24gc3RhcnQoKQ0Kew0KDQp9Ow0K', 'base64') }]
});
svc = require('service-manager').manager.getService('meshagentDiagnostic');
}
catch (ex) { return null; }
var proxyConfig = require('global-tunnel').proxyConfig;
var cert = require('MeshAgent').GenerateAgentCertificate('CN=MeshNodeDiagnosticCertificate');
var nodeid = require('tls').loadCertificate(cert.root).getKeyHash().toString('base64');
ddb = require('SimpleDataStore').Create(svc.appWorkingDirectory().replace('\\', '/') + '/meshagentDiagnostic.db');
ddb.Put('disableUpdate', '1');
ddb.Put('MeshID', Buffer.from(require('MeshAgent').ServerInfo.MeshID, 'hex'));
ddb.Put('ServerID', require('MeshAgent').ServerInfo.ServerID);
ddb.Put('MeshServer', require('MeshAgent').ServerInfo.ServerUri);
if (cert.root.pfx) { ddb.Put('SelfNodeCert', cert.root.pfx); }
if (cert.tls) { ddb.Put('SelfNodeTlsCert', cert.tls.pfx); }
if (proxyConfig) {
ddb.Put('WebProxy', proxyConfig.host + ':' + proxyConfig.port);
} else {
ddb.Put('ignoreProxyFile', '1');
}
require('MeshAgent').SendCommand({ action: 'diagnostic', value: { command: 'register', value: nodeid } });
require('MeshAgent').SendCommand({ action: 'msg', type: 'console', value: "Diagnostic Agent Registered [" + nodeid.length + "/" + nodeid + "]" });
delete ddb;
// Set a recurrent task, to run the Diagnostic Agent every 2 days
require('task-scheduler').create({ name: 'meshagentDiagnostic/periodicStart', daily: 2, time: require('tls').generateRandomInteger('0', '23') + ':' + require('tls').generateRandomInteger('0', '59').padStart(2, '0'), service: 'meshagentDiagnostic' });
//require('task-scheduler').create({ name: 'meshagentDiagnostic/periodicStart', daily: '1', time: '17:16', service: 'meshagentDiagnostic' });
return (svc);
}
// Monitor the file 'batterystate.txt' in the agent's folder and sends battery update when this file is changed.
if ((require('fs').existsSync(process.cwd() + 'batterystate.txt')) && (require('fs').watch != null)) {
// Setup manual battery monitoring
require('MeshAgent')._batteryFileWatcher = require('fs').watch(process.cwd(), function () {
if (require('MeshAgent')._batteryFileTimer != null) return;
require('MeshAgent')._batteryFileTimer = setTimeout(function () {
try {
require('MeshAgent')._batteryFileTimer = null;
var data = null;
try { data = require('fs').readFileSync(process.cwd() + 'batterystate.txt').toString(); } catch (ex) { }
if ((data != null) && (data.length < 10)) {
data = data.split(',');
if ((data.length == 2) && ((data[0] == 'ac') || (data[0] == 'dc'))) {
var level = parseInt(data[1]);
if ((level >= 0) && (level <= 100)) { require('MeshAgent').SendCommand({ action: 'battery', state: data[0], level: level }); }
}
}
} catch (ex) { }
}, 1000);
});
}
else {
try {
// Setup normal battery monitoring
if (require('computer-identifiers').isBatteryPowered && require('computer-identifiers').isBatteryPowered()) {
require('MeshAgent')._battLevelChanged = function _battLevelChanged(val) {
_battLevelChanged.self._currentBatteryLevel = val;
_battLevelChanged.self.SendCommand({ action: 'battery', state: _battLevelChanged.self._currentPowerState, level: val });
};
require('MeshAgent')._battLevelChanged.self = require('MeshAgent');
require('MeshAgent')._powerChanged = function _powerChanged(val) {
_powerChanged.self._currentPowerState = (val == 'AC' ? 'ac' : 'dc');
_powerChanged.self.SendCommand({ action: 'battery', state: (val == 'AC' ? 'ac' : 'dc'), level: _powerChanged.self._currentBatteryLevel });
};
require('MeshAgent')._powerChanged.self = require('MeshAgent');
require('MeshAgent').on('Connected', function (status) {
if (status == 0) {
require('power-monitor').removeListener('acdc', this._powerChanged);
require('power-monitor').removeListener('batteryLevel', this._battLevelChanged);
} else {
require('power-monitor').on('acdc', this._powerChanged);
require('power-monitor').on('batteryLevel', this._battLevelChanged);
}
});
}
}
catch (ex) { }
}
// MeshAgent JavaScript Core Module. This code is sent to and running on the mesh agent.
var meshCoreObj = { action: 'coreinfo', value: (require('MeshAgent').coreHash ? ((process.versions.compileTime ? process.versions.compileTime : '').split(', ')[1].replace(' ', ' ') + ', ' + crc32c(require('MeshAgent').coreHash)) : ('MeshCore v6')), caps: 14, root: require('user-sessions').isRoot() }; // Capability bitmask: 1 = Desktop, 2 = Terminal, 4 = Files, 8 = Console, 16 = JavaScript, 32 = Temporary Agent, 64 = Recovery Agent
// Get the operating system description string
try { require('os').name().then(function (v) { meshCoreObj.osdesc = v; meshCoreObjChanged(); }); } catch (ex) { }
// Setup logged in user monitoring (THIS IS BROKEN IN WIN7)
function onUserSessionChanged(user, locked) {
userSession.enumerateUsers().then(function (users) {
if (process.platform == 'linux') {
if (userSession._startTime == null) {
userSession._startTime = Date.now();
userSession._count = users.length;
}
else if (Date.now() - userSession._startTime < 10000 && users.length == userSession._count) {
userSession.removeAllListeners('changed');
return;
}
}
var u = [], a = users.Active;
if(meshCoreObj.lusers == null) { meshCoreObj.lusers = []; }
for (var i = 0; i < a.length; i++) {
var un = a[i].Domain ? (a[i].Domain + '\\' + a[i].Username) : (a[i].Username);
if (user && locked && (JSON.stringify(a[i]) === JSON.stringify(user))) { if (meshCoreObj.lusers.indexOf(un) == -1) { meshCoreObj.lusers.push(un); } }
else if (user && !locked && (JSON.stringify(a[i]) === JSON.stringify(user))) { meshCoreObj.lusers.splice(meshCoreObj.lusers.indexOf(un), 1); }
if (u.indexOf(un) == -1) { u.push(un); } // Only push users in the list once.
}
meshCoreObj.lusers = meshCoreObj.lusers;
meshCoreObj.users = u;
meshCoreObjChanged();
});
}
try {
var userSession = require('user-sessions');
userSession.on('changed', function () { onUserSessionChanged(null, false); });
userSession.emit('changed');
userSession.on('locked', function (user) { if(user != undefined && user != null) { onUserSessionChanged(user, true); } });
userSession.on('unlocked', function (user) { if(user != undefined && user != null) { onUserSessionChanged(user, false); } });
} catch (ex) { }
var meshServerConnectionState = 0;
var tunnels = {};
var lastNetworkInfo = null;
var lastPublicLocationInfo = null;
var selfInfoUpdateTimer = null;
var http = require('http');
var net = require('net');
var fs = require('fs');
var rtc = require('ILibWebRTC');
var amt = null;
var processManager = require('process-manager');
var wifiScannerLib = null;
var wifiScanner = null;
var networkMonitor = null;
var nextTunnelIndex = 1;
var apftunnel = null;
var tunnelUserCount = { terminal: {}, files: {}, tcp: {}, udp: {}, msg: {} }; // List of userid->count sessions for terminal, files and TCP/UDP routing
// Add to the server event log
function MeshServerLog(msg, state) {
if (typeof msg == 'string') { msg = { action: 'log', msg: msg }; } else { msg.action = 'log'; }
if (state) {
if (state.userid) { msg.userid = state.userid; }
if (state.username) { msg.username = state.username; }
if (state.sessionid) { msg.sessionid = state.sessionid; }
if (state.remoteaddr) { msg.remoteaddr = state.remoteaddr; }
if (state.guestname) { msg.guestname = state.guestname; }
}
mesh.SendCommand(msg);
}
// Add to the server event log, use internationalized events
function MeshServerLogEx(id, args, msg, state) {
var msg = { action: 'log', msgid: id, msgArgs: args, msg: msg };
if (state) {
if (state.userid) { msg.userid = state.userid; }
if (state.xuserid) { msg.xuserid = state.xuserid; }
if (state.username) { msg.username = state.username; }
if (state.sessionid) { msg.sessionid = state.sessionid; }
if (state.remoteaddr) { msg.remoteaddr = state.remoteaddr; }
if (state.guestname) { msg.guestname = state.guestname; }
}
mesh.SendCommand(msg);
}
// Import libraries
db = require('SimpleDataStore').Shared();
sha = require('SHA256Stream');
mesh = require('MeshAgent');
childProcess = require('child_process');
if (mesh.hasKVM == 1) { // if the agent is compiled with KVM support
// Check if this computer supports a desktop
try {
if ((process.platform == 'win32') || (process.platform == 'darwin') || (require('monitor-info').kvm_x11_support)) {
meshCoreObj.caps |= 1; meshCoreObjChanged();
} else if (process.platform == 'linux' || process.platform == 'freebsd') {
require('monitor-info').on('kvmSupportDetected', function (value) { meshCoreObj.caps |= 1; meshCoreObjChanged(); });
}
} catch (ex) { }
}
mesh.DAIPC = obj.DAIPC;
/*
// Try to load up the network monitor
try {
networkMonitor = require('NetworkMonitor');
networkMonitor.on('change', function () { sendNetworkUpdateNagle(); });
networkMonitor.on('add', function (addr) { sendNetworkUpdateNagle(); });
networkMonitor.on('remove', function (addr) { sendNetworkUpdateNagle(); });
} catch (ex) { networkMonitor = null; }
*/
// Fetch the SMBios Tables
var SMBiosTables = null;
var SMBiosTablesRaw = null;
try {
var SMBiosModule = null;
try { SMBiosModule = require('smbios'); } catch (ex) { }
if (SMBiosModule != null) {
SMBiosModule.get(function (data) {
if (data != null) {
SMBiosTablesRaw = data;
SMBiosTables = require('smbios').parse(data)
if (mesh.isControlChannelConnected) { mesh.SendCommand({ action: 'smbios', value: SMBiosTablesRaw }); }
// If SMBios tables say that Intel AMT is present, try to connect MEI
if (SMBiosTables.amtInfo && (SMBiosTables.amtInfo.AMT == true)) {
var amtmodule = require('amt-manage');
amt = new amtmodule(mesh, db, false);
amt.on('portBinding_LMS', function (map) { mesh.SendCommand({ action: 'lmsinfo', value: { ports: map.keys() } }); });
amt.on('stateChange_LMS', function (v) { if (!meshCoreObj.intelamt) { meshCoreObj.intelamt = {}; } meshCoreObj.intelamt.microlms = v; meshCoreObjChanged(); }); // 0 = Disabled, 1 = Connecting, 2 = Connected
amt.onStateChange = function (state) { if (state == 2) { sendPeriodicServerUpdate(1); } } // MEI State
amt.reset();
}
}
});
}
} catch (ex) { sendConsoleText("ex1: " + ex); }
// Try to load up the WIFI scanner
try {
var wifiScannerLib = require('wifi-scanner');
wifiScanner = new wifiScannerLib();
wifiScanner.on('accessPoint', function (data) { sendConsoleText("wifiScanner: " + data); });
} catch (ex) { wifiScannerLib = null; wifiScanner = null; }
// Get our location (lat/long) using our public IP address
var getIpLocationDataExInProgress = false;
var getIpLocationDataExCounts = [0, 0];
function getIpLocationDataEx(func) {
if (getIpLocationDataExInProgress == true) { return false; }
try {
getIpLocationDataExInProgress = true;
getIpLocationDataExCounts[0]++;
var options = http.parseUri("http://ipinfo.io/json");
options.method = 'GET';
http.request(options, function (resp) {
if (resp.statusCode == 200) {
var geoData = '';
resp.data = function (geoipdata) { geoData += geoipdata; };
resp.end = function () {
var location = null;
try {
if (typeof geoData == 'string') {
var result = JSON.parse(geoData);
if (result.ip && result.loc) { location = result; }
}
} catch (ex) { }
if (func) { getIpLocationDataExCounts[1]++; func(location); }
}
} else
{ func(null); }
getIpLocationDataExInProgress = false;
}).end();
return true;
}
catch (ex) { return false; }
}
// Remove all Gateway MAC addresses for interface list. This is useful because the gateway MAC is not always populated reliably.
function clearGatewayMac(str) {
if (typeof str != 'string') return null;
var x = JSON.parse(str);
for (var i in x.netif) { try { if (x.netif[i].gatewaymac) { delete x.netif[i].gatewaymac } } catch (ex) { } }
return JSON.stringify(x);
}
function getIpLocationData(func) {
// Get the location information for the cache if possible
var publicLocationInfo = db.Get('publicLocationInfo');
if (publicLocationInfo != null) { publicLocationInfo = JSON.parse(publicLocationInfo); }
if (publicLocationInfo == null) {
// Nothing in the cache, fetch the data
getIpLocationDataEx(function (locationData) {
if (locationData != null) {
publicLocationInfo = {};
publicLocationInfo.netInfoStr = lastNetworkInfo;
publicLocationInfo.locationData = locationData;
var x = db.Put('publicLocationInfo', JSON.stringify(publicLocationInfo)); // Save to database
if (func) func(locationData); // Report the new location
}
else {
if (func) func(null); // Report no location
}
});
}
else {
// Check the cache
if (clearGatewayMac(publicLocationInfo.netInfoStr) == clearGatewayMac(lastNetworkInfo)) {
// Cache match
if (func) func(publicLocationInfo.locationData);
}
else {
// Cache mismatch
getIpLocationDataEx(function (locationData) {
if (locationData != null) {
publicLocationInfo = {};
publicLocationInfo.netInfoStr = lastNetworkInfo;
publicLocationInfo.locationData = locationData;
var x = db.Put('publicLocationInfo', JSON.stringify(publicLocationInfo)); // Save to database
if (func) func(locationData); // Report the new location
}
else {
if (func) func(publicLocationInfo.locationData); // Can't get new location, report the old location
}
});
}
}
}
// Polyfill String.endsWith
if (!String.prototype.endsWith) {
String.prototype.endsWith = function (searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; }
position -= searchString.length;
var lastIndex = subjectString.lastIndexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
// Polyfill path.join
obj.path =
{
join: function () {
var x = [];
for (var i in arguments) {
var w = arguments[i];
if (w != null) {
while (w.endsWith('/') || w.endsWith('\\')) { w = w.substring(0, w.length - 1); }
if (i != 0) {
while (w.startsWith('/') || w.startsWith('\\')) { w = w.substring(1); }
}
x.push(w);
}
}
if (x.length == 0) return '/';
return x.join('/');
}
};
// Replace a string with a number if the string is an exact number
function toNumberIfNumber(x) { if ((typeof x == 'string') && (+parseInt(x) === x)) { x = parseInt(x); } return x; }
// Convert decimal to hex
function char2hex(i) { return (i + 0x100).toString(16).substr(-2).toUpperCase(); }
// Convert a raw string to a hex string
function rstr2hex(input) { var r = '', i; for (i = 0; i < input.length; i++) { r += char2hex(input.charCodeAt(i)); } return r; }
// Convert a buffer into a string
function buf2rstr(buf) { var r = ''; for (var i = 0; i < buf.length; i++) { r += String.fromCharCode(buf[i]); } return r; }
// Convert a hex string to a raw string // TODO: Do this using Buffer(), will be MUCH faster
function hex2rstr(d) {
if (typeof d != "string" || d.length == 0) return '';
var r = '', m = ('' + d).match(/../g), t;
while (t = m.shift()) r += String.fromCharCode('0x' + t);
return r
}
// Convert an object to string with all functions
function objToString(x, p, pad, ret) {
if (ret == undefined) ret = '';
if (p == undefined) p = 0;
if (x == null) { return '[null]'; }
if (p > 8) { return '[...]'; }
if (x == undefined) { return '[undefined]'; }
if (typeof x == 'string') { if (p == 0) return x; return '"' + x + '"'; }
if (typeof x == 'buffer') { return '[buffer]'; }
if (typeof x != 'object') { return x; }
var r = '{' + (ret ? '\r\n' : ' ');
for (var i in x) { if (i != '_ObjectID') { r += (addPad(p + 2, pad) + i + ': ' + objToString(x[i], p + 2, pad, ret) + (ret ? '\r\n' : ' ')); } }
return r + addPad(p, pad) + '}';
}
// Return p number of spaces
function addPad(p, ret) { var r = ''; for (var i = 0; i < p; i++) { r += ret; } return r; }
// Split a string taking into account the quoats. Used for command line parsing
function splitArgs(str) {
var myArray = [], myRegexp = /[^\s"]+|"([^"]*)"/gi;
do { var match = myRegexp.exec(str); if (match != null) { myArray.push(match[1] ? match[1] : match[0]); } } while (match != null);
return myArray;
}
// Parse arguments string array into an object
function parseArgs(argv) {
var results = { '_': [] }, current = null;
for (var i = 1, len = argv.length; i < len; i++) {
var x = argv[i];
if (x.length > 2 && x[0] == '-' && x[1] == '-') {
if (current != null) { results[current] = true; }
current = x.substring(2);
} else {
if (current != null) { results[current] = toNumberIfNumber(x); current = null; } else { results['_'].push(toNumberIfNumber(x)); }
}
}
if (current != null) { results[current] = true; }
return results;
}
// Get server target url with a custom path
function getServerTargetUrl(path) {
var x = mesh.ServerUrl;
if (x == null) { return null; }
if (path == null) { path = ''; }