forked from BELABOX/belaUI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbelaUI.js
2074 lines (1747 loc) · 54.4 KB
/
belaUI.js
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
/*
belaUI - web UI for the BELABOX project
Copyright (C) 2020-2022 BELABOX project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
const http = require('http');
const finalhandler = require('finalhandler');
const serveStatic = require('serve-static');
const ws = require('ws');
const { exec, execSync, spawn, spawnSync, execFileSync, execFile } = require("child_process");
const fs = require('fs')
const crypto = require('crypto');
const path = require('path');
const dns = require('dns');
const bcrypt = require('bcrypt');
const process = require('process');
const util = require('util');
const SETUP_FILE = 'setup.json';
const CONFIG_FILE = 'config.json';
const AUTH_TOKENS_FILE = 'auth_tokens.json';
const BCRYPT_ROUNDS = 10;
const ACTIVE_TO = 15000;
/* Disable localization for any CLI commands we run */
process.env['LANG'] = 'C.UTF-8';
/* Make sure apt-get doesn't expect any interactive user input */
process.env['DEBIAN_FRONTEND'] = 'noninteractive';
/* Read the config and setup files */
const setup = JSON.parse(fs.readFileSync(SETUP_FILE, 'utf8'));
console.log(setup);
let belacoderExec, belacoderPipelinesDir;
if (setup.belacoder_path) {
belacoderExec = setup.belacoder_path + '/belacoder';
belacoderPipelinesDir = setup.belacoder_path + '/pipeline';
} else {
belacoderExec = "/usr/bin/belacoder";
belacoderPipelinesDir = "/usr/share/belacoder/pipelines";
}
let srtlaSendExec;
if (setup.srtla_path) {
srtlaSendExec = setup.srtla_path + '/srtla_send';
} else {
srtlaSendExec = "/usr/bin/srtla_send";
}
function checkExecPath(path) {
try {
fs.accessSync(path, fs.constants.R_OK);
} catch (err) {
console.log(`\n\n${path} not found, double check the settings in setup.json`);
process.exit(1);
}
}
checkExecPath(belacoderExec);
checkExecPath(srtlaSendExec);
/* Read the revision numbers */
function getRevision(cmd) {
try {
return execSync(cmd).toString().trim();
} catch (err) {
return 'unknown revision';
}
}
const revisions = {};
try {
revisions['belaUI'] = fs.readFileSync('revision', 'utf8');
} catch(err) {
revisions['belaUI'] = getRevision('git rev-parse --short HEAD');
}
revisions['belacoder'] = getRevision(`${belacoderExec} -v`);
revisions['srtla'] = getRevision(`${srtlaSendExec} -v`);
// Only show a BELABOX image version if it exists
try {
revisions['BELABOX image'] = fs.readFileSync('/etc/belabox_img_version', 'utf8').trim();
} catch(err) {};
console.log(revisions);
let config;
let sshPasswordHash;
try {
config = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
console.log(config);
sshPasswordHash = config.ssh_pass_hash;
delete config.ssh_pass_hash;
} catch (err) {
console.log(`Failed to open the config file: ${err.message}. Creating an empty config`);
config = {};
}
/* tempTokens stores temporary login tokens in memory,
persistentTokens stores login tokens to the disc */
const tempTokens = {};
let persistentTokens;
try {
persistentTokens = JSON.parse(fs.readFileSync(AUTH_TOKENS_FILE, 'utf8'));
} catch(err) {
persistentTokens = {};
}
function saveConfig() {
config.ssh_pass_hash = sshPasswordHash;
const c = JSON.stringify(config);
delete config.ssh_pass_hash;
fs.writeFileSync(CONFIG_FILE, c);
}
function savePersistentTokens() {
fs.writeFileSync(AUTH_TOKENS_FILE, JSON.stringify(persistentTokens));
}
/* Initialize the server */
const staticHttp = serveStatic("public");
const server = http.createServer(function(req, res) {
const done = finalhandler(req, res);
staticHttp(req, res, done);
});
const wss = new ws.Server({ server });
wss.on('connection', function connection(conn) {
conn.lastActive = getms();
if (!config.password_hash) {
conn.send(buildMsg('status', {set_password: true}));
}
conn.on('message', function incoming(msg) {
try {
msg = JSON.parse(msg);
handleMessage(conn, msg);
} catch (err) {
console.log(`Error parsing client message: ${err.message}`);
}
});
});
/* Misc helpers */
const oneMinute = 60 * 1000;
const oneHour = 60 * oneMinute;
const oneDay = 24 * oneHour;
function getms() {
const [sec, ns] = process.hrtime();
return sec * 1000 + Math.floor(ns / 1000 / 1000);
}
async function readTextFile(file) {
const readFile = util.promisify(fs.readFile);
const contents = await readFile(file).catch(function(err) {return undefined});
if (contents === undefined) return;
return contents.toString('utf8');
}
async function writeTextFile(file, contents) {
const writeFile = util.promisify(fs.writeFile);
await writeFile(file, contents).catch(function() {return false});
return true;
}
/* WS helpers */
function buildMsg(type, data, id = undefined) {
const obj = {};
obj[type] = data;
obj.id = id;
return JSON.stringify(obj);
}
function broadcastMsgLocal(type, data, activeMin = 0, except = undefined) {
const msg = buildMsg(type, data);
for (const c of wss.clients) {
if (c !== except && c.lastActive >= activeMin && c.isAuthed) c.send(msg);
}
return msg;
}
function broadcastMsg(type, data, activeMin = 0) {
const msg = broadcastMsgLocal(type, data, activeMin);
if (remoteWs && remoteWs.isAuthed) {
remoteWs.send(msg);
}
}
function broadcastMsgExcept(conn, type, data) {
broadcastMsgLocal(type, data, 0, conn);
if (remoteWs && remoteWs.isAuthed) {
const msg = buildMsg(type, data, conn.senderId);
remoteWs.send(msg);
}
}
/* Read the list of pipeline files */
function readDirAbsPath(dir) {
const files = fs.readdirSync(dir);
const basename = path.basename(dir);
const pipelines = {};
for (const f in files) {
const name = basename + '/' + files[f];
const id = crypto.createHash('sha1').update(name).digest('hex');
const path = dir + files[f];
pipelines[id] = {name: name, path: path};
}
return pipelines;
}
function getPipelines() {
const ps = {};
if (setup['hw'] == 'jetson') {
Object.assign(ps, readDirAbsPath(belacoderPipelinesDir + '/jetson/'));
}
Object.assign(ps, readDirAbsPath(belacoderPipelinesDir + '/generic/'));
return ps;
}
function searchPipelines(id) {
const pipelines = getPipelines();
if (pipelines[id]) return pipelines[id].path;
return null;
}
// pipeline list in the format needed by the frontend
function getPipelineList() {
const pipelines = getPipelines();
const list = {};
for (const id in pipelines) {
list[id] = pipelines[id].name;
}
return list;
}
/* Network interface list */
let netif = {};
function setNetifError(int, err) {
int.enabled = false;
int.error = err;
}
function setNetifDup(int) {
setNetifError(int, 'duplicate IP addr');
}
function updateNetif() {
exec("ifconfig", (error, stdout, stderr) => {
if (error) {
console.log(error.message);
return;
}
let intsChanged = false;
const newints = {};
wiFiDeviceListStartUpdate();
const interfaces = stdout.split("\n\n");
for (const int of interfaces) {
try {
const name = int.split(':')[0];
let inetAddr = int.match(/inet (\d+\.\d+\.\d+\.\d+)/);
if (inetAddr) inetAddr = inetAddr[1];
// update the list of WiFi devices
if (name && name.match('^wlan')) {
let hwAddr = int.match(/ether ([0-9a-f:]+)/);
if (hwAddr) {
wiFiDeviceListAdd(name, hwAddr[1], inetAddr);
}
}
if (name == 'lo' || name.match('^docker') || name.match('^l4tbr')) continue;
if (!inetAddr) continue;
const flags = int.match(/flags=\d+<([A-Z,]+)>/)[1].split(',');
if (!flags.includes('RUNNING')) continue;
let txBytes = int.match(/TX packets \d+ bytes \d+/);
txBytes = parseInt(txBytes[0].split(' ').pop());
if (netif[name]) {
tp = txBytes - netif[name]['txb'];
} else {
tp = 0;
}
const enabled = (netif[name] && netif[name].enabled == false) ? false : true;
const error = netif[name] ? netif[name].error : undefined;
newints[name] = {ip: inetAddr, txb: txBytes, tp, enabled, error};
// Detect interfaces that are new or with a different address
if (!netif[name] || netif[name].ip != inetAddr) {
intsChanged = true;
}
} catch (err) {};
}
// Detect removed interfaces
for (const i in netif) {
if (!newints[i]) {
intsChanged = true;
}
}
if (intsChanged) {
const intAddrs = {};
// Detect duplicate IP adddresses and set error status
for (const i in newints) {
const int = newints[i];
delete int.error;
if (intAddrs[int.ip] === undefined) {
intAddrs[int.ip] = i;
} else {
if (Array.isArray(intAddrs[int.ip])) {
intAddrs[int.ip].push(i);
} else {
setNetifDup(newints[intAddrs[int.ip]]);
intAddrs[int.ip] = [intAddrs[int.ip], i];
}
setNetifDup(int);
}
}
// Send out an error message for duplicate IP addresses
let msg = '';
for (const d in intAddrs) {
if (Array.isArray(intAddrs[d])) {
if (msg != '') {
msg += '; ';
}
msg += `Interfaces ${intAddrs[d].join(', ')} can't be used because they share the same IP address: ${d}`;
}
}
if (msg == '') {
notificationRemove('netif_dup_ip');
} else {
notificationBroadcast('netif_dup_ip', 'error', msg, 0, true, true);
}
}
if (wiFiDeviceListEndUpdate()) {
console.log("updated wifi devices");
// a delay seems to be needed before NM registers new devices
setTimeout(wifiUpdateDevices, 1000);
}
netif = newints;
if (intsChanged && isStreaming) {
updateSrtlaIps();
}
broadcastMsg('netif', netif, getms() - ACTIVE_TO);
});
}
updateNetif();
setInterval(updateNetif, 1000);
function countActiveNetif() {
let count = 0;
for (const int in netif) {
if (netif[int].enabled) count++;
}
return count;
}
function handleNetif(conn, msg) {
const int = netif[msg['name']];
if (!int) return;
if (int.ip != msg.ip) return;
if (msg['enabled'] === true || msg['enabled'] === false) {
if (!msg['enabled'] && int.enabled && countActiveNetif() == 1) {
notificationSend(conn, "netif_disable_all", "error", "Can't disable all networks", 10);
} else if (msg['enabled'] && int.error) {
notificationSend(conn, "netif_enable_error", "error", `Can't enable ${msg['name']}: ${int.error}`, 10);
} else {
int.enabled = msg['enabled'];
if (isStreaming) {
updateSrtlaIps();
}
}
}
conn.send(buildMsg('netif', netif));
}
/*
WiFi device list / status maintained by periodic ifconfig updates
It tracks and detects changes by device name, physical (MAC) addresses and
IPv4 address. It allows us to only update the WiFi status via nmcli when
something has changed, because NM is very CPU / power intensive compared
to the periodic ifconfig polling that belaUI is already doing
*/
let wifiDeviceHwAddr = {};
let wiFiDeviceListIsModified = false;
let wiFiDeviceListIsUpdating = false;
function wiFiDeviceListStartUpdate() {
if (wiFiDeviceListIsUpdating) {
throw "Called while an update was already in progress";
}
for (const i in wifiDeviceHwAddr) {
wifiDeviceHwAddr[i].removed = true;
}
wiFiDeviceListIsUpdating = true;
wiFiDeviceListIsModified = false
}
function wiFiDeviceListAdd(ifname, hwAddr, inetAddr) {
if (!wiFiDeviceListIsUpdating) {
throw "Called without starting an update";
}
if (wifiDeviceHwAddr[ifname]) {
if (wifiDeviceHwAddr[ifname].hwAddr != hwAddr) {
wifiDeviceHwAddr[ifname].hwAddr = hwAddr;
wiFiDeviceListIsModified = true;
}
if (wifiDeviceHwAddr[ifname].inetAddr != inetAddr) {
wifiDeviceHwAddr[ifname].inetAddr = inetAddr;
wiFiDeviceListIsModified = true;
}
wifiDeviceHwAddr[ifname].removed = false;
} else {
wifiDeviceHwAddr[ifname] = {
hwAddr,
inetAddr
};
wiFiDeviceListIsModified = true;
}
}
function wiFiDeviceListEndUpdate() {
if (!wiFiDeviceListIsUpdating) {
throw "Called without starting an update";
}
for (const i in wifiDeviceHwAddr) {
if (wifiDeviceHwAddr[i].removed) {
delete wifiDeviceHwAddr[i];
wiFiDeviceListIsModified = true;
}
}
wiFiDeviceListIsUpdating = false;
return wiFiDeviceListIsModified;
}
function wifiDeviceListGetAddr(ifname) {
if (wifiDeviceHwAddr[ifname]) {
return wifiDeviceHwAddr[ifname].hwAddr;
}
}
/* NetworkManager / nmcli helpers */
function nmConnsGet(fields) {
try {
const result = execFileSync("nmcli", [
"--terse",
"--fields",
fields,
"connection",
"show",
]).toString("utf-8").split("\n");
return result;
} catch ({message}) {
console.log(`nmConnsGet err: ${message}`);
}
}
function nmConnGetFields(uuid, fields) {
try {
const result = execFileSync("nmcli", [
"--terse",
"--escape", "no",
"--get-values",
fields,
"connection",
"show",
uuid,
]).toString("utf-8").split("\n");
return result;
} catch ({message}) {
console.log(`nmConnGetFields err: ${message}`);
}
}
function nmConnDelete(uuid, callback) {
execFile("nmcli", ["conn", "del", uuid], function (error, stdout, stderr) {
let success = true;
if (error || !stdout.match("successfully deleted")) {
console.log(`nmConnDelete err: ${stdout}`);
success = false;
}
if (callback) {
callback(success);
}
});
}
function nmConnect(uuid, callback) {
execFile("nmcli", ["conn", "up", uuid], function (error, stdout, stderr) {
let success = true;
if (error || !stdout.match("^Connection successfully activated")) {
console.log(`nmConnect err: ${stdout}`);
success = false;
}
if (callback) {
callback(success);
}
});
}
function nmDisconnect(uuid, callback) {
execFile("nmcli", ["conn", "down", uuid], function (error, stdout, stderr) {
let success = true;
if (error || !stdout.match("successfully deactivated")) {
console.log(`nmDisconnect err: ${stdout}`);
success = false;
}
if (callback) {
callback(success);
}
});
}
function nmDevices(fields) {
try {
const result = execFileSync("nmcli", [
"--terse",
"--fields",
fields,
"device",
"status",
]).toString("utf-8").split("\n");
return result;
} catch ({message}) {
console.log(`nmDevices err: ${message}`);
}
}
function nmRescan(device, callback) {
const args = ["device", "wifi", "rescan"];
if (device) {
args.push("ifname");
args.push(device);
}
execFile("nmcli", args, function (error, stdout, stderr) {
let success = true;
if (error || stdout != "") {
console.log(`nmRescan err: ${stdout}`);
success = false;
}
if (callback) {
callback(success);
}
});
}
function nmScanResults(fields) {
try {
const result = execFileSync("nmcli", [
"--terse",
"--fields",
fields,
"device",
"wifi",
]).toString("utf-8").split("\n");
return result;
} catch ({message}) {
console.log(`nmScanResults err: ${message}`);
}
}
// parses : separated values, with automatic \ escape detection and stripping
function nmcliParseSep(value) {
return value.split(/(?<!\\):/).map(a => a.replace(/\\:/g, ':'));
}
/*
NetworkManager / nmcli based Wifi Manager
Structs:
WiFi list <wifiIfs>:
{
'mac': <wd>
}
WiFi id to MAC address mapping <wifiIdToHwAddr>:
{
id: 'mac'
}
Wifi device <wd>:
{
'id', // numeric id for the adapter - temporary for each belaUI execution
'ifname': 'wlanX',
'conn': 'uuid' or undefined; // the active connection
'available': Map{<an>},
'saved': {<sn>}
}
Available network <an>:
{
active, // is it currently connected?
ssid,
signal: 0-100,
security,
freq
}
Saved networks {<sn>}:
{
ssid: uuid,
}
*/
let wifiIfId = 0;
let wifiIfs = {};
let wifiIdToHwAddr = {};
/* Builds the WiFi status structure sent over the network from the <wd> structures */
function wifiBuildMsg() {
const ifs = {};
for (const i in wifiIfs) {
const id = wifiIfs[i].id;
const s = wifiIfs[i];
ifs[id] = {
ifname: s.ifname,
conn: s.conn,
available: Array.from(s.available.values()),
saved: s.saved
};
}
return ifs;
}
function wifiBroadcastState() {
broadcastMsg('status', {wifi: wifiBuildMsg()});
}
function wifiUpdateSavedConns() {
let connections = nmConnsGet("uuid,type");
if (connections === undefined) return;
for (const i in wifiIfs) {
wifiIfs[i].saved = {};
}
for (const connection of connections) {
try {
const [uuid, type] = nmcliParseSep(connection);
if (type !== "802-11-wireless") continue;
// Get the device the connection is bound to and the ssid
const [ssid, macTmp] = nmConnGetFields(uuid, "802-11-wireless.ssid,802-11-wireless.mac-address");
if (!ssid || !macTmp) continue;
const macAddr = macTmp.toLowerCase();
if (wifiIfs[macAddr]) {
wifiIfs[macAddr].saved[ssid] = uuid;
}
} catch (err) {
console.log(`Error getting the nmcli connection information: ${err.message}`);
}
}
}
function wifiUpdateScanResult() {
const wifiNetworks = nmScanResults("active,ssid,signal,security,freq,device");
if (!wifiNetworks) return;
for (const i in wifiIfs) {
wifiIfs[i].available = new Map();
}
for (const wifiNetwork of wifiNetworks) {
const [active, ssid, signal, security, freq, device] =
nmcliParseSep(wifiNetwork);
if (ssid == null || ssid == "") continue;
const hwAddr = wifiDeviceListGetAddr(device);
if (!wifiIfs[hwAddr] || (active != 'yes' && wifiIfs[hwAddr].available.has(ssid))) continue;
wifiIfs[hwAddr].available.set(ssid, {
active: (active == 'yes'),
ssid,
signal: parseInt(signal),
security,
freq: parseInt(freq),
});
}
wifiBroadcastState();
}
/*
The WiFi scan results are updated some time after a rescan command is issued /
some time after a new WiFi adapter is plugged in.
This function sets up a number of timers to broadcast the updated scan results
with the expectation that eventually it will capture any relevant new results
*/
function wifiScheduleScanUpdates() {
setTimeout(wifiUpdateScanResult, 1000);
setTimeout(wifiUpdateScanResult, 3000);
setTimeout(wifiUpdateScanResult, 5000);
setTimeout(wifiUpdateScanResult, 10000);
}
let unavailableDeviceRetryExpiry = 0;
function wifiUpdateDevices() {
let newDevices = false;
let statusChange = false;
let unavailableDevices = false;
let networkDevices = nmDevices("device,type,state,con-uuid");
if (!networkDevices) return;
// sorts the results alphabetically by interface name
networkDevices.sort();
// mark all WiFi adapters as removed
for (const i in wifiIfs) {
wifiIfs[i].removed = true;
}
// Rebuild the id-to-hwAddr map
wifiIdToHwAddr = {};
for (const networkDevice of networkDevices) {
try {
const [ifname, type, state, connUuid] = nmcliParseSep(networkDevice);
const conn = (connUuid != '') ? connUuid : null;
if (type !== "wifi") continue;
if (state == "unavailable") {
unavailableDevices = true;
continue;
}
const hwAddr = wifiDeviceListGetAddr(ifname);
if (!hwAddr) continue;
if (wifiIfs[hwAddr]) {
// the interface is still available
delete wifiIfs[hwAddr].removed;
if (ifname != wifiIfs[hwAddr].ifname) {
wifiIfs[hwAddr].ifname = ifname;
statusChange = true;
}
if (conn != wifiIfs[hwAddr].conn) {
wifiIfs[hwAddr].conn = conn;
statusChange = true;
}
} else {
const id = wifiIfId++;
wifiIfs[hwAddr] = {
id,
ifname,
conn,
available: new Map(),
saved: {}
};
newDevices = true;
statusChange = true;
}
wifiIdToHwAddr[wifiIfs[hwAddr].id] = hwAddr;
} catch (err) {
console.log(`Error getting the nmcli WiFi device information: ${err.message}`);
}
}
// delete removed adapters
for (const i in wifiIfs) {
if (wifiIfs[i].removed) {
delete wifiIfs[i];
statusChange = true;
}
}
if (newDevices) {
wifiUpdateSavedConns();
wifiScheduleScanUpdates();
}
if (statusChange) {
wifiUpdateScanResult();
}
if (newDevices || statusChange) {
wifiBroadcastState();
}
console.log(wifiIfs);
/* If some wifi adapters were marked unavailable, recheck periodically
This might happen when the system has just booted up and the adapter
typically becomes available within 30 seconds.
Uses a 5 minute timeout to avoid polling nmcli forever */
if (unavailableDevices) {
if (unavailableDeviceRetryExpiry == 0) {
unavailableDeviceRetryExpiry = getms() + 5 * 60 * 1000; // 5 minute timeout
setTimeout(wifiUpdateDevices, 3000);
console.log("One or more Wifi interfaces are unavailable. Will retry periodically for the next 5 minutes");
} else if (getms() < unavailableDeviceRetryExpiry) {
setTimeout(wifiUpdateDevices, 3000);
console.log("One or more Wifi interfaces are still unavailable. Retrying in 3 seconds...");
}
} else {
unavailableDeviceRetryExpiry = 0;
}
return statusChange;
}
function wifiRescan() {
nmRescan(undefined, function(success) {
/* A rescan request will fail if a previous one is in progress,
but we still attempt to update the results */
wifiUpdateScanResult();
wifiScheduleScanUpdates();
});
}
/* Searches saved connections in wifiIfs by UUID */
function wifiSearchConnection(uuid) {
let connFound;
for (const i in wifiIdToHwAddr) {
const macAddr = wifiIdToHwAddr[i];
for (const s in wifiIfs[macAddr].saved) {
if (wifiIfs[macAddr].saved[s] == uuid) {
connFound = i;
break;
}
}
}
return connFound;
}
function wifiDisconnect(uuid) {
if (wifiSearchConnection(uuid) === undefined) return;
nmDisconnect(uuid, function(success) {
if (success) {
wifiUpdateScanResult();
wifiScheduleScanUpdates();
}
});
}
function wifiForget(uuid) {
if (wifiSearchConnection(uuid) === undefined) return;
nmConnDelete(uuid, function(success) {
if (success) {
wifiUpdateSavedConns();
wifiUpdateScanResult();
wifiScheduleScanUpdates();
}
});
}
function wifiDeleteFailedConns() {
const connections = nmConnsGet("uuid,type,timestamp");
for (const c in connections) {
const [uuid, type, ts] = nmcliParseSep(connections[c]);
if (type !== "802-11-wireless") continue;
if (ts == 0) {
nmConnDelete(uuid);
}
}
}
function wifiNew(conn, msg) {
if (!msg.device || !msg.ssid) return;
if (!wifiIdToHwAddr[msg.device]) return;
const device = wifiIfs[wifiIdToHwAddr[msg.device]].ifname;
const args = [
"-w",
"15",
"device",
"wifi",
"connect",
msg.ssid,
"ifname",
device
];
if (msg.password) {
args.push('password');
args.push(msg.password);
}
const senderId = conn.senderId;
execFile("nmcli", args, function(error, stdout, stderr) {
if (error || stdout.match('^Error:')) {
wifiDeleteFailedConns();
if (stdout.match('Secrets were required, but not provided')) {
conn.send(buildMsg('wifi', {new: {error: "auth", device: msg.device}}, senderId));
} else {
conn.send(buildMsg('wifi', {new: {error: "generic", device: msg.device}}, senderId));
}
} else if (stdout.match('successfully activated')) {
wifiUpdateSavedConns();
wifiUpdateScanResult();
conn.send(buildMsg('wifi', {new: {success: true, device: msg.device}}, senderId));
}
});
}
function wifiConnect(conn, uuid) {
const deviceId = wifiSearchConnection(uuid);
if (deviceId === undefined) return;
const senderId = conn.senderId;
nmConnect(uuid, function(success) {
wifiUpdateScanResult();
conn.send(buildMsg('wifi', {connect: success, device: deviceId}, senderId));
});
}
function handleWifi(conn, msg) {
for (const type in msg) {
switch(type) {
case 'connect':
wifiConnect(conn, msg[type]);
break;
case 'disconnect':
wifiDisconnect(msg[type]);
break;
case 'scan':
wifiRescan();
break;
case 'new':
wifiNew(conn, msg[type]);
break;
case 'forget':
wifiForget(msg[type]);
break;
}
}
}