-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
belaUI.js
4516 lines (3825 loc) · 125 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 { Resolver} = require('dns');
const bcrypt = require('bcrypt');
const process = require('process');
const util = require('util');
const assert = require('assert');
const SETUP_FILE = 'setup.json';
const CONFIG_FILE = 'config.json';
const AUTH_TOKENS_FILE = 'auth_tokens.json';
const RELAYS_CACHE_FILE = 'relays_cache.json';
const GSM_OPERATORS_CACHE_FILE = 'gsm_operator_cache.json';
const DNS_CACHE_FILE = 'dns_cache.json';
/* Minimum age of an updated record to trigger a persistent DNS cache update (in ms)
Some records change with almost every query if using CDNs, etc
This limits the frequency of file writes */
const DNS_MIN_AGE = 60000; // in ms
const DNS_TIMEOUT = 2000; // in ms
const DNS_WELLKNOWN_NAME = 'wellknown.belabox.net';
const DNS_WELLKNOWN_ADDR = '127.1.33.7';
const CONNECTIVITY_CHECK_DOMAIN = 'www.gstatic.com';
const CONNECTIVITY_CHECK_PATH = '/generate_204';
const CONNECTIVITY_CHECK_CODE = 204;
const CONNECTIVITY_CHECK_BODY = '';
const BCRYPT_ROUNDS = 10;
const ACTIVE_TO = 15000;
/* Disable localization for any CLI commands we run */
process.env['LANG'] = 'C.UTF-8';
process.env['LANGUAGE'] = 'C';
/* 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 passwordHash;
let sshPasswordHash;
try {
config = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
console.log(config);
passwordHash = config.password_hash;
sshPasswordHash = config.ssh_pass_hash;
delete config.password_hash;
delete config.ssh_pass_hash;
} catch (err) {
console.log(`Failed to open the config file: ${err.message}. Creating an empty config`);
config = {};
// Configure the default audio source depending on the platform
switch (setup.hw) {
case 'jetson':
config.asrc = fs.existsSync('/dev/hdmi_capture') ? 'HDMI' : 'C4K';
break;
case 'rk3588':
config.asrc = fs.existsSync('/dev/hdmirx') ? 'HDMI' : 'USB audio';
break;
}
}
/* 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.password_hash = passwordHash;
config.ssh_pass_hash = sshPasswordHash;
const c = JSON.stringify(config);
delete config.password_hash;
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 (!passwordHash) {
conn.send(buildMsg('status', {set_password: true}));
}
notificationSendPersistent(conn, false);
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;
}
const execP = util.promisify(exec);
const execFileP = util.promisify(execFile);
// Promise-based exec(), but without rejections
async function execPNR(cmd) {
try {
const res = await execP(cmd);
return {stdout: res.stdout, stderr: res.stderr, code: 0};
} catch (err) {
return {stdout: err.stdout, stderr: err.stderr, code: err.code};
}
}
const readdirP = util.promisify(fs.readdir);
/* 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, authedOnly = true) {
const msg = buildMsg(type, data);
for (const c of wss.clients) {
if (c !== except && c.lastActive >= activeMin && (authedOnly === false || c.isAuthed)) c.send(msg);
}
return msg;
}
function broadcastMsg(type, data, activeMin = 0, authedOnly = true) {
const msg = broadcastMsgLocal(type, data, activeMin, undefined, authedOnly);
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);
}
}
/* Network interface list */
let netif = {};
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];
const flags = int.match(/flags=\d+<([A-Z,]+)>/)[1].split(',');
const isRunning = flags.includes('RUNNING');
// 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], isRunning ? inetAddr : null);
}
}
if (name == 'lo' || name.match('^docker') || name.match('^l4tbr')) continue;
if (!inetAddr) continue;
if (!isRunning) 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 : 0;
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];
clearNetifDup(int);
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', netIfBuildMsg(), getms() - ACTIVE_TO);
});
}
updateNetif();
setInterval(updateNetif, 1000);
const NETIF_ERR_DUPIPV4 = 0x01;
const NETIF_ERR_HOTSPOT = 0x02;
// The order is deliberate, we want *hotspot* to have higher priority
const netIfErrors = {
2: 'WiFi hotspot',
1: 'duplicate IPv4 addr'
}
function setNetifError(int, err) {
if (!int) return;
int.enabled = false;
int.error |= err;
}
function clearNetifError(int, err) {
if (!int) return;
int.error &= ~err;
}
function setNetifDup(int) {
setNetifError(int, NETIF_ERR_DUPIPV4);
}
function clearNetifDup(int) {
clearNetifError(int, NETIF_ERR_DUPIPV4);
}
function setNetifHotspot(int) {
setNetifError(int, NETIF_ERR_HOTSPOT);
}
function netIfGetErrorMsg(i) {
if (i.error == 0) return;
for (const e in netIfErrors) {
if (i.error & e) return netIfErrors[e];
}
}
function netIfBuildMsg() {
const m = {};
for (const i in netif) {
m[i] = {ip: netif[i].ip, tp: netif[i].tp, enabled: netif[i].enabled};
const error = netIfGetErrorMsg(netif[i]);
if (error) {
m[i].error = error;
}
}
return m;
}
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) {
const err = netIfGetErrorMsg(int);
if (err) {
notificationSend(conn, "netif_enable_error", "error", `Can't enable ${msg.name}: ${err}`, 10);
return;
}
} else {
if (int.enabled && countActiveNetif() == 1) {
notificationSend(conn, "netif_disable_all", "error", "Can't disable all networks", 10);
return;
}
}
int.enabled = msg.enabled;
if (isStreaming) {
updateSrtlaIps();
}
}
conn.send(buildMsg('netif', netIfBuildMsg()));
}
/*
DNS utils w/ a persistent cache
*/
/*
dns.Resolver uses c-ares, with each instance (and the global
dns.resolve*() functions) mapped one-to-one to a c-ares channel
c-ares channels re-use the underlying UDP sockets for multi queries,
which is good for performance but the incorrect behaviour for us, as
it can end up trying to use stale connections long after we change
the default route after a network becomes unavailable
For simplicity, we create a new instance for each query unless one
is provided by the caller. The callers shouldn't reuse Resolver
instances for unrelated queries as we call resolver.cancel() on
timeout, which will make all pending queries time out.
*/
function resolveP(hostname, rrtype = undefined, resolver = undefined) {
if (rrtype !== undefined && rrtype !== 'a' && rrtype !== 'aaaa') {
throw(`invalid rrtype ${rrtype}`);
}
if (!resolver) {
resolver = new Resolver();
}
return new Promise(function(resolve, reject) {
let to;
if (DNS_TIMEOUT) {
to = setTimeout(function() {
resolver.cancel();
reject(`DNS timeout for ${hostname}`);
}, DNS_TIMEOUT);
}
let ipv4Res;
if (rrtype === undefined || rrtype == 'a') {
resolver.resolve4(hostname, {}, function(err, address) {
ipv4Res = err ? null : address;
returnResults();
});
}
let ipv6Res;
if (rrtype === undefined || rrtype == 'aaaa') {
resolver.resolve6(hostname, {}, function(err, address) {
ipv6Res = err ? null : address;
returnResults();
});
}
const returnResults = function() {
// If querying both for A and AAAA records, wait for the IPv4 result
if (rrtype === undefined && ipv4Res === undefined) return;
let res;
if (ipv4Res) {
res = ipv4Res;
} else if (ipv6Res) {
res = ipv6Res;
}
if (res) {
if (to) {
clearTimeout(to);
}
resolve(res);
} else {
reject(`DNS record not found for ${hostname}`);
}
}
});
}
let dnsCache = {};
let dnsResults = {};
try {
dnsCache = JSON.parse(fs.readFileSync(DNS_CACHE_FILE, 'utf8'));
} catch(err) {
console.log("Failed to load the persistent DNS cache, starting with an empty cache");
}
function isIpv4Addr(val) {
return val.match(/^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/) != null;
}
async function dnsCacheResolve(name, rrtype = undefined) {
if (rrtype) {
rrtype = rrtype.toLowerCase();
if (rrtype !== 'a' && rrtype !== 'aaaa') {
throw('Invalid rrtype');
}
}
if (isIpv4Addr(name) && rrtype != 'aaaa') {
return {addrs: [name], fromCache: false};
}
let badDns = true;
// Reuse the Resolver instance for the actual query after a succesful validation
const resolver = new Resolver();
/* Assume that DNS resolving is broken, unless it returns
the expected result for a known name */
try {
const lookup = await resolveP(DNS_WELLKNOWN_NAME, 'a', resolver);
if (lookup.length == 1 && lookup[0] == DNS_WELLKNOWN_ADDR) {
badDns = false;
} else {
console.log(`DNS validation failure: got result ${lookup} instead of the expected ${DNS_WELLKNOWN_ADDR}`);
}
} catch(e) {
console.log(`DNS validation failure: ${e}`);
}
if (badDns) {
delete dnsResults[name];
} else {
try {
const res = await resolveP(name, rrtype, resolver);
dnsResults[name] = res;
return {addrs: res, fromCache: false};
} catch(err) {
console.log('dns error ' + err);
}
}
if (dnsCache[name]) return {addrs: dnsCache[name].result, fromCache: true};
throw('DNS query failed and no cached value is available');
}
function compareArrayElements(a1, a2) {
if (!Array.isArray(a1) || !Array.isArray(a2)) return false;
const cmp = {};
for (e of a1) {
cmp[e] = false;
}
// check that all elements of a2 are in a1
for (e of a2) {
if (cmp[e] === undefined) {
return false;
}
cmp[e] = true;
}
// check that all elements of a1 are in a2
for (e in cmp) {
if (!cmp[e]) return false;
}
return true;
}
async function dnsCacheValidate(name) {
if (!dnsResults[name]) {
console.log(`DNS: error validating results for ${name}: not found`);
return;
}
if (!dnsCache[name] || !compareArrayElements(dnsResults[name], dnsCache[name].results)) {
let writeFile = true;
if (!dnsCache[name]) {
dnsCache[name] = {};
}
if (dnsCache[name].ts &&
(Date.now() - dnsCache[name].ts) < DNS_MIN_AGE) writeFile = false;
dnsCache[name].result = dnsResults[name];
if (writeFile) {
dnsCache[name].ts = Date.now();
await writeTextFile(DNS_CACHE_FILE, JSON.stringify(dnsCache));
}
}
}
/*
Check Internet connectivity and if needed update the default route
*/
function httpGet(options) {
return new Promise(function(resolve, reject) {
let to;
if (options.timeout) {
to = setTimeout(function() {
req.destroy();
reject('timeout');
}, options.timeout);
}
var req = http.get(options, function(res) {
let response = '';
res.on('data', function(d) {
response += d;
});
res.on('end', function() {
if (to) {
clearTimeout(to);
}
resolve( {code: res.statusCode, body: response} );
});
});
req.on('error', function(e) {
if (to) {
clearTimeout(to);
}
reject(e);
});
});
}
async function checkConnectivity(remoteAddr, localAddress) {
try {
let url = {};
url.headers = {'Host': CONNECTIVITY_CHECK_DOMAIN};
url.path = CONNECTIVITY_CHECK_PATH;
url.host = remoteAddr;
url.timeout = 4000;
if (localAddress) {
url.localAddress = localAddress;
}
const res = await httpGet(url);
if (res.code == CONNECTIVITY_CHECK_CODE && res.body == CONNECTIVITY_CHECK_BODY) {
return true;
}
} catch(err) {
console.log('Internet connectivity HTTP check error ' + (err.code || err));
}
return false;
}
async function clear_default_gws() {
try {
while(1) {
await execP("ip route del default");
}
} catch(err) {
return;
}
}
let updateGwLock = false;
let updateGwLastRun = 0;
let updateGwQueue = true;
function queueUpdateGw() {
updateGwQueue = true;
updateGwWrapper();
}
async function updateGw() {
try {
var {addrs, fromCache} = await dnsCacheResolve(CONNECTIVITY_CHECK_DOMAIN);
} catch (err) {
console.log(`Failed to resolve ${CONNECTIVITY_CHECK_DOMAIN}: ${err}`);
return false;
}
for (const addr of addrs) {
if (await checkConnectivity(addr)) {
if (!fromCache) dnsCacheValidate(CONNECTIVITY_CHECK_DOMAIN);
console.log('Internet reachable via the default route');
notificationRemove('no_internet');
return true;
}
}
const m = 'No Internet connectivity via the default connection, re-checking all connections...';
notificationBroadcast('no_internet', 'warning', m, 10, true, false);
let goodIf;
for (const addr of addrs) {
for (const i in netif) {
const error = netIfGetErrorMsg(netif[i]);
if (error) {
console.log(`Not probing internet connectivity via ${i} (${netif[i].ip}): ${error}`);
continue;
}
console.log(`Probing internet connectivity via ${i} (${netif[i].ip})`);
if (await checkConnectivity(addr, netif[i].ip)) {
console.log(`Internet reachable via ${i} (${netif[i].ip})`);
if (!fromCache) dnsCacheValidate(CONNECTIVITY_CHECK_DOMAIN);
goodIf = i;
break;
}
}
}
if (goodIf) {
try {
const gw = (await execP(`ip route show table ${goodIf} default`)).stdout;
await clear_default_gws();
const route = `ip route add ${gw}`;
await execP(route);
console.log(`Set default route: ${route}`);
notificationRemove('no_internet');
return true;
} catch (err) {
console.log(`Error updating the default route: ${err}`);
}
}
return false;
}
const UPDATE_GW_INT = 2000;
async function updateGwWrapper() {
// Do nothing if no request is queued
if (!updateGwQueue) return;
// Rate limit
const ts = getms();
const to = updateGwLastRun + UPDATE_GW_INT;
if (ts < to) return;
// Don't allow simultaneous execution
if (updateGwLock) return;
// Proceeding, update status
updateGwLastRun = ts;
updateGwLock = true;
updateGwQueue = false;
const r = await updateGw();
if (!r) {
updateGwQueue = true;
}
updateGwLock = false;
}
updateGwWrapper();
setInterval(updateGwWrapper, UPDATE_GW_INT);
/*
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 wifiDeviceListGetHwAddr(ifname) {
if (wifiDeviceHwAddr[ifname]) {
return wifiDeviceHwAddr[ifname].hwAddr;
}
}
function wifiDeviceListGetInetAddr(ifname) {
if (wifiDeviceHwAddr[ifname]) {
return wifiDeviceHwAddr[ifname].inetAddr;
}
}
/* NetworkManager / nmcli helpers */
async function nmConnAdd(fields) {
try {
let args = [
"connection",
"add"
];
for (const field in fields) {
args.push(field);
args.push(fields[field]);
}
const result = await execFileP("nmcli", args);
const success = result.stdout.match(/Connection '.+' \((.+)\) successfully added./);
if (success) return success[1];
} catch ({message}) {
console.log(`nmConnNew err: ${message}`);
}
}
async function nmConnsGet(fields) {
try {
const result = await execFileP("nmcli", [
"--terse",
"--fields",
fields,
"connection",
"show",
]);
return result.stdout.toString("utf-8").split("\n");
} catch ({message}) {
console.log(`nmConnsGet err: ${message}`);
}
}
async function nmConnGetFields(uuid, fields) {
try {
const result = await execFileP("nmcli", [
"--terse",
"--escape", "no",
"--show-secrets",
"--get-values",
fields,
"connection",
"show",
uuid,
]);
return result.stdout.toString("utf-8").split("\n");
} catch ({message}) {
console.log(`nmConnGetFields err: ${message}`);
}
}
async function nmConnSetFields(uuid, fields) {
try {
let args = [
"con",
"modify",
uuid,
];
for (const field in fields) {
args.push(field);
args.push(fields[field]);
}
const result = await execFileP("nmcli", args);
return (result.stdout == "");
} catch ({message}) {
console.log(`nmConnSetFields err: ${message}`);
}
return false;
}
async function nmConnSetWifiMac(uuid, mac) {
return nmConnSetFields(uuid, {'connection.interface-name': '', '802-11-wireless.mac-address': mac});
}
async function nmConnDelete(uuid) {
try {
const result = await execFileP("nmcli", ["conn", "del", uuid]);
return result.stdout.match("successfully deleted");
} catch ({message}) {
console.log(`nmConnDelete err: ${message}`);
}
return false;
}
async function nmConnect(uuid, timeout = undefined) {
try {