c79022968ccc99132ab83285e40716f1f8b63dd4
[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
6 var proto_errors = {
7 CONNECT_FAILED: _('Connection attempt failed'),
8 INVALID_ADDRESS: _('IP address is invalid'),
9 INVALID_GATEWAY: _('Gateway address is invalid'),
10 INVALID_LOCAL_ADDRESS: _('Local IP address is invalid'),
11 MISSING_ADDRESS: _('IP address is missing'),
12 MISSING_PEER_ADDRESS: _('Peer address is missing'),
13 NO_DEVICE: _('Network device is not present'),
14 NO_IFACE: _('Unable to determine device name'),
15 NO_IFNAME: _('Unable to determine device name'),
16 NO_WAN_ADDRESS: _('Unable to determine external IP address'),
17 NO_WAN_LINK: _('Unable to determine upstream interface'),
18 PEER_RESOLVE_FAIL: _('Unable to resolve peer host name'),
19 PIN_FAILED: _('PIN code rejected')
20 };
21
22 var iface_patterns_ignore = [
23 /^wmaster\d+/,
24 /^wifi\d+/,
25 /^hwsim\d+/,
26 /^imq\d+/,
27 /^ifb\d+/,
28 /^mon\.wlan\d+/,
29 /^sit\d+/,
30 /^gre\d+/,
31 /^gretap\d+/,
32 /^ip6gre\d+/,
33 /^ip6tnl\d+/,
34 /^tunl\d+/,
35 /^lo$/
36 ];
37
38 var iface_patterns_wireless = [
39 /^wlan\d+/,
40 /^wl\d+/,
41 /^ath\d+/,
42 /^\w+\.network\d+/
43 ];
44
45 var iface_patterns_virtual = [ ];
46
47 var callLuciNetworkDevices = rpc.declare({
48 object: 'luci-rpc',
49 method: 'getNetworkDevices',
50 expect: { '': {} }
51 });
52
53 var callLuciWirelessDevices = rpc.declare({
54 object: 'luci-rpc',
55 method: 'getWirelessDevices',
56 expect: { '': {} }
57 });
58
59 var callLuciBoardJSON = rpc.declare({
60 object: 'luci-rpc',
61 method: 'getBoardJSON'
62 });
63
64 var callLuciHostHints = rpc.declare({
65 object: 'luci-rpc',
66 method: 'getHostHints',
67 expect: { '': {} }
68 });
69
70 var callIwinfoAssoclist = rpc.declare({
71 object: 'iwinfo',
72 method: 'assoclist',
73 params: [ 'device', 'mac' ],
74 expect: { results: [] }
75 });
76
77 var callIwinfoScan = rpc.declare({
78 object: 'iwinfo',
79 method: 'scan',
80 params: [ 'device' ],
81 nobatch: true,
82 expect: { results: [] }
83 });
84
85 var callNetworkInterfaceDump = rpc.declare({
86 object: 'network.interface',
87 method: 'dump',
88 expect: { 'interface': [] }
89 });
90
91 var callNetworkProtoHandlers = rpc.declare({
92 object: 'network',
93 method: 'get_proto_handlers',
94 expect: { '': {} }
95 });
96
97 var _init = null,
98 _state = null,
99 _protocols = {},
100 _protospecs = {};
101
102 function getProtocolHandlers(cache) {
103 return callNetworkProtoHandlers().then(function(protos) {
104 /* Register "none" protocol */
105 if (!protos.hasOwnProperty('none'))
106 Object.assign(protos, { none: { no_device: false } });
107
108 /* Hack: emulate relayd protocol */
109 if (!protos.hasOwnProperty('relay'))
110 Object.assign(protos, { relay: { no_device: true } });
111
112 Object.assign(_protospecs, protos);
113
114 return Promise.all(Object.keys(protos).map(function(p) {
115 return Promise.resolve(L.require('protocol.%s'.format(p))).catch(function(err) {
116 if (L.isObject(err) && err.name != 'NetworkError')
117 L.error(err);
118 });
119 })).then(function() {
120 return protos;
121 });
122 }).catch(function() {
123 return {};
124 });
125 }
126
127 function getWifiStateBySid(sid) {
128 var s = uci.get('wireless', sid);
129
130 if (s != null && s['.type'] == 'wifi-iface') {
131 for (var radioname in _state.radios) {
132 for (var i = 0; i < _state.radios[radioname].interfaces.length; i++) {
133 var netstate = _state.radios[radioname].interfaces[i];
134
135 if (typeof(netstate.section) != 'string')
136 continue;
137
138 var s2 = uci.get('wireless', netstate.section);
139
140 if (s2 != null && s['.type'] == s2['.type'] && s['.name'] == s2['.name']) {
141 if (s2['.anonymous'] == false && netstate.section.charAt(0) == '@')
142 return null;
143
144 return [ radioname, _state.radios[radioname], netstate ];
145 }
146 }
147 }
148 }
149
150 return null;
151 }
152
153 function getWifiStateByIfname(ifname) {
154 for (var radioname in _state.radios) {
155 for (var i = 0; i < _state.radios[radioname].interfaces.length; i++) {
156 var netstate = _state.radios[radioname].interfaces[i];
157
158 if (typeof(netstate.ifname) != 'string')
159 continue;
160
161 if (netstate.ifname == ifname)
162 return [ radioname, _state.radios[radioname], netstate ];
163 }
164 }
165
166 return null;
167 }
168
169 function isWifiIfname(ifname) {
170 for (var i = 0; i < iface_patterns_wireless.length; i++)
171 if (iface_patterns_wireless[i].test(ifname))
172 return true;
173
174 return false;
175 }
176
177 function getWifiSidByNetid(netid) {
178 var m = /^(\w+)\.network(\d+)$/.exec(netid);
179 if (m) {
180 var sections = uci.sections('wireless', 'wifi-iface');
181 for (var i = 0, n = 0; i < sections.length; i++) {
182 if (sections[i].device != m[1])
183 continue;
184
185 if (++n == +m[2])
186 return sections[i]['.name'];
187 }
188 }
189
190 return null;
191 }
192
193 function getWifiSidByIfname(ifname) {
194 var sid = getWifiSidByNetid(ifname);
195
196 if (sid != null)
197 return sid;
198
199 var res = getWifiStateByIfname(ifname);
200
201 if (res != null && L.isObject(res[2]) && typeof(res[2].section) == 'string')
202 return res[2].section;
203
204 return null;
205 }
206
207 function getWifiNetidBySid(sid) {
208 var s = uci.get('wireless', sid);
209 if (s != null && s['.type'] == 'wifi-iface') {
210 var radioname = s.device;
211 if (typeof(s.device) == 'string') {
212 var i = 0, netid = null, sections = uci.sections('wireless', 'wifi-iface');
213 for (var i = 0, n = 0; i < sections.length; i++) {
214 if (sections[i].device != s.device)
215 continue;
216
217 n++;
218
219 if (sections[i]['.name'] != s['.name'])
220 continue;
221
222 return [ '%s.network%d'.format(s.device, n), s.device ];
223 }
224
225 }
226 }
227
228 return null;
229 }
230
231 function getWifiNetidByNetname(name) {
232 var sections = uci.sections('wireless', 'wifi-iface');
233 for (var i = 0; i < sections.length; i++) {
234 if (typeof(sections[i].network) != 'string')
235 continue;
236
237 var nets = sections[i].network.split(/\s+/);
238 for (var j = 0; j < nets.length; j++) {
239 if (nets[j] != name)
240 continue;
241
242 return getWifiNetidBySid(sections[i]['.name']);
243 }
244 }
245
246 return null;
247 }
248
249 function isVirtualIfname(ifname) {
250 for (var i = 0; i < iface_patterns_virtual.length; i++)
251 if (iface_patterns_virtual[i].test(ifname))
252 return true;
253
254 return false;
255 }
256
257 function isIgnoredIfname(ifname) {
258 for (var i = 0; i < iface_patterns_ignore.length; i++)
259 if (iface_patterns_ignore[i].test(ifname))
260 return true;
261
262 return false;
263 }
264
265 function appendValue(config, section, option, value) {
266 var values = uci.get(config, section, option),
267 isArray = Array.isArray(values),
268 rv = false;
269
270 if (isArray == false)
271 values = L.toArray(values);
272
273 if (values.indexOf(value) == -1) {
274 values.push(value);
275 rv = true;
276 }
277
278 uci.set(config, section, option, isArray ? values : values.join(' '));
279
280 return rv;
281 }
282
283 function removeValue(config, section, option, value) {
284 var values = uci.get(config, section, option),
285 isArray = Array.isArray(values),
286 rv = false;
287
288 if (isArray == false)
289 values = L.toArray(values);
290
291 for (var i = values.length - 1; i >= 0; i--) {
292 if (values[i] == value) {
293 values.splice(i, 1);
294 rv = true;
295 }
296 }
297
298 if (values.length > 0)
299 uci.set(config, section, option, isArray ? values : values.join(' '));
300 else
301 uci.unset(config, section, option);
302
303 return rv;
304 }
305
306 function prefixToMask(bits, v6) {
307 var w = v6 ? 128 : 32,
308 m = [];
309
310 if (bits > w)
311 return null;
312
313 for (var i = 0; i < w / 16; i++) {
314 var b = Math.min(16, bits);
315 m.push((0xffff << (16 - b)) & 0xffff);
316 bits -= b;
317 }
318
319 if (v6)
320 return String.prototype.format.apply('%x:%x:%x:%x:%x:%x:%x:%x', m).replace(/:0(?::0)+$/, '::');
321 else
322 return '%d.%d.%d.%d'.format(m[0] >>> 8, m[0] & 0xff, m[1] >>> 8, m[1] & 0xff);
323 }
324
325 function maskToPrefix(mask, v6) {
326 var m = v6 ? validation.parseIPv6(mask) : validation.parseIPv4(mask);
327
328 if (!m)
329 return null;
330
331 var bits = 0;
332
333 for (var i = 0, z = false; i < m.length; i++) {
334 z = z || !m[i];
335
336 while (!z && (m[i] & (v6 ? 0x8000 : 0x80))) {
337 m[i] = (m[i] << 1) & (v6 ? 0xffff : 0xff);
338 bits++;
339 }
340
341 if (m[i])
342 return null;
343 }
344
345 return bits;
346 }
347
348 function initNetworkState(refresh) {
349 if (_state == null || refresh) {
350 _init = _init || Promise.all([
351 L.resolveDefault(callNetworkInterfaceDump(), []),
352 L.resolveDefault(callLuciBoardJSON(), {}),
353 L.resolveDefault(callLuciNetworkDevices(), {}),
354 L.resolveDefault(callLuciWirelessDevices(), {}),
355 L.resolveDefault(callLuciHostHints(), {}),
356 getProtocolHandlers(),
357 uci.load(['network', 'wireless', 'luci'])
358 ]).then(function(data) {
359 var netifd_ifaces = data[0],
360 board_json = data[1],
361 luci_devs = data[2];
362
363 var s = {
364 isTunnel: {}, isBridge: {}, isSwitch: {}, isWifi: {},
365 ifaces: netifd_ifaces, radios: data[3], hosts: data[4],
366 netdevs: {}, bridges: {}, switches: {}, hostapd: {}
367 };
368
369 for (var name in luci_devs) {
370 var dev = luci_devs[name];
371
372 if (isVirtualIfname(name))
373 s.isTunnel[name] = true;
374
375 if (!s.isTunnel[name] && isIgnoredIfname(name))
376 continue;
377
378 s.netdevs[name] = s.netdevs[name] || {
379 idx: dev.ifindex,
380 name: name,
381 rawname: name,
382 flags: dev.flags,
383 stats: dev.stats,
384 macaddr: dev.mac,
385 type: dev.type,
386 mtu: dev.mtu,
387 qlen: dev.qlen,
388 wireless: dev.wireless,
389 ipaddrs: [],
390 ip6addrs: []
391 };
392
393 if (Array.isArray(dev.ipaddrs))
394 for (var i = 0; i < dev.ipaddrs.length; i++)
395 s.netdevs[name].ipaddrs.push(dev.ipaddrs[i].address + '/' + dev.ipaddrs[i].netmask);
396
397 if (Array.isArray(dev.ip6addrs))
398 for (var i = 0; i < dev.ip6addrs.length; i++)
399 s.netdevs[name].ip6addrs.push(dev.ip6addrs[i].address + '/' + dev.ip6addrs[i].netmask);
400 }
401
402 for (var name in luci_devs) {
403 var dev = luci_devs[name];
404
405 if (!dev.bridge)
406 continue;
407
408 var b = {
409 name: name,
410 id: dev.id,
411 stp: dev.stp,
412 ifnames: []
413 };
414
415 for (var i = 0; dev.ports && i < dev.ports.length; i++) {
416 var subdev = s.netdevs[dev.ports[i]];
417
418 if (subdev == null)
419 continue;
420
421 b.ifnames.push(subdev);
422 subdev.bridge = b;
423 }
424
425 s.bridges[name] = b;
426 s.isBridge[name] = true;
427 }
428
429 if (L.isObject(board_json.switch)) {
430 for (var switchname in board_json.switch) {
431 var layout = board_json.switch[switchname],
432 netdevs = {},
433 nports = {},
434 ports = [],
435 pnum = null,
436 role = null;
437
438 if (L.isObject(layout) && Array.isArray(layout.ports)) {
439 for (var i = 0, port; (port = layout.ports[i]) != null; i++) {
440 if (typeof(port) == 'object' && typeof(port.num) == 'number' &&
441 (typeof(port.role) == 'string' || typeof(port.device) == 'string')) {
442 var spec = {
443 num: port.num,
444 role: port.role || 'cpu',
445 index: (port.index != null) ? port.index : port.num
446 };
447
448 if (port.device != null) {
449 spec.device = port.device;
450 spec.tagged = spec.need_tag;
451 netdevs[port.num] = port.device;
452 }
453
454 ports.push(spec);
455
456 if (port.role != null)
457 nports[port.role] = (nports[port.role] || 0) + 1;
458 }
459 }
460
461 ports.sort(function(a, b) {
462 if (a.role != b.role)
463 return (a.role < b.role) ? -1 : 1;
464
465 return (a.index - b.index);
466 });
467
468 for (var i = 0, port; (port = ports[i]) != null; i++) {
469 if (port.role != role) {
470 role = port.role;
471 pnum = 1;
472 }
473
474 if (role == 'cpu')
475 port.label = 'CPU (%s)'.format(port.device);
476 else if (nports[role] > 1)
477 port.label = '%s %d'.format(role.toUpperCase(), pnum++);
478 else
479 port.label = role.toUpperCase();
480
481 delete port.role;
482 delete port.index;
483 }
484
485 s.switches[switchname] = {
486 ports: ports,
487 netdevs: netdevs
488 };
489 }
490 }
491 }
492
493 if (L.isObject(board_json.dsl) && L.isObject(board_json.dsl.modem)) {
494 s.hasDSLModem = board_json.dsl.modem;
495 }
496
497 _init = null;
498
499 var objects = [];
500
501 if (L.isObject(s.radios))
502 for (var radio in s.radios)
503 if (L.isObject(s.radios[radio]) && Array.isArray(s.radios[radio].interfaces))
504 for (var i = 0; i < s.radios[radio].interfaces.length; i++)
505 if (L.isObject(s.radios[radio].interfaces[i]) && s.radios[radio].interfaces[i].ifname)
506 objects.push('hostapd.%s'.format(s.radios[radio].interfaces[i].ifname));
507
508 return (objects.length ? L.resolveDefault(rpc.list.apply(rpc, objects), {}) : Promise.resolve({})).then(function(res) {
509 for (var k in res) {
510 var m = k.match(/^hostapd\.(.+)$/);
511 if (m)
512 s.hostapd[m[1]] = res[k];
513 }
514
515 return (_state = s);
516 });
517 });
518 }
519
520 return (_state != null ? Promise.resolve(_state) : _init);
521 }
522
523 function ifnameOf(obj) {
524 if (obj instanceof Protocol)
525 return obj.getIfname();
526 else if (obj instanceof Device)
527 return obj.getName();
528 else if (obj instanceof WifiDevice)
529 return obj.getName();
530 else if (obj instanceof WifiNetwork)
531 return obj.getIfname();
532 else if (typeof(obj) == 'string')
533 return obj.replace(/:.+$/, '');
534
535 return null;
536 }
537
538 function networkSort(a, b) {
539 return a.getName() > b.getName();
540 }
541
542 function deviceSort(a, b) {
543 var typeWeigth = { wifi: 2, alias: 3 },
544 weightA = typeWeigth[a.getType()] || 1,
545 weightB = typeWeigth[b.getType()] || 1;
546
547 if (weightA != weightB)
548 return weightA - weightB;
549
550 return a.getName() > b.getName();
551 }
552
553 function formatWifiEncryption(enc) {
554 if (!L.isObject(enc))
555 return null;
556
557 if (!enc.enabled)
558 return 'None';
559
560 var ciphers = Array.isArray(enc.ciphers)
561 ? enc.ciphers.map(function(c) { return c.toUpperCase() }) : [ 'NONE' ];
562
563 if (Array.isArray(enc.wep)) {
564 var has_open = false,
565 has_shared = false;
566
567 for (var i = 0; i < enc.wep.length; i++)
568 if (enc.wep[i] == 'open')
569 has_open = true;
570 else if (enc.wep[i] == 'shared')
571 has_shared = true;
572
573 if (has_open && has_shared)
574 return 'WEP Open/Shared (%s)'.format(ciphers.join(', '));
575 else if (has_open)
576 return 'WEP Open System (%s)'.format(ciphers.join(', '));
577 else if (has_shared)
578 return 'WEP Shared Auth (%s)'.format(ciphers.join(', '));
579
580 return 'WEP';
581 }
582
583 if (Array.isArray(enc.wpa)) {
584 var versions = [],
585 suites = Array.isArray(enc.authentication)
586 ? enc.authentication.map(function(a) { return a.toUpperCase() }) : [ 'NONE' ];
587
588 for (var i = 0; i < enc.wpa.length; i++)
589 switch (enc.wpa[i]) {
590 case 1:
591 versions.push('WPA');
592 break;
593
594 default:
595 versions.push('WPA%d'.format(enc.wpa[i]));
596 break;
597 }
598
599 if (versions.length > 1)
600 return 'mixed %s %s (%s)'.format(versions.join('/'), suites.join(', '), ciphers.join(', '));
601
602 return '%s %s (%s)'.format(versions[0], suites.join(', '), ciphers.join(', '));
603 }
604
605 return 'Unknown';
606 }
607
608 function enumerateNetworks() {
609 var uciInterfaces = uci.sections('network', 'interface'),
610 networks = {};
611
612 for (var i = 0; i < uciInterfaces.length; i++)
613 networks[uciInterfaces[i]['.name']] = this.instantiateNetwork(uciInterfaces[i]['.name']);
614
615 for (var i = 0; i < _state.ifaces.length; i++)
616 if (networks[_state.ifaces[i].interface] == null)
617 networks[_state.ifaces[i].interface] =
618 this.instantiateNetwork(_state.ifaces[i].interface, _state.ifaces[i].proto);
619
620 var rv = [];
621
622 for (var network in networks)
623 if (networks.hasOwnProperty(network))
624 rv.push(networks[network]);
625
626 rv.sort(networkSort);
627
628 return rv;
629 }
630
631
632 var Hosts, Network, Protocol, Device, WifiDevice, WifiNetwork;
633
634 /**
635 * @class
636 * @memberof LuCI
637 * @hideconstructor
638 * @classdesc
639 *
640 * The `LuCI.Network` class combines data from multiple `ubus` apis to
641 * provide an abstraction of the current network configuration state.
642 *
643 * It provides methods to enumerate interfaces and devices, to query
644 * current configuration details and to manipulate settings.
645 */
646 Network = L.Class.extend(/** @lends LuCI.Network.prototype */ {
647 /**
648 * Converts the given prefix size in bits to a netmask.
649 *
650 * @method
651 *
652 * @param {number} bits
653 * The prefix size in bits.
654 *
655 * @param {boolean} [v6=false]
656 * Whether to convert the bits value into an IPv4 netmask (`false`) or
657 * an IPv6 netmask (`true`).
658 *
659 * @returns {null|string}
660 * Returns a string containing the netmask corresponding to the bit count
661 * or `null` when the given amount of bits exceeds the maximum possible
662 * value of `32` for IPv4 or `128` for IPv6.
663 */
664 prefixToMask: prefixToMask,
665
666 /**
667 * Converts the given netmask to a prefix size in bits.
668 *
669 * @method
670 *
671 * @param {string} netmask
672 * The netmask to convert into a bit count.
673 *
674 * @param {boolean} [v6=false]
675 * Whether to parse the given netmask as IPv4 (`false`) or IPv6 (`true`)
676 * address.
677 *
678 * @returns {null|number}
679 * Returns the number of prefix bits contained in the netmask or `null`
680 * if the given netmask value was invalid.
681 */
682 maskToPrefix: maskToPrefix,
683
684 /**
685 * An encryption entry describes active wireless encryption settings
686 * such as the used key management protocols, active ciphers and
687 * protocol versions.
688 *
689 * @typedef {Object<string, boolean|Array<number|string>>} LuCI.Network.WifiEncryption
690 * @memberof LuCI.Network
691 *
692 * @property {boolean} enabled
693 * Specifies whether any kind of encryption, such as `WEP` or `WPA` is
694 * enabled. If set to `false`, then no encryption is active and the
695 * corresponding network is open.
696 *
697 * @property {string[]} [wep]
698 * When the `wep` property exists, the network uses WEP encryption.
699 * In this case, the property is set to an array of active WEP modes
700 * which might be either `open`, `shared` or both.
701 *
702 * @property {number[]} [wpa]
703 * When the `wpa` property exists, the network uses WPA security.
704 * In this case, the property is set to an array containing the WPA
705 * protocol versions used, e.g. `[ 1, 2 ]` for WPA/WPA2 mixed mode or
706 * `[ 3 ]` for WPA3-SAE.
707 *
708 * @property {string[]} [authentication]
709 * The `authentication` property only applies to WPA encryption and
710 * is defined when the `wpa` property is set as well. It points to
711 * an array of active authentication suites used by the network, e.g.
712 * `[ "psk" ]` for a WPA(2)-PSK network or `[ "psk", "sae" ]` for
713 * mixed WPA2-PSK/WPA3-SAE encryption.
714 *
715 * @property {string[]} [ciphers]
716 * If either WEP or WPA encryption is active, then the `ciphers`
717 * property will be set to an array describing the active encryption
718 * ciphers used by the network, e.g. `[ "tkip", "ccmp" ]` for a
719 * WPA/WPA2-PSK mixed network or `[ "wep-40", "wep-104" ]` for an
720 * WEP network.
721 */
722
723 /**
724 * Converts a given {@link LuCI.Network.WifiEncryption encryption entry}
725 * into a human readable string such as `mixed WPA/WPA2 PSK (TKIP, CCMP)`
726 * or `WPA3 SAE (CCMP)`.
727 *
728 * @method
729 *
730 * @param {LuCI.Network.WifiEncryption} encryption
731 * The wireless encryption entry to convert.
732 *
733 * @returns {null|string}
734 * Returns the description string for the given encryption entry or
735 * `null` if the given entry was invalid.
736 */
737 formatWifiEncryption: formatWifiEncryption,
738
739 /**
740 * Flushes the local network state cache and fetches updated information
741 * from the remote `ubus` apis.
742 *
743 * @returns {Promise<Object>}
744 * Returns a promise resolving to the internal network state object.
745 */
746 flushCache: function() {
747 initNetworkState(true);
748 return _init;
749 },
750
751 /**
752 * Instantiates the given {@link LuCI.Network.Protocol Protocol} backend,
753 * optionally using the given network name.
754 *
755 * @param {string} protoname
756 * The protocol backend to use, e.g. `static` or `dhcp`.
757 *
758 * @param {string} [netname=__dummy__]
759 * The network name to use for the instantiated protocol. This should be
760 * usually set to one of the interfaces described in /etc/config/network
761 * but it is allowed to omit it, e.g. to query protocol capabilities
762 * without the need for an existing interface.
763 *
764 * @returns {null|LuCI.Network.Protocol}
765 * Returns the instantiated protocol backend class or `null` if the given
766 * protocol isn't known.
767 */
768 getProtocol: function(protoname, netname) {
769 var v = _protocols[protoname];
770 if (v != null)
771 return new v(netname || '__dummy__');
772
773 return null;
774 },
775
776 /**
777 * Obtains instances of all known {@link LuCI.Network.Protocol Protocol}
778 * backend classes.
779 *
780 * @returns {Array<LuCI.Network.Protocol>}
781 * Returns an array of protocol class instances.
782 */
783 getProtocols: function() {
784 var rv = [];
785
786 for (var protoname in _protocols)
787 rv.push(new _protocols[protoname]('__dummy__'));
788
789 return rv;
790 },
791
792 /**
793 * Registers a new {@link LuCI.Network.Protocol Protocol} subclass
794 * with the given methods and returns the resulting subclass value.
795 *
796 * This functions internally calls
797 * {@link LuCI.Class.extend Class.extend()} on the `Network.Protocol`
798 * base class.
799 *
800 * @param {string} protoname
801 * The name of the new protocol to register.
802 *
803 * @param {Object<string, *>} methods
804 * The member methods and values of the new `Protocol` subclass to
805 * be passed to {@link LuCI.Class.extend Class.extend()}.
806 *
807 * @returns {LuCI.Network.Protocol}
808 * Returns the new `Protocol` subclass.
809 */
810 registerProtocol: function(protoname, methods) {
811 var spec = L.isObject(_protospecs) ? _protospecs[protoname] : null;
812 var proto = Protocol.extend(Object.assign({
813 getI18n: function() {
814 return protoname;
815 },
816
817 isFloating: function() {
818 return false;
819 },
820
821 isVirtual: function() {
822 return (L.isObject(spec) && spec.no_device == true);
823 },
824
825 renderFormOptions: function(section) {
826
827 }
828 }, methods, {
829 __init__: function(name) {
830 this.sid = name;
831 },
832
833 getProtocol: function() {
834 return protoname;
835 }
836 }));
837
838 _protocols[protoname] = proto;
839
840 return proto;
841 },
842
843 /**
844 * Registers a new regular expression pattern to recognize
845 * virtual interfaces.
846 *
847 * @param {RegExp} pat
848 * A `RegExp` instance to match a virtual interface name
849 * such as `6in4-wan` or `tun0`.
850 */
851 registerPatternVirtual: function(pat) {
852 iface_patterns_virtual.push(pat);
853 },
854
855 /**
856 * Registers a new human readable translation string for a `Protocol`
857 * error code.
858 *
859 * @param {string} code
860 * The `ubus` protocol error code to register a translation for, e.g.
861 * `NO_DEVICE`.
862 *
863 * @param {string} message
864 * The message to use as translation for the given protocol error code.
865 *
866 * @returns {boolean}
867 * Returns `true` if the error code description has been added or `false`
868 * if either the arguments were invalid or if there already was a
869 * description for the given code.
870 */
871 registerErrorCode: function(code, message) {
872 if (typeof(code) == 'string' &&
873 typeof(message) == 'string' &&
874 !proto_errors.hasOwnProperty(code)) {
875 proto_errors[code] = message;
876 return true;
877 }
878
879 return false;
880 },
881
882 /**
883 * Adds a new network of the given name and update it with the given
884 * uci option values.
885 *
886 * If a network with the given name already exist but is empty, then
887 * this function will update its option, otherwise it will do nothing.
888 *
889 * @param {string} name
890 * The name of the network to add. Must be in the format `[a-zA-Z0-9_]+`.
891 *
892 * @param {Object<string, string|string[]>} [options]
893 * An object of uci option values to set on the new network or to
894 * update in an existing, empty network.
895 *
896 * @returns {Promise<null|LuCI.Network.Protocol>}
897 * Returns a promise resolving to the `Protocol` subclass instance
898 * describing the added network or resolving to `null` if the name
899 * was invalid or if a non-empty network of the given name already
900 * existed.
901 */
902 addNetwork: function(name, options) {
903 return this.getNetwork(name).then(L.bind(function(existingNetwork) {
904 if (name != null && /^[a-zA-Z0-9_]+$/.test(name) && existingNetwork == null) {
905 var sid = uci.add('network', 'interface', name);
906
907 if (sid != null) {
908 if (L.isObject(options))
909 for (var key in options)
910 if (options.hasOwnProperty(key))
911 uci.set('network', sid, key, options[key]);
912
913 return this.instantiateNetwork(sid);
914 }
915 }
916 else if (existingNetwork != null && existingNetwork.isEmpty()) {
917 if (L.isObject(options))
918 for (var key in options)
919 if (options.hasOwnProperty(key))
920 existingNetwork.set(key, options[key]);
921
922 return existingNetwork;
923 }
924 }, this));
925 },
926
927 /**
928 * Get a {@link LuCI.Network.Protocol Protocol} instance describing
929 * the network with the given name.
930 *
931 * @param {string} name
932 * The logical interface name of the network get, e.g. `lan` or `wan`.
933 *
934 * @returns {Promise<null|LuCI.Network.Protocol>}
935 * Returns a promise resolving to a
936 * {@link LuCI.Network.Protocol Protocol} subclass instance describing
937 * the network or `null` if the network did not exist.
938 */
939 getNetwork: function(name) {
940 return initNetworkState().then(L.bind(function() {
941 var section = (name != null) ? uci.get('network', name) : null;
942
943 if (section != null && section['.type'] == 'interface') {
944 return this.instantiateNetwork(name);
945 }
946 else if (name != null) {
947 for (var i = 0; i < _state.ifaces.length; i++)
948 if (_state.ifaces[i].interface == name)
949 return this.instantiateNetwork(name, _state.ifaces[i].proto);
950 }
951
952 return null;
953 }, this));
954 },
955
956 /**
957 * Gets an array containing all known networks.
958 *
959 * @returns {Promise<Array<LuCI.Network.Protocol>>}
960 * Returns a promise resolving to a name-sorted array of
961 * {@link LuCI.Network.Protocol Protocol} subclass instances
962 * describing all known networks.
963 */
964 getNetworks: function() {
965 return initNetworkState().then(L.bind(enumerateNetworks, this));
966 },
967
968 /**
969 * Deletes the given network and its references from the network and
970 * firewall configuration.
971 *
972 * @param {string} name
973 * The name of the network to delete.
974 *
975 * @returns {Promise<boolean>}
976 * Returns a promise resolving to either `true` if the network and
977 * references to it were successfully deleted from the configuration or
978 * `false` if the given network could not be found.
979 */
980 deleteNetwork: function(name) {
981 var requireFirewall = Promise.resolve(L.require('firewall')).catch(function() {}),
982 network = this.instantiateNetwork(name);
983
984 return Promise.all([ requireFirewall, initNetworkState() ]).then(function() {
985 var uciInterface = uci.get('network', name);
986
987 if (uciInterface != null && uciInterface['.type'] == 'interface') {
988 return Promise.resolve(network ? network.deleteConfiguration() : null).then(function() {
989 uci.remove('network', name);
990
991 uci.sections('luci', 'ifstate', function(s) {
992 if (s.interface == name)
993 uci.remove('luci', s['.name']);
994 });
995
996 uci.sections('network', 'alias', function(s) {
997 if (s.interface == name)
998 uci.remove('network', s['.name']);
999 });
1000
1001 uci.sections('network', 'route', function(s) {
1002 if (s.interface == name)
1003 uci.remove('network', s['.name']);
1004 });
1005
1006 uci.sections('network', 'route6', function(s) {
1007 if (s.interface == name)
1008 uci.remove('network', s['.name']);
1009 });
1010
1011 uci.sections('wireless', 'wifi-iface', function(s) {
1012 var networks = L.toArray(s.network).filter(function(network) { return network != name });
1013
1014 if (networks.length > 0)
1015 uci.set('wireless', s['.name'], 'network', networks.join(' '));
1016 else
1017 uci.unset('wireless', s['.name'], 'network');
1018 });
1019
1020 if (L.firewall)
1021 return L.firewall.deleteNetwork(name).then(function() { return true });
1022
1023 return true;
1024 }).catch(function() {
1025 return false;
1026 });
1027 }
1028
1029 return false;
1030 });
1031 },
1032
1033 /**
1034 * Rename the given network and its references to a new name.
1035 *
1036 * @param {string} oldName
1037 * The current name of the network.
1038 *
1039 * @param {string} newName
1040 * The name to rename the network to, must be in the format
1041 * `[a-z-A-Z0-9_]+`.
1042 *
1043 * @returns {Promise<boolean>}
1044 * Returns a promise resolving to either `true` if the network was
1045 * successfully renamed or `false` if the new name was invalid, if
1046 * a network with the new name already exists or if the network to
1047 * rename could not be found.
1048 */
1049 renameNetwork: function(oldName, newName) {
1050 return initNetworkState().then(function() {
1051 if (newName == null || !/^[a-zA-Z0-9_]+$/.test(newName) || uci.get('network', newName) != null)
1052 return false;
1053
1054 var oldNetwork = uci.get('network', oldName);
1055
1056 if (oldNetwork == null || oldNetwork['.type'] != 'interface')
1057 return false;
1058
1059 var sid = uci.add('network', 'interface', newName);
1060
1061 for (var key in oldNetwork)
1062 if (oldNetwork.hasOwnProperty(key) && key.charAt(0) != '.')
1063 uci.set('network', sid, key, oldNetwork[key]);
1064
1065 uci.sections('luci', 'ifstate', function(s) {
1066 if (s.interface == oldName)
1067 uci.set('luci', s['.name'], 'interface', newName);
1068 });
1069
1070 uci.sections('network', 'alias', function(s) {
1071 if (s.interface == oldName)
1072 uci.set('network', s['.name'], 'interface', newName);
1073 });
1074
1075 uci.sections('network', 'route', function(s) {
1076 if (s.interface == oldName)
1077 uci.set('network', s['.name'], 'interface', newName);
1078 });
1079
1080 uci.sections('network', 'route6', function(s) {
1081 if (s.interface == oldName)
1082 uci.set('network', s['.name'], 'interface', newName);
1083 });
1084
1085 uci.sections('wireless', 'wifi-iface', function(s) {
1086 var networks = L.toArray(s.network).map(function(network) { return (network == oldName ? newName : network) });
1087
1088 if (networks.length > 0)
1089 uci.set('wireless', s['.name'], 'network', networks.join(' '));
1090 });
1091
1092 uci.remove('network', oldName);
1093
1094 return true;
1095 });
1096 },
1097
1098 /**
1099 * Get a {@link LuCI.Network.Device Device} instance describing the
1100 * given network device.
1101 *
1102 * @param {string} name
1103 * The name of the network device to get, e.g. `eth0` or `br-lan`.
1104 *
1105 * @returns {Promise<null|LuCI.Network.Device>}
1106 * Returns a promise resolving to the `Device` instance describing
1107 * the network device or `null` if the given device name could not
1108 * be found.
1109 */
1110 getDevice: function(name) {
1111 return initNetworkState().then(L.bind(function() {
1112 if (name == null)
1113 return null;
1114
1115 if (_state.netdevs.hasOwnProperty(name) || isWifiIfname(name))
1116 return this.instantiateDevice(name);
1117
1118 var netid = getWifiNetidBySid(name);
1119 if (netid != null)
1120 return this.instantiateDevice(netid[0]);
1121
1122 return null;
1123 }, this));
1124 },
1125
1126 /**
1127 * Get a sorted list of all found network devices.
1128 *
1129 * @returns {Promise<Array<LuCI.Network.Device>>}
1130 * Returns a promise resolving to a sorted array of `Device` class
1131 * instances describing the network devices found on the system.
1132 */
1133 getDevices: function() {
1134 return initNetworkState().then(L.bind(function() {
1135 var devices = {};
1136
1137 /* find simple devices */
1138 var uciInterfaces = uci.sections('network', 'interface');
1139 for (var i = 0; i < uciInterfaces.length; i++) {
1140 var ifnames = L.toArray(uciInterfaces[i].ifname);
1141
1142 for (var j = 0; j < ifnames.length; j++) {
1143 if (ifnames[j].charAt(0) == '@')
1144 continue;
1145
1146 if (isIgnoredIfname(ifnames[j]) || isVirtualIfname(ifnames[j]) || isWifiIfname(ifnames[j]))
1147 continue;
1148
1149 devices[ifnames[j]] = this.instantiateDevice(ifnames[j]);
1150 }
1151 }
1152
1153 for (var ifname in _state.netdevs) {
1154 if (devices.hasOwnProperty(ifname))
1155 continue;
1156
1157 if (isIgnoredIfname(ifname) || isWifiIfname(ifname))
1158 continue;
1159
1160 if (_state.netdevs[ifname].wireless)
1161 continue;
1162
1163 devices[ifname] = this.instantiateDevice(ifname);
1164 }
1165
1166 /* find VLAN devices */
1167 var uciSwitchVLANs = uci.sections('network', 'switch_vlan');
1168 for (var i = 0; i < uciSwitchVLANs.length; i++) {
1169 if (typeof(uciSwitchVLANs[i].ports) != 'string' ||
1170 typeof(uciSwitchVLANs[i].device) != 'string' ||
1171 !_state.switches.hasOwnProperty(uciSwitchVLANs[i].device))
1172 continue;
1173
1174 var ports = uciSwitchVLANs[i].ports.split(/\s+/);
1175 for (var j = 0; j < ports.length; j++) {
1176 var m = ports[j].match(/^(\d+)([tu]?)$/);
1177 if (m == null)
1178 continue;
1179
1180 var netdev = _state.switches[uciSwitchVLANs[i].device].netdevs[m[1]];
1181 if (netdev == null)
1182 continue;
1183
1184 if (!devices.hasOwnProperty(netdev))
1185 devices[netdev] = this.instantiateDevice(netdev);
1186
1187 _state.isSwitch[netdev] = true;
1188
1189 if (m[2] != 't')
1190 continue;
1191
1192 var vid = uciSwitchVLANs[i].vid || uciSwitchVLANs[i].vlan;
1193 vid = (vid != null ? +vid : null);
1194
1195 if (vid == null || vid < 0 || vid > 4095)
1196 continue;
1197
1198 var vlandev = '%s.%d'.format(netdev, vid);
1199
1200 if (!devices.hasOwnProperty(vlandev))
1201 devices[vlandev] = this.instantiateDevice(vlandev);
1202
1203 _state.isSwitch[vlandev] = true;
1204 }
1205 }
1206
1207 /* find wireless interfaces */
1208 var uciWifiIfaces = uci.sections('wireless', 'wifi-iface'),
1209 networkCount = {};
1210
1211 for (var i = 0; i < uciWifiIfaces.length; i++) {
1212 if (typeof(uciWifiIfaces[i].device) != 'string')
1213 continue;
1214
1215 networkCount[uciWifiIfaces[i].device] = (networkCount[uciWifiIfaces[i].device] || 0) + 1;
1216
1217 var netid = '%s.network%d'.format(uciWifiIfaces[i].device, networkCount[uciWifiIfaces[i].device]);
1218
1219 devices[netid] = this.instantiateDevice(netid);
1220 }
1221
1222 var rv = [];
1223
1224 for (var netdev in devices)
1225 if (devices.hasOwnProperty(netdev))
1226 rv.push(devices[netdev]);
1227
1228 rv.sort(deviceSort);
1229
1230 return rv;
1231 }, this));
1232 },
1233
1234 /**
1235 * Test if a given network device name is in the list of patterns for
1236 * device names to ignore.
1237 *
1238 * Ignored device names are usually Linux network devices which are
1239 * spawned implicitly by kernel modules such as `tunl0` or `hwsim0`
1240 * and which are unsuitable for use in network configuration.
1241 *
1242 * @param {string} name
1243 * The device name to test.
1244 *
1245 * @returns {boolean}
1246 * Returns `true` if the given name is in the ignore pattern list,
1247 * else returns `false`.
1248 */
1249 isIgnoredDevice: function(name) {
1250 return isIgnoredIfname(name);
1251 },
1252
1253 /**
1254 * Get a {@link LuCI.Network.WifiDevice WifiDevice} instance describing
1255 * the given wireless radio.
1256 *
1257 * @param {string} devname
1258 * The configuration name of the wireless radio to lookup, e.g. `radio0`
1259 * for the first mac80211 phy on the system.
1260 *
1261 * @returns {Promise<null|LuCI.Network.WifiDevice>}
1262 * Returns a promise resolving to the `WifiDevice` instance describing
1263 * the underlying radio device or `null` if the wireless radio could not
1264 * be found.
1265 */
1266 getWifiDevice: function(devname) {
1267 return initNetworkState().then(L.bind(function() {
1268 var existingDevice = uci.get('wireless', devname);
1269
1270 if (existingDevice == null || existingDevice['.type'] != 'wifi-device')
1271 return null;
1272
1273 return this.instantiateWifiDevice(devname, _state.radios[devname] || {});
1274 }, this));
1275 },
1276
1277 /**
1278 * Obtain a list of all configured radio devices.
1279 *
1280 * @returns {Promise<Array<LuCI.Network.WifiDevice>>}
1281 * Returns a promise resolving to an array of `WifiDevice` instances
1282 * describing the wireless radios configured in the system.
1283 * The order of the array corresponds to the order of the radios in
1284 * the configuration.
1285 */
1286 getWifiDevices: function() {
1287 return initNetworkState().then(L.bind(function() {
1288 var uciWifiDevices = uci.sections('wireless', 'wifi-device'),
1289 rv = [];
1290
1291 for (var i = 0; i < uciWifiDevices.length; i++) {
1292 var devname = uciWifiDevices[i]['.name'];
1293 rv.push(this.instantiateWifiDevice(devname, _state.radios[devname] || {}));
1294 }
1295
1296 return rv;
1297 }, this));
1298 },
1299
1300 /**
1301 * Get a {@link LuCI.Network.WifiNetwork WifiNetwork} instance describing
1302 * the given wireless network.
1303 *
1304 * @param {string} netname
1305 * The name of the wireless network to lookup. This may be either an uci
1306 * configuration section ID, a network ID in the form `radio#.network#`
1307 * or a Linux network device name like `wlan0` which is resolved to the
1308 * corresponding configuration section through `ubus` runtime information.
1309 *
1310 * @returns {Promise<null|LuCI.Network.WifiNetwork>}
1311 * Returns a promise resolving to the `WifiNetwork` instance describing
1312 * the wireless network or `null` if the corresponding network could not
1313 * be found.
1314 */
1315 getWifiNetwork: function(netname) {
1316 return initNetworkState()
1317 .then(L.bind(this.lookupWifiNetwork, this, netname));
1318 },
1319
1320 /**
1321 * Get an array of all {@link LuCI.Network.WifiNetwork WifiNetwork}
1322 * instances describing the wireless networks present on the system.
1323 *
1324 * @returns {Promise<Array<LuCI.Network.WifiNetwork>>}
1325 * Returns a promise resolving to an array of `WifiNetwork` instances
1326 * describing the wireless networks. The array will be empty if no networks
1327 * are found.
1328 */
1329 getWifiNetworks: function() {
1330 return initNetworkState().then(L.bind(function() {
1331 var wifiIfaces = uci.sections('wireless', 'wifi-iface'),
1332 rv = [];
1333
1334 for (var i = 0; i < wifiIfaces.length; i++)
1335 rv.push(this.lookupWifiNetwork(wifiIfaces[i]['.name']));
1336
1337 rv.sort(function(a, b) {
1338 return (a.getID() > b.getID());
1339 });
1340
1341 return rv;
1342 }, this));
1343 },
1344
1345 /**
1346 * Adds a new wireless network to the configuration and sets its options
1347 * to the provided values.
1348 *
1349 * @param {Object<string, string|string[]>} options
1350 * The options to set for the newly added wireless network. This object
1351 * must at least contain a `device` property which is set to the radio
1352 * name the new network belongs to.
1353 *
1354 * @returns {Promise<null|LuCI.Network.WifiNetwork>}
1355 * Returns a promise resolving to a `WifiNetwork` instance describing
1356 * the newly added wireless network or `null` if the given options
1357 * were invalid or if the associated radio device could not be found.
1358 */
1359 addWifiNetwork: function(options) {
1360 return initNetworkState().then(L.bind(function() {
1361 if (options == null ||
1362 typeof(options) != 'object' ||
1363 typeof(options.device) != 'string')
1364 return null;
1365
1366 var existingDevice = uci.get('wireless', options.device);
1367 if (existingDevice == null || existingDevice['.type'] != 'wifi-device')
1368 return null;
1369
1370 /* XXX: need to add a named section (wifinet#) here */
1371 var sid = uci.add('wireless', 'wifi-iface');
1372 for (var key in options)
1373 if (options.hasOwnProperty(key))
1374 uci.set('wireless', sid, key, options[key]);
1375
1376 var radioname = existingDevice['.name'],
1377 netid = getWifiNetidBySid(sid) || [];
1378
1379 return this.instantiateWifiNetwork(sid, radioname, _state.radios[radioname], netid[0], null);
1380 }, this));
1381 },
1382
1383 /**
1384 * Deletes the given wireless network from the configuration.
1385 *
1386 * @param {string} netname
1387 * The name of the network to remove. This may be either a
1388 * network ID in the form `radio#.network#` or a Linux network device
1389 * name like `wlan0` which is resolved to the corresponding configuration
1390 * section through `ubus` runtime information.
1391 *
1392 * @returns {Promise<boolean>}
1393 * Returns a promise resolving to `true` if the wireless network has been
1394 * successfully deleted from the configuration or `false` if it could not
1395 * be found.
1396 */
1397 deleteWifiNetwork: function(netname) {
1398 return initNetworkState().then(L.bind(function() {
1399 var sid = getWifiSidByIfname(netname);
1400
1401 if (sid == null)
1402 return false;
1403
1404 uci.remove('wireless', sid);
1405 return true;
1406 }, this));
1407 },
1408
1409 /* private */
1410 getStatusByRoute: function(addr, mask) {
1411 return initNetworkState().then(L.bind(function() {
1412 var rv = [];
1413
1414 for (var i = 0; i < _state.ifaces.length; i++) {
1415 if (!Array.isArray(_state.ifaces[i].route))
1416 continue;
1417
1418 for (var j = 0; j < _state.ifaces[i].route.length; j++) {
1419 if (typeof(_state.ifaces[i].route[j]) != 'object' ||
1420 typeof(_state.ifaces[i].route[j].target) != 'string' ||
1421 typeof(_state.ifaces[i].route[j].mask) != 'number')
1422 continue;
1423
1424 if (_state.ifaces[i].route[j].table)
1425 continue;
1426
1427 if (_state.ifaces[i].route[j].target != addr ||
1428 _state.ifaces[i].route[j].mask != mask)
1429 continue;
1430
1431 rv.push(_state.ifaces[i]);
1432 }
1433 }
1434
1435 return rv;
1436 }, this));
1437 },
1438
1439 /* private */
1440 getStatusByAddress: function(addr) {
1441 return initNetworkState().then(L.bind(function() {
1442 var rv = [];
1443
1444 for (var i = 0; i < _state.ifaces.length; i++) {
1445 if (Array.isArray(_state.ifaces[i]['ipv4-address']))
1446 for (var j = 0; j < _state.ifaces[i]['ipv4-address'].length; j++)
1447 if (typeof(_state.ifaces[i]['ipv4-address'][j]) == 'object' &&
1448 _state.ifaces[i]['ipv4-address'][j].address == addr)
1449 return _state.ifaces[i];
1450
1451 if (Array.isArray(_state.ifaces[i]['ipv6-address']))
1452 for (var j = 0; j < _state.ifaces[i]['ipv6-address'].length; j++)
1453 if (typeof(_state.ifaces[i]['ipv6-address'][j]) == 'object' &&
1454 _state.ifaces[i]['ipv6-address'][j].address == addr)
1455 return _state.ifaces[i];
1456
1457 if (Array.isArray(_state.ifaces[i]['ipv6-prefix-assignment']))
1458 for (var j = 0; j < _state.ifaces[i]['ipv6-prefix-assignment'].length; j++)
1459 if (typeof(_state.ifaces[i]['ipv6-prefix-assignment'][j]) == 'object' &&
1460 typeof(_state.ifaces[i]['ipv6-prefix-assignment'][j]['local-address']) == 'object' &&
1461 _state.ifaces[i]['ipv6-prefix-assignment'][j]['local-address'].address == addr)
1462 return _state.ifaces[i];
1463 }
1464
1465 return null;
1466 }, this));
1467 },
1468
1469 /**
1470 * Get IPv4 wan networks.
1471 *
1472 * This function looks up all networks having a default `0.0.0.0/0` route
1473 * and returns them as array.
1474 *
1475 * @returns {Promise<Array<LuCI.Network.Protocol>>}
1476 * Returns a promise resolving to an array of `Protocol` subclass
1477 * instances describing the found default route interfaces.
1478 */
1479 getWANNetworks: function() {
1480 return this.getStatusByRoute('0.0.0.0', 0).then(L.bind(function(statuses) {
1481 var rv = [], seen = {};
1482
1483 for (var i = 0; i < statuses.length; i++) {
1484 if (!seen.hasOwnProperty(statuses[i].interface)) {
1485 rv.push(this.instantiateNetwork(statuses[i].interface, statuses[i].proto));
1486 seen[statuses[i].interface] = true;
1487 }
1488 }
1489
1490 return rv;
1491 }, this));
1492 },
1493
1494 /**
1495 * Get IPv6 wan networks.
1496 *
1497 * This function looks up all networks having a default `::/0` route
1498 * and returns them as array.
1499 *
1500 * @returns {Promise<Array<LuCI.Network.Protocol>>}
1501 * Returns a promise resolving to an array of `Protocol` subclass
1502 * instances describing the found IPv6 default route interfaces.
1503 */
1504 getWAN6Networks: function() {
1505 return this.getStatusByRoute('::', 0).then(L.bind(function(statuses) {
1506 var rv = [], seen = {};
1507
1508 for (var i = 0; i < statuses.length; i++) {
1509 if (!seen.hasOwnProperty(statuses[i].interface)) {
1510 rv.push(this.instantiateNetwork(statuses[i].interface, statuses[i].proto));
1511 seen[statuses[i].interface] = true;
1512 }
1513 }
1514
1515 return rv;
1516 }, this));
1517 },
1518
1519 /**
1520 * Describes an swconfig switch topology by specifying the CPU
1521 * connections and external port labels of a switch.
1522 *
1523 * @typedef {Object<string, Object|Array>} SwitchTopology
1524 * @memberof LuCI.Network
1525 *
1526 * @property {Object<number, string>} netdevs
1527 * The `netdevs` property points to an object describing the CPU port
1528 * connections of the switch. The numeric key of the enclosed object is
1529 * the port number, the value contains the Linux network device name the
1530 * port is hardwired to.
1531 *
1532 * @property {Array<Object<string, boolean|number|string>>} ports
1533 * The `ports` property points to an array describing the populated
1534 * ports of the switch in the external label order. Each array item is
1535 * an object containg the following keys:
1536 * - `num` - the internal switch port number
1537 * - `label` - the label of the port, e.g. `LAN 1` or `CPU (eth0)`
1538 * - `device` - the connected Linux network device name (CPU ports only)
1539 * - `tagged` - a boolean indicating whether the port must be tagged to
1540 * function (CPU ports only)
1541 */
1542
1543 /**
1544 * Returns the topologies of all swconfig switches found on the system.
1545 *
1546 * @returns {Promise<Object<string, LuCI.Network.SwitchTopology>>}
1547 * Returns a promise resolving to an object containing the topologies
1548 * of each switch. The object keys correspond to the name of the switches
1549 * such as `switch0`, the values are
1550 * {@link LuCI.Network.SwitchTopology SwitchTopology} objects describing
1551 * the layout.
1552 */
1553 getSwitchTopologies: function() {
1554 return initNetworkState().then(function() {
1555 return _state.switches;
1556 });
1557 },
1558
1559 /* private */
1560 instantiateNetwork: function(name, proto) {
1561 if (name == null)
1562 return null;
1563
1564 proto = (proto == null ? uci.get('network', name, 'proto') : proto);
1565
1566 var protoClass = _protocols[proto] || Protocol;
1567 return new protoClass(name);
1568 },
1569
1570 /* private */
1571 instantiateDevice: function(name, network, extend) {
1572 if (extend != null)
1573 return new (Device.extend(extend))(name, network);
1574
1575 return new Device(name, network);
1576 },
1577
1578 /* private */
1579 instantiateWifiDevice: function(radioname, radiostate) {
1580 return new WifiDevice(radioname, radiostate);
1581 },
1582
1583 /* private */
1584 instantiateWifiNetwork: function(sid, radioname, radiostate, netid, netstate, hostapd) {
1585 return new WifiNetwork(sid, radioname, radiostate, netid, netstate, hostapd);
1586 },
1587
1588 /* private */
1589 lookupWifiNetwork: function(netname) {
1590 var sid, res, netid, radioname, radiostate, netstate;
1591
1592 sid = getWifiSidByNetid(netname);
1593
1594 if (sid != null) {
1595 res = getWifiStateBySid(sid);
1596 netid = netname;
1597 radioname = res ? res[0] : null;
1598 radiostate = res ? res[1] : null;
1599 netstate = res ? res[2] : null;
1600 }
1601 else {
1602 res = getWifiStateByIfname(netname);
1603
1604 if (res != null) {
1605 radioname = res[0];
1606 radiostate = res[1];
1607 netstate = res[2];
1608 sid = netstate.section;
1609 netid = L.toArray(getWifiNetidBySid(sid))[0];
1610 }
1611 else {
1612 res = getWifiStateBySid(netname);
1613
1614 if (res != null) {
1615 radioname = res[0];
1616 radiostate = res[1];
1617 netstate = res[2];
1618 sid = netname;
1619 netid = L.toArray(getWifiNetidBySid(sid))[0];
1620 }
1621 else {
1622 res = getWifiNetidBySid(netname);
1623
1624 if (res != null) {
1625 netid = res[0];
1626 radioname = res[1];
1627 sid = netname;
1628 }
1629 }
1630 }
1631 }
1632
1633 return this.instantiateWifiNetwork(sid || netname, radioname,
1634 radiostate, netid, netstate,
1635 netstate ? _state.hostapd[netstate.ifname] : null);
1636 },
1637
1638 /**
1639 * Obtains the the network device name of the given object.
1640 *
1641 * @param {LuCI.Network.Protocol|LuCI.Network.Device|LuCI.Network.WifiDevice|LuCI.Network.WifiNetwork|string} obj
1642 * The object to get the device name from.
1643 *
1644 * @returns {null|string}
1645 * Returns a string containing the device name or `null` if the given
1646 * object could not be converted to a name.
1647 */
1648 getIfnameOf: function(obj) {
1649 return ifnameOf(obj);
1650 },
1651
1652 /**
1653 * Queries the internal DSL modem type from board information.
1654 *
1655 * @returns {Promise<null|string>}
1656 * Returns a promise resolving to the type of the internal modem
1657 * (e.g. `vdsl`) or to `null` if no internal modem is present.
1658 */
1659 getDSLModemType: function() {
1660 return initNetworkState().then(function() {
1661 return _state.hasDSLModem ? _state.hasDSLModem.type : null;
1662 });
1663 },
1664
1665 /**
1666 * Queries aggregated information about known hosts.
1667 *
1668 * This function aggregates information from various sources such as
1669 * DHCP lease databases, ARP and IPv6 neighbour entries, wireless
1670 * association list etc. and returns a {@link LuCI.Network.Hosts Hosts}
1671 * class instance describing the found hosts.
1672 *
1673 * @returns {Promise<LuCI.Network.Hosts>}
1674 * Returns a `Hosts` instance describing host known on the system.
1675 */
1676 getHostHints: function() {
1677 return initNetworkState().then(function() {
1678 return new Hosts(_state.hosts);
1679 });
1680 }
1681 });
1682
1683 /**
1684 * @class
1685 * @memberof LuCI.Network
1686 * @hideconstructor
1687 * @classdesc
1688 *
1689 * The `LuCI.Network.Hosts` class encapsulates host information aggregated
1690 * from multiple sources and provides convenience functions to access the
1691 * host information by different criteria.
1692 */
1693 Hosts = L.Class.extend(/** @lends LuCI.Network.Hosts.prototype */ {
1694 __init__: function(hosts) {
1695 this.hosts = hosts;
1696 },
1697
1698 /**
1699 * Lookup the hostname associated with the given MAC address.
1700 *
1701 * @param {string} mac
1702 * The MAC address to lookup.
1703 *
1704 * @returns {null|string}
1705 * Returns the hostname associated with the given MAC or `null` if
1706 * no matching host could be found or if no hostname is known for
1707 * the corresponding host.
1708 */
1709 getHostnameByMACAddr: function(mac) {
1710 return this.hosts[mac] ? this.hosts[mac].name : null;
1711 },
1712
1713 /**
1714 * Lookup the IPv4 address associated with the given MAC address.
1715 *
1716 * @param {string} mac
1717 * The MAC address to lookup.
1718 *
1719 * @returns {null|string}
1720 * Returns the IPv4 address associated with the given MAC or `null` if
1721 * no matching host could be found or if no IPv4 address is known for
1722 * the corresponding host.
1723 */
1724 getIPAddrByMACAddr: function(mac) {
1725 return this.hosts[mac] ? this.hosts[mac].ipv4 : null;
1726 },
1727
1728 /**
1729 * Lookup the IPv6 address associated with the given MAC address.
1730 *
1731 * @param {string} mac
1732 * The MAC address to lookup.
1733 *
1734 * @returns {null|string}
1735 * Returns the IPv6 address associated with the given MAC or `null` if
1736 * no matching host could be found or if no IPv6 address is known for
1737 * the corresponding host.
1738 */
1739 getIP6AddrByMACAddr: function(mac) {
1740 return this.hosts[mac] ? this.hosts[mac].ipv6 : null;
1741 },
1742
1743 /**
1744 * Lookup the hostname associated with the given IPv4 address.
1745 *
1746 * @param {string} ipaddr
1747 * The IPv4 address to lookup.
1748 *
1749 * @returns {null|string}
1750 * Returns the hostname associated with the given IPv4 or `null` if
1751 * no matching host could be found or if no hostname is known for
1752 * the corresponding host.
1753 */
1754 getHostnameByIPAddr: function(ipaddr) {
1755 for (var mac in this.hosts)
1756 if (this.hosts[mac].ipv4 == ipaddr && this.hosts[mac].name != null)
1757 return this.hosts[mac].name;
1758 return null;
1759 },
1760
1761 /**
1762 * Lookup the MAC address associated with the given IPv4 address.
1763 *
1764 * @param {string} ipaddr
1765 * The IPv4 address to lookup.
1766 *
1767 * @returns {null|string}
1768 * Returns the MAC address associated with the given IPv4 or `null` if
1769 * no matching host could be found or if no MAC address is known for
1770 * the corresponding host.
1771 */
1772 getMACAddrByIPAddr: function(ipaddr) {
1773 for (var mac in this.hosts)
1774 if (this.hosts[mac].ipv4 == ipaddr)
1775 return mac;
1776 return null;
1777 },
1778
1779 /**
1780 * Lookup the hostname associated with the given IPv6 address.
1781 *
1782 * @param {string} ipaddr
1783 * The IPv6 address to lookup.
1784 *
1785 * @returns {null|string}
1786 * Returns the hostname associated with the given IPv6 or `null` if
1787 * no matching host could be found or if no hostname is known for
1788 * the corresponding host.
1789 */
1790 getHostnameByIP6Addr: function(ip6addr) {
1791 for (var mac in this.hosts)
1792 if (this.hosts[mac].ipv6 == ip6addr && this.hosts[mac].name != null)
1793 return this.hosts[mac].name;
1794 return null;
1795 },
1796
1797 /**
1798 * Lookup the MAC address associated with the given IPv6 address.
1799 *
1800 * @param {string} ipaddr
1801 * The IPv6 address to lookup.
1802 *
1803 * @returns {null|string}
1804 * Returns the MAC address associated with the given IPv6 or `null` if
1805 * no matching host could be found or if no MAC address is known for
1806 * the corresponding host.
1807 */
1808 getMACAddrByIP6Addr: function(ip6addr) {
1809 for (var mac in this.hosts)
1810 if (this.hosts[mac].ipv6 == ip6addr)
1811 return mac;
1812 return null;
1813 },
1814
1815 /**
1816 * Return an array of (MAC address, name hint) tuples sorted by
1817 * MAC address.
1818 *
1819 * @param {boolean} [preferIp6=false]
1820 * Whether to prefer IPv6 addresses (`true`) or IPv4 addresses (`false`)
1821 * as name hint when no hostname is known for a specific MAC address.
1822 *
1823 * @returns {Array<Array<string>>}
1824 * Returns an array of arrays containing a name hint for each found
1825 * MAC address on the system. The array is sorted ascending by MAC.
1826 *
1827 * Each item of the resulting array is a two element array with the
1828 * MAC being the first element and the name hint being the second
1829 * element. The name hint is either the hostname, an IPv4 or an IPv6
1830 * address related to the MAC address.
1831 *
1832 * If no hostname but both IPv4 and IPv6 addresses are known, the
1833 * `preferIP6` flag specifies whether the IPv6 or the IPv4 address
1834 * is used as hint.
1835 */
1836 getMACHints: function(preferIp6) {
1837 var rv = [];
1838 for (var mac in this.hosts) {
1839 var hint = this.hosts[mac].name ||
1840 this.hosts[mac][preferIp6 ? 'ipv6' : 'ipv4'] ||
1841 this.hosts[mac][preferIp6 ? 'ipv4' : 'ipv6'];
1842
1843 rv.push([mac, hint]);
1844 }
1845 return rv.sort(function(a, b) { return a[0] > b[0] });
1846 }
1847 });
1848
1849 /**
1850 * @class
1851 * @memberof LuCI.Network
1852 * @hideconstructor
1853 * @classdesc
1854 *
1855 * The `Network.Protocol` class serves as base for protocol specific
1856 * subclasses which describe logical UCI networks defined by `config
1857 * interface` sections in `/etc/config/network`.
1858 */
1859 Protocol = L.Class.extend(/** @lends LuCI.Network.Protocol.prototype */ {
1860 __init__: function(name) {
1861 this.sid = name;
1862 },
1863
1864 _get: function(opt) {
1865 var val = uci.get('network', this.sid, opt);
1866
1867 if (Array.isArray(val))
1868 return val.join(' ');
1869
1870 return val || '';
1871 },
1872
1873 _ubus: function(field) {
1874 for (var i = 0; i < _state.ifaces.length; i++) {
1875 if (_state.ifaces[i].interface != this.sid)
1876 continue;
1877
1878 return (field != null ? _state.ifaces[i][field] : _state.ifaces[i]);
1879 }
1880 },
1881
1882 /**
1883 * Read the given UCI option value of this network.
1884 *
1885 * @param {string} opt
1886 * The UCI option name to read.
1887 *
1888 * @returns {null|string|string[]}
1889 * Returns the UCI option value or `null` if the requested option is
1890 * not found.
1891 */
1892 get: function(opt) {
1893 return uci.get('network', this.sid, opt);
1894 },
1895
1896 /**
1897 * Set the given UCI option of this network to the given value.
1898 *
1899 * @param {string} opt
1900 * The name of the UCI option to set.
1901 *
1902 * @param {null|string|string[]} val
1903 * The value to set or `null` to remove the given option from the
1904 * configuration.
1905 */
1906 set: function(opt, val) {
1907 return uci.set('network', this.sid, opt, val);
1908 },
1909
1910 /**
1911 * Get the associared Linux network device of this network.
1912 *
1913 * @returns {null|string}
1914 * Returns the name of the associated network device or `null` if
1915 * it could not be determined.
1916 */
1917 getIfname: function() {
1918 var ifname;
1919
1920 if (this.isFloating())
1921 ifname = this._ubus('l3_device');
1922 else
1923 ifname = this._ubus('device') || this._ubus('l3_device');
1924
1925 if (ifname != null)
1926 return ifname;
1927
1928 var res = getWifiNetidByNetname(this.sid);
1929 return (res != null ? res[0] : null);
1930 },
1931
1932 /**
1933 * Get the name of this network protocol class.
1934 *
1935 * This function will be overwritten by subclasses created by
1936 * {@link LuCI.Network#registerProtocol Network.registerProtocol()}.
1937 *
1938 * @abstract
1939 * @returns {string}
1940 * Returns the name of the network protocol implementation, e.g.
1941 * `static` or `dhcp`.
1942 */
1943 getProtocol: function() {
1944 return null;
1945 },
1946
1947 /**
1948 * Return a human readable description for the protcol, such as
1949 * `Static address` or `DHCP client`.
1950 *
1951 * This function should be overwritten by subclasses.
1952 *
1953 * @abstract
1954 * @returns {string}
1955 * Returns the description string.
1956 */
1957 getI18n: function() {
1958 switch (this.getProtocol()) {
1959 case 'none': return _('Unmanaged');
1960 case 'static': return _('Static address');
1961 case 'dhcp': return _('DHCP client');
1962 default: return _('Unknown');
1963 }
1964 },
1965
1966 /**
1967 * Get the type of the underlying interface.
1968 *
1969 * This function actually is a convenience wrapper around
1970 * `proto.get("type")` and is mainly used by other `LuCI.Network` code
1971 * to check whether the interface is declared as bridge in UCI.
1972 *
1973 * @returns {null|string}
1974 * Returns the value of the `type` option of the associated logical
1975 * interface or `null` if no `type` option is set.
1976 */
1977 getType: function() {
1978 return this._get('type');
1979 },
1980
1981 /**
1982 * Get the name of the associated logical interface.
1983 *
1984 * @returns {string}
1985 * Returns the logical interface name, such as `lan` or `wan`.
1986 */
1987 getName: function() {
1988 return this.sid;
1989 },
1990
1991 /**
1992 * Get the uptime of the logical interface.
1993 *
1994 * @returns {number}
1995 * Returns the uptime of the associated interface in seconds.
1996 */
1997 getUptime: function() {
1998 return this._ubus('uptime') || 0;
1999 },
2000
2001 /**
2002 * Get the logical interface expiry time in seconds.
2003 *
2004 * For protocols that have a concept of a lease, such as DHCP or
2005 * DHCPv6, this function returns the remaining time in seconds
2006 * until the lease expires.
2007 *
2008 * @returns {number}
2009 * Returns the amount of seconds until the lease expires or `-1`
2010 * if it isn't applicable to the associated protocol.
2011 */
2012 getExpiry: function() {
2013 var u = this._ubus('uptime'),
2014 d = this._ubus('data');
2015
2016 if (typeof(u) == 'number' && d != null &&
2017 typeof(d) == 'object' && typeof(d.leasetime) == 'number') {
2018 var r = d.leasetime - (u % d.leasetime);
2019 return (r > 0 ? r : 0);
2020 }
2021
2022 return -1;
2023 },
2024
2025 /**
2026 * Get the metric value of the logical interface.
2027 *
2028 * @returns {number}
2029 * Returns the current metric value used for device and network
2030 * routes spawned by the associated logical interface.
2031 */
2032 getMetric: function() {
2033 return this._ubus('metric') || 0;
2034 },
2035
2036 /**
2037 * Get the requested firewall zone name of the logical interface.
2038 *
2039 * Some protocol implementations request a specific firewall zone
2040 * to trigger inclusion of their resulting network devices into the
2041 * firewall rule set.
2042 *
2043 * @returns {null|string}
2044 * Returns the requested firewall zone name as published in the
2045 * `ubus` runtime information or `null` if the remote protocol
2046 * handler didn't request a zone.
2047 */
2048 getZoneName: function() {
2049 var d = this._ubus('data');
2050
2051 if (L.isObject(d) && typeof(d.zone) == 'string')
2052 return d.zone;
2053
2054 return null;
2055 },
2056
2057 /**
2058 * Query the first (primary) IPv4 address of the logical interface.
2059 *
2060 * @returns {null|string}
2061 * Returns the primary IPv4 address registered by the protocol handler
2062 * or `null` if no IPv4 addresses were set.
2063 */
2064 getIPAddr: function() {
2065 var addrs = this._ubus('ipv4-address');
2066 return ((Array.isArray(addrs) && addrs.length) ? addrs[0].address : null);
2067 },
2068
2069 /**
2070 * Query all IPv4 addresses of the logical interface.
2071 *
2072 * @returns {string[]}
2073 * Returns an array of IPv4 addresses in CIDR notation which have been
2074 * registered by the protocol handler. The order of the resulting array
2075 * follows the order of the addresses in `ubus` runtime information.
2076 */
2077 getIPAddrs: function() {
2078 var addrs = this._ubus('ipv4-address'),
2079 rv = [];
2080
2081 if (Array.isArray(addrs))
2082 for (var i = 0; i < addrs.length; i++)
2083 rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
2084
2085 return rv;
2086 },
2087
2088 /**
2089 * Query the first (primary) IPv4 netmask of the logical interface.
2090 *
2091 * @returns {null|string}
2092 * Returns the netmask of the primary IPv4 address registered by the
2093 * protocol handler or `null` if no IPv4 addresses were set.
2094 */
2095 getNetmask: function() {
2096 var addrs = this._ubus('ipv4-address');
2097 if (Array.isArray(addrs) && addrs.length)
2098 return prefixToMask(addrs[0].mask, false);
2099 },
2100
2101 /**
2102 * Query the gateway (nexthop) of the default route associated with
2103 * this logical interface.
2104 *
2105 * @returns {string}
2106 * Returns a string containing the IPv4 nexthop address of the associated
2107 * default route or `null` if no default route was found.
2108 */
2109 getGatewayAddr: function() {
2110 var routes = this._ubus('route');
2111
2112 if (Array.isArray(routes))
2113 for (var i = 0; i < routes.length; i++)
2114 if (typeof(routes[i]) == 'object' &&
2115 routes[i].target == '0.0.0.0' &&
2116 routes[i].mask == 0)
2117 return routes[i].nexthop;
2118
2119 return null;
2120 },
2121
2122 /**
2123 * Query the IPv4 DNS servers associated with the logical interface.
2124 *
2125 * @returns {string[]}
2126 * Returns an array of IPv4 DNS servers registered by the remote
2127 * protocol backend.
2128 */
2129 getDNSAddrs: function() {
2130 var addrs = this._ubus('dns-server'),
2131 rv = [];
2132
2133 if (Array.isArray(addrs))
2134 for (var i = 0; i < addrs.length; i++)
2135 if (!/:/.test(addrs[i]))
2136 rv.push(addrs[i]);
2137
2138 return rv;
2139 },
2140
2141 /**
2142 * Query the first (primary) IPv6 address of the logical interface.
2143 *
2144 * @returns {null|string}
2145 * Returns the primary IPv6 address registered by the protocol handler
2146 * in CIDR notation or `null` if no IPv6 addresses were set.
2147 */
2148 getIP6Addr: function() {
2149 var addrs = this._ubus('ipv6-address');
2150
2151 if (Array.isArray(addrs) && L.isObject(addrs[0]))
2152 return '%s/%d'.format(addrs[0].address, addrs[0].mask);
2153
2154 addrs = this._ubus('ipv6-prefix-assignment');
2155
2156 if (Array.isArray(addrs) && L.isObject(addrs[0]) && L.isObject(addrs[0]['local-address']))
2157 return '%s/%d'.format(addrs[0]['local-address'].address, addrs[0]['local-address'].mask);
2158
2159 return null;
2160 },
2161
2162 /**
2163 * Query all IPv6 addresses of the logical interface.
2164 *
2165 * @returns {string[]}
2166 * Returns an array of IPv6 addresses in CIDR notation which have been
2167 * registered by the protocol handler. The order of the resulting array
2168 * follows the order of the addresses in `ubus` runtime information.
2169 */
2170 getIP6Addrs: function() {
2171 var addrs = this._ubus('ipv6-address'),
2172 rv = [];
2173
2174 if (Array.isArray(addrs))
2175 for (var i = 0; i < addrs.length; i++)
2176 if (L.isObject(addrs[i]))
2177 rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
2178
2179 addrs = this._ubus('ipv6-prefix-assignment');
2180
2181 if (Array.isArray(addrs))
2182 for (var i = 0; i < addrs.length; i++)
2183 if (L.isObject(addrs[i]) && L.isObject(addrs[i]['local-address']))
2184 rv.push('%s/%d'.format(addrs[i]['local-address'].address, addrs[i]['local-address'].mask));
2185
2186 return rv;
2187 },
2188
2189 /**
2190 * Query the gateway (nexthop) of the IPv6 default route associated with
2191 * this logical interface.
2192 *
2193 * @returns {string}
2194 * Returns a string containing the IPv6 nexthop address of the associated
2195 * default route or `null` if no default route was found.
2196 */
2197 getGateway6Addr: function() {
2198 var routes = this._ubus('route');
2199
2200 if (Array.isArray(routes))
2201 for (var i = 0; i < routes.length; i++)
2202 if (typeof(routes[i]) == 'object' &&
2203 routes[i].target == '::' &&
2204 routes[i].mask == 0)
2205 return routes[i].nexthop;
2206
2207 return null;
2208 },
2209
2210 /**
2211 * Query the IPv6 DNS servers associated with the logical interface.
2212 *
2213 * @returns {string[]}
2214 * Returns an array of IPv6 DNS servers registered by the remote
2215 * protocol backend.
2216 */
2217 getDNS6Addrs: function() {
2218 var addrs = this._ubus('dns-server'),
2219 rv = [];
2220
2221 if (Array.isArray(addrs))
2222 for (var i = 0; i < addrs.length; i++)
2223 if (/:/.test(addrs[i]))
2224 rv.push(addrs[i]);
2225
2226 return rv;
2227 },
2228
2229 /**
2230 * Query the routed IPv6 prefix associated with the logical interface.
2231 *
2232 * @returns {null|string}
2233 * Returns the routed IPv6 prefix registered by the remote protocol
2234 * handler or `null` if no prefix is present.
2235 */
2236 getIP6Prefix: function() {
2237 var prefixes = this._ubus('ipv6-prefix');
2238
2239 if (Array.isArray(prefixes) && L.isObject(prefixes[0]))
2240 return '%s/%d'.format(prefixes[0].address, prefixes[0].mask);
2241
2242 return null;
2243 },
2244
2245 /**
2246 * Query interface error messages published in `ubus` runtime state.
2247 *
2248 * Interface errors are emitted by remote protocol handlers if the setup
2249 * of the underlying logical interface failed, e.g. due to bad
2250 * configuration or network connectivity issues.
2251 *
2252 * This function will translate the found error codes to human readable
2253 * messages using the descriptions registered by
2254 * {@link LuCI.Network#registerErrorCode Network.registerErrorCode()}
2255 * and fall back to `"Unknown error (%s)"` where `%s` is replaced by the
2256 * error code in case no translation can be found.
2257 *
2258 * @returns {string[]}
2259 * Returns an array of translated interface error messages.
2260 */
2261 getErrors: function() {
2262 var errors = this._ubus('errors'),
2263 rv = null;
2264
2265 if (Array.isArray(errors)) {
2266 for (var i = 0; i < errors.length; i++) {
2267 if (!L.isObject(errors[i]) || typeof(errors[i].code) != 'string')
2268 continue;
2269
2270 rv = rv || [];
2271 rv.push(proto_errors[errors[i].code] || _('Unknown error (%s)').format(errors[i].code));
2272 }
2273 }
2274
2275 return rv;
2276 },
2277
2278 /**
2279 * Checks whether the underlying logical interface is declared as bridge.
2280 *
2281 * @returns {boolean}
2282 * Returns `true` when the interface is declared with `option type bridge`
2283 * and when the associated protocol implementation is not marked virtual
2284 * or `false` when the logical interface is no bridge.
2285 */
2286 isBridge: function() {
2287 return (!this.isVirtual() && this.getType() == 'bridge');
2288 },
2289
2290 /**
2291 * Get the name of the opkg package providing the protocol functionality.
2292 *
2293 * This function should be overwritten by protocol specific subclasses.
2294 *
2295 * @abstract
2296 *
2297 * @returns {string}
2298 * Returns the name of the opkg package required for the protocol to
2299 * function, e.g. `odhcp6c` for the `dhcpv6` prototocol.
2300 */
2301 getOpkgPackage: function() {
2302 return null;
2303 },
2304
2305 /**
2306 * Check function for the protocol handler if a new interface is createable.
2307 *
2308 * This function should be overwritten by protocol specific subclasses.
2309 *
2310 * @abstract
2311 *
2312 * @param {string} ifname
2313 * The name of the interface to be created.
2314 *
2315 * @returns {Promise<null|error message>}
2316 * Returns `null` if new interface is createable, else returns (error) message.
2317 */
2318 isCreateable: function(ifname) {
2319 return Promise.resolve(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 L.network.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]) ? L.network.instantiateDevice(m[1], this) : null);
2536 }
2537
2538 ifname = getWifiNetidByNetname(this.sid);
2539
2540 return (ifname != null ? L.network.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 ? L.network.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 ? L.network.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(L.network.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(L.network.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 = L.Class.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(L.network.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 = L.Class.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 L.network.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 L.network.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 L.network.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 = L.Class.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 L.network.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(L.network.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 L.network.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;