80d413e4d4aafc269db5e6ca2ed56e63c2f27a46
[project/luci.git] / modules / luci-base / htdocs / luci-static / resources / network.js
1 'use strict';
2 'require uci';
3 'require rpc';
4 'require validation';
5 'require baseclass';
6 'require firewall';
7
8 var proto_errors = {
9 CONNECT_FAILED: _('Connection attempt failed'),
10 INVALID_ADDRESS: _('IP address is invalid'),
11 INVALID_GATEWAY: _('Gateway address is invalid'),
12 INVALID_LOCAL_ADDRESS: _('Local IP address is invalid'),
13 MISSING_ADDRESS: _('IP address is missing'),
14 MISSING_PEER_ADDRESS: _('Peer address is missing'),
15 NO_DEVICE: _('Network device is not present'),
16 NO_IFACE: _('Unable to determine device name'),
17 NO_IFNAME: _('Unable to determine device name'),
18 NO_WAN_ADDRESS: _('Unable to determine external IP address'),
19 NO_WAN_LINK: _('Unable to determine upstream interface'),
20 PEER_RESOLVE_FAIL: _('Unable to resolve peer host name'),
21 PIN_FAILED: _('PIN code rejected')
22 };
23
24 var iface_patterns_ignore = [
25 /^wmaster\d+/,
26 /^wifi\d+/,
27 /^hwsim\d+/,
28 /^imq\d+/,
29 /^ifb\d+/,
30 /^mon\.wlan\d+/,
31 /^sit\d+/,
32 /^gre\d+/,
33 /^gretap\d+/,
34 /^ip6gre\d+/,
35 /^ip6tnl\d+/,
36 /^tunl\d+/,
37 /^lo$/
38 ];
39
40 var iface_patterns_wireless = [
41 /^wlan\d+/,
42 /^wl\d+/,
43 /^ath\d+/,
44 /^\w+\.network\d+/
45 ];
46
47 var iface_patterns_virtual = [ ];
48
49 var callLuciNetworkDevices = rpc.declare({
50 object: 'luci-rpc',
51 method: 'getNetworkDevices',
52 expect: { '': {} }
53 });
54
55 var callLuciWirelessDevices = rpc.declare({
56 object: 'luci-rpc',
57 method: 'getWirelessDevices',
58 expect: { '': {} }
59 });
60
61 var callLuciBoardJSON = rpc.declare({
62 object: 'luci-rpc',
63 method: 'getBoardJSON'
64 });
65
66 var callLuciHostHints = rpc.declare({
67 object: 'luci-rpc',
68 method: 'getHostHints',
69 expect: { '': {} }
70 });
71
72 var callIwinfoAssoclist = rpc.declare({
73 object: 'iwinfo',
74 method: 'assoclist',
75 params: [ 'device', 'mac' ],
76 expect: { results: [] }
77 });
78
79 var callIwinfoScan = rpc.declare({
80 object: 'iwinfo',
81 method: 'scan',
82 params: [ 'device' ],
83 nobatch: true,
84 expect: { results: [] }
85 });
86
87 var callNetworkInterfaceDump = rpc.declare({
88 object: 'network.interface',
89 method: 'dump',
90 expect: { 'interface': [] }
91 });
92
93 var callNetworkProtoHandlers = rpc.declare({
94 object: 'network',
95 method: 'get_proto_handlers',
96 expect: { '': {} }
97 });
98
99 var _init = null,
100 _state = null,
101 _protocols = {},
102 _protospecs = {};
103
104 function getProtocolHandlers(cache) {
105 return callNetworkProtoHandlers().then(function(protos) {
106 /* Register "none" protocol */
107 if (!protos.hasOwnProperty('none'))
108 Object.assign(protos, { none: { no_device: false } });
109
110 /* Hack: emulate relayd protocol */
111 if (!protos.hasOwnProperty('relay') && L.hasSystemFeature('relayd'))
112 Object.assign(protos, { relay: { no_device: true } });
113
114 Object.assign(_protospecs, protos);
115
116 return Promise.all(Object.keys(protos).map(function(p) {
117 return Promise.resolve(L.require('protocol.%s'.format(p))).catch(function(err) {
118 if (L.isObject(err) && err.name != 'NetworkError')
119 L.error(err);
120 });
121 })).then(function() {
122 return protos;
123 });
124 }).catch(function() {
125 return {};
126 });
127 }
128
129 function getWifiStateBySid(sid) {
130 var s = uci.get('wireless', sid);
131
132 if (s != null && s['.type'] == 'wifi-iface') {
133 for (var radioname in _state.radios) {
134 for (var i = 0; i < _state.radios[radioname].interfaces.length; i++) {
135 var netstate = _state.radios[radioname].interfaces[i];
136
137 if (typeof(netstate.section) != 'string')
138 continue;
139
140 var s2 = uci.get('wireless', netstate.section);
141
142 if (s2 != null && s['.type'] == s2['.type'] && s['.name'] == s2['.name']) {
143 if (s2['.anonymous'] == false && netstate.section.charAt(0) == '@')
144 return null;
145
146 return [ radioname, _state.radios[radioname], netstate ];
147 }
148 }
149 }
150 }
151
152 return null;
153 }
154
155 function getWifiStateByIfname(ifname) {
156 for (var radioname in _state.radios) {
157 for (var i = 0; i < _state.radios[radioname].interfaces.length; i++) {
158 var netstate = _state.radios[radioname].interfaces[i];
159
160 if (typeof(netstate.ifname) != 'string')
161 continue;
162
163 if (netstate.ifname == ifname)
164 return [ radioname, _state.radios[radioname], netstate ];
165 }
166 }
167
168 return null;
169 }
170
171 function isWifiIfname(ifname) {
172 for (var i = 0; i < iface_patterns_wireless.length; i++)
173 if (iface_patterns_wireless[i].test(ifname))
174 return true;
175
176 return false;
177 }
178
179 function getWifiSidByNetid(netid) {
180 var m = /^(\w+)\.network(\d+)$/.exec(netid);
181 if (m) {
182 var sections = uci.sections('wireless', 'wifi-iface');
183 for (var i = 0, n = 0; i < sections.length; i++) {
184 if (sections[i].device != m[1])
185 continue;
186
187 if (++n == +m[2])
188 return sections[i]['.name'];
189 }
190 }
191
192 return null;
193 }
194
195 function getWifiSidByIfname(ifname) {
196 var sid = getWifiSidByNetid(ifname);
197
198 if (sid != null)
199 return sid;
200
201 var res = getWifiStateByIfname(ifname);
202
203 if (res != null && L.isObject(res[2]) && typeof(res[2].section) == 'string')
204 return res[2].section;
205
206 return null;
207 }
208
209 function getWifiNetidBySid(sid) {
210 var s = uci.get('wireless', sid);
211 if (s != null && s['.type'] == 'wifi-iface') {
212 var radioname = s.device;
213 if (typeof(s.device) == 'string') {
214 var i = 0, netid = null, sections = uci.sections('wireless', 'wifi-iface');
215 for (var i = 0, n = 0; i < sections.length; i++) {
216 if (sections[i].device != s.device)
217 continue;
218
219 n++;
220
221 if (sections[i]['.name'] != s['.name'])
222 continue;
223
224 return [ '%s.network%d'.format(s.device, n), s.device ];
225 }
226
227 }
228 }
229
230 return null;
231 }
232
233 function getWifiNetidByNetname(name) {
234 var sections = uci.sections('wireless', 'wifi-iface');
235 for (var i = 0; i < sections.length; i++) {
236 if (typeof(sections[i].network) != 'string')
237 continue;
238
239 var nets = sections[i].network.split(/\s+/);
240 for (var j = 0; j < nets.length; j++) {
241 if (nets[j] != name)
242 continue;
243
244 return getWifiNetidBySid(sections[i]['.name']);
245 }
246 }
247
248 return null;
249 }
250
251 function isVirtualIfname(ifname) {
252 for (var i = 0; i < iface_patterns_virtual.length; i++)
253 if (iface_patterns_virtual[i].test(ifname))
254 return true;
255
256 return false;
257 }
258
259 function isIgnoredIfname(ifname) {
260 for (var i = 0; i < iface_patterns_ignore.length; i++)
261 if (iface_patterns_ignore[i].test(ifname))
262 return true;
263
264 return false;
265 }
266
267 function appendValue(config, section, option, value) {
268 var values = uci.get(config, section, option),
269 isArray = Array.isArray(values),
270 rv = false;
271
272 if (isArray == false)
273 values = L.toArray(values);
274
275 if (values.indexOf(value) == -1) {
276 values.push(value);
277 rv = true;
278 }
279
280 uci.set(config, section, option, isArray ? values : values.join(' '));
281
282 return rv;
283 }
284
285 function removeValue(config, section, option, value) {
286 var values = uci.get(config, section, option),
287 isArray = Array.isArray(values),
288 rv = false;
289
290 if (isArray == false)
291 values = L.toArray(values);
292
293 for (var i = values.length - 1; i >= 0; i--) {
294 if (values[i] == value) {
295 values.splice(i, 1);
296 rv = true;
297 }
298 }
299
300 if (values.length > 0)
301 uci.set(config, section, option, isArray ? values : values.join(' '));
302 else
303 uci.unset(config, section, option);
304
305 return rv;
306 }
307
308 function prefixToMask(bits, v6) {
309 var w = v6 ? 128 : 32,
310 m = [];
311
312 if (bits > w)
313 return null;
314
315 for (var i = 0; i < w / 16; i++) {
316 var b = Math.min(16, bits);
317 m.push((0xffff << (16 - b)) & 0xffff);
318 bits -= b;
319 }
320
321 if (v6)
322 return String.prototype.format.apply('%x:%x:%x:%x:%x:%x:%x:%x', m).replace(/:0(?::0)+$/, '::');
323 else
324 return '%d.%d.%d.%d'.format(m[0] >>> 8, m[0] & 0xff, m[1] >>> 8, m[1] & 0xff);
325 }
326
327 function maskToPrefix(mask, v6) {
328 var m = v6 ? validation.parseIPv6(mask) : validation.parseIPv4(mask);
329
330 if (!m)
331 return null;
332
333 var bits = 0;
334
335 for (var i = 0, z = false; i < m.length; i++) {
336 z = z || !m[i];
337
338 while (!z && (m[i] & (v6 ? 0x8000 : 0x80))) {
339 m[i] = (m[i] << 1) & (v6 ? 0xffff : 0xff);
340 bits++;
341 }
342
343 if (m[i])
344 return null;
345 }
346
347 return bits;
348 }
349
350 function initNetworkState(refresh) {
351 if (_state == null || refresh) {
352 _init = _init || Promise.all([
353 L.resolveDefault(callNetworkInterfaceDump(), []),
354 L.resolveDefault(callLuciBoardJSON(), {}),
355 L.resolveDefault(callLuciNetworkDevices(), {}),
356 L.resolveDefault(callLuciWirelessDevices(), {}),
357 L.resolveDefault(callLuciHostHints(), {}),
358 getProtocolHandlers(),
359 L.resolveDefault(uci.load('network')),
360 L.resolveDefault(uci.load('wireless')),
361 L.resolveDefault(uci.load('luci'))
362 ]).then(function(data) {
363 var netifd_ifaces = data[0],
364 board_json = data[1],
365 luci_devs = data[2];
366
367 var s = {
368 isTunnel: {}, isBridge: {}, isSwitch: {}, isWifi: {},
369 ifaces: netifd_ifaces, radios: data[3], hosts: data[4],
370 netdevs: {}, bridges: {}, switches: {}, hostapd: {}
371 };
372
373 for (var name in luci_devs) {
374 var dev = luci_devs[name];
375
376 if (isVirtualIfname(name))
377 s.isTunnel[name] = true;
378
379 if (!s.isTunnel[name] && isIgnoredIfname(name))
380 continue;
381
382 s.netdevs[name] = s.netdevs[name] || {
383 idx: dev.ifindex,
384 name: name,
385 rawname: name,
386 flags: dev.flags,
387 stats: dev.stats,
388 macaddr: dev.mac,
389 type: dev.type,
390 mtu: dev.mtu,
391 qlen: dev.qlen,
392 wireless: dev.wireless,
393 ipaddrs: [],
394 ip6addrs: []
395 };
396
397 if (Array.isArray(dev.ipaddrs))
398 for (var i = 0; i < dev.ipaddrs.length; i++)
399 s.netdevs[name].ipaddrs.push(dev.ipaddrs[i].address + '/' + dev.ipaddrs[i].netmask);
400
401 if (Array.isArray(dev.ip6addrs))
402 for (var i = 0; i < dev.ip6addrs.length; i++)
403 s.netdevs[name].ip6addrs.push(dev.ip6addrs[i].address + '/' + dev.ip6addrs[i].netmask);
404 }
405
406 for (var name in luci_devs) {
407 var dev = luci_devs[name];
408
409 if (!dev.bridge)
410 continue;
411
412 var b = {
413 name: name,
414 id: dev.id,
415 stp: dev.stp,
416 ifnames: []
417 };
418
419 for (var i = 0; dev.ports && i < dev.ports.length; i++) {
420 var subdev = s.netdevs[dev.ports[i]];
421
422 if (subdev == null)
423 continue;
424
425 b.ifnames.push(subdev);
426 subdev.bridge = b;
427 }
428
429 s.bridges[name] = b;
430 s.isBridge[name] = true;
431 }
432
433 if (L.isObject(board_json.switch)) {
434 for (var switchname in board_json.switch) {
435 var layout = board_json.switch[switchname],
436 netdevs = {},
437 nports = {},
438 ports = [],
439 pnum = null,
440 role = null;
441
442 if (L.isObject(layout) && Array.isArray(layout.ports)) {
443 for (var i = 0, port; (port = layout.ports[i]) != null; i++) {
444 if (typeof(port) == 'object' && typeof(port.num) == 'number' &&
445 (typeof(port.role) == 'string' || typeof(port.device) == 'string')) {
446 var spec = {
447 num: port.num,
448 role: port.role || 'cpu',
449 index: (port.index != null) ? port.index : port.num
450 };
451
452 if (port.device != null) {
453 spec.device = port.device;
454 spec.tagged = spec.need_tag;
455 netdevs[port.num] = port.device;
456 }
457
458 ports.push(spec);
459
460 if (port.role != null)
461 nports[port.role] = (nports[port.role] || 0) + 1;
462 }
463 }
464
465 ports.sort(function(a, b) {
466 if (a.role != b.role)
467 return (a.role < b.role) ? -1 : 1;
468
469 return (a.index - b.index);
470 });
471
472 for (var i = 0, port; (port = ports[i]) != null; i++) {
473 if (port.role != role) {
474 role = port.role;
475 pnum = 1;
476 }
477
478 if (role == 'cpu')
479 port.label = 'CPU (%s)'.format(port.device);
480 else if (nports[role] > 1)
481 port.label = '%s %d'.format(role.toUpperCase(), pnum++);
482 else
483 port.label = role.toUpperCase();
484
485 delete port.role;
486 delete port.index;
487 }
488
489 s.switches[switchname] = {
490 ports: ports,
491 netdevs: netdevs
492 };
493 }
494 }
495 }
496
497 if (L.isObject(board_json.dsl) && L.isObject(board_json.dsl.modem)) {
498 s.hasDSLModem = board_json.dsl.modem;
499 }
500
501 _init = null;
502
503 var objects = [];
504
505 if (L.isObject(s.radios))
506 for (var radio in s.radios)
507 if (L.isObject(s.radios[radio]) && Array.isArray(s.radios[radio].interfaces))
508 for (var i = 0; i < s.radios[radio].interfaces.length; i++)
509 if (L.isObject(s.radios[radio].interfaces[i]) && s.radios[radio].interfaces[i].ifname)
510 objects.push('hostapd.%s'.format(s.radios[radio].interfaces[i].ifname));
511
512 return (objects.length ? L.resolveDefault(rpc.list.apply(rpc, objects), {}) : Promise.resolve({})).then(function(res) {
513 for (var k in res) {
514 var m = k.match(/^hostapd\.(.+)$/);
515 if (m)
516 s.hostapd[m[1]] = res[k];
517 }
518
519 return (_state = s);
520 });
521 });
522 }
523
524 return (_state != null ? Promise.resolve(_state) : _init);
525 }
526
527 function ifnameOf(obj) {
528 if (obj instanceof Protocol)
529 return obj.getIfname();
530 else if (obj instanceof Device)
531 return obj.getName();
532 else if (obj instanceof WifiDevice)
533 return obj.getName();
534 else if (obj instanceof WifiNetwork)
535 return obj.getIfname();
536 else if (typeof(obj) == 'string')
537 return obj.replace(/:.+$/, '');
538
539 return null;
540 }
541
542 function networkSort(a, b) {
543 return a.getName() > b.getName();
544 }
545
546 function deviceSort(a, b) {
547 var typeWeigth = { wifi: 2, alias: 3 },
548 weightA = typeWeigth[a.getType()] || 1,
549 weightB = typeWeigth[b.getType()] || 1;
550
551 if (weightA != weightB)
552 return weightA - weightB;
553
554 return a.getName() > b.getName();
555 }
556
557 function formatWifiEncryption(enc) {
558 if (!L.isObject(enc))
559 return null;
560
561 if (!enc.enabled)
562 return 'None';
563
564 var ciphers = Array.isArray(enc.ciphers)
565 ? enc.ciphers.map(function(c) { return c.toUpperCase() }) : [ 'NONE' ];
566
567 if (Array.isArray(enc.wep)) {
568 var has_open = false,
569 has_shared = false;
570
571 for (var i = 0; i < enc.wep.length; i++)
572 if (enc.wep[i] == 'open')
573 has_open = true;
574 else if (enc.wep[i] == 'shared')
575 has_shared = true;
576
577 if (has_open && has_shared)
578 return 'WEP Open/Shared (%s)'.format(ciphers.join(', '));
579 else if (has_open)
580 return 'WEP Open System (%s)'.format(ciphers.join(', '));
581 else if (has_shared)
582 return 'WEP Shared Auth (%s)'.format(ciphers.join(', '));
583
584 return 'WEP';
585 }
586
587 if (Array.isArray(enc.wpa)) {
588 var versions = [],
589 suites = Array.isArray(enc.authentication)
590 ? enc.authentication.map(function(a) { return a.toUpperCase() }) : [ 'NONE' ];
591
592 for (var i = 0; i < enc.wpa.length; i++)
593 switch (enc.wpa[i]) {
594 case 1:
595 versions.push('WPA');
596 break;
597
598 default:
599 versions.push('WPA%d'.format(enc.wpa[i]));
600 break;
601 }
602
603 if (versions.length > 1)
604 return 'mixed %s %s (%s)'.format(versions.join('/'), suites.join(', '), ciphers.join(', '));
605
606 return '%s %s (%s)'.format(versions[0], suites.join(', '), ciphers.join(', '));
607 }
608
609 return 'Unknown';
610 }
611
612 function enumerateNetworks() {
613 var uciInterfaces = uci.sections('network', 'interface'),
614 networks = {};
615
616 for (var i = 0; i < uciInterfaces.length; i++)
617 networks[uciInterfaces[i]['.name']] = this.instantiateNetwork(uciInterfaces[i]['.name']);
618
619 for (var i = 0; i < _state.ifaces.length; i++)
620 if (networks[_state.ifaces[i].interface] == null)
621 networks[_state.ifaces[i].interface] =
622 this.instantiateNetwork(_state.ifaces[i].interface, _state.ifaces[i].proto);
623
624 var rv = [];
625
626 for (var network in networks)
627 if (networks.hasOwnProperty(network))
628 rv.push(networks[network]);
629
630 rv.sort(networkSort);
631
632 return rv;
633 }
634
635
636 var Hosts, Network, Protocol, Device, WifiDevice, WifiNetwork;
637
638 /**
639 * @class network
640 * @memberof LuCI
641 * @hideconstructor
642 * @classdesc
643 *
644 * The `LuCI.network` class combines data from multiple `ubus` apis to
645 * provide an abstraction of the current network configuration state.
646 *
647 * It provides methods to enumerate interfaces and devices, to query
648 * current configuration details and to manipulate settings.
649 */
650 Network = baseclass.extend(/** @lends LuCI.network.prototype */ {
651 /**
652 * Converts the given prefix size in bits to a netmask.
653 *
654 * @method
655 *
656 * @param {number} bits
657 * The prefix size in bits.
658 *
659 * @param {boolean} [v6=false]
660 * Whether to convert the bits value into an IPv4 netmask (`false`) or
661 * an IPv6 netmask (`true`).
662 *
663 * @returns {null|string}
664 * Returns a string containing the netmask corresponding to the bit count
665 * or `null` when the given amount of bits exceeds the maximum possible
666 * value of `32` for IPv4 or `128` for IPv6.
667 */
668 prefixToMask: prefixToMask,
669
670 /**
671 * Converts the given netmask to a prefix size in bits.
672 *
673 * @method
674 *
675 * @param {string} netmask
676 * The netmask to convert into a bit count.
677 *
678 * @param {boolean} [v6=false]
679 * Whether to parse the given netmask as IPv4 (`false`) or IPv6 (`true`)
680 * address.
681 *
682 * @returns {null|number}
683 * Returns the number of prefix bits contained in the netmask or `null`
684 * if the given netmask value was invalid.
685 */
686 maskToPrefix: maskToPrefix,
687
688 /**
689 * An encryption entry describes active wireless encryption settings
690 * such as the used key management protocols, active ciphers and
691 * protocol versions.
692 *
693 * @typedef {Object<string, boolean|Array<number|string>>} LuCI.network.WifiEncryption
694 * @memberof LuCI.network
695 *
696 * @property {boolean} enabled
697 * Specifies whether any kind of encryption, such as `WEP` or `WPA` is
698 * enabled. If set to `false`, then no encryption is active and the
699 * corresponding network is open.
700 *
701 * @property {string[]} [wep]
702 * When the `wep` property exists, the network uses WEP encryption.
703 * In this case, the property is set to an array of active WEP modes
704 * which might be either `open`, `shared` or both.
705 *
706 * @property {number[]} [wpa]
707 * When the `wpa` property exists, the network uses WPA security.
708 * In this case, the property is set to an array containing the WPA
709 * protocol versions used, e.g. `[ 1, 2 ]` for WPA/WPA2 mixed mode or
710 * `[ 3 ]` for WPA3-SAE.
711 *
712 * @property {string[]} [authentication]
713 * The `authentication` property only applies to WPA encryption and
714 * is defined when the `wpa` property is set as well. It points to
715 * an array of active authentication suites used by the network, e.g.
716 * `[ "psk" ]` for a WPA(2)-PSK network or `[ "psk", "sae" ]` for
717 * mixed WPA2-PSK/WPA3-SAE encryption.
718 *
719 * @property {string[]} [ciphers]
720 * If either WEP or WPA encryption is active, then the `ciphers`
721 * property will be set to an array describing the active encryption
722 * ciphers used by the network, e.g. `[ "tkip", "ccmp" ]` for a
723 * WPA/WPA2-PSK mixed network or `[ "wep-40", "wep-104" ]` for an
724 * WEP network.
725 */
726
727 /**
728 * Converts a given {@link LuCI.network.WifiEncryption encryption entry}
729 * into a human readable string such as `mixed WPA/WPA2 PSK (TKIP, CCMP)`
730 * or `WPA3 SAE (CCMP)`.
731 *
732 * @method
733 *
734 * @param {LuCI.network.WifiEncryption} encryption
735 * The wireless encryption entry to convert.
736 *
737 * @returns {null|string}
738 * Returns the description string for the given encryption entry or
739 * `null` if the given entry was invalid.
740 */
741 formatWifiEncryption: formatWifiEncryption,
742
743 /**
744 * Flushes the local network state cache and fetches updated information
745 * from the remote `ubus` apis.
746 *
747 * @returns {Promise<Object>}
748 * Returns a promise resolving to the internal network state object.
749 */
750 flushCache: function() {
751 initNetworkState(true);
752 return _init;
753 },
754
755 /**
756 * Instantiates the given {@link LuCI.network.Protocol Protocol} backend,
757 * optionally using the given network name.
758 *
759 * @param {string} protoname
760 * The protocol backend to use, e.g. `static` or `dhcp`.
761 *
762 * @param {string} [netname=__dummy__]
763 * The network name to use for the instantiated protocol. This should be
764 * usually set to one of the interfaces described in /etc/config/network
765 * but it is allowed to omit it, e.g. to query protocol capabilities
766 * without the need for an existing interface.
767 *
768 * @returns {null|LuCI.network.Protocol}
769 * Returns the instantiated protocol backend class or `null` if the given
770 * protocol isn't known.
771 */
772 getProtocol: function(protoname, netname) {
773 var v = _protocols[protoname];
774 if (v != null)
775 return new v(netname || '__dummy__');
776
777 return null;
778 },
779
780 /**
781 * Obtains instances of all known {@link LuCI.network.Protocol Protocol}
782 * backend classes.
783 *
784 * @returns {Array<LuCI.network.Protocol>}
785 * Returns an array of protocol class instances.
786 */
787 getProtocols: function() {
788 var rv = [];
789
790 for (var protoname in _protocols)
791 rv.push(new _protocols[protoname]('__dummy__'));
792
793 return rv;
794 },
795
796 /**
797 * Registers a new {@link LuCI.network.Protocol Protocol} subclass
798 * with the given methods and returns the resulting subclass value.
799 *
800 * This functions internally calls
801 * {@link LuCI.Class.extend Class.extend()} on the `Network.Protocol`
802 * base class.
803 *
804 * @param {string} protoname
805 * The name of the new protocol to register.
806 *
807 * @param {Object<string, *>} methods
808 * The member methods and values of the new `Protocol` subclass to
809 * be passed to {@link LuCI.Class.extend Class.extend()}.
810 *
811 * @returns {LuCI.network.Protocol}
812 * Returns the new `Protocol` subclass.
813 */
814 registerProtocol: function(protoname, methods) {
815 var spec = L.isObject(_protospecs) ? _protospecs[protoname] : null;
816 var proto = Protocol.extend(Object.assign({
817 getI18n: function() {
818 return protoname;
819 },
820
821 isFloating: function() {
822 return false;
823 },
824
825 isVirtual: function() {
826 return (L.isObject(spec) && spec.no_device == true);
827 },
828
829 renderFormOptions: function(section) {
830
831 }
832 }, methods, {
833 __init__: function(name) {
834 this.sid = name;
835 },
836
837 getProtocol: function() {
838 return protoname;
839 }
840 }));
841
842 _protocols[protoname] = proto;
843
844 return proto;
845 },
846
847 /**
848 * Registers a new regular expression pattern to recognize
849 * virtual interfaces.
850 *
851 * @param {RegExp} pat
852 * A `RegExp` instance to match a virtual interface name
853 * such as `6in4-wan` or `tun0`.
854 */
855 registerPatternVirtual: function(pat) {
856 iface_patterns_virtual.push(pat);
857 },
858
859 /**
860 * Registers a new human readable translation string for a `Protocol`
861 * error code.
862 *
863 * @param {string} code
864 * The `ubus` protocol error code to register a translation for, e.g.
865 * `NO_DEVICE`.
866 *
867 * @param {string} message
868 * The message to use as translation for the given protocol error code.
869 *
870 * @returns {boolean}
871 * Returns `true` if the error code description has been added or `false`
872 * if either the arguments were invalid or if there already was a
873 * description for the given code.
874 */
875 registerErrorCode: function(code, message) {
876 if (typeof(code) == 'string' &&
877 typeof(message) == 'string' &&
878 !proto_errors.hasOwnProperty(code)) {
879 proto_errors[code] = message;
880 return true;
881 }
882
883 return false;
884 },
885
886 /**
887 * Adds a new network of the given name and update it with the given
888 * uci option values.
889 *
890 * If a network with the given name already exist but is empty, then
891 * this function will update its option, otherwise it will do nothing.
892 *
893 * @param {string} name
894 * The name of the network to add. Must be in the format `[a-zA-Z0-9_]+`.
895 *
896 * @param {Object<string, string|string[]>} [options]
897 * An object of uci option values to set on the new network or to
898 * update in an existing, empty network.
899 *
900 * @returns {Promise<null|LuCI.network.Protocol>}
901 * Returns a promise resolving to the `Protocol` subclass instance
902 * describing the added network or resolving to `null` if the name
903 * was invalid or if a non-empty network of the given name already
904 * existed.
905 */
906 addNetwork: function(name, options) {
907 return this.getNetwork(name).then(L.bind(function(existingNetwork) {
908 if (name != null && /^[a-zA-Z0-9_]+$/.test(name) && existingNetwork == null) {
909 var sid = uci.add('network', 'interface', name);
910
911 if (sid != null) {
912 if (L.isObject(options))
913 for (var key in options)
914 if (options.hasOwnProperty(key))
915 uci.set('network', sid, key, options[key]);
916
917 return this.instantiateNetwork(sid);
918 }
919 }
920 else if (existingNetwork != null && existingNetwork.isEmpty()) {
921 if (L.isObject(options))
922 for (var key in options)
923 if (options.hasOwnProperty(key))
924 existingNetwork.set(key, options[key]);
925
926 return existingNetwork;
927 }
928 }, this));
929 },
930
931 /**
932 * Get a {@link LuCI.network.Protocol Protocol} instance describing
933 * the network with the given name.
934 *
935 * @param {string} name
936 * The logical interface name of the network get, e.g. `lan` or `wan`.
937 *
938 * @returns {Promise<null|LuCI.network.Protocol>}
939 * Returns a promise resolving to a
940 * {@link LuCI.network.Protocol Protocol} subclass instance describing
941 * the network or `null` if the network did not exist.
942 */
943 getNetwork: function(name) {
944 return initNetworkState().then(L.bind(function() {
945 var section = (name != null) ? uci.get('network', name) : null;
946
947 if (section != null && section['.type'] == 'interface') {
948 return this.instantiateNetwork(name);
949 }
950 else if (name != null) {
951 for (var i = 0; i < _state.ifaces.length; i++)
952 if (_state.ifaces[i].interface == name)
953 return this.instantiateNetwork(name, _state.ifaces[i].proto);
954 }
955
956 return null;
957 }, this));
958 },
959
960 /**
961 * Gets an array containing all known networks.
962 *
963 * @returns {Promise<Array<LuCI.network.Protocol>>}
964 * Returns a promise resolving to a name-sorted array of
965 * {@link LuCI.network.Protocol Protocol} subclass instances
966 * describing all known networks.
967 */
968 getNetworks: function() {
969 return initNetworkState().then(L.bind(enumerateNetworks, this));
970 },
971
972 /**
973 * Deletes the given network and its references from the network and
974 * firewall configuration.
975 *
976 * @param {string} name
977 * The name of the network to delete.
978 *
979 * @returns {Promise<boolean>}
980 * Returns a promise resolving to either `true` if the network and
981 * references to it were successfully deleted from the configuration or
982 * `false` if the given network could not be found.
983 */
984 deleteNetwork: function(name) {
985 var requireFirewall = Promise.resolve(L.require('firewall')).catch(function() {}),
986 network = this.instantiateNetwork(name);
987
988 return Promise.all([ requireFirewall, initNetworkState() ]).then(function(res) {
989 var uciInterface = uci.get('network', name),
990 firewall = res[0];
991
992 if (uciInterface != null && uciInterface['.type'] == 'interface') {
993 return Promise.resolve(network ? network.deleteConfiguration() : null).then(function() {
994 uci.remove('network', name);
995
996 uci.sections('luci', 'ifstate', function(s) {
997 if (s.interface == name)
998 uci.remove('luci', s['.name']);
999 });
1000
1001 uci.sections('network', 'alias', function(s) {
1002 if (s.interface == name)
1003 uci.remove('network', s['.name']);
1004 });
1005
1006 uci.sections('network', 'route', function(s) {
1007 if (s.interface == name)
1008 uci.remove('network', s['.name']);
1009 });
1010
1011 uci.sections('network', 'route6', function(s) {
1012 if (s.interface == name)
1013 uci.remove('network', s['.name']);
1014 });
1015
1016 uci.sections('wireless', 'wifi-iface', function(s) {
1017 var networks = L.toArray(s.network).filter(function(network) { return network != name });
1018
1019 if (networks.length > 0)
1020 uci.set('wireless', s['.name'], 'network', networks.join(' '));
1021 else
1022 uci.unset('wireless', s['.name'], 'network');
1023 });
1024
1025 if (firewall)
1026 return firewall.deleteNetwork(name).then(function() { return true });
1027
1028 return true;
1029 }).catch(function() {
1030 return false;
1031 });
1032 }
1033
1034 return false;
1035 });
1036 },
1037
1038 /**
1039 * Rename the given network and its references to a new name.
1040 *
1041 * @param {string} oldName
1042 * The current name of the network.
1043 *
1044 * @param {string} newName
1045 * The name to rename the network to, must be in the format
1046 * `[a-z-A-Z0-9_]+`.
1047 *
1048 * @returns {Promise<boolean>}
1049 * Returns a promise resolving to either `true` if the network was
1050 * successfully renamed or `false` if the new name was invalid, if
1051 * a network with the new name already exists or if the network to
1052 * rename could not be found.
1053 */
1054 renameNetwork: function(oldName, newName) {
1055 return initNetworkState().then(function() {
1056 if (newName == null || !/^[a-zA-Z0-9_]+$/.test(newName) || uci.get('network', newName) != null)
1057 return false;
1058
1059 var oldNetwork = uci.get('network', oldName);
1060
1061 if (oldNetwork == null || oldNetwork['.type'] != 'interface')
1062 return false;
1063
1064 var sid = uci.add('network', 'interface', newName);
1065
1066 for (var key in oldNetwork)
1067 if (oldNetwork.hasOwnProperty(key) && key.charAt(0) != '.')
1068 uci.set('network', sid, key, oldNetwork[key]);
1069
1070 uci.sections('luci', 'ifstate', function(s) {
1071 if (s.interface == oldName)
1072 uci.set('luci', s['.name'], 'interface', newName);
1073 });
1074
1075 uci.sections('network', 'alias', function(s) {
1076 if (s.interface == oldName)
1077 uci.set('network', s['.name'], 'interface', newName);
1078 });
1079
1080 uci.sections('network', 'route', function(s) {
1081 if (s.interface == oldName)
1082 uci.set('network', s['.name'], 'interface', newName);
1083 });
1084
1085 uci.sections('network', 'route6', function(s) {
1086 if (s.interface == oldName)
1087 uci.set('network', s['.name'], 'interface', newName);
1088 });
1089
1090 uci.sections('wireless', 'wifi-iface', function(s) {
1091 var networks = L.toArray(s.network).map(function(network) { return (network == oldName ? newName : network) });
1092
1093 if (networks.length > 0)
1094 uci.set('wireless', s['.name'], 'network', networks.join(' '));
1095 });
1096
1097 uci.remove('network', oldName);
1098
1099 return true;
1100 });
1101 },
1102
1103 /**
1104 * Get a {@link LuCI.network.Device Device} instance describing the
1105 * given network device.
1106 *
1107 * @param {string} name
1108 * The name of the network device to get, e.g. `eth0` or `br-lan`.
1109 *
1110 * @returns {Promise<null|LuCI.network.Device>}
1111 * Returns a promise resolving to the `Device` instance describing
1112 * the network device or `null` if the given device name could not
1113 * be found.
1114 */
1115 getDevice: function(name) {
1116 return initNetworkState().then(L.bind(function() {
1117 if (name == null)
1118 return null;
1119
1120 if (_state.netdevs.hasOwnProperty(name) || isWifiIfname(name))
1121 return this.instantiateDevice(name);
1122
1123 var netid = getWifiNetidBySid(name);
1124 if (netid != null)
1125 return this.instantiateDevice(netid[0]);
1126
1127 return null;
1128 }, this));
1129 },
1130
1131 /**
1132 * Get a sorted list of all found network devices.
1133 *
1134 * @returns {Promise<Array<LuCI.network.Device>>}
1135 * Returns a promise resolving to a sorted array of `Device` class
1136 * instances describing the network devices found on the system.
1137 */
1138 getDevices: function() {
1139 return initNetworkState().then(L.bind(function() {
1140 var devices = {};
1141
1142 /* find simple devices */
1143 var uciInterfaces = uci.sections('network', 'interface');
1144 for (var i = 0; i < uciInterfaces.length; i++) {
1145 var ifnames = L.toArray(uciInterfaces[i].ifname);
1146
1147 for (var j = 0; j < ifnames.length; j++) {
1148 if (ifnames[j].charAt(0) == '@')
1149 continue;
1150
1151 if (isIgnoredIfname(ifnames[j]) || isVirtualIfname(ifnames[j]) || isWifiIfname(ifnames[j]))
1152 continue;
1153
1154 devices[ifnames[j]] = this.instantiateDevice(ifnames[j]);
1155 }
1156 }
1157
1158 for (var ifname in _state.netdevs) {
1159 if (devices.hasOwnProperty(ifname))
1160 continue;
1161
1162 if (isIgnoredIfname(ifname) || isWifiIfname(ifname))
1163 continue;
1164
1165 if (_state.netdevs[ifname].wireless)
1166 continue;
1167
1168 devices[ifname] = this.instantiateDevice(ifname);
1169 }
1170
1171 /* find VLAN devices */
1172 var uciSwitchVLANs = uci.sections('network', 'switch_vlan');
1173 for (var i = 0; i < uciSwitchVLANs.length; i++) {
1174 if (typeof(uciSwitchVLANs[i].ports) != 'string' ||
1175 typeof(uciSwitchVLANs[i].device) != 'string' ||
1176 !_state.switches.hasOwnProperty(uciSwitchVLANs[i].device))
1177 continue;
1178
1179 var ports = uciSwitchVLANs[i].ports.split(/\s+/);
1180 for (var j = 0; j < ports.length; j++) {
1181 var m = ports[j].match(/^(\d+)([tu]?)$/);
1182 if (m == null)
1183 continue;
1184
1185 var netdev = _state.switches[uciSwitchVLANs[i].device].netdevs[m[1]];
1186 if (netdev == null)
1187 continue;
1188
1189 if (!devices.hasOwnProperty(netdev))
1190 devices[netdev] = this.instantiateDevice(netdev);
1191
1192 _state.isSwitch[netdev] = true;
1193
1194 if (m[2] != 't')
1195 continue;
1196
1197 var vid = uciSwitchVLANs[i].vid || uciSwitchVLANs[i].vlan;
1198 vid = (vid != null ? +vid : null);
1199
1200 if (vid == null || vid < 0 || vid > 4095)
1201 continue;
1202
1203 var vlandev = '%s.%d'.format(netdev, vid);
1204
1205 if (!devices.hasOwnProperty(vlandev))
1206 devices[vlandev] = this.instantiateDevice(vlandev);
1207
1208 _state.isSwitch[vlandev] = true;
1209 }
1210 }
1211
1212 /* find wireless interfaces */
1213 var uciWifiIfaces = uci.sections('wireless', 'wifi-iface'),
1214 networkCount = {};
1215
1216 for (var i = 0; i < uciWifiIfaces.length; i++) {
1217 if (typeof(uciWifiIfaces[i].device) != 'string')
1218 continue;
1219
1220 networkCount[uciWifiIfaces[i].device] = (networkCount[uciWifiIfaces[i].device] || 0) + 1;
1221
1222 var netid = '%s.network%d'.format(uciWifiIfaces[i].device, networkCount[uciWifiIfaces[i].device]);
1223
1224 devices[netid] = this.instantiateDevice(netid);
1225 }
1226
1227 var rv = [];
1228
1229 for (var netdev in devices)
1230 if (devices.hasOwnProperty(netdev))
1231 rv.push(devices[netdev]);
1232
1233 rv.sort(deviceSort);
1234
1235 return rv;
1236 }, this));
1237 },
1238
1239 /**
1240 * Test if a given network device name is in the list of patterns for
1241 * device names to ignore.
1242 *
1243 * Ignored device names are usually Linux network devices which are
1244 * spawned implicitly by kernel modules such as `tunl0` or `hwsim0`
1245 * and which are unsuitable for use in network configuration.
1246 *
1247 * @param {string} name
1248 * The device name to test.
1249 *
1250 * @returns {boolean}
1251 * Returns `true` if the given name is in the ignore pattern list,
1252 * else returns `false`.
1253 */
1254 isIgnoredDevice: function(name) {
1255 return isIgnoredIfname(name);
1256 },
1257
1258 /**
1259 * Get a {@link LuCI.network.WifiDevice WifiDevice} instance describing
1260 * the given wireless radio.
1261 *
1262 * @param {string} devname
1263 * The configuration name of the wireless radio to lookup, e.g. `radio0`
1264 * for the first mac80211 phy on the system.
1265 *
1266 * @returns {Promise<null|LuCI.network.WifiDevice>}
1267 * Returns a promise resolving to the `WifiDevice` instance describing
1268 * the underlying radio device or `null` if the wireless radio could not
1269 * be found.
1270 */
1271 getWifiDevice: function(devname) {
1272 return initNetworkState().then(L.bind(function() {
1273 var existingDevice = uci.get('wireless', devname);
1274
1275 if (existingDevice == null || existingDevice['.type'] != 'wifi-device')
1276 return null;
1277
1278 return this.instantiateWifiDevice(devname, _state.radios[devname] || {});
1279 }, this));
1280 },
1281
1282 /**
1283 * Obtain a list of all configured radio devices.
1284 *
1285 * @returns {Promise<Array<LuCI.network.WifiDevice>>}
1286 * Returns a promise resolving to an array of `WifiDevice` instances
1287 * describing the wireless radios configured in the system.
1288 * The order of the array corresponds to the order of the radios in
1289 * the configuration.
1290 */
1291 getWifiDevices: function() {
1292 return initNetworkState().then(L.bind(function() {
1293 var uciWifiDevices = uci.sections('wireless', 'wifi-device'),
1294 rv = [];
1295
1296 for (var i = 0; i < uciWifiDevices.length; i++) {
1297 var devname = uciWifiDevices[i]['.name'];
1298 rv.push(this.instantiateWifiDevice(devname, _state.radios[devname] || {}));
1299 }
1300
1301 return rv;
1302 }, this));
1303 },
1304
1305 /**
1306 * Get a {@link LuCI.network.WifiNetwork WifiNetwork} instance describing
1307 * the given wireless network.
1308 *
1309 * @param {string} netname
1310 * The name of the wireless network to lookup. This may be either an uci
1311 * configuration section ID, a network ID in the form `radio#.network#`
1312 * or a Linux network device name like `wlan0` which is resolved to the
1313 * corresponding configuration section through `ubus` runtime information.
1314 *
1315 * @returns {Promise<null|LuCI.network.WifiNetwork>}
1316 * Returns a promise resolving to the `WifiNetwork` instance describing
1317 * the wireless network or `null` if the corresponding network could not
1318 * be found.
1319 */
1320 getWifiNetwork: function(netname) {
1321 return initNetworkState()
1322 .then(L.bind(this.lookupWifiNetwork, this, netname));
1323 },
1324
1325 /**
1326 * Get an array of all {@link LuCI.network.WifiNetwork WifiNetwork}
1327 * instances describing the wireless networks present on the system.
1328 *
1329 * @returns {Promise<Array<LuCI.network.WifiNetwork>>}
1330 * Returns a promise resolving to an array of `WifiNetwork` instances
1331 * describing the wireless networks. The array will be empty if no networks
1332 * are found.
1333 */
1334 getWifiNetworks: function() {
1335 return initNetworkState().then(L.bind(function() {
1336 var wifiIfaces = uci.sections('wireless', 'wifi-iface'),
1337 rv = [];
1338
1339 for (var i = 0; i < wifiIfaces.length; i++)
1340 rv.push(this.lookupWifiNetwork(wifiIfaces[i]['.name']));
1341
1342 rv.sort(function(a, b) {
1343 return (a.getID() > b.getID());
1344 });
1345
1346 return rv;
1347 }, this));
1348 },
1349
1350 /**
1351 * Adds a new wireless network to the configuration and sets its options
1352 * to the provided values.
1353 *
1354 * @param {Object<string, string|string[]>} options
1355 * The options to set for the newly added wireless network. This object
1356 * must at least contain a `device` property which is set to the radio
1357 * name the new network belongs to.
1358 *
1359 * @returns {Promise<null|LuCI.network.WifiNetwork>}
1360 * Returns a promise resolving to a `WifiNetwork` instance describing
1361 * the newly added wireless network or `null` if the given options
1362 * were invalid or if the associated radio device could not be found.
1363 */
1364 addWifiNetwork: function(options) {
1365 return initNetworkState().then(L.bind(function() {
1366 if (options == null ||
1367 typeof(options) != 'object' ||
1368 typeof(options.device) != 'string')
1369 return null;
1370
1371 var existingDevice = uci.get('wireless', options.device);
1372 if (existingDevice == null || existingDevice['.type'] != 'wifi-device')
1373 return null;
1374
1375 /* XXX: need to add a named section (wifinet#) here */
1376 var sid = uci.add('wireless', 'wifi-iface');
1377 for (var key in options)
1378 if (options.hasOwnProperty(key))
1379 uci.set('wireless', sid, key, options[key]);
1380
1381 var radioname = existingDevice['.name'],
1382 netid = getWifiNetidBySid(sid) || [];
1383
1384 return this.instantiateWifiNetwork(sid, radioname, _state.radios[radioname], netid[0], null);
1385 }, this));
1386 },
1387
1388 /**
1389 * Deletes the given wireless network from the configuration.
1390 *
1391 * @param {string} netname
1392 * The name of the network to remove. This may be either a
1393 * network ID in the form `radio#.network#` or a Linux network device
1394 * name like `wlan0` which is resolved to the corresponding configuration
1395 * section through `ubus` runtime information.
1396 *
1397 * @returns {Promise<boolean>}
1398 * Returns a promise resolving to `true` if the wireless network has been
1399 * successfully deleted from the configuration or `false` if it could not
1400 * be found.
1401 */
1402 deleteWifiNetwork: function(netname) {
1403 return initNetworkState().then(L.bind(function() {
1404 var sid = getWifiSidByIfname(netname);
1405
1406 if (sid == null)
1407 return false;
1408
1409 uci.remove('wireless', sid);
1410 return true;
1411 }, this));
1412 },
1413
1414 /* private */
1415 getStatusByRoute: function(addr, mask) {
1416 return initNetworkState().then(L.bind(function() {
1417 var rv = [];
1418
1419 for (var i = 0; i < _state.ifaces.length; i++) {
1420 if (!Array.isArray(_state.ifaces[i].route))
1421 continue;
1422
1423 for (var j = 0; j < _state.ifaces[i].route.length; j++) {
1424 if (typeof(_state.ifaces[i].route[j]) != 'object' ||
1425 typeof(_state.ifaces[i].route[j].target) != 'string' ||
1426 typeof(_state.ifaces[i].route[j].mask) != 'number')
1427 continue;
1428
1429 if (_state.ifaces[i].route[j].table)
1430 continue;
1431
1432 if (_state.ifaces[i].route[j].target != addr ||
1433 _state.ifaces[i].route[j].mask != mask)
1434 continue;
1435
1436 rv.push(_state.ifaces[i]);
1437 }
1438 }
1439
1440 rv.sort(function(a, b) {
1441 if (a.metric != b.metric)
1442 return (a.metric - b.metric);
1443
1444 if (a.interface < b.interface)
1445 return -1;
1446 else if (a.interface > b.interface)
1447 return 1;
1448
1449 return 0;
1450 });
1451
1452 return rv;
1453 }, this));
1454 },
1455
1456 /* private */
1457 getStatusByAddress: function(addr) {
1458 return initNetworkState().then(L.bind(function() {
1459 var rv = [];
1460
1461 for (var i = 0; i < _state.ifaces.length; i++) {
1462 if (Array.isArray(_state.ifaces[i]['ipv4-address']))
1463 for (var j = 0; j < _state.ifaces[i]['ipv4-address'].length; j++)
1464 if (typeof(_state.ifaces[i]['ipv4-address'][j]) == 'object' &&
1465 _state.ifaces[i]['ipv4-address'][j].address == addr)
1466 return _state.ifaces[i];
1467
1468 if (Array.isArray(_state.ifaces[i]['ipv6-address']))
1469 for (var j = 0; j < _state.ifaces[i]['ipv6-address'].length; j++)
1470 if (typeof(_state.ifaces[i]['ipv6-address'][j]) == 'object' &&
1471 _state.ifaces[i]['ipv6-address'][j].address == addr)
1472 return _state.ifaces[i];
1473
1474 if (Array.isArray(_state.ifaces[i]['ipv6-prefix-assignment']))
1475 for (var j = 0; j < _state.ifaces[i]['ipv6-prefix-assignment'].length; j++)
1476 if (typeof(_state.ifaces[i]['ipv6-prefix-assignment'][j]) == 'object' &&
1477 typeof(_state.ifaces[i]['ipv6-prefix-assignment'][j]['local-address']) == 'object' &&
1478 _state.ifaces[i]['ipv6-prefix-assignment'][j]['local-address'].address == addr)
1479 return _state.ifaces[i];
1480 }
1481
1482 return null;
1483 }, this));
1484 },
1485
1486 /**
1487 * Get IPv4 wan networks.
1488 *
1489 * This function looks up all networks having a default `0.0.0.0/0` route
1490 * and returns them as array.
1491 *
1492 * @returns {Promise<Array<LuCI.network.Protocol>>}
1493 * Returns a promise resolving to an array of `Protocol` subclass
1494 * instances describing the found default route interfaces.
1495 */
1496 getWANNetworks: function() {
1497 return this.getStatusByRoute('0.0.0.0', 0).then(L.bind(function(statuses) {
1498 var rv = [], seen = {};
1499
1500 for (var i = 0; i < statuses.length; i++) {
1501 if (!seen.hasOwnProperty(statuses[i].interface)) {
1502 rv.push(this.instantiateNetwork(statuses[i].interface, statuses[i].proto));
1503 seen[statuses[i].interface] = true;
1504 }
1505 }
1506
1507 return rv;
1508 }, this));
1509 },
1510
1511 /**
1512 * Get IPv6 wan networks.
1513 *
1514 * This function looks up all networks having a default `::/0` route
1515 * and returns them as array.
1516 *
1517 * @returns {Promise<Array<LuCI.network.Protocol>>}
1518 * Returns a promise resolving to an array of `Protocol` subclass
1519 * instances describing the found IPv6 default route interfaces.
1520 */
1521 getWAN6Networks: function() {
1522 return this.getStatusByRoute('::', 0).then(L.bind(function(statuses) {
1523 var rv = [], seen = {};
1524
1525 for (var i = 0; i < statuses.length; i++) {
1526 if (!seen.hasOwnProperty(statuses[i].interface)) {
1527 rv.push(this.instantiateNetwork(statuses[i].interface, statuses[i].proto));
1528 seen[statuses[i].interface] = true;
1529 }
1530 }
1531
1532 return rv;
1533 }, this));
1534 },
1535
1536 /**
1537 * Describes an swconfig switch topology by specifying the CPU
1538 * connections and external port labels of a switch.
1539 *
1540 * @typedef {Object<string, Object|Array>} SwitchTopology
1541 * @memberof LuCI.network
1542 *
1543 * @property {Object<number, string>} netdevs
1544 * The `netdevs` property points to an object describing the CPU port
1545 * connections of the switch. The numeric key of the enclosed object is
1546 * the port number, the value contains the Linux network device name the
1547 * port is hardwired to.
1548 *
1549 * @property {Array<Object<string, boolean|number|string>>} ports
1550 * The `ports` property points to an array describing the populated
1551 * ports of the switch in the external label order. Each array item is
1552 * an object containg the following keys:
1553 * - `num` - the internal switch port number
1554 * - `label` - the label of the port, e.g. `LAN 1` or `CPU (eth0)`
1555 * - `device` - the connected Linux network device name (CPU ports only)
1556 * - `tagged` - a boolean indicating whether the port must be tagged to
1557 * function (CPU ports only)
1558 */
1559
1560 /**
1561 * Returns the topologies of all swconfig switches found on the system.
1562 *
1563 * @returns {Promise<Object<string, LuCI.network.SwitchTopology>>}
1564 * Returns a promise resolving to an object containing the topologies
1565 * of each switch. The object keys correspond to the name of the switches
1566 * such as `switch0`, the values are
1567 * {@link LuCI.network.SwitchTopology SwitchTopology} objects describing
1568 * the layout.
1569 */
1570 getSwitchTopologies: function() {
1571 return initNetworkState().then(function() {
1572 return _state.switches;
1573 });
1574 },
1575
1576 /* private */
1577 instantiateNetwork: function(name, proto) {
1578 if (name == null)
1579 return null;
1580
1581 proto = (proto == null ? uci.get('network', name, 'proto') : proto);
1582
1583 var protoClass = _protocols[proto] || Protocol;
1584 return new protoClass(name);
1585 },
1586
1587 /* private */
1588 instantiateDevice: function(name, network, extend) {
1589 if (extend != null)
1590 return new (Device.extend(extend))(name, network);
1591
1592 return new Device(name, network);
1593 },
1594
1595 /* private */
1596 instantiateWifiDevice: function(radioname, radiostate) {
1597 return new WifiDevice(radioname, radiostate);
1598 },
1599
1600 /* private */
1601 instantiateWifiNetwork: function(sid, radioname, radiostate, netid, netstate, hostapd) {
1602 return new WifiNetwork(sid, radioname, radiostate, netid, netstate, hostapd);
1603 },
1604
1605 /* private */
1606 lookupWifiNetwork: function(netname) {
1607 var sid, res, netid, radioname, radiostate, netstate;
1608
1609 sid = getWifiSidByNetid(netname);
1610
1611 if (sid != null) {
1612 res = getWifiStateBySid(sid);
1613 netid = netname;
1614 radioname = res ? res[0] : null;
1615 radiostate = res ? res[1] : null;
1616 netstate = res ? res[2] : null;
1617 }
1618 else {
1619 res = getWifiStateByIfname(netname);
1620
1621 if (res != null) {
1622 radioname = res[0];
1623 radiostate = res[1];
1624 netstate = res[2];
1625 sid = netstate.section;
1626 netid = L.toArray(getWifiNetidBySid(sid))[0];
1627 }
1628 else {
1629 res = getWifiStateBySid(netname);
1630
1631 if (res != null) {
1632 radioname = res[0];
1633 radiostate = res[1];
1634 netstate = res[2];
1635 sid = netname;
1636 netid = L.toArray(getWifiNetidBySid(sid))[0];
1637 }
1638 else {
1639 res = getWifiNetidBySid(netname);
1640
1641 if (res != null) {
1642 netid = res[0];
1643 radioname = res[1];
1644 sid = netname;
1645 }
1646 }
1647 }
1648 }
1649
1650 return this.instantiateWifiNetwork(sid || netname, radioname,
1651 radiostate, netid, netstate,
1652 netstate ? _state.hostapd[netstate.ifname] : null);
1653 },
1654
1655 /**
1656 * Obtains the the network device name of the given object.
1657 *
1658 * @param {LuCI.network.Protocol|LuCI.network.Device|LuCI.network.WifiDevice|LuCI.network.WifiNetwork|string} obj
1659 * The object to get the device name from.
1660 *
1661 * @returns {null|string}
1662 * Returns a string containing the device name or `null` if the given
1663 * object could not be converted to a name.
1664 */
1665 getIfnameOf: function(obj) {
1666 return ifnameOf(obj);
1667 },
1668
1669 /**
1670 * Queries the internal DSL modem type from board information.
1671 *
1672 * @returns {Promise<null|string>}
1673 * Returns a promise resolving to the type of the internal modem
1674 * (e.g. `vdsl`) or to `null` if no internal modem is present.
1675 */
1676 getDSLModemType: function() {
1677 return initNetworkState().then(function() {
1678 return _state.hasDSLModem ? _state.hasDSLModem.type : null;
1679 });
1680 },
1681
1682 /**
1683 * Queries aggregated information about known hosts.
1684 *
1685 * This function aggregates information from various sources such as
1686 * DHCP lease databases, ARP and IPv6 neighbour entries, wireless
1687 * association list etc. and returns a {@link LuCI.network.Hosts Hosts}
1688 * class instance describing the found hosts.
1689 *
1690 * @returns {Promise<LuCI.network.Hosts>}
1691 * Returns a `Hosts` instance describing host known on the system.
1692 */
1693 getHostHints: function() {
1694 return initNetworkState().then(function() {
1695 return new Hosts(_state.hosts);
1696 });
1697 }
1698 });
1699
1700 /**
1701 * @class
1702 * @memberof LuCI.network
1703 * @hideconstructor
1704 * @classdesc
1705 *
1706 * The `LuCI.network.Hosts` class encapsulates host information aggregated
1707 * from multiple sources and provides convenience functions to access the
1708 * host information by different criteria.
1709 */
1710 Hosts = baseclass.extend(/** @lends LuCI.network.Hosts.prototype */ {
1711 __init__: function(hosts) {
1712 this.hosts = hosts;
1713 },
1714
1715 /**
1716 * Lookup the hostname associated with the given MAC address.
1717 *
1718 * @param {string} mac
1719 * The MAC address to lookup.
1720 *
1721 * @returns {null|string}
1722 * Returns the hostname associated with the given MAC or `null` if
1723 * no matching host could be found or if no hostname is known for
1724 * the corresponding host.
1725 */
1726 getHostnameByMACAddr: function(mac) {
1727 return this.hosts[mac] ? this.hosts[mac].name : null;
1728 },
1729
1730 /**
1731 * Lookup the IPv4 address associated with the given MAC address.
1732 *
1733 * @param {string} mac
1734 * The MAC address to lookup.
1735 *
1736 * @returns {null|string}
1737 * Returns the IPv4 address associated with the given MAC or `null` if
1738 * no matching host could be found or if no IPv4 address is known for
1739 * the corresponding host.
1740 */
1741 getIPAddrByMACAddr: function(mac) {
1742 return this.hosts[mac] ? this.hosts[mac].ipv4 : null;
1743 },
1744
1745 /**
1746 * Lookup the IPv6 address associated with the given MAC address.
1747 *
1748 * @param {string} mac
1749 * The MAC address to lookup.
1750 *
1751 * @returns {null|string}
1752 * Returns the IPv6 address associated with the given MAC or `null` if
1753 * no matching host could be found or if no IPv6 address is known for
1754 * the corresponding host.
1755 */
1756 getIP6AddrByMACAddr: function(mac) {
1757 return this.hosts[mac] ? this.hosts[mac].ipv6 : null;
1758 },
1759
1760 /**
1761 * Lookup the hostname associated with the given IPv4 address.
1762 *
1763 * @param {string} ipaddr
1764 * The IPv4 address to lookup.
1765 *
1766 * @returns {null|string}
1767 * Returns the hostname associated with the given IPv4 or `null` if
1768 * no matching host could be found or if no hostname is known for
1769 * the corresponding host.
1770 */
1771 getHostnameByIPAddr: function(ipaddr) {
1772 for (var mac in this.hosts)
1773 if (this.hosts[mac].ipv4 == ipaddr && this.hosts[mac].name != null)
1774 return this.hosts[mac].name;
1775 return null;
1776 },
1777
1778 /**
1779 * Lookup the MAC address associated with the given IPv4 address.
1780 *
1781 * @param {string} ipaddr
1782 * The IPv4 address to lookup.
1783 *
1784 * @returns {null|string}
1785 * Returns the MAC address associated with the given IPv4 or `null` if
1786 * no matching host could be found or if no MAC address is known for
1787 * the corresponding host.
1788 */
1789 getMACAddrByIPAddr: function(ipaddr) {
1790 for (var mac in this.hosts)
1791 if (this.hosts[mac].ipv4 == ipaddr)
1792 return mac;
1793 return null;
1794 },
1795
1796 /**
1797 * Lookup the hostname associated with the given IPv6 address.
1798 *
1799 * @param {string} ipaddr
1800 * The IPv6 address to lookup.
1801 *
1802 * @returns {null|string}
1803 * Returns the hostname associated with the given IPv6 or `null` if
1804 * no matching host could be found or if no hostname is known for
1805 * the corresponding host.
1806 */
1807 getHostnameByIP6Addr: function(ip6addr) {
1808 for (var mac in this.hosts)
1809 if (this.hosts[mac].ipv6 == ip6addr && this.hosts[mac].name != null)
1810 return this.hosts[mac].name;
1811 return null;
1812 },
1813
1814 /**
1815 * Lookup the MAC address associated with the given IPv6 address.
1816 *
1817 * @param {string} ipaddr
1818 * The IPv6 address to lookup.
1819 *
1820 * @returns {null|string}
1821 * Returns the MAC address associated with the given IPv6 or `null` if
1822 * no matching host could be found or if no MAC address is known for
1823 * the corresponding host.
1824 */
1825 getMACAddrByIP6Addr: function(ip6addr) {
1826 for (var mac in this.hosts)
1827 if (this.hosts[mac].ipv6 == ip6addr)
1828 return mac;
1829 return null;
1830 },
1831
1832 /**
1833 * Return an array of (MAC address, name hint) tuples sorted by
1834 * MAC address.
1835 *
1836 * @param {boolean} [preferIp6=false]
1837 * Whether to prefer IPv6 addresses (`true`) or IPv4 addresses (`false`)
1838 * as name hint when no hostname is known for a specific MAC address.
1839 *
1840 * @returns {Array<Array<string>>}
1841 * Returns an array of arrays containing a name hint for each found
1842 * MAC address on the system. The array is sorted ascending by MAC.
1843 *
1844 * Each item of the resulting array is a two element array with the
1845 * MAC being the first element and the name hint being the second
1846 * element. The name hint is either the hostname, an IPv4 or an IPv6
1847 * address related to the MAC address.
1848 *
1849 * If no hostname but both IPv4 and IPv6 addresses are known, the
1850 * `preferIP6` flag specifies whether the IPv6 or the IPv4 address
1851 * is used as hint.
1852 */
1853 getMACHints: function(preferIp6) {
1854 var rv = [];
1855 for (var mac in this.hosts) {
1856 var hint = this.hosts[mac].name ||
1857 this.hosts[mac][preferIp6 ? 'ipv6' : 'ipv4'] ||
1858 this.hosts[mac][preferIp6 ? 'ipv4' : 'ipv6'];
1859
1860 rv.push([mac, hint]);
1861 }
1862 return rv.sort(function(a, b) { return a[0] > b[0] });
1863 }
1864 });
1865
1866 /**
1867 * @class
1868 * @memberof LuCI.network
1869 * @hideconstructor
1870 * @classdesc
1871 *
1872 * The `Network.Protocol` class serves as base for protocol specific
1873 * subclasses which describe logical UCI networks defined by `config
1874 * interface` sections in `/etc/config/network`.
1875 */
1876 Protocol = baseclass.extend(/** @lends LuCI.network.Protocol.prototype */ {
1877 __init__: function(name) {
1878 this.sid = name;
1879 },
1880
1881 _get: function(opt) {
1882 var val = uci.get('network', this.sid, opt);
1883
1884 if (Array.isArray(val))
1885 return val.join(' ');
1886
1887 return val || '';
1888 },
1889
1890 _ubus: function(field) {
1891 for (var i = 0; i < _state.ifaces.length; i++) {
1892 if (_state.ifaces[i].interface != this.sid)
1893 continue;
1894
1895 return (field != null ? _state.ifaces[i][field] : _state.ifaces[i]);
1896 }
1897 },
1898
1899 /**
1900 * Read the given UCI option value of this network.
1901 *
1902 * @param {string} opt
1903 * The UCI option name to read.
1904 *
1905 * @returns {null|string|string[]}
1906 * Returns the UCI option value or `null` if the requested option is
1907 * not found.
1908 */
1909 get: function(opt) {
1910 return uci.get('network', this.sid, opt);
1911 },
1912
1913 /**
1914 * Set the given UCI option of this network to the given value.
1915 *
1916 * @param {string} opt
1917 * The name of the UCI option to set.
1918 *
1919 * @param {null|string|string[]} val
1920 * The value to set or `null` to remove the given option from the
1921 * configuration.
1922 */
1923 set: function(opt, val) {
1924 return uci.set('network', this.sid, opt, val);
1925 },
1926
1927 /**
1928 * Get the associared Linux network device of this network.
1929 *
1930 * @returns {null|string}
1931 * Returns the name of the associated network device or `null` if
1932 * it could not be determined.
1933 */
1934 getIfname: function() {
1935 var ifname;
1936
1937 if (this.isFloating())
1938 ifname = this._ubus('l3_device');
1939 else
1940 ifname = this._ubus('device') || this._ubus('l3_device');
1941
1942 if (ifname != null)
1943 return ifname;
1944
1945 var res = getWifiNetidByNetname(this.sid);
1946 return (res != null ? res[0] : null);
1947 },
1948
1949 /**
1950 * Get the name of this network protocol class.
1951 *
1952 * This function will be overwritten by subclasses created by
1953 * {@link LuCI.network#registerProtocol Network.registerProtocol()}.
1954 *
1955 * @abstract
1956 * @returns {string}
1957 * Returns the name of the network protocol implementation, e.g.
1958 * `static` or `dhcp`.
1959 */
1960 getProtocol: function() {
1961 return null;
1962 },
1963
1964 /**
1965 * Return a human readable description for the protcol, such as
1966 * `Static address` or `DHCP client`.
1967 *
1968 * This function should be overwritten by subclasses.
1969 *
1970 * @abstract
1971 * @returns {string}
1972 * Returns the description string.
1973 */
1974 getI18n: function() {
1975 switch (this.getProtocol()) {
1976 case 'none': return _('Unmanaged');
1977 case 'static': return _('Static address');
1978 case 'dhcp': return _('DHCP client');
1979 default: return _('Unknown');
1980 }
1981 },
1982
1983 /**
1984 * Get the type of the underlying interface.
1985 *
1986 * This function actually is a convenience wrapper around
1987 * `proto.get("type")` and is mainly used by other `LuCI.network` code
1988 * to check whether the interface is declared as bridge in UCI.
1989 *
1990 * @returns {null|string}
1991 * Returns the value of the `type` option of the associated logical
1992 * interface or `null` if no `type` option is set.
1993 */
1994 getType: function() {
1995 return this._get('type');
1996 },
1997
1998 /**
1999 * Get the name of the associated logical interface.
2000 *
2001 * @returns {string}
2002 * Returns the logical interface name, such as `lan` or `wan`.
2003 */
2004 getName: function() {
2005 return this.sid;
2006 },
2007
2008 /**
2009 * Get the uptime of the logical interface.
2010 *
2011 * @returns {number}
2012 * Returns the uptime of the associated interface in seconds.
2013 */
2014 getUptime: function() {
2015 return this._ubus('uptime') || 0;
2016 },
2017
2018 /**
2019 * Get the logical interface expiry time in seconds.
2020 *
2021 * For protocols that have a concept of a lease, such as DHCP or
2022 * DHCPv6, this function returns the remaining time in seconds
2023 * until the lease expires.
2024 *
2025 * @returns {number}
2026 * Returns the amount of seconds until the lease expires or `-1`
2027 * if it isn't applicable to the associated protocol.
2028 */
2029 getExpiry: function() {
2030 var u = this._ubus('uptime'),
2031 d = this._ubus('data');
2032
2033 if (typeof(u) == 'number' && d != null &&
2034 typeof(d) == 'object' && typeof(d.leasetime) == 'number') {
2035 var r = d.leasetime - (u % d.leasetime);
2036 return (r > 0 ? r : 0);
2037 }
2038
2039 return -1;
2040 },
2041
2042 /**
2043 * Get the metric value of the logical interface.
2044 *
2045 * @returns {number}
2046 * Returns the current metric value used for device and network
2047 * routes spawned by the associated logical interface.
2048 */
2049 getMetric: function() {
2050 return this._ubus('metric') || 0;
2051 },
2052
2053 /**
2054 * Get the requested firewall zone name of the logical interface.
2055 *
2056 * Some protocol implementations request a specific firewall zone
2057 * to trigger inclusion of their resulting network devices into the
2058 * firewall rule set.
2059 *
2060 * @returns {null|string}
2061 * Returns the requested firewall zone name as published in the
2062 * `ubus` runtime information or `null` if the remote protocol
2063 * handler didn't request a zone.
2064 */
2065 getZoneName: function() {
2066 var d = this._ubus('data');
2067
2068 if (L.isObject(d) && typeof(d.zone) == 'string')
2069 return d.zone;
2070
2071 return null;
2072 },
2073
2074 /**
2075 * Query the first (primary) IPv4 address of the logical interface.
2076 *
2077 * @returns {null|string}
2078 * Returns the primary IPv4 address registered by the protocol handler
2079 * or `null` if no IPv4 addresses were set.
2080 */
2081 getIPAddr: function() {
2082 var addrs = this._ubus('ipv4-address');
2083 return ((Array.isArray(addrs) && addrs.length) ? addrs[0].address : null);
2084 },
2085
2086 /**
2087 * Query all IPv4 addresses of the logical interface.
2088 *
2089 * @returns {string[]}
2090 * Returns an array of IPv4 addresses in CIDR notation which have been
2091 * registered by the protocol handler. The order of the resulting array
2092 * follows the order of the addresses in `ubus` runtime information.
2093 */
2094 getIPAddrs: function() {
2095 var addrs = this._ubus('ipv4-address'),
2096 rv = [];
2097
2098 if (Array.isArray(addrs))
2099 for (var i = 0; i < addrs.length; i++)
2100 rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
2101
2102 return rv;
2103 },
2104
2105 /**
2106 * Query the first (primary) IPv4 netmask of the logical interface.
2107 *
2108 * @returns {null|string}
2109 * Returns the netmask of the primary IPv4 address registered by the
2110 * protocol handler or `null` if no IPv4 addresses were set.
2111 */
2112 getNetmask: function() {
2113 var addrs = this._ubus('ipv4-address');
2114 if (Array.isArray(addrs) && addrs.length)
2115 return prefixToMask(addrs[0].mask, false);
2116 },
2117
2118 /**
2119 * Query the gateway (nexthop) of the default route associated with
2120 * this logical interface.
2121 *
2122 * @returns {string}
2123 * Returns a string containing the IPv4 nexthop address of the associated
2124 * default route or `null` if no default route was found.
2125 */
2126 getGatewayAddr: function() {
2127 var routes = this._ubus('route');
2128
2129 if (Array.isArray(routes))
2130 for (var i = 0; i < routes.length; i++)
2131 if (typeof(routes[i]) == 'object' &&
2132 routes[i].target == '0.0.0.0' &&
2133 routes[i].mask == 0)
2134 return routes[i].nexthop;
2135
2136 return null;
2137 },
2138
2139 /**
2140 * Query the IPv4 DNS servers associated with the logical interface.
2141 *
2142 * @returns {string[]}
2143 * Returns an array of IPv4 DNS servers registered by the remote
2144 * protocol backend.
2145 */
2146 getDNSAddrs: function() {
2147 var addrs = this._ubus('dns-server'),
2148 rv = [];
2149
2150 if (Array.isArray(addrs))
2151 for (var i = 0; i < addrs.length; i++)
2152 if (!/:/.test(addrs[i]))
2153 rv.push(addrs[i]);
2154
2155 return rv;
2156 },
2157
2158 /**
2159 * Query the first (primary) IPv6 address of the logical interface.
2160 *
2161 * @returns {null|string}
2162 * Returns the primary IPv6 address registered by the protocol handler
2163 * in CIDR notation or `null` if no IPv6 addresses were set.
2164 */
2165 getIP6Addr: function() {
2166 var addrs = this._ubus('ipv6-address');
2167
2168 if (Array.isArray(addrs) && L.isObject(addrs[0]))
2169 return '%s/%d'.format(addrs[0].address, addrs[0].mask);
2170
2171 addrs = this._ubus('ipv6-prefix-assignment');
2172
2173 if (Array.isArray(addrs) && L.isObject(addrs[0]) && L.isObject(addrs[0]['local-address']))
2174 return '%s/%d'.format(addrs[0]['local-address'].address, addrs[0]['local-address'].mask);
2175
2176 return null;
2177 },
2178
2179 /**
2180 * Query all IPv6 addresses of the logical interface.
2181 *
2182 * @returns {string[]}
2183 * Returns an array of IPv6 addresses in CIDR notation which have been
2184 * registered by the protocol handler. The order of the resulting array
2185 * follows the order of the addresses in `ubus` runtime information.
2186 */
2187 getIP6Addrs: function() {
2188 var addrs = this._ubus('ipv6-address'),
2189 rv = [];
2190
2191 if (Array.isArray(addrs))
2192 for (var i = 0; i < addrs.length; i++)
2193 if (L.isObject(addrs[i]))
2194 rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
2195
2196 addrs = this._ubus('ipv6-prefix-assignment');
2197
2198 if (Array.isArray(addrs))
2199 for (var i = 0; i < addrs.length; i++)
2200 if (L.isObject(addrs[i]) && L.isObject(addrs[i]['local-address']))
2201 rv.push('%s/%d'.format(addrs[i]['local-address'].address, addrs[i]['local-address'].mask));
2202
2203 return rv;
2204 },
2205
2206 /**
2207 * Query the gateway (nexthop) of the IPv6 default route associated with
2208 * this logical interface.
2209 *
2210 * @returns {string}
2211 * Returns a string containing the IPv6 nexthop address of the associated
2212 * default route or `null` if no default route was found.
2213 */
2214 getGateway6Addr: function() {
2215 var routes = this._ubus('route');
2216
2217 if (Array.isArray(routes))
2218 for (var i = 0; i < routes.length; i++)
2219 if (typeof(routes[i]) == 'object' &&
2220 routes[i].target == '::' &&
2221 routes[i].mask == 0)
2222 return routes[i].nexthop;
2223
2224 return null;
2225 },
2226
2227 /**
2228 * Query the IPv6 DNS servers associated with the logical interface.
2229 *
2230 * @returns {string[]}
2231 * Returns an array of IPv6 DNS servers registered by the remote
2232 * protocol backend.
2233 */
2234 getDNS6Addrs: function() {
2235 var addrs = this._ubus('dns-server'),
2236 rv = [];
2237
2238 if (Array.isArray(addrs))
2239 for (var i = 0; i < addrs.length; i++)
2240 if (/:/.test(addrs[i]))
2241 rv.push(addrs[i]);
2242
2243 return rv;
2244 },
2245
2246 /**
2247 * Query the routed IPv6 prefix associated with the logical interface.
2248 *
2249 * @returns {null|string}
2250 * Returns the routed IPv6 prefix registered by the remote protocol
2251 * handler or `null` if no prefix is present.
2252 */
2253 getIP6Prefix: function() {
2254 var prefixes = this._ubus('ipv6-prefix');
2255
2256 if (Array.isArray(prefixes) && L.isObject(prefixes[0]))
2257 return '%s/%d'.format(prefixes[0].address, prefixes[0].mask);
2258
2259 return null;
2260 },
2261
2262 /**
2263 * Query interface error messages published in `ubus` runtime state.
2264 *
2265 * Interface errors are emitted by remote protocol handlers if the setup
2266 * of the underlying logical interface failed, e.g. due to bad
2267 * configuration or network connectivity issues.
2268 *
2269 * This function will translate the found error codes to human readable
2270 * messages using the descriptions registered by
2271 * {@link LuCI.network#registerErrorCode Network.registerErrorCode()}
2272 * and fall back to `"Unknown error (%s)"` where `%s` is replaced by the
2273 * error code in case no translation can be found.
2274 *
2275 * @returns {string[]}
2276 * Returns an array of translated interface error messages.
2277 */
2278 getErrors: function() {
2279 var errors = this._ubus('errors'),
2280 rv = null;
2281
2282 if (Array.isArray(errors)) {
2283 for (var i = 0; i < errors.length; i++) {
2284 if (!L.isObject(errors[i]) || typeof(errors[i].code) != 'string')
2285 continue;
2286
2287 rv = rv || [];
2288 rv.push(proto_errors[errors[i].code] || _('Unknown error (%s)').format(errors[i].code));
2289 }
2290 }
2291
2292 return rv;
2293 },
2294
2295 /**
2296 * Checks whether the underlying logical interface is declared as bridge.
2297 *
2298 * @returns {boolean}
2299 * Returns `true` when the interface is declared with `option type bridge`
2300 * and when the associated protocol implementation is not marked virtual
2301 * or `false` when the logical interface is no bridge.
2302 */
2303 isBridge: function() {
2304 return (!this.isVirtual() && this.getType() == 'bridge');
2305 },
2306
2307 /**
2308 * Get the name of the opkg package providing the protocol functionality.
2309 *
2310 * This function should be overwritten by protocol specific subclasses.
2311 *
2312 * @abstract
2313 *
2314 * @returns {string}
2315 * Returns the name of the opkg package required for the protocol to
2316 * function, e.g. `odhcp6c` for the `dhcpv6` prototocol.
2317 */
2318 getOpkgPackage: function() {
2319 return null;
2320 },
2321
2322 /**
2323 * Checks whether the protocol functionality is installed.
2324 *
2325 * This function exists for compatibility with old code, it always
2326 * returns `true`.
2327 *
2328 * @deprecated
2329 * @abstract
2330 *
2331 * @returns {boolean}
2332 * Returns `true` if the protocol support is installed, else `false`.
2333 */
2334 isInstalled: function() {
2335 return true;
2336 },
2337
2338 /**
2339 * Checks whether this protocol is "virtual".
2340 *
2341 * A "virtual" protocol is a protocol which spawns its own interfaces
2342 * on demand instead of using existing physical interfaces.
2343 *
2344 * Examples for virtual protocols are `6in4` which `gre` spawn tunnel
2345 * network device on startup, examples for non-virtual protcols are
2346 * `dhcp` or `static` which apply IP configuration to existing interfaces.
2347 *
2348 * This function should be overwritten by subclasses.
2349 *
2350 * @returns {boolean}
2351 * Returns a boolean indicating whether the underlying protocol spawns
2352 * dynamic interfaces (`true`) or not (`false`).
2353 */
2354 isVirtual: function() {
2355 return false;
2356 },
2357
2358 /**
2359 * Checks whether this protocol is "floating".
2360 *
2361 * A "floating" protocol is a protocol which spawns its own interfaces
2362 * on demand, like a virtual one but which relies on an existinf lower
2363 * level interface to initiate the connection.
2364 *
2365 * An example for such a protocol is "pppoe".
2366 *
2367 * This function exists for backwards compatibility with older code
2368 * but should not be used anymore.
2369 *
2370 * @deprecated
2371 * @returns {boolean}
2372 * Returns a boolean indicating whether this protocol is floating (`true`)
2373 * or not (`false`).
2374 */
2375 isFloating: function() {
2376 return false;
2377 },
2378
2379 /**
2380 * Checks whether this logical interface is dynamic.
2381 *
2382 * A dynamic interface is an interface which has been created at runtime,
2383 * e.g. as sub-interface of another interface, but which is not backed by
2384 * any user configuration. Such dynamic interfaces cannot be edited but
2385 * only brought down or restarted.
2386 *
2387 * @returns {boolean}
2388 * Returns a boolean indicating whether this interface is dynamic (`true`)
2389 * or not (`false`).
2390 */
2391 isDynamic: function() {
2392 return (this._ubus('dynamic') == true);
2393 },
2394
2395 /**
2396 * Checks whether this interface is an alias interface.
2397 *
2398 * Alias interfaces are interfaces layering on top of another interface
2399 * and are denoted by a special `@interfacename` notation in the
2400 * underlying `ifname` option.
2401 *
2402 * @returns {null|string}
2403 * Returns the name of the parent interface if this logical interface
2404 * is an alias or `null` if it is not an alias interface.
2405 */
2406 isAlias: function() {
2407 var ifnames = L.toArray(uci.get('network', this.sid, 'ifname')),
2408 parent = null;
2409
2410 for (var i = 0; i < ifnames.length; i++)
2411 if (ifnames[i].charAt(0) == '@')
2412 parent = ifnames[i].substr(1);
2413 else if (parent != null)
2414 parent = null;
2415
2416 return parent;
2417 },
2418
2419 /**
2420 * Checks whether this logical interface is "empty", meaning that ut
2421 * has no network devices attached.
2422 *
2423 * @returns {boolean}
2424 * Returns `true` if this logical interface is empty, else `false`.
2425 */
2426 isEmpty: function() {
2427 if (this.isFloating())
2428 return false;
2429
2430 var empty = true,
2431 ifname = this._get('ifname');
2432
2433 if (ifname != null && ifname.match(/\S+/))
2434 empty = false;
2435
2436 if (empty == true && getWifiNetidBySid(this.sid) != null)
2437 empty = false;
2438
2439 return empty;
2440 },
2441
2442 /**
2443 * Checks whether this logical interface is configured and running.
2444 *
2445 * @returns {boolean}
2446 * Returns `true` when the interface is active or `false` when it is not.
2447 */
2448 isUp: function() {
2449 return (this._ubus('up') == true);
2450 },
2451
2452 /**
2453 * Add the given network device to the logical interface.
2454 *
2455 * @param {LuCI.network.Protocol|LuCI.network.Device|LuCI.network.WifiDevice|LuCI.network.WifiNetwork|string} device
2456 * The object or device name to add to the logical interface. In case the
2457 * given argument is not a string, it is resolved though the
2458 * {@link LuCI.network#getIfnameOf Network.getIfnameOf()} function.
2459 *
2460 * @returns {boolean}
2461 * Returns `true` if the device name has been added or `false` if any
2462 * argument was invalid, if the device was already part of the logical
2463 * interface or if the logical interface is virtual.
2464 */
2465 addDevice: function(ifname) {
2466 ifname = ifnameOf(ifname);
2467
2468 if (ifname == null || this.isFloating())
2469 return false;
2470
2471 var wif = getWifiSidByIfname(ifname);
2472
2473 if (wif != null)
2474 return appendValue('wireless', wif, 'network', this.sid);
2475
2476 return appendValue('network', this.sid, 'ifname', ifname);
2477 },
2478
2479 /**
2480 * Remove the given network device from the logical interface.
2481 *
2482 * @param {LuCI.network.Protocol|LuCI.network.Device|LuCI.network.WifiDevice|LuCI.network.WifiNetwork|string} device
2483 * The object or device name to remove from the logical interface. In case
2484 * the given argument is not a string, it is resolved though the
2485 * {@link LuCI.network#getIfnameOf Network.getIfnameOf()} function.
2486 *
2487 * @returns {boolean}
2488 * Returns `true` if the device name has been added or `false` if any
2489 * argument was invalid, if the device was already part of the logical
2490 * interface or if the logical interface is virtual.
2491 */
2492 deleteDevice: function(ifname) {
2493 var rv = false;
2494
2495 ifname = ifnameOf(ifname);
2496
2497 if (ifname == null || this.isFloating())
2498 return false;
2499
2500 var wif = getWifiSidByIfname(ifname);
2501
2502 if (wif != null)
2503 rv = removeValue('wireless', wif, 'network', this.sid);
2504
2505 if (removeValue('network', this.sid, 'ifname', ifname))
2506 rv = true;
2507
2508 return rv;
2509 },
2510
2511 /**
2512 * Returns the Linux network device associated with this logical
2513 * interface.
2514 *
2515 * @returns {LuCI.network.Device}
2516 * Returns a `Network.Device` class instance representing the
2517 * expected Linux network device according to the configuration.
2518 */
2519 getDevice: function() {
2520 if (this.isVirtual()) {
2521 var ifname = '%s-%s'.format(this.getProtocol(), this.sid);
2522 _state.isTunnel[this.getProtocol() + '-' + this.sid] = true;
2523 return Network.prototype.instantiateDevice(ifname, this);
2524 }
2525 else if (this.isBridge()) {
2526 var ifname = 'br-%s'.format(this.sid);
2527 _state.isBridge[ifname] = true;
2528 return new Device(ifname, this);
2529 }
2530 else {
2531 var ifnames = L.toArray(uci.get('network', this.sid, 'ifname'));
2532
2533 for (var i = 0; i < ifnames.length; i++) {
2534 var m = ifnames[i].match(/^([^:/]+)/);
2535 return ((m && m[1]) ? Network.prototype.instantiateDevice(m[1], this) : null);
2536 }
2537
2538 ifname = getWifiNetidByNetname(this.sid);
2539
2540 return (ifname != null ? Network.prototype.instantiateDevice(ifname[0], this) : null);
2541 }
2542 },
2543
2544 /**
2545 * Returns the layer 2 linux network device currently associated
2546 * with this logical interface.
2547 *
2548 * @returns {LuCI.network.Device}
2549 * Returns a `Network.Device` class instance representing the Linux
2550 * network device currently associated with the logical interface.
2551 */
2552 getL2Device: function() {
2553 var ifname = this._ubus('device');
2554 return (ifname != null ? Network.prototype.instantiateDevice(ifname, this) : null);
2555 },
2556
2557 /**
2558 * Returns the layer 3 linux network device currently associated
2559 * with this logical interface.
2560 *
2561 * @returns {LuCI.network.Device}
2562 * Returns a `Network.Device` class instance representing the Linux
2563 * network device currently associated with the logical interface.
2564 */
2565 getL3Device: function() {
2566 var ifname = this._ubus('l3_device');
2567 return (ifname != null ? Network.prototype.instantiateDevice(ifname, this) : null);
2568 },
2569
2570 /**
2571 * Returns a list of network sub-devices associated with this logical
2572 * interface.
2573 *
2574 * @returns {null|Array<LuCI.network.Device>}
2575 * Returns an array of of `Network.Device` class instances representing
2576 * the sub-devices attached to this logical interface or `null` if the
2577 * logical interface does not support sub-devices, e.g. because it is
2578 * virtual and not a bridge.
2579 */
2580 getDevices: function() {
2581 var rv = [];
2582
2583 if (!this.isBridge() && !(this.isVirtual() && !this.isFloating()))
2584 return null;
2585
2586 var ifnames = L.toArray(uci.get('network', this.sid, 'ifname'));
2587
2588 for (var i = 0; i < ifnames.length; i++) {
2589 if (ifnames[i].charAt(0) == '@')
2590 continue;
2591
2592 var m = ifnames[i].match(/^([^:/]+)/);
2593 if (m != null)
2594 rv.push(Network.prototype.instantiateDevice(m[1], this));
2595 }
2596
2597 var uciWifiIfaces = uci.sections('wireless', 'wifi-iface');
2598
2599 for (var i = 0; i < uciWifiIfaces.length; i++) {
2600 if (typeof(uciWifiIfaces[i].device) != 'string')
2601 continue;
2602
2603 var networks = L.toArray(uciWifiIfaces[i].network);
2604
2605 for (var j = 0; j < networks.length; j++) {
2606 if (networks[j] != this.sid)
2607 continue;
2608
2609 var netid = getWifiNetidBySid(uciWifiIfaces[i]['.name']);
2610
2611 if (netid != null)
2612 rv.push(Network.prototype.instantiateDevice(netid[0], this));
2613 }
2614 }
2615
2616 rv.sort(deviceSort);
2617
2618 return rv;
2619 },
2620
2621 /**
2622 * Checks whether this logical interface contains the given device
2623 * object.
2624 *
2625 * @param {LuCI.network.Protocol|LuCI.network.Device|LuCI.network.WifiDevice|LuCI.network.WifiNetwork|string} device
2626 * The object or device name to check. In case the given argument is not
2627 * a string, it is resolved though the
2628 * {@link LuCI.network#getIfnameOf Network.getIfnameOf()} function.
2629 *
2630 * @returns {boolean}
2631 * Returns `true` when this logical interface contains the given network
2632 * device or `false` if not.
2633 */
2634 containsDevice: function(ifname) {
2635 ifname = ifnameOf(ifname);
2636
2637 if (ifname == null)
2638 return false;
2639 else if (this.isVirtual() && '%s-%s'.format(this.getProtocol(), this.sid) == ifname)
2640 return true;
2641 else if (this.isBridge() && 'br-%s'.format(this.sid) == ifname)
2642 return true;
2643
2644 var ifnames = L.toArray(uci.get('network', this.sid, 'ifname'));
2645
2646 for (var i = 0; i < ifnames.length; i++) {
2647 var m = ifnames[i].match(/^([^:/]+)/);
2648 if (m != null && m[1] == ifname)
2649 return true;
2650 }
2651
2652 var wif = getWifiSidByIfname(ifname);
2653
2654 if (wif != null) {
2655 var networks = L.toArray(uci.get('wireless', wif, 'network'));
2656
2657 for (var i = 0; i < networks.length; i++)
2658 if (networks[i] == this.sid)
2659 return true;
2660 }
2661
2662 return false;
2663 },
2664
2665 /**
2666 * Cleanup related configuration entries.
2667 *
2668 * This function will be invoked if an interface is about to be removed
2669 * from the configuration and is responsible for performing any required
2670 * cleanup tasks, such as unsetting uci entries in related configurations.
2671 *
2672 * It should be overwritten by protocol specific subclasses.
2673 *
2674 * @abstract
2675 *
2676 * @returns {*|Promise<*>}
2677 * This function may return a promise which is awaited before the rest of
2678 * the configuration is removed. Any non-promise return value and any
2679 * resolved promise value is ignored. If the returned promise is rejected,
2680 * the interface removal will be aborted.
2681 */
2682 deleteConfiguration: function() {}
2683 });
2684
2685 /**
2686 * @class
2687 * @memberof LuCI.network
2688 * @hideconstructor
2689 * @classdesc
2690 *
2691 * A `Network.Device` class instance represents an underlying Linux network
2692 * device and allows querying device details such as packet statistics or MTU.
2693 */
2694 Device = baseclass.extend(/** @lends LuCI.network.Device.prototype */ {
2695 __init__: function(ifname, network) {
2696 var wif = getWifiSidByIfname(ifname);
2697
2698 if (wif != null) {
2699 var res = getWifiStateBySid(wif) || [],
2700 netid = getWifiNetidBySid(wif) || [];
2701
2702 this.wif = new WifiNetwork(wif, res[0], res[1], netid[0], res[2], { ifname: ifname });
2703 this.ifname = this.wif.getIfname();
2704 }
2705
2706 this.ifname = this.ifname || ifname;
2707 this.dev = _state.netdevs[this.ifname];
2708 this.network = network;
2709 },
2710
2711 _devstate: function(/* ... */) {
2712 var rv = this.dev;
2713
2714 for (var i = 0; i < arguments.length; i++)
2715 if (L.isObject(rv))
2716 rv = rv[arguments[i]];
2717 else
2718 return null;
2719
2720 return rv;
2721 },
2722
2723 /**
2724 * Get the name of the network device.
2725 *
2726 * @returns {string}
2727 * Returns the name of the device, e.g. `eth0` or `wlan0`.
2728 */
2729 getName: function() {
2730 return (this.wif != null ? this.wif.getIfname() : this.ifname);
2731 },
2732
2733 /**
2734 * Get the MAC address of the device.
2735 *
2736 * @returns {null|string}
2737 * Returns the MAC address of the device or `null` if not applicable,
2738 * e.g. for non-ethernet tunnel devices.
2739 */
2740 getMAC: function() {
2741 var mac = this._devstate('macaddr');
2742 return mac ? mac.toUpperCase() : null;
2743 },
2744
2745 /**
2746 * Get the MTU of the device.
2747 *
2748 * @returns {number}
2749 * Returns the MTU of the device.
2750 */
2751 getMTU: function() {
2752 return this._devstate('mtu');
2753 },
2754
2755 /**
2756 * Get the IPv4 addresses configured on the device.
2757 *
2758 * @returns {string[]}
2759 * Returns an array of IPv4 address strings.
2760 */
2761 getIPAddrs: function() {
2762 var addrs = this._devstate('ipaddrs');
2763 return (Array.isArray(addrs) ? addrs : []);
2764 },
2765
2766 /**
2767 * Get the IPv6 addresses configured on the device.
2768 *
2769 * @returns {string[]}
2770 * Returns an array of IPv6 address strings.
2771 */
2772 getIP6Addrs: function() {
2773 var addrs = this._devstate('ip6addrs');
2774 return (Array.isArray(addrs) ? addrs : []);
2775 },
2776
2777 /**
2778 * Get the type of the device..
2779 *
2780 * @returns {string}
2781 * Returns a string describing the type of the network device:
2782 * - `alias` if it is an abstract alias device (`@` notation)
2783 * - `wifi` if it is a wireless interface (e.g. `wlan0`)
2784 * - `bridge` if it is a bridge device (e.g. `br-lan`)
2785 * - `tunnel` if it is a tun or tap device (e.g. `tun0`)
2786 * - `vlan` if it is a vlan device (e.g. `eth0.1`)
2787 * - `switch` if it is a switch device (e.g.`eth1` connected to switch0)
2788 * - `ethernet` for all other device types
2789 */
2790 getType: function() {
2791 if (this.ifname != null && this.ifname.charAt(0) == '@')
2792 return 'alias';
2793 else if (this.wif != null || isWifiIfname(this.ifname))
2794 return 'wifi';
2795 else if (_state.isBridge[this.ifname])
2796 return 'bridge';
2797 else if (_state.isTunnel[this.ifname])
2798 return 'tunnel';
2799 else if (this.ifname.indexOf('.') > -1)
2800 return 'vlan';
2801 else if (_state.isSwitch[this.ifname])
2802 return 'switch';
2803 else
2804 return 'ethernet';
2805 },
2806
2807 /**
2808 * Get a short description string for the device.
2809 *
2810 * @returns {string}
2811 * Returns the device name for non-wifi devices or a string containing
2812 * the operation mode and SSID for wifi devices.
2813 */
2814 getShortName: function() {
2815 if (this.wif != null)
2816 return this.wif.getShortName();
2817
2818 return this.ifname;
2819 },
2820
2821 /**
2822 * Get a long description string for the device.
2823 *
2824 * @returns {string}
2825 * Returns a string containing the type description and device name
2826 * for non-wifi devices or operation mode and ssid for wifi ones.
2827 */
2828 getI18n: function() {
2829 if (this.wif != null) {
2830 return '%s: %s "%s"'.format(
2831 _('Wireless Network'),
2832 this.wif.getActiveMode(),
2833 this.wif.getActiveSSID() || this.wif.getActiveBSSID() || this.wif.getID() || '?');
2834 }
2835
2836 return '%s: "%s"'.format(this.getTypeI18n(), this.getName());
2837 },
2838
2839 /**
2840 * Get a string describing the device type.
2841 *
2842 * @returns {string}
2843 * Returns a string describing the type, e.g. "Wireless Adapter" or
2844 * "Bridge".
2845 */
2846 getTypeI18n: function() {
2847 switch (this.getType()) {
2848 case 'alias':
2849 return _('Alias Interface');
2850
2851 case 'wifi':
2852 return _('Wireless Adapter');
2853
2854 case 'bridge':
2855 return _('Bridge');
2856
2857 case 'switch':
2858 return _('Ethernet Switch');
2859
2860 case 'vlan':
2861 return (_state.isSwitch[this.ifname] ? _('Switch VLAN') : _('Software VLAN'));
2862
2863 case 'tunnel':
2864 return _('Tunnel Interface');
2865
2866 default:
2867 return _('Ethernet Adapter');
2868 }
2869 },
2870
2871 /**
2872 * Get the associated bridge ports of the device.
2873 *
2874 * @returns {null|Array<LuCI.network.Device>}
2875 * Returns an array of `Network.Device` instances representing the ports
2876 * (slave interfaces) of the bridge or `null` when this device isn't
2877 * a Linux bridge.
2878 */
2879 getPorts: function() {
2880 var br = _state.bridges[this.ifname],
2881 rv = [];
2882
2883 if (br == null || !Array.isArray(br.ifnames))
2884 return null;
2885
2886 for (var i = 0; i < br.ifnames.length; i++)
2887 rv.push(Network.prototype.instantiateDevice(br.ifnames[i].name));
2888
2889 rv.sort(deviceSort);
2890
2891 return rv;
2892 },
2893
2894 /**
2895 * Get the bridge ID
2896 *
2897 * @returns {null|string}
2898 * Returns the ID of this network bridge or `null` if this network
2899 * device is not a Linux bridge.
2900 */
2901 getBridgeID: function() {
2902 var br = _state.bridges[this.ifname];
2903 return (br != null ? br.id : null);
2904 },
2905
2906 /**
2907 * Get the bridge STP setting
2908 *
2909 * @returns {boolean}
2910 * Returns `true` when this device is a Linux bridge and has `stp`
2911 * enabled, else `false`.
2912 */
2913 getBridgeSTP: function() {
2914 var br = _state.bridges[this.ifname];
2915 return (br != null ? !!br.stp : false);
2916 },
2917
2918 /**
2919 * Checks whether this device is up.
2920 *
2921 * @returns {boolean}
2922 * Returns `true` when the associated device is running pr `false`
2923 * when it is down or absent.
2924 */
2925 isUp: function() {
2926 var up = this._devstate('flags', 'up');
2927
2928 if (up == null)
2929 up = (this.getType() == 'alias');
2930
2931 return up;
2932 },
2933
2934 /**
2935 * Checks whether this device is a Linux bridge.
2936 *
2937 * @returns {boolean}
2938 * Returns `true` when the network device is present and a Linux bridge,
2939 * else `false`.
2940 */
2941 isBridge: function() {
2942 return (this.getType() == 'bridge');
2943 },
2944
2945 /**
2946 * Checks whether this device is part of a Linux bridge.
2947 *
2948 * @returns {boolean}
2949 * Returns `true` when this network device is part of a bridge,
2950 * else `false`.
2951 */
2952 isBridgePort: function() {
2953 return (this._devstate('bridge') != null);
2954 },
2955
2956 /**
2957 * Get the amount of transmitted bytes.
2958 *
2959 * @returns {number}
2960 * Returns the amount of bytes transmitted by the network device.
2961 */
2962 getTXBytes: function() {
2963 var stat = this._devstate('stats');
2964 return (stat != null ? stat.tx_bytes || 0 : 0);
2965 },
2966
2967 /**
2968 * Get the amount of received bytes.
2969 *
2970 * @returns {number}
2971 * Returns the amount of bytes received by the network device.
2972 */
2973 getRXBytes: function() {
2974 var stat = this._devstate('stats');
2975 return (stat != null ? stat.rx_bytes || 0 : 0);
2976 },
2977
2978 /**
2979 * Get the amount of transmitted packets.
2980 *
2981 * @returns {number}
2982 * Returns the amount of packets transmitted by the network device.
2983 */
2984 getTXPackets: function() {
2985 var stat = this._devstate('stats');
2986 return (stat != null ? stat.tx_packets || 0 : 0);
2987 },
2988
2989 /**
2990 * Get the amount of received packets.
2991 *
2992 * @returns {number}
2993 * Returns the amount of packets received by the network device.
2994 */
2995 getRXPackets: function() {
2996 var stat = this._devstate('stats');
2997 return (stat != null ? stat.rx_packets || 0 : 0);
2998 },
2999
3000 /**
3001 * Get the primary logical interface this device is assigned to.
3002 *
3003 * @returns {null|LuCI.network.Protocol}
3004 * Returns a `Network.Protocol` instance representing the logical
3005 * interface this device is attached to or `null` if it is not
3006 * assigned to any logical interface.
3007 */
3008 getNetwork: function() {
3009 return this.getNetworks()[0];
3010 },
3011
3012 /**
3013 * Get the logical interfaces this device is assigned to.
3014 *
3015 * @returns {Array<LuCI.network.Protocol>}
3016 * Returns an array of `Network.Protocol` instances representing the
3017 * logical interfaces this device is assigned to.
3018 */
3019 getNetworks: function() {
3020 if (this.networks == null) {
3021 this.networks = [];
3022
3023 var networks = enumerateNetworks.apply(L.network);
3024
3025 for (var i = 0; i < networks.length; i++)
3026 if (networks[i].containsDevice(this.ifname) || networks[i].getIfname() == this.ifname)
3027 this.networks.push(networks[i]);
3028
3029 this.networks.sort(networkSort);
3030 }
3031
3032 return this.networks;
3033 },
3034
3035 /**
3036 * Get the related wireless network this device is related to.
3037 *
3038 * @returns {null|LuCI.network.WifiNetwork}
3039 * Returns a `Network.WifiNetwork` instance representing the wireless
3040 * network corresponding to this network device or `null` if this device
3041 * is not a wireless device.
3042 */
3043 getWifiNetwork: function() {
3044 return (this.wif != null ? this.wif : null);
3045 }
3046 });
3047
3048 /**
3049 * @class
3050 * @memberof LuCI.network
3051 * @hideconstructor
3052 * @classdesc
3053 *
3054 * A `Network.WifiDevice` class instance represents a wireless radio device
3055 * present on the system and provides wireless capability information as
3056 * well as methods for enumerating related wireless networks.
3057 */
3058 WifiDevice = baseclass.extend(/** @lends LuCI.network.WifiDevice.prototype */ {
3059 __init__: function(name, radiostate) {
3060 var uciWifiDevice = uci.get('wireless', name);
3061
3062 if (uciWifiDevice != null &&
3063 uciWifiDevice['.type'] == 'wifi-device' &&
3064 uciWifiDevice['.name'] != null) {
3065 this.sid = uciWifiDevice['.name'];
3066 }
3067
3068 this.sid = this.sid || name;
3069 this._ubusdata = {
3070 radio: name,
3071 dev: radiostate
3072 };
3073 },
3074
3075 /* private */
3076 ubus: function(/* ... */) {
3077 var v = this._ubusdata;
3078
3079 for (var i = 0; i < arguments.length; i++)
3080 if (L.isObject(v))
3081 v = v[arguments[i]];
3082 else
3083 return null;
3084
3085 return v;
3086 },
3087
3088 /**
3089 * Read the given UCI option value of this wireless device.
3090 *
3091 * @param {string} opt
3092 * The UCI option name to read.
3093 *
3094 * @returns {null|string|string[]}
3095 * Returns the UCI option value or `null` if the requested option is
3096 * not found.
3097 */
3098 get: function(opt) {
3099 return uci.get('wireless', this.sid, opt);
3100 },
3101
3102 /**
3103 * Set the given UCI option of this network to the given value.
3104 *
3105 * @param {string} opt
3106 * The name of the UCI option to set.
3107 *
3108 * @param {null|string|string[]} val
3109 * The value to set or `null` to remove the given option from the
3110 * configuration.
3111 */
3112 set: function(opt, value) {
3113 return uci.set('wireless', this.sid, opt, value);
3114 },
3115
3116 /**
3117 * Checks whether this wireless radio is disabled.
3118 *
3119 * @returns {boolean}
3120 * Returns `true` when the wireless radio is marked as disabled in `ubus`
3121 * runtime state or when the `disabled` option is set in the corresponding
3122 * UCI configuration.
3123 */
3124 isDisabled: function() {
3125 return this.ubus('dev', 'disabled') || this.get('disabled') == '1';
3126 },
3127
3128 /**
3129 * Get the configuration name of this wireless radio.
3130 *
3131 * @returns {string}
3132 * Returns the UCI section name (e.g. `radio0`) of the corresponding
3133 * radio configuration which also serves as unique logical identifier
3134 * for the wireless phy.
3135 */
3136 getName: function() {
3137 return this.sid;
3138 },
3139
3140 /**
3141 * Gets a list of supported hwmodes.
3142 *
3143 * The hwmode values describe the frequency band and wireless standard
3144 * versions supported by the wireless phy.
3145 *
3146 * @returns {string[]}
3147 * Returns an array of valid hwmode values for this radio. Currently
3148 * known mode values are:
3149 * - `a` - Legacy 802.11a mode, 5 GHz, up to 54 Mbit/s
3150 * - `b` - Legacy 802.11b mode, 2.4 GHz, up to 11 Mbit/s
3151 * - `g` - Legacy 802.11g mode, 2.4 GHz, up to 54 Mbit/s
3152 * - `n` - IEEE 802.11n mode, 2.4 or 5 GHz, up to 600 Mbit/s
3153 * - `ac` - IEEE 802.11ac mode, 5 GHz, up to 6770 Mbit/s
3154 */
3155 getHWModes: function() {
3156 var hwmodes = this.ubus('dev', 'iwinfo', 'hwmodes');
3157 return Array.isArray(hwmodes) ? hwmodes : [ 'b', 'g' ];
3158 },
3159
3160 /**
3161 * Gets a list of supported htmodes.
3162 *
3163 * The htmode values describe the wide-frequency options supported by
3164 * the wireless phy.
3165 *
3166 * @returns {string[]}
3167 * Returns an array of valid htmode values for this radio. Currently
3168 * known mode values are:
3169 * - `HT20` - applicable to IEEE 802.11n, 20 MHz wide channels
3170 * - `HT40` - applicable to IEEE 802.11n, 40 MHz wide channels
3171 * - `VHT20` - applicable to IEEE 802.11ac, 20 MHz wide channels
3172 * - `VHT40` - applicable to IEEE 802.11ac, 40 MHz wide channels
3173 * - `VHT80` - applicable to IEEE 802.11ac, 80 MHz wide channels
3174 * - `VHT160` - applicable to IEEE 802.11ac, 160 MHz wide channels
3175 */
3176 getHTModes: function() {
3177 var htmodes = this.ubus('dev', 'iwinfo', 'htmodes');
3178 return (Array.isArray(htmodes) && htmodes.length) ? htmodes : null;
3179 },
3180
3181 /**
3182 * Get a string describing the wireless radio hardware.
3183 *
3184 * @returns {string}
3185 * Returns the description string.
3186 */
3187 getI18n: function() {
3188 var hw = this.ubus('dev', 'iwinfo', 'hardware'),
3189 type = L.isObject(hw) ? hw.name : null;
3190
3191 if (this.ubus('dev', 'iwinfo', 'type') == 'wl')
3192 type = 'Broadcom';
3193
3194 var hwmodes = this.getHWModes(),
3195 modestr = '';
3196
3197 hwmodes.sort(function(a, b) {
3198 return (a.length != b.length ? a.length > b.length : a > b);
3199 });
3200
3201 modestr = hwmodes.join('');
3202
3203 return '%s 802.11%s Wireless Controller (%s)'.format(type || 'Generic', modestr, this.getName());
3204 },
3205
3206 /**
3207 * A wireless scan result object describes a neighbouring wireless
3208 * network found in the vincinity.
3209 *
3210 * @typedef {Object<string, number|string|LuCI.network.WifiEncryption>} WifiScanResult
3211 * @memberof LuCI.network
3212 *
3213 * @property {string} ssid
3214 * The SSID / Mesh ID of the network.
3215 *
3216 * @property {string} bssid
3217 * The BSSID if the network.
3218 *
3219 * @property {string} mode
3220 * The operation mode of the network (`Master`, `Ad-Hoc`, `Mesh Point`).
3221 *
3222 * @property {number} channel
3223 * The wireless channel of the network.
3224 *
3225 * @property {number} signal
3226 * The received signal strength of the network in dBm.
3227 *
3228 * @property {number} quality
3229 * The numeric quality level of the signal, can be used in conjunction
3230 * with `quality_max` to calculate a quality percentage.
3231 *
3232 * @property {number} quality_max
3233 * The maximum possible quality level of the signal, can be used in
3234 * conjunction with `quality` to calculate a quality percentage.
3235 *
3236 * @property {LuCI.network.WifiEncryption} encryption
3237 * The encryption used by the wireless network.
3238 */
3239
3240 /**
3241 * Trigger a wireless scan on this radio device and obtain a list of
3242 * nearby networks.
3243 *
3244 * @returns {Promise<Array<LuCI.network.WifiScanResult>>}
3245 * Returns a promise resolving to an array of scan result objects
3246 * describing the networks found in the vincinity.
3247 */
3248 getScanList: function() {
3249 return callIwinfoScan(this.sid);
3250 },
3251
3252 /**
3253 * Check whether the wireless radio is marked as up in the `ubus`
3254 * runtime state.
3255 *
3256 * @returns {boolean}
3257 * Returns `true` when the radio device is up, else `false`.
3258 */
3259 isUp: function() {
3260 if (L.isObject(_state.radios[this.sid]))
3261 return (_state.radios[this.sid].up == true);
3262
3263 return false;
3264 },
3265
3266 /**
3267 * Get the wifi network of the given name belonging to this radio device
3268 *
3269 * @param {string} network
3270 * The name of the wireless network to lookup. This may be either an uci
3271 * configuration section ID, a network ID in the form `radio#.network#`
3272 * or a Linux network device name like `wlan0` which is resolved to the
3273 * corresponding configuration section through `ubus` runtime information.
3274 *
3275 * @returns {Promise<LuCI.network.WifiNetwork>}
3276 * Returns a promise resolving to a `Network.WifiNetwork` instance
3277 * representing the wireless network and rejecting with `null` if
3278 * the given network could not be found or is not associated with
3279 * this radio device.
3280 */
3281 getWifiNetwork: function(network) {
3282 return Network.prototype.getWifiNetwork(network).then(L.bind(function(networkInstance) {
3283 var uciWifiIface = (networkInstance.sid ? uci.get('wireless', networkInstance.sid) : null);
3284
3285 if (uciWifiIface == null || uciWifiIface['.type'] != 'wifi-iface' || uciWifiIface.device != this.sid)
3286 return Promise.reject();
3287
3288 return networkInstance;
3289 }, this));
3290 },
3291
3292 /**
3293 * Get all wireless networks associated with this wireless radio device.
3294 *
3295 * @returns {Promise<Array<LuCI.network.WifiNetwork>>}
3296 * Returns a promise resolving to an array of `Network.WifiNetwork`
3297 * instances respresenting the wireless networks associated with this
3298 * radio device.
3299 */
3300 getWifiNetworks: function() {
3301 return Network.prototype.getWifiNetworks().then(L.bind(function(networks) {
3302 var rv = [];
3303
3304 for (var i = 0; i < networks.length; i++)
3305 if (networks[i].getWifiDeviceName() == this.getName())
3306 rv.push(networks[i]);
3307
3308 return rv;
3309 }, this));
3310 },
3311
3312 /**
3313 * Adds a new wireless network associated with this radio device to the
3314 * configuration and sets its options to the provided values.
3315 *
3316 * @param {Object<string, string|string[]>} [options]
3317 * The options to set for the newly added wireless network.
3318 *
3319 * @returns {Promise<null|LuCI.network.WifiNetwork>}
3320 * Returns a promise resolving to a `WifiNetwork` instance describing
3321 * the newly added wireless network or `null` if the given options
3322 * were invalid.
3323 */
3324 addWifiNetwork: function(options) {
3325 if (!L.isObject(options))
3326 options = {};
3327
3328 options.device = this.sid;
3329
3330 return Network.prototype.addWifiNetwork(options);
3331 },
3332
3333 /**
3334 * Deletes the wireless network with the given name associated with this
3335 * radio device.
3336 *
3337 * @param {string} network
3338 * The name of the wireless network to lookup. This may be either an uci
3339 * configuration section ID, a network ID in the form `radio#.network#`
3340 * or a Linux network device name like `wlan0` which is resolved to the
3341 * corresponding configuration section through `ubus` runtime information.
3342 *
3343 * @returns {Promise<boolean>}
3344 * Returns a promise resolving to `true` when the wireless network was
3345 * successfully deleted from the configuration or `false` when the given
3346 * network could not be found or if the found network was not associated
3347 * with this wireless radio device.
3348 */
3349 deleteWifiNetwork: function(network) {
3350 var sid = null;
3351
3352 if (network instanceof WifiNetwork) {
3353 sid = network.sid;
3354 }
3355 else {
3356 var uciWifiIface = uci.get('wireless', network);
3357
3358 if (uciWifiIface == null || uciWifiIface['.type'] != 'wifi-iface')
3359 sid = getWifiSidByIfname(network);
3360 }
3361
3362 if (sid == null || uci.get('wireless', sid, 'device') != this.sid)
3363 return Promise.resolve(false);
3364
3365 uci.delete('wireless', network);
3366
3367 return Promise.resolve(true);
3368 }
3369 });
3370
3371 /**
3372 * @class
3373 * @memberof LuCI.network
3374 * @hideconstructor
3375 * @classdesc
3376 *
3377 * A `Network.WifiNetwork` instance represents a wireless network (vif)
3378 * configured on top of a radio device and provides functions for querying
3379 * the runtime state of the network. Most radio devices support multiple
3380 * such networks in parallel.
3381 */
3382 WifiNetwork = baseclass.extend(/** @lends LuCI.network.WifiNetwork.prototype */ {
3383 __init__: function(sid, radioname, radiostate, netid, netstate, hostapd) {
3384 this.sid = sid;
3385 this.netid = netid;
3386 this._ubusdata = {
3387 hostapd: hostapd,
3388 radio: radioname,
3389 dev: radiostate,
3390 net: netstate
3391 };
3392 },
3393
3394 ubus: function(/* ... */) {
3395 var v = this._ubusdata;
3396
3397 for (var i = 0; i < arguments.length; i++)
3398 if (L.isObject(v))
3399 v = v[arguments[i]];
3400 else
3401 return null;
3402
3403 return v;
3404 },
3405
3406 /**
3407 * Read the given UCI option value of this wireless network.
3408 *
3409 * @param {string} opt
3410 * The UCI option name to read.
3411 *
3412 * @returns {null|string|string[]}
3413 * Returns the UCI option value or `null` if the requested option is
3414 * not found.
3415 */
3416 get: function(opt) {
3417 return uci.get('wireless', this.sid, opt);
3418 },
3419
3420 /**
3421 * Set the given UCI option of this network to the given value.
3422 *
3423 * @param {string} opt
3424 * The name of the UCI option to set.
3425 *
3426 * @param {null|string|string[]} val
3427 * The value to set or `null` to remove the given option from the
3428 * configuration.
3429 */
3430 set: function(opt, value) {
3431 return uci.set('wireless', this.sid, opt, value);
3432 },
3433
3434 /**
3435 * Checks whether this wireless network is disabled.
3436 *
3437 * @returns {boolean}
3438 * Returns `true` when the wireless radio is marked as disabled in `ubus`
3439 * runtime state or when the `disabled` option is set in the corresponding
3440 * UCI configuration.
3441 */
3442 isDisabled: function() {
3443 return this.ubus('dev', 'disabled') || this.get('disabled') == '1';
3444 },
3445
3446 /**
3447 * Get the configured operation mode of the wireless network.
3448 *
3449 * @returns {string}
3450 * Returns the configured operation mode. Possible values are:
3451 * - `ap` - Master (Access Point) mode
3452 * - `sta` - Station (client) mode
3453 * - `adhoc` - Ad-Hoc (IBSS) mode
3454 * - `mesh` - Mesh (IEEE 802.11s) mode
3455 * - `monitor` - Monitor mode
3456 */
3457 getMode: function() {
3458 return this.ubus('net', 'config', 'mode') || this.get('mode') || 'ap';
3459 },
3460
3461 /**
3462 * Get the configured SSID of the wireless network.
3463 *
3464 * @returns {null|string}
3465 * Returns the configured SSID value or `null` when this network is
3466 * in mesh mode.
3467 */
3468 getSSID: function() {
3469 if (this.getMode() == 'mesh')
3470 return null;
3471
3472 return this.ubus('net', 'config', 'ssid') || this.get('ssid');
3473 },
3474
3475 /**
3476 * Get the configured Mesh ID of the wireless network.
3477 *
3478 * @returns {null|string}
3479 * Returns the configured mesh ID value or `null` when this network
3480 * is not in mesh mode.
3481 */
3482 getMeshID: function() {
3483 if (this.getMode() != 'mesh')
3484 return null;
3485
3486 return this.ubus('net', 'config', 'mesh_id') || this.get('mesh_id');
3487 },
3488
3489 /**
3490 * Get the configured BSSID of the wireless network.
3491 *
3492 * @returns {null|string}
3493 * Returns the BSSID value or `null` if none has been specified.
3494 */
3495 getBSSID: function() {
3496 return this.ubus('net', 'config', 'bssid') || this.get('bssid');
3497 },
3498
3499 /**
3500 * Get the names of the logical interfaces this wireless network is
3501 * attached to.
3502 *
3503 * @returns {string[]}
3504 * Returns an array of logical interface names.
3505 */
3506 getNetworkNames: function() {
3507 return L.toArray(this.ubus('net', 'config', 'network') || this.get('network'));
3508 },
3509
3510 /**
3511 * Get the internal network ID of this wireless network.
3512 *
3513 * The network ID is a LuCI specific identifer in the form
3514 * `radio#.network#` to identify wireless networks by their corresponding
3515 * radio and network index numbers.
3516 *
3517 * @returns {string}
3518 * Returns the LuCI specific network ID.
3519 */
3520 getID: function() {
3521 return this.netid;
3522 },
3523
3524 /**
3525 * Get the configuration ID of this wireless network.
3526 *
3527 * @returns {string}
3528 * Returns the corresponding UCI section ID of the network.
3529 */
3530 getName: function() {
3531 return this.sid;
3532 },
3533
3534 /**
3535 * Get the Linux network device name.
3536 *
3537 * @returns {null|string}
3538 * Returns the current Linux network device name as resolved from
3539 * `ubus` runtime information or `null` if this network has no
3540 * associated network device, e.g. when not configured or up.
3541 */
3542 getIfname: function() {
3543 var ifname = this.ubus('net', 'ifname') || this.ubus('net', 'iwinfo', 'ifname');
3544
3545 if (ifname == null || ifname.match(/^(wifi|radio)\d/))
3546 ifname = this.netid;
3547
3548 return ifname;
3549 },
3550
3551 /**
3552 * Get the name of the corresponding wifi radio device.
3553 *
3554 * @returns {null|string}
3555 * Returns the name of the radio device this network is configured on
3556 * or `null` if it cannot be determined.
3557 */
3558 getWifiDeviceName: function() {
3559 return this.ubus('radio') || this.get('device');
3560 },
3561
3562 /**
3563 * Get the corresponding wifi radio device.
3564 *
3565 * @returns {null|LuCI.network.WifiDevice}
3566 * Returns a `Network.WifiDevice` instance representing the corresponding
3567 * wifi radio device or `null` if the related radio device could not be
3568 * found.
3569 */
3570 getWifiDevice: function() {
3571 var radioname = this.getWifiDeviceName();
3572
3573 if (radioname == null)
3574 return Promise.reject();
3575
3576 return Network.prototype.getWifiDevice(radioname);
3577 },
3578
3579 /**
3580 * Check whether the radio network is up.
3581 *
3582 * This function actually queries the up state of the related radio
3583 * device and assumes this network to be up as well when the parent
3584 * radio is up. This is due to the fact that OpenWrt does not control
3585 * virtual interfaces individually but within one common hostapd
3586 * instance.
3587 *
3588 * @returns {boolean}
3589 * Returns `true` when the network is up, else `false`.
3590 */
3591 isUp: function() {
3592 var device = this.getDevice();
3593
3594 if (device == null)
3595 return false;
3596
3597 return device.isUp();
3598 },
3599
3600 /**
3601 * Query the current operation mode from runtime information.
3602 *
3603 * @returns {string}
3604 * Returns the human readable mode name as reported by `ubus` runtime
3605 * state. Possible returned values are:
3606 * - `Master`
3607 * - `Ad-Hoc`
3608 * - `Client`
3609 * - `Monitor`
3610 * - `Master (VLAN)`
3611 * - `WDS`
3612 * - `Mesh Point`
3613 * - `P2P Client`
3614 * - `P2P Go`
3615 * - `Unknown`
3616 */
3617 getActiveMode: function() {
3618 var mode = this.ubus('net', 'iwinfo', 'mode') || this.ubus('net', 'config', 'mode') || this.get('mode') || 'ap';
3619
3620 switch (mode) {
3621 case 'ap': return 'Master';
3622 case 'sta': return 'Client';
3623 case 'adhoc': return 'Ad-Hoc';
3624 case 'mesh': return 'Mesh';
3625 case 'monitor': return 'Monitor';
3626 default: return mode;
3627 }
3628 },
3629
3630 /**
3631 * Query the current operation mode from runtime information as
3632 * translated string.
3633 *
3634 * @returns {string}
3635 * Returns the translated, human readable mode name as reported by
3636 *`ubus` runtime state.
3637 */
3638 getActiveModeI18n: function() {
3639 var mode = this.getActiveMode();
3640
3641 switch (mode) {
3642 case 'Master': return _('Master');
3643 case 'Client': return _('Client');
3644 case 'Ad-Hoc': return _('Ad-Hoc');
3645 case 'Mash': return _('Mesh');
3646 case 'Monitor': return _('Monitor');
3647 default: return mode;
3648 }
3649 },
3650
3651 /**
3652 * Query the current SSID from runtime information.
3653 *
3654 * @returns {string}
3655 * Returns the current SSID or Mesh ID as reported by `ubus` runtime
3656 * information.
3657 */
3658 getActiveSSID: function() {
3659 return this.ubus('net', 'iwinfo', 'ssid') || this.ubus('net', 'config', 'ssid') || this.get('ssid');
3660 },
3661
3662 /**
3663 * Query the current BSSID from runtime information.
3664 *
3665 * @returns {string}
3666 * Returns the current BSSID or Mesh ID as reported by `ubus` runtime
3667 * information.
3668 */
3669 getActiveBSSID: function() {
3670 return this.ubus('net', 'iwinfo', 'bssid') || this.ubus('net', 'config', 'bssid') || this.get('bssid');
3671 },
3672
3673 /**
3674 * Query the current encryption settings from runtime information.
3675 *
3676 * @returns {string}
3677 * Returns a string describing the current encryption or `-` if the the
3678 * encryption state could not be found in `ubus` runtime information.
3679 */
3680 getActiveEncryption: function() {
3681 return formatWifiEncryption(this.ubus('net', 'iwinfo', 'encryption')) || '-';
3682 },
3683
3684 /**
3685 * A wireless peer entry describes the properties of a remote wireless
3686 * peer associated with a local network.
3687 *
3688 * @typedef {Object<string, boolean|number|string|LuCI.network.WifiRateEntry>} WifiPeerEntry
3689 * @memberof LuCI.network
3690 *
3691 * @property {string} mac
3692 * The MAC address (BSSID).
3693 *
3694 * @property {number} signal
3695 * The received signal strength.
3696 *
3697 * @property {number} [signal_avg]
3698 * The average signal strength if supported by the driver.
3699 *
3700 * @property {number} [noise]
3701 * The current noise floor of the radio. May be `0` or absent if not
3702 * supported by the driver.
3703 *
3704 * @property {number} inactive
3705 * The amount of milliseconds the peer has been inactive, e.g. due
3706 * to powersave.
3707 *
3708 * @property {number} connected_time
3709 * The amount of milliseconds the peer is associated to this network.
3710 *
3711 * @property {number} [thr]
3712 * The estimated throughput of the peer, May be `0` or absent if not
3713 * supported by the driver.
3714 *
3715 * @property {boolean} authorized
3716 * Specifies whether the peer is authorized to associate to this network.
3717 *
3718 * @property {boolean} authenticated
3719 * Specifies whether the peer completed authentication to this network.
3720 *
3721 * @property {string} preamble
3722 * The preamble mode used by the peer. May be `long` or `short`.
3723 *
3724 * @property {boolean} wme
3725 * Specifies whether the peer supports WME/WMM capabilities.
3726 *
3727 * @property {boolean} mfp
3728 * Specifies whether management frame protection is active.
3729 *
3730 * @property {boolean} tdls
3731 * Specifies whether TDLS is active.
3732 *
3733 * @property {number} [mesh llid]
3734 * The mesh LLID, may be `0` or absent if not applicable or supported
3735 * by the driver.
3736 *
3737 * @property {number} [mesh plid]
3738 * The mesh PLID, may be `0` or absent if not applicable or supported
3739 * by the driver.
3740 *
3741 * @property {string} [mesh plink]
3742 * The mesh peer link state description, may be an empty string (`''`)
3743 * or absent if not applicable or supported by the driver.
3744 *
3745 * The following states are known:
3746 * - `LISTEN`
3747 * - `OPN_SNT`
3748 * - `OPN_RCVD`
3749 * - `CNF_RCVD`
3750 * - `ESTAB`
3751 * - `HOLDING`
3752 * - `BLOCKED`
3753 * - `UNKNOWN`
3754 *
3755 * @property {number} [mesh local PS]
3756 * The local powersafe mode for the peer link, may be an empty
3757 * string (`''`) or absent if not applicable or supported by
3758 * the driver.
3759 *
3760 * The following modes are known:
3761 * - `ACTIVE` (no power save)
3762 * - `LIGHT SLEEP`
3763 * - `DEEP SLEEP`
3764 * - `UNKNOWN`
3765 *
3766 * @property {number} [mesh peer PS]
3767 * The remote powersafe mode for the peer link, may be an empty
3768 * string (`''`) or absent if not applicable or supported by
3769 * the driver.
3770 *
3771 * The following modes are known:
3772 * - `ACTIVE` (no power save)
3773 * - `LIGHT SLEEP`
3774 * - `DEEP SLEEP`
3775 * - `UNKNOWN`
3776 *
3777 * @property {number} [mesh non-peer PS]
3778 * The powersafe mode for all non-peer neigbours, may be an empty
3779 * string (`''`) or absent if not applicable or supported by the driver.
3780 *
3781 * The following modes are known:
3782 * - `ACTIVE` (no power save)
3783 * - `LIGHT SLEEP`
3784 * - `DEEP SLEEP`
3785 * - `UNKNOWN`
3786 *
3787 * @property {LuCI.network.WifiRateEntry} rx
3788 * Describes the receiving wireless rate from the peer.
3789 *
3790 * @property {LuCI.network.WifiRateEntry} tx
3791 * Describes the transmitting wireless rate to the peer.
3792 */
3793
3794 /**
3795 * A wireless rate entry describes the properties of a wireless
3796 * transmission rate to or from a peer.
3797 *
3798 * @typedef {Object<string, boolean|number>} WifiRateEntry
3799 * @memberof LuCI.network
3800 *
3801 * @property {number} [drop_misc]
3802 * The amount of received misc. packages that have been dropped, e.g.
3803 * due to corruption or missing authentication. Only applicable to
3804 * receiving rates.
3805 *
3806 * @property {number} packets
3807 * The amount of packets that have been received or sent.
3808 *
3809 * @property {number} bytes
3810 * The amount of bytes that have been received or sent.
3811 *
3812 * @property {number} [failed]
3813 * The amount of failed tranmission attempts. Only applicable to
3814 * transmit rates.
3815 *
3816 * @property {number} [retries]
3817 * The amount of retried transmissions. Only applicable to transmit
3818 * rates.
3819 *
3820 * @property {boolean} is_ht
3821 * Specifies whether this rate is an HT (IEEE 802.11n) rate.
3822 *
3823 * @property {boolean} is_vht
3824 * Specifies whether this rate is an VHT (IEEE 802.11ac) rate.
3825 *
3826 * @property {number} mhz
3827 * The channel width in MHz used for the transmission.
3828 *
3829 * @property {number} rate
3830 * The bitrate in bit/s of the transmission.
3831 *
3832 * @property {number} [mcs]
3833 * The MCS index of the used transmission rate. Only applicable to
3834 * HT or VHT rates.
3835 *
3836 * @property {number} [40mhz]
3837 * Specifies whether the tranmission rate used 40MHz wide channel.
3838 * Only applicable to HT or VHT rates.
3839 *
3840 * Note: this option exists for backwards compatibility only and its
3841 * use is discouraged. The `mhz` field should be used instead to
3842 * determine the channel width.
3843 *
3844 * @property {boolean} [short_gi]
3845 * Specifies whether a short guard interval is used for the transmission.
3846 * Only applicable to HT or VHT rates.
3847 *
3848 * @property {number} [nss]
3849 * Specifies the number of spatial streams used by the transmission.
3850 * Only applicable to VHT rates.
3851 */
3852
3853 /**
3854 * Fetch the list of associated peers.
3855 *
3856 * @returns {Promise<Array<LuCI.network.WifiPeerEntry>>}
3857 * Returns a promise resolving to an array of wireless peers associated
3858 * with this network.
3859 */
3860 getAssocList: function() {
3861 return callIwinfoAssoclist(this.getIfname());
3862 },
3863
3864 /**
3865 * Query the current operating frequency of the wireless network.
3866 *
3867 * @returns {null|string}
3868 * Returns the current operating frequency of the network from `ubus`
3869 * runtime information in GHz or `null` if the information is not
3870 * available.
3871 */
3872 getFrequency: function() {
3873 var freq = this.ubus('net', 'iwinfo', 'frequency');
3874
3875 if (freq != null && freq > 0)
3876 return '%.03f'.format(freq / 1000);
3877
3878 return null;
3879 },
3880
3881 /**
3882 * Query the current average bitrate of all peers associated to this
3883 * wireless network.
3884 *
3885 * @returns {null|number}
3886 * Returns the average bit rate among all peers associated to the network
3887 * as reported by `ubus` runtime information or `null` if the information
3888 * is not available.
3889 */
3890 getBitRate: function() {
3891 var rate = this.ubus('net', 'iwinfo', 'bitrate');
3892
3893 if (rate != null && rate > 0)
3894 return (rate / 1000);
3895
3896 return null;
3897 },
3898
3899 /**
3900 * Query the current wireless channel.
3901 *
3902 * @returns {null|number}
3903 * Returns the wireless channel as reported by `ubus` runtime information
3904 * or `null` if it cannot be determined.
3905 */
3906 getChannel: function() {
3907 return this.ubus('net', 'iwinfo', 'channel') || this.ubus('dev', 'config', 'channel') || this.get('channel');
3908 },
3909
3910 /**
3911 * Query the current wireless signal.
3912 *
3913 * @returns {null|number}
3914 * Returns the wireless signal in dBm as reported by `ubus` runtime
3915 * information or `null` if it cannot be determined.
3916 */
3917 getSignal: function() {
3918 return this.ubus('net', 'iwinfo', 'signal') || 0;
3919 },
3920
3921 /**
3922 * Query the current radio noise floor.
3923 *
3924 * @returns {number}
3925 * Returns the radio noise floor in dBm as reported by `ubus` runtime
3926 * information or `0` if it cannot be determined.
3927 */
3928 getNoise: function() {
3929 return this.ubus('net', 'iwinfo', 'noise') || 0;
3930 },
3931
3932 /**
3933 * Query the current country code.
3934 *
3935 * @returns {string}
3936 * Returns the wireless country code as reported by `ubus` runtime
3937 * information or `00` if it cannot be determined.
3938 */
3939 getCountryCode: function() {
3940 return this.ubus('net', 'iwinfo', 'country') || this.ubus('dev', 'config', 'country') || '00';
3941 },
3942
3943 /**
3944 * Query the current radio TX power.
3945 *
3946 * @returns {null|number}
3947 * Returns the wireless network transmit power in dBm as reported by
3948 * `ubus` runtime information or `null` if it cannot be determined.
3949 */
3950 getTXPower: function() {
3951 return this.ubus('net', 'iwinfo', 'txpower');
3952 },
3953
3954 /**
3955 * Query the radio TX power offset.
3956 *
3957 * Some wireless radios have a fixed power offset, e.g. due to the
3958 * use of external amplifiers.
3959 *
3960 * @returns {number}
3961 * Returns the wireless network transmit power offset in dBm as reported
3962 * by `ubus` runtime information or `0` if there is no offset, or if it
3963 * cannot be determined.
3964 */
3965 getTXPowerOffset: function() {
3966 return this.ubus('net', 'iwinfo', 'txpower_offset') || 0;
3967 },
3968
3969 /**
3970 * Calculate the current signal.
3971 *
3972 * @deprecated
3973 * @returns {number}
3974 * Returns the calculated signal level, which is the difference between
3975 * noise and signal (SNR), divided by 5.
3976 */
3977 getSignalLevel: function(signal, noise) {
3978 if (this.getActiveBSSID() == '00:00:00:00:00:00')
3979 return -1;
3980
3981 signal = signal || this.getSignal();
3982 noise = noise || this.getNoise();
3983
3984 if (signal < 0 && noise < 0) {
3985 var snr = -1 * (noise - signal);
3986 return Math.floor(snr / 5);
3987 }
3988
3989 return 0;
3990 },
3991
3992 /**
3993 * Calculate the current signal quality percentage.
3994 *
3995 * @returns {number}
3996 * Returns the calculated signal quality in percent. The value is
3997 * calculated from the `quality` and `quality_max` indicators reported
3998 * by `ubus` runtime state.
3999 */
4000 getSignalPercent: function() {
4001 var qc = this.ubus('net', 'iwinfo', 'quality') || 0,
4002 qm = this.ubus('net', 'iwinfo', 'quality_max') || 0;
4003
4004 if (qc > 0 && qm > 0)
4005 return Math.floor((100 / qm) * qc);
4006
4007 return 0;
4008 },
4009
4010 /**
4011 * Get a short description string for this wireless network.
4012 *
4013 * @returns {string}
4014 * Returns a string describing this network, consisting of the
4015 * active operation mode, followed by either the SSID, BSSID or
4016 * internal network ID, depending on which information is available.
4017 */
4018 getShortName: function() {
4019 return '%s "%s"'.format(
4020 this.getActiveModeI18n(),
4021 this.getActiveSSID() || this.getActiveBSSID() || this.getID());
4022 },
4023
4024 /**
4025 * Get a description string for this wireless network.
4026 *
4027 * @returns {string}
4028 * Returns a string describing this network, consisting of the
4029 * term `Wireless Network`, followed by the active operation mode,
4030 * the SSID, BSSID or internal network ID and the Linux network device
4031 * name, depending on which information is available.
4032 */
4033 getI18n: function() {
4034 return '%s: %s "%s" (%s)'.format(
4035 _('Wireless Network'),
4036 this.getActiveModeI18n(),
4037 this.getActiveSSID() || this.getActiveBSSID() || this.getID(),
4038 this.getIfname());
4039 },
4040
4041 /**
4042 * Get the primary logical interface this wireless network is attached to.
4043 *
4044 * @returns {null|LuCI.network.Protocol}
4045 * Returns a `Network.Protocol` instance representing the logical
4046 * interface or `null` if this network is not attached to any logical
4047 * interface.
4048 */
4049 getNetwork: function() {
4050 return this.getNetworks()[0];
4051 },
4052
4053 /**
4054 * Get the logical interfaces this wireless network is attached to.
4055 *
4056 * @returns {Array<LuCI.network.Protocol>}
4057 * Returns an array of `Network.Protocol` instances representing the
4058 * logical interfaces this wireless network is attached to.
4059 */
4060 getNetworks: function() {
4061 var networkNames = this.getNetworkNames(),
4062 networks = [];
4063
4064 for (var i = 0; i < networkNames.length; i++) {
4065 var uciInterface = uci.get('network', networkNames[i]);
4066
4067 if (uciInterface == null || uciInterface['.type'] != 'interface')
4068 continue;
4069
4070 networks.push(Network.prototype.instantiateNetwork(networkNames[i]));
4071 }
4072
4073 networks.sort(networkSort);
4074
4075 return networks;
4076 },
4077
4078 /**
4079 * Get the associated Linux network device.
4080 *
4081 * @returns {LuCI.network.Device}
4082 * Returns a `Network.Device` instance representing the Linux network
4083 * device associted with this wireless network.
4084 */
4085 getDevice: function() {
4086 return Network.prototype.instantiateDevice(this.getIfname());
4087 },
4088
4089 /**
4090 * Check whether this wifi network supports deauthenticating clients.
4091 *
4092 * @returns {boolean}
4093 * Returns `true` when this wifi network instance supports forcibly
4094 * deauthenticating clients, otherwise `false`.
4095 */
4096 isClientDisconnectSupported: function() {
4097 return L.isObject(this.ubus('hostapd', 'del_client'));
4098 },
4099
4100 /**
4101 * Forcibly disconnect the given client from the wireless network.
4102 *
4103 * @param {string} mac
4104 * The MAC address of the client to disconnect.
4105 *
4106 * @param {boolean} [deauth=false]
4107 * Specifies whether to deauthenticate (`true`) or disassociate (`false`)
4108 * the client.
4109 *
4110 * @param {number} [reason=1]
4111 * Specifies the IEEE 802.11 reason code to disassoc/deauth the client
4112 * with. Default is `1` which corresponds to `Unspecified reason`.
4113 *
4114 * @param {number} [ban_time=0]
4115 * Specifies the amount of milliseconds to ban the client from
4116 * reconnecting. By default, no ban time is set which allows the client
4117 * to reassociate / reauthenticate immediately.
4118 *
4119 * @returns {Promise<number>}
4120 * Returns a promise resolving to the underlying ubus call result code
4121 * which is typically `0`, even for not existing MAC addresses.
4122 * The promise might reject with an error in case invalid arguments
4123 * are passed.
4124 */
4125 disconnectClient: function(mac, deauth, reason, ban_time) {
4126 if (reason == null || reason == 0)
4127 reason = 1;
4128
4129 if (ban_time == 0)
4130 ban_time = null;
4131
4132 return rpc.declare({
4133 object: 'hostapd.%s'.format(this.getIfname()),
4134 method: 'del_client',
4135 params: [ 'addr', 'deauth', 'reason', 'ban_time' ]
4136 })(mac, deauth, reason, ban_time);
4137 }
4138 });
4139
4140 return Network;