9 CONNECT_FAILED
: _('Connection attempt failed'),
10 INVALID_ADDRESS
: _('IP address is invalid'),
11 INVALID_GATEWAY
: _('Gateway address is invalid'),
12 INVALID_LOCAL_ADDRESS
: _('Local IP address is invalid'),
13 MISSING_ADDRESS
: _('IP address is missing'),
14 MISSING_PEER_ADDRESS
: _('Peer address is missing'),
15 NO_DEVICE
: _('Network device is not present'),
16 NO_IFACE
: _('Unable to determine device name'),
17 NO_IFNAME
: _('Unable to determine device name'),
18 NO_WAN_ADDRESS
: _('Unable to determine external IP address'),
19 NO_WAN_LINK
: _('Unable to determine upstream interface'),
20 PEER_RESOLVE_FAIL
: _('Unable to resolve peer host name'),
21 PIN_FAILED
: _('PIN code rejected')
24 var iface_patterns_ignore
= [
40 var iface_patterns_wireless
= [
47 var iface_patterns_virtual
= [ ];
49 var callLuciNetworkDevices
= rpc
.declare({
51 method
: 'getNetworkDevices',
55 var callLuciWirelessDevices
= rpc
.declare({
57 method
: 'getWirelessDevices',
61 var callLuciBoardJSON
= rpc
.declare({
63 method
: 'getBoardJSON'
66 var callLuciHostHints
= rpc
.declare({
68 method
: 'getHostHints',
72 var callIwinfoAssoclist
= rpc
.declare({
75 params
: [ 'device', 'mac' ],
76 expect
: { results
: [] }
79 var callIwinfoScan
= rpc
.declare({
84 expect
: { results
: [] }
87 var callNetworkInterfaceDump
= rpc
.declare({
88 object
: 'network.interface',
90 expect
: { 'interface': [] }
93 var callNetworkProtoHandlers
= rpc
.declare({
95 method
: 'get_proto_handlers',
104 function getProtocolHandlers(cache
) {
105 return callNetworkProtoHandlers().then(function(protos
) {
106 /* Register "none" protocol */
107 if (!protos
.hasOwnProperty('none'))
108 Object
.assign(protos
, { none
: { no_device
: false } });
110 /* Hack: emulate relayd protocol */
111 if (!protos
.hasOwnProperty('relay') && L
.hasSystemFeature('relayd'))
112 Object
.assign(protos
, { relay
: { no_device
: true } });
114 Object
.assign(_protospecs
, protos
);
116 return Promise
.all(Object
.keys(protos
).map(function(p
) {
117 return Promise
.resolve(L
.require('protocol.%s'.format(p
))).catch(function(err
) {
118 if (L
.isObject(err
) && err
.name
!= 'NetworkError')
121 })).then(function() {
124 }).catch(function() {
129 function getWifiStateBySid(sid
) {
130 var s
= uci
.get('wireless', sid
);
132 if (s
!= null && s
['.type'] == 'wifi-iface') {
133 for (var radioname
in _state
.radios
) {
134 for (var i
= 0; i
< _state
.radios
[radioname
].interfaces
.length
; i
++) {
135 var netstate
= _state
.radios
[radioname
].interfaces
[i
];
137 if (typeof(netstate
.section
) != 'string')
140 var s2
= uci
.get('wireless', netstate
.section
);
142 if (s2
!= null && s
['.type'] == s2
['.type'] && s
['.name'] == s2
['.name']) {
143 if (s2
['.anonymous'] == false && netstate
.section
.charAt(0) == '@')
146 return [ radioname
, _state
.radios
[radioname
], netstate
];
155 function getWifiStateByIfname(ifname
) {
156 for (var radioname
in _state
.radios
) {
157 for (var i
= 0; i
< _state
.radios
[radioname
].interfaces
.length
; i
++) {
158 var netstate
= _state
.radios
[radioname
].interfaces
[i
];
160 if (typeof(netstate
.ifname
) != 'string')
163 if (netstate
.ifname
== ifname
)
164 return [ radioname
, _state
.radios
[radioname
], netstate
];
171 function isWifiIfname(ifname
) {
172 for (var i
= 0; i
< iface_patterns_wireless
.length
; i
++)
173 if (iface_patterns_wireless
[i
].test(ifname
))
179 function getWifiSidByNetid(netid
) {
180 var m
= /^(\w+)\.network(\d+)$/.exec(netid
);
182 var sections
= uci
.sections('wireless', 'wifi-iface');
183 for (var i
= 0, n
= 0; i
< sections
.length
; i
++) {
184 if (sections
[i
].device
!= m
[1])
188 return sections
[i
]['.name'];
195 function getWifiSidByIfname(ifname
) {
196 var sid
= getWifiSidByNetid(ifname
);
201 var res
= getWifiStateByIfname(ifname
);
203 if (res
!= null && L
.isObject(res
[2]) && typeof(res
[2].section
) == 'string')
204 return res
[2].section
;
209 function getWifiNetidBySid(sid
) {
210 var s
= uci
.get('wireless', sid
);
211 if (s
!= null && s
['.type'] == 'wifi-iface') {
212 var radioname
= s
.device
;
213 if (typeof(s
.device
) == 'string') {
214 var i
= 0, netid
= null, sections
= uci
.sections('wireless', 'wifi-iface');
215 for (var i
= 0, n
= 0; i
< sections
.length
; i
++) {
216 if (sections
[i
].device
!= s
.device
)
221 if (sections
[i
]['.name'] != s
['.name'])
224 return [ '%s.network%d'.format(s
.device
, n
), s
.device
];
233 function getWifiNetidByNetname(name
) {
234 var sections
= uci
.sections('wireless', 'wifi-iface');
235 for (var i
= 0; i
< sections
.length
; i
++) {
236 if (typeof(sections
[i
].network
) != 'string')
239 var nets
= sections
[i
].network
.split(/\s+/);
240 for (var j
= 0; j
< nets
.length
; j
++) {
244 return getWifiNetidBySid(sections
[i
]['.name']);
251 function isVirtualIfname(ifname
) {
252 for (var i
= 0; i
< iface_patterns_virtual
.length
; i
++)
253 if (iface_patterns_virtual
[i
].test(ifname
))
259 function isIgnoredIfname(ifname
) {
260 for (var i
= 0; i
< iface_patterns_ignore
.length
; i
++)
261 if (iface_patterns_ignore
[i
].test(ifname
))
267 function appendValue(config
, section
, option
, value
) {
268 var values
= uci
.get(config
, section
, option
),
269 isArray
= Array
.isArray(values
),
272 if (isArray
== false)
273 values
= L
.toArray(values
);
275 if (values
.indexOf(value
) == -1) {
280 uci
.set(config
, section
, option
, isArray
? values
: values
.join(' '));
285 function removeValue(config
, section
, option
, value
) {
286 var values
= uci
.get(config
, section
, option
),
287 isArray
= Array
.isArray(values
),
290 if (isArray
== false)
291 values
= L
.toArray(values
);
293 for (var i
= values
.length
- 1; i
>= 0; i
--) {
294 if (values
[i
] == value
) {
300 if (values
.length
> 0)
301 uci
.set(config
, section
, option
, isArray
? values
: values
.join(' '));
303 uci
.unset(config
, section
, option
);
308 function prefixToMask(bits
, v6
) {
309 var w
= v6
? 128 : 32,
315 for (var i
= 0; i
< w
/ 16; i
++) {
316 var b
= Math
.min(16, bits
);
317 m
.push((0xffff << (16 - b
)) & 0xffff);
322 return String
.prototype.format
.apply('%x:%x:%x:%x:%x:%x:%x:%x', m
).replace(/:0(?::0)+$/, '::');
324 return '%d.%d.%d.%d'.format(m
[0] >>> 8, m
[0] & 0xff, m
[1] >>> 8, m
[1] & 0xff);
327 function maskToPrefix(mask
, v6
) {
328 var m
= v6
? validation
.parseIPv6(mask
) : validation
.parseIPv4(mask
);
335 for (var i
= 0, z
= false; i
< m
.length
; i
++) {
338 while (!z
&& (m
[i
] & (v6
? 0x8000 : 0x80))) {
339 m
[i
] = (m
[i
] << 1) & (v6
? 0xffff : 0xff);
350 function initNetworkState(refresh
) {
351 if (_state
== null || refresh
) {
352 _init
= _init
|| Promise
.all([
353 L
.resolveDefault(callNetworkInterfaceDump(), []),
354 L
.resolveDefault(callLuciBoardJSON(), {}),
355 L
.resolveDefault(callLuciNetworkDevices(), {}),
356 L
.resolveDefault(callLuciWirelessDevices(), {}),
357 L
.resolveDefault(callLuciHostHints(), {}),
358 getProtocolHandlers(),
359 L
.resolveDefault(uci
.load('network')),
360 L
.resolveDefault(uci
.load('wireless')),
361 L
.resolveDefault(uci
.load('luci'))
362 ]).then(function(data
) {
363 var netifd_ifaces
= data
[0],
364 board_json
= data
[1],
368 isTunnel
: {}, isBridge
: {}, isSwitch
: {}, isWifi
: {},
369 ifaces
: netifd_ifaces
, radios
: data
[3], hosts
: data
[4],
370 netdevs
: {}, bridges
: {}, switches
: {}, hostapd
: {}
373 for (var name
in luci_devs
) {
374 var dev
= luci_devs
[name
];
376 if (isVirtualIfname(name
))
377 s
.isTunnel
[name
] = true;
379 if (!s
.isTunnel
[name
] && isIgnoredIfname(name
))
382 s
.netdevs
[name
] = s
.netdevs
[name
] || {
392 wireless
: dev
.wireless
,
397 if (Array
.isArray(dev
.ipaddrs
))
398 for (var i
= 0; i
< dev
.ipaddrs
.length
; i
++)
399 s
.netdevs
[name
].ipaddrs
.push(dev
.ipaddrs
[i
].address
+ '/' + dev
.ipaddrs
[i
].netmask
);
401 if (Array
.isArray(dev
.ip6addrs
))
402 for (var i
= 0; i
< dev
.ip6addrs
.length
; i
++)
403 s
.netdevs
[name
].ip6addrs
.push(dev
.ip6addrs
[i
].address
+ '/' + dev
.ip6addrs
[i
].netmask
);
406 for (var name
in luci_devs
) {
407 var dev
= luci_devs
[name
];
419 for (var i
= 0; dev
.ports
&& i
< dev
.ports
.length
; i
++) {
420 var subdev
= s
.netdevs
[dev
.ports
[i
]];
425 b
.ifnames
.push(subdev
);
430 s
.isBridge
[name
] = true;
433 if (L
.isObject(board_json
.switch)) {
434 for (var switchname
in board_json
.switch) {
435 var layout
= board_json
.switch[switchname
],
442 if (L
.isObject(layout
) && Array
.isArray(layout
.ports
)) {
443 for (var i
= 0, port
; (port
= layout
.ports
[i
]) != null; i
++) {
444 if (typeof(port
) == 'object' && typeof(port
.num
) == 'number' &&
445 (typeof(port
.role
) == 'string' || typeof(port
.device
) == 'string')) {
448 role
: port
.role
|| 'cpu',
449 index
: (port
.index
!= null) ? port
.index
: port
.num
452 if (port
.device
!= null) {
453 spec
.device
= port
.device
;
454 spec
.tagged
= spec
.need_tag
;
455 netdevs
[port
.num
] = port
.device
;
460 if (port
.role
!= null)
461 nports
[port
.role
] = (nports
[port
.role
] || 0) + 1;
465 ports
.sort(function(a
, b
) {
466 if (a
.role
!= b
.role
)
467 return (a
.role
< b
.role
) ? -1 : 1;
469 return (a
.index
- b
.index
);
472 for (var i
= 0, port
; (port
= ports
[i
]) != null; i
++) {
473 if (port
.role
!= role
) {
479 port
.label
= 'CPU (%s)'.format(port
.device
);
480 else if (nports
[role
] > 1)
481 port
.label
= '%s %d'.format(role
.toUpperCase(), pnum
++);
483 port
.label
= role
.toUpperCase();
489 s
.switches
[switchname
] = {
497 if (L
.isObject(board_json
.dsl
) && L
.isObject(board_json
.dsl
.modem
)) {
498 s
.hasDSLModem
= board_json
.dsl
.modem
;
505 if (L
.isObject(s
.radios
))
506 for (var radio
in s
.radios
)
507 if (L
.isObject(s
.radios
[radio
]) && Array
.isArray(s
.radios
[radio
].interfaces
))
508 for (var i
= 0; i
< s
.radios
[radio
].interfaces
.length
; i
++)
509 if (L
.isObject(s
.radios
[radio
].interfaces
[i
]) && s
.radios
[radio
].interfaces
[i
].ifname
)
510 objects
.push('hostapd.%s'.format(s
.radios
[radio
].interfaces
[i
].ifname
));
512 return (objects
.length
? L
.resolveDefault(rpc
.list
.apply(rpc
, objects
), {}) : Promise
.resolve({})).then(function(res
) {
514 var m
= k
.match(/^hostapd\.(.+)$/);
516 s
.hostapd
[m
[1]] = res
[k
];
524 return (_state
!= null ? Promise
.resolve(_state
) : _init
);
527 function ifnameOf(obj
) {
528 if (obj
instanceof Protocol
)
529 return obj
.getIfname();
530 else if (obj
instanceof Device
)
531 return obj
.getName();
532 else if (obj
instanceof WifiDevice
)
533 return obj
.getName();
534 else if (obj
instanceof WifiNetwork
)
535 return obj
.getIfname();
536 else if (typeof(obj
) == 'string')
537 return obj
.replace(/:.+$/, '');
542 function networkSort(a
, b
) {
543 return a
.getName() > b
.getName();
546 function deviceSort(a
, b
) {
547 var typeWeigth
= { wifi
: 2, alias
: 3 },
548 weightA
= typeWeigth
[a
.getType()] || 1,
549 weightB
= typeWeigth
[b
.getType()] || 1;
551 if (weightA
!= weightB
)
552 return weightA
- weightB
;
554 return a
.getName() > b
.getName();
557 function formatWifiEncryption(enc
) {
558 if (!L
.isObject(enc
))
564 var ciphers
= Array
.isArray(enc
.ciphers
)
565 ? enc
.ciphers
.map(function(c
) { return c
.toUpperCase() }) : [ 'NONE' ];
567 if (Array
.isArray(enc
.wep
)) {
568 var has_open
= false,
571 for (var i
= 0; i
< enc
.wep
.length
; i
++)
572 if (enc
.wep
[i
] == 'open')
574 else if (enc
.wep
[i
] == 'shared')
577 if (has_open
&& has_shared
)
578 return 'WEP Open/Shared (%s)'.format(ciphers
.join(', '));
580 return 'WEP Open System (%s)'.format(ciphers
.join(', '));
582 return 'WEP Shared Auth (%s)'.format(ciphers
.join(', '));
587 if (Array
.isArray(enc
.wpa
)) {
589 suites
= Array
.isArray(enc
.authentication
)
590 ? enc
.authentication
.map(function(a
) { return a
.toUpperCase() }) : [ 'NONE' ];
592 for (var i
= 0; i
< enc
.wpa
.length
; i
++)
593 switch (enc
.wpa
[i
]) {
595 versions
.push('WPA');
599 versions
.push('WPA%d'.format(enc
.wpa
[i
]));
603 if (versions
.length
> 1)
604 return 'mixed %s %s (%s)'.format(versions
.join('/'), suites
.join(', '), ciphers
.join(', '));
606 return '%s %s (%s)'.format(versions
[0], suites
.join(', '), ciphers
.join(', '));
612 function enumerateNetworks() {
613 var uciInterfaces
= uci
.sections('network', 'interface'),
616 for (var i
= 0; i
< uciInterfaces
.length
; i
++)
617 networks
[uciInterfaces
[i
]['.name']] = this.instantiateNetwork(uciInterfaces
[i
]['.name']);
619 for (var i
= 0; i
< _state
.ifaces
.length
; i
++)
620 if (networks
[_state
.ifaces
[i
].interface] == null)
621 networks
[_state
.ifaces
[i
].interface] =
622 this.instantiateNetwork(_state
.ifaces
[i
].interface, _state
.ifaces
[i
].proto
);
626 for (var network
in networks
)
627 if (networks
.hasOwnProperty(network
))
628 rv
.push(networks
[network
]);
630 rv
.sort(networkSort
);
636 var Hosts
, Network
, Protocol
, Device
, WifiDevice
, WifiNetwork
;
644 * The `LuCI.network` class combines data from multiple `ubus` apis to
645 * provide an abstraction of the current network configuration state.
647 * It provides methods to enumerate interfaces and devices, to query
648 * current configuration details and to manipulate settings.
650 Network
= baseclass
.extend(/** @lends LuCI.network.prototype */ {
652 * Converts the given prefix size in bits to a netmask.
656 * @param {number} bits
657 * The prefix size in bits.
659 * @param {boolean} [v6=false]
660 * Whether to convert the bits value into an IPv4 netmask (`false`) or
661 * an IPv6 netmask (`true`).
663 * @returns {null|string}
664 * Returns a string containing the netmask corresponding to the bit count
665 * or `null` when the given amount of bits exceeds the maximum possible
666 * value of `32` for IPv4 or `128` for IPv6.
668 prefixToMask
: prefixToMask
,
671 * Converts the given netmask to a prefix size in bits.
675 * @param {string} netmask
676 * The netmask to convert into a bit count.
678 * @param {boolean} [v6=false]
679 * Whether to parse the given netmask as IPv4 (`false`) or IPv6 (`true`)
682 * @returns {null|number}
683 * Returns the number of prefix bits contained in the netmask or `null`
684 * if the given netmask value was invalid.
686 maskToPrefix
: maskToPrefix
,
689 * An encryption entry describes active wireless encryption settings
690 * such as the used key management protocols, active ciphers and
693 * @typedef {Object<string, boolean|Array<number|string>>} LuCI.network.WifiEncryption
694 * @memberof LuCI.network
696 * @property {boolean} enabled
697 * Specifies whether any kind of encryption, such as `WEP` or `WPA` is
698 * enabled. If set to `false`, then no encryption is active and the
699 * corresponding network is open.
701 * @property {string[]} [wep]
702 * When the `wep` property exists, the network uses WEP encryption.
703 * In this case, the property is set to an array of active WEP modes
704 * which might be either `open`, `shared` or both.
706 * @property {number[]} [wpa]
707 * When the `wpa` property exists, the network uses WPA security.
708 * In this case, the property is set to an array containing the WPA
709 * protocol versions used, e.g. `[ 1, 2 ]` for WPA/WPA2 mixed mode or
710 * `[ 3 ]` for WPA3-SAE.
712 * @property {string[]} [authentication]
713 * The `authentication` property only applies to WPA encryption and
714 * is defined when the `wpa` property is set as well. It points to
715 * an array of active authentication suites used by the network, e.g.
716 * `[ "psk" ]` for a WPA(2)-PSK network or `[ "psk", "sae" ]` for
717 * mixed WPA2-PSK/WPA3-SAE encryption.
719 * @property {string[]} [ciphers]
720 * If either WEP or WPA encryption is active, then the `ciphers`
721 * property will be set to an array describing the active encryption
722 * ciphers used by the network, e.g. `[ "tkip", "ccmp" ]` for a
723 * WPA/WPA2-PSK mixed network or `[ "wep-40", "wep-104" ]` for an
728 * Converts a given {@link LuCI.network.WifiEncryption encryption entry}
729 * into a human readable string such as `mixed WPA/WPA2 PSK (TKIP, CCMP)`
730 * or `WPA3 SAE (CCMP)`.
734 * @param {LuCI.network.WifiEncryption} encryption
735 * The wireless encryption entry to convert.
737 * @returns {null|string}
738 * Returns the description string for the given encryption entry or
739 * `null` if the given entry was invalid.
741 formatWifiEncryption
: formatWifiEncryption
,
744 * Flushes the local network state cache and fetches updated information
745 * from the remote `ubus` apis.
747 * @returns {Promise<Object>}
748 * Returns a promise resolving to the internal network state object.
750 flushCache: function() {
751 initNetworkState(true);
756 * Instantiates the given {@link LuCI.network.Protocol Protocol} backend,
757 * optionally using the given network name.
759 * @param {string} protoname
760 * The protocol backend to use, e.g. `static` or `dhcp`.
762 * @param {string} [netname=__dummy__]
763 * The network name to use for the instantiated protocol. This should be
764 * usually set to one of the interfaces described in /etc/config/network
765 * but it is allowed to omit it, e.g. to query protocol capabilities
766 * without the need for an existing interface.
768 * @returns {null|LuCI.network.Protocol}
769 * Returns the instantiated protocol backend class or `null` if the given
770 * protocol isn't known.
772 getProtocol: function(protoname
, netname
) {
773 var v
= _protocols
[protoname
];
775 return new v(netname
|| '__dummy__');
781 * Obtains instances of all known {@link LuCI.network.Protocol Protocol}
784 * @returns {Array<LuCI.network.Protocol>}
785 * Returns an array of protocol class instances.
787 getProtocols: function() {
790 for (var protoname
in _protocols
)
791 rv
.push(new _protocols
[protoname
]('__dummy__'));
797 * Registers a new {@link LuCI.network.Protocol Protocol} subclass
798 * with the given methods and returns the resulting subclass value.
800 * This functions internally calls
801 * {@link LuCI.Class.extend Class.extend()} on the `Network.Protocol`
804 * @param {string} protoname
805 * The name of the new protocol to register.
807 * @param {Object<string, *>} methods
808 * The member methods and values of the new `Protocol` subclass to
809 * be passed to {@link LuCI.Class.extend Class.extend()}.
811 * @returns {LuCI.network.Protocol}
812 * Returns the new `Protocol` subclass.
814 registerProtocol: function(protoname
, methods
) {
815 var spec
= L
.isObject(_protospecs
) ? _protospecs
[protoname
] : null;
816 var proto
= Protocol
.extend(Object
.assign({
817 getI18n: function() {
821 isFloating: function() {
825 isVirtual: function() {
826 return (L
.isObject(spec
) && spec
.no_device
== true);
829 renderFormOptions: function(section
) {
833 __init__: function(name
) {
837 getProtocol: function() {
842 _protocols
[protoname
] = proto
;
848 * Registers a new regular expression pattern to recognize
849 * virtual interfaces.
851 * @param {RegExp} pat
852 * A `RegExp` instance to match a virtual interface name
853 * such as `6in4-wan` or `tun0`.
855 registerPatternVirtual: function(pat
) {
856 iface_patterns_virtual
.push(pat
);
860 * Registers a new human readable translation string for a `Protocol`
863 * @param {string} code
864 * The `ubus` protocol error code to register a translation for, e.g.
867 * @param {string} message
868 * The message to use as translation for the given protocol error code.
871 * Returns `true` if the error code description has been added or `false`
872 * if either the arguments were invalid or if there already was a
873 * description for the given code.
875 registerErrorCode: function(code
, message
) {
876 if (typeof(code
) == 'string' &&
877 typeof(message
) == 'string' &&
878 !proto_errors
.hasOwnProperty(code
)) {
879 proto_errors
[code
] = message
;
887 * Adds a new network of the given name and update it with the given
890 * If a network with the given name already exist but is empty, then
891 * this function will update its option, otherwise it will do nothing.
893 * @param {string} name
894 * The name of the network to add. Must be in the format `[a-zA-Z0-9_]+`.
896 * @param {Object<string, string|string[]>} [options]
897 * An object of uci option values to set on the new network or to
898 * update in an existing, empty network.
900 * @returns {Promise<null|LuCI.network.Protocol>}
901 * Returns a promise resolving to the `Protocol` subclass instance
902 * describing the added network or resolving to `null` if the name
903 * was invalid or if a non-empty network of the given name already
906 addNetwork: function(name
, options
) {
907 return this.getNetwork(name
).then(L
.bind(function(existingNetwork
) {
908 if (name
!= null && /^[a-zA-Z0-9_]+$/.test(name
) && existingNetwork
== null) {
909 var sid
= uci
.add('network', 'interface', name
);
912 if (L
.isObject(options
))
913 for (var key
in options
)
914 if (options
.hasOwnProperty(key
))
915 uci
.set('network', sid
, key
, options
[key
]);
917 return this.instantiateNetwork(sid
);
920 else if (existingNetwork
!= null && existingNetwork
.isEmpty()) {
921 if (L
.isObject(options
))
922 for (var key
in options
)
923 if (options
.hasOwnProperty(key
))
924 existingNetwork
.set(key
, options
[key
]);
926 return existingNetwork
;
932 * Get a {@link LuCI.network.Protocol Protocol} instance describing
933 * the network with the given name.
935 * @param {string} name
936 * The logical interface name of the network get, e.g. `lan` or `wan`.
938 * @returns {Promise<null|LuCI.network.Protocol>}
939 * Returns a promise resolving to a
940 * {@link LuCI.network.Protocol Protocol} subclass instance describing
941 * the network or `null` if the network did not exist.
943 getNetwork: function(name
) {
944 return initNetworkState().then(L
.bind(function() {
945 var section
= (name
!= null) ? uci
.get('network', name
) : null;
947 if (section
!= null && section
['.type'] == 'interface') {
948 return this.instantiateNetwork(name
);
950 else if (name
!= null) {
951 for (var i
= 0; i
< _state
.ifaces
.length
; i
++)
952 if (_state
.ifaces
[i
].interface == name
)
953 return this.instantiateNetwork(name
, _state
.ifaces
[i
].proto
);
961 * Gets an array containing all known networks.
963 * @returns {Promise<Array<LuCI.network.Protocol>>}
964 * Returns a promise resolving to a name-sorted array of
965 * {@link LuCI.network.Protocol Protocol} subclass instances
966 * describing all known networks.
968 getNetworks: function() {
969 return initNetworkState().then(L
.bind(enumerateNetworks
, this));
973 * Deletes the given network and its references from the network and
974 * firewall configuration.
976 * @param {string} name
977 * The name of the network to delete.
979 * @returns {Promise<boolean>}
980 * Returns a promise resolving to either `true` if the network and
981 * references to it were successfully deleted from the configuration or
982 * `false` if the given network could not be found.
984 deleteNetwork: function(name
) {
985 var requireFirewall
= Promise
.resolve(L
.require('firewall')).catch(function() {}),
986 network
= this.instantiateNetwork(name
);
988 return Promise
.all([ requireFirewall
, initNetworkState() ]).then(function(res
) {
989 var uciInterface
= uci
.get('network', name
),
992 if (uciInterface
!= null && uciInterface
['.type'] == 'interface') {
993 return Promise
.resolve(network
? network
.deleteConfiguration() : null).then(function() {
994 uci
.remove('network', name
);
996 uci
.sections('luci', 'ifstate', function(s
) {
997 if (s
.interface == name
)
998 uci
.remove('luci', s
['.name']);
1001 uci
.sections('network', 'alias', function(s
) {
1002 if (s
.interface == name
)
1003 uci
.remove('network', s
['.name']);
1006 uci
.sections('network', 'route', function(s
) {
1007 if (s
.interface == name
)
1008 uci
.remove('network', s
['.name']);
1011 uci
.sections('network', 'route6', function(s
) {
1012 if (s
.interface == name
)
1013 uci
.remove('network', s
['.name']);
1016 uci
.sections('wireless', 'wifi-iface', function(s
) {
1017 var networks
= L
.toArray(s
.network
).filter(function(network
) { return network
!= name
});
1019 if (networks
.length
> 0)
1020 uci
.set('wireless', s
['.name'], 'network', networks
.join(' '));
1022 uci
.unset('wireless', s
['.name'], 'network');
1026 return firewall
.deleteNetwork(name
).then(function() { return true });
1029 }).catch(function() {
1039 * Rename the given network and its references to a new name.
1041 * @param {string} oldName
1042 * The current name of the network.
1044 * @param {string} newName
1045 * The name to rename the network to, must be in the format
1048 * @returns {Promise<boolean>}
1049 * Returns a promise resolving to either `true` if the network was
1050 * successfully renamed or `false` if the new name was invalid, if
1051 * a network with the new name already exists or if the network to
1052 * rename could not be found.
1054 renameNetwork: function(oldName
, newName
) {
1055 return initNetworkState().then(function() {
1056 if (newName
== null || !/^[a-zA-Z0-9_]+$/.test(newName
) || uci
.get('network', newName
) != null)
1059 var oldNetwork
= uci
.get('network', oldName
);
1061 if (oldNetwork
== null || oldNetwork
['.type'] != 'interface')
1064 var sid
= uci
.add('network', 'interface', newName
);
1066 for (var key
in oldNetwork
)
1067 if (oldNetwork
.hasOwnProperty(key
) && key
.charAt(0) != '.')
1068 uci
.set('network', sid
, key
, oldNetwork
[key
]);
1070 uci
.sections('luci', 'ifstate', function(s
) {
1071 if (s
.interface == oldName
)
1072 uci
.set('luci', s
['.name'], 'interface', newName
);
1075 uci
.sections('network', 'alias', function(s
) {
1076 if (s
.interface == oldName
)
1077 uci
.set('network', s
['.name'], 'interface', newName
);
1080 uci
.sections('network', 'route', function(s
) {
1081 if (s
.interface == oldName
)
1082 uci
.set('network', s
['.name'], 'interface', newName
);
1085 uci
.sections('network', 'route6', function(s
) {
1086 if (s
.interface == oldName
)
1087 uci
.set('network', s
['.name'], 'interface', newName
);
1090 uci
.sections('wireless', 'wifi-iface', function(s
) {
1091 var networks
= L
.toArray(s
.network
).map(function(network
) { return (network
== oldName
? newName
: network
) });
1093 if (networks
.length
> 0)
1094 uci
.set('wireless', s
['.name'], 'network', networks
.join(' '));
1097 uci
.remove('network', oldName
);
1104 * Get a {@link LuCI.network.Device Device} instance describing the
1105 * given network device.
1107 * @param {string} name
1108 * The name of the network device to get, e.g. `eth0` or `br-lan`.
1110 * @returns {Promise<null|LuCI.network.Device>}
1111 * Returns a promise resolving to the `Device` instance describing
1112 * the network device or `null` if the given device name could not
1115 getDevice: function(name
) {
1116 return initNetworkState().then(L
.bind(function() {
1120 if (_state
.netdevs
.hasOwnProperty(name
) || isWifiIfname(name
))
1121 return this.instantiateDevice(name
);
1123 var netid
= getWifiNetidBySid(name
);
1125 return this.instantiateDevice(netid
[0]);
1132 * Get a sorted list of all found network devices.
1134 * @returns {Promise<Array<LuCI.network.Device>>}
1135 * Returns a promise resolving to a sorted array of `Device` class
1136 * instances describing the network devices found on the system.
1138 getDevices: function() {
1139 return initNetworkState().then(L
.bind(function() {
1142 /* find simple devices */
1143 var uciInterfaces
= uci
.sections('network', 'interface');
1144 for (var i
= 0; i
< uciInterfaces
.length
; i
++) {
1145 var ifnames
= L
.toArray(uciInterfaces
[i
].ifname
);
1147 for (var j
= 0; j
< ifnames
.length
; j
++) {
1148 if (ifnames
[j
].charAt(0) == '@')
1151 if (isIgnoredIfname(ifnames
[j
]) || isVirtualIfname(ifnames
[j
]) || isWifiIfname(ifnames
[j
]))
1154 devices
[ifnames
[j
]] = this.instantiateDevice(ifnames
[j
]);
1158 for (var ifname
in _state
.netdevs
) {
1159 if (devices
.hasOwnProperty(ifname
))
1162 if (isIgnoredIfname(ifname
) || isWifiIfname(ifname
))
1165 if (_state
.netdevs
[ifname
].wireless
)
1168 devices
[ifname
] = this.instantiateDevice(ifname
);
1171 /* find VLAN devices */
1172 var uciSwitchVLANs
= uci
.sections('network', 'switch_vlan');
1173 for (var i
= 0; i
< uciSwitchVLANs
.length
; i
++) {
1174 if (typeof(uciSwitchVLANs
[i
].ports
) != 'string' ||
1175 typeof(uciSwitchVLANs
[i
].device
) != 'string' ||
1176 !_state
.switches
.hasOwnProperty(uciSwitchVLANs
[i
].device
))
1179 var ports
= uciSwitchVLANs
[i
].ports
.split(/\s+/);
1180 for (var j
= 0; j
< ports
.length
; j
++) {
1181 var m
= ports
[j
].match(/^(\d+)([tu]?)$/);
1185 var netdev
= _state
.switches
[uciSwitchVLANs
[i
].device
].netdevs
[m
[1]];
1189 if (!devices
.hasOwnProperty(netdev
))
1190 devices
[netdev
] = this.instantiateDevice(netdev
);
1192 _state
.isSwitch
[netdev
] = true;
1197 var vid
= uciSwitchVLANs
[i
].vid
|| uciSwitchVLANs
[i
].vlan
;
1198 vid
= (vid
!= null ? +vid
: null);
1200 if (vid
== null || vid
< 0 || vid
> 4095)
1203 var vlandev
= '%s.%d'.format(netdev
, vid
);
1205 if (!devices
.hasOwnProperty(vlandev
))
1206 devices
[vlandev
] = this.instantiateDevice(vlandev
);
1208 _state
.isSwitch
[vlandev
] = true;
1212 /* find wireless interfaces */
1213 var uciWifiIfaces
= uci
.sections('wireless', 'wifi-iface'),
1216 for (var i
= 0; i
< uciWifiIfaces
.length
; i
++) {
1217 if (typeof(uciWifiIfaces
[i
].device
) != 'string')
1220 networkCount
[uciWifiIfaces
[i
].device
] = (networkCount
[uciWifiIfaces
[i
].device
] || 0) + 1;
1222 var netid
= '%s.network%d'.format(uciWifiIfaces
[i
].device
, networkCount
[uciWifiIfaces
[i
].device
]);
1224 devices
[netid
] = this.instantiateDevice(netid
);
1227 /* find uci declared devices */
1228 var uciDevices
= uci
.sections('network', 'device');
1230 for (var i
= 0; i
< uciDevices
.length
; i
++) {
1231 var type
= uciDevices
[i
].type
,
1232 name
= uciDevices
[i
].name
;
1234 if (!type
|| !name
|| devices
.hasOwnProperty(name
))
1237 if (type
== 'bridge')
1238 _state
.isBridge
[name
] = true;
1240 devices
[name
] = this.instantiateDevice(name
);
1245 for (var netdev
in devices
)
1246 if (devices
.hasOwnProperty(netdev
))
1247 rv
.push(devices
[netdev
]);
1249 rv
.sort(deviceSort
);
1256 * Test if a given network device name is in the list of patterns for
1257 * device names to ignore.
1259 * Ignored device names are usually Linux network devices which are
1260 * spawned implicitly by kernel modules such as `tunl0` or `hwsim0`
1261 * and which are unsuitable for use in network configuration.
1263 * @param {string} name
1264 * The device name to test.
1266 * @returns {boolean}
1267 * Returns `true` if the given name is in the ignore pattern list,
1268 * else returns `false`.
1270 isIgnoredDevice: function(name
) {
1271 return isIgnoredIfname(name
);
1275 * Get a {@link LuCI.network.WifiDevice WifiDevice} instance describing
1276 * the given wireless radio.
1278 * @param {string} devname
1279 * The configuration name of the wireless radio to lookup, e.g. `radio0`
1280 * for the first mac80211 phy on the system.
1282 * @returns {Promise<null|LuCI.network.WifiDevice>}
1283 * Returns a promise resolving to the `WifiDevice` instance describing
1284 * the underlying radio device or `null` if the wireless radio could not
1287 getWifiDevice: function(devname
) {
1288 return initNetworkState().then(L
.bind(function() {
1289 var existingDevice
= uci
.get('wireless', devname
);
1291 if (existingDevice
== null || existingDevice
['.type'] != 'wifi-device')
1294 return this.instantiateWifiDevice(devname
, _state
.radios
[devname
] || {});
1299 * Obtain a list of all configured radio devices.
1301 * @returns {Promise<Array<LuCI.network.WifiDevice>>}
1302 * Returns a promise resolving to an array of `WifiDevice` instances
1303 * describing the wireless radios configured in the system.
1304 * The order of the array corresponds to the order of the radios in
1305 * the configuration.
1307 getWifiDevices: function() {
1308 return initNetworkState().then(L
.bind(function() {
1309 var uciWifiDevices
= uci
.sections('wireless', 'wifi-device'),
1312 for (var i
= 0; i
< uciWifiDevices
.length
; i
++) {
1313 var devname
= uciWifiDevices
[i
]['.name'];
1314 rv
.push(this.instantiateWifiDevice(devname
, _state
.radios
[devname
] || {}));
1322 * Get a {@link LuCI.network.WifiNetwork WifiNetwork} instance describing
1323 * the given wireless network.
1325 * @param {string} netname
1326 * The name of the wireless network to lookup. This may be either an uci
1327 * configuration section ID, a network ID in the form `radio#.network#`
1328 * or a Linux network device name like `wlan0` which is resolved to the
1329 * corresponding configuration section through `ubus` runtime information.
1331 * @returns {Promise<null|LuCI.network.WifiNetwork>}
1332 * Returns a promise resolving to the `WifiNetwork` instance describing
1333 * the wireless network or `null` if the corresponding network could not
1336 getWifiNetwork: function(netname
) {
1337 return initNetworkState()
1338 .then(L
.bind(this.lookupWifiNetwork
, this, netname
));
1342 * Get an array of all {@link LuCI.network.WifiNetwork WifiNetwork}
1343 * instances describing the wireless networks present on the system.
1345 * @returns {Promise<Array<LuCI.network.WifiNetwork>>}
1346 * Returns a promise resolving to an array of `WifiNetwork` instances
1347 * describing the wireless networks. The array will be empty if no networks
1350 getWifiNetworks: function() {
1351 return initNetworkState().then(L
.bind(function() {
1352 var wifiIfaces
= uci
.sections('wireless', 'wifi-iface'),
1355 for (var i
= 0; i
< wifiIfaces
.length
; i
++)
1356 rv
.push(this.lookupWifiNetwork(wifiIfaces
[i
]['.name']));
1358 rv
.sort(function(a
, b
) {
1359 return (a
.getID() > b
.getID());
1367 * Adds a new wireless network to the configuration and sets its options
1368 * to the provided values.
1370 * @param {Object<string, string|string[]>} options
1371 * The options to set for the newly added wireless network. This object
1372 * must at least contain a `device` property which is set to the radio
1373 * name the new network belongs to.
1375 * @returns {Promise<null|LuCI.network.WifiNetwork>}
1376 * Returns a promise resolving to a `WifiNetwork` instance describing
1377 * the newly added wireless network or `null` if the given options
1378 * were invalid or if the associated radio device could not be found.
1380 addWifiNetwork: function(options
) {
1381 return initNetworkState().then(L
.bind(function() {
1382 if (options
== null ||
1383 typeof(options
) != 'object' ||
1384 typeof(options
.device
) != 'string')
1387 var existingDevice
= uci
.get('wireless', options
.device
);
1388 if (existingDevice
== null || existingDevice
['.type'] != 'wifi-device')
1391 /* XXX: need to add a named section (wifinet#) here */
1392 var sid
= uci
.add('wireless', 'wifi-iface');
1393 for (var key
in options
)
1394 if (options
.hasOwnProperty(key
))
1395 uci
.set('wireless', sid
, key
, options
[key
]);
1397 var radioname
= existingDevice
['.name'],
1398 netid
= getWifiNetidBySid(sid
) || [];
1400 return this.instantiateWifiNetwork(sid
, radioname
, _state
.radios
[radioname
], netid
[0], null);
1405 * Deletes the given wireless network from the configuration.
1407 * @param {string} netname
1408 * The name of the network to remove. This may be either a
1409 * network ID in the form `radio#.network#` or a Linux network device
1410 * name like `wlan0` which is resolved to the corresponding configuration
1411 * section through `ubus` runtime information.
1413 * @returns {Promise<boolean>}
1414 * Returns a promise resolving to `true` if the wireless network has been
1415 * successfully deleted from the configuration or `false` if it could not
1418 deleteWifiNetwork: function(netname
) {
1419 return initNetworkState().then(L
.bind(function() {
1420 var sid
= getWifiSidByIfname(netname
);
1425 uci
.remove('wireless', sid
);
1431 getStatusByRoute: function(addr
, mask
) {
1432 return initNetworkState().then(L
.bind(function() {
1435 for (var i
= 0; i
< _state
.ifaces
.length
; i
++) {
1436 if (!Array
.isArray(_state
.ifaces
[i
].route
))
1439 for (var j
= 0; j
< _state
.ifaces
[i
].route
.length
; j
++) {
1440 if (typeof(_state
.ifaces
[i
].route
[j
]) != 'object' ||
1441 typeof(_state
.ifaces
[i
].route
[j
].target
) != 'string' ||
1442 typeof(_state
.ifaces
[i
].route
[j
].mask
) != 'number')
1445 if (_state
.ifaces
[i
].route
[j
].table
)
1448 if (_state
.ifaces
[i
].route
[j
].target
!= addr
||
1449 _state
.ifaces
[i
].route
[j
].mask
!= mask
)
1452 rv
.push(_state
.ifaces
[i
]);
1461 getStatusByAddress: function(addr
) {
1462 return initNetworkState().then(L
.bind(function() {
1465 for (var i
= 0; i
< _state
.ifaces
.length
; i
++) {
1466 if (Array
.isArray(_state
.ifaces
[i
]['ipv4-address']))
1467 for (var j
= 0; j
< _state
.ifaces
[i
]['ipv4-address'].length
; j
++)
1468 if (typeof(_state
.ifaces
[i
]['ipv4-address'][j
]) == 'object' &&
1469 _state
.ifaces
[i
]['ipv4-address'][j
].address
== addr
)
1470 return _state
.ifaces
[i
];
1472 if (Array
.isArray(_state
.ifaces
[i
]['ipv6-address']))
1473 for (var j
= 0; j
< _state
.ifaces
[i
]['ipv6-address'].length
; j
++)
1474 if (typeof(_state
.ifaces
[i
]['ipv6-address'][j
]) == 'object' &&
1475 _state
.ifaces
[i
]['ipv6-address'][j
].address
== addr
)
1476 return _state
.ifaces
[i
];
1478 if (Array
.isArray(_state
.ifaces
[i
]['ipv6-prefix-assignment']))
1479 for (var j
= 0; j
< _state
.ifaces
[i
]['ipv6-prefix-assignment'].length
; j
++)
1480 if (typeof(_state
.ifaces
[i
]['ipv6-prefix-assignment'][j
]) == 'object' &&
1481 typeof(_state
.ifaces
[i
]['ipv6-prefix-assignment'][j
]['local-address']) == 'object' &&
1482 _state
.ifaces
[i
]['ipv6-prefix-assignment'][j
]['local-address'].address
== addr
)
1483 return _state
.ifaces
[i
];
1491 * Get IPv4 wan networks.
1493 * This function looks up all networks having a default `0.0.0.0/0` route
1494 * and returns them as array.
1496 * @returns {Promise<Array<LuCI.network.Protocol>>}
1497 * Returns a promise resolving to an array of `Protocol` subclass
1498 * instances describing the found default route interfaces.
1500 getWANNetworks: function() {
1501 return this.getStatusByRoute('0.0.0.0', 0).then(L
.bind(function(statuses
) {
1502 var rv
= [], seen
= {};
1504 for (var i
= 0; i
< statuses
.length
; i
++) {
1505 if (!seen
.hasOwnProperty(statuses
[i
].interface)) {
1506 rv
.push(this.instantiateNetwork(statuses
[i
].interface, statuses
[i
].proto
));
1507 seen
[statuses
[i
].interface] = true;
1516 * Get IPv6 wan networks.
1518 * This function looks up all networks having a default `::/0` route
1519 * and returns them as array.
1521 * @returns {Promise<Array<LuCI.network.Protocol>>}
1522 * Returns a promise resolving to an array of `Protocol` subclass
1523 * instances describing the found IPv6 default route interfaces.
1525 getWAN6Networks: function() {
1526 return this.getStatusByRoute('::', 0).then(L
.bind(function(statuses
) {
1527 var rv
= [], seen
= {};
1529 for (var i
= 0; i
< statuses
.length
; i
++) {
1530 if (!seen
.hasOwnProperty(statuses
[i
].interface)) {
1531 rv
.push(this.instantiateNetwork(statuses
[i
].interface, statuses
[i
].proto
));
1532 seen
[statuses
[i
].interface] = true;
1541 * Describes an swconfig switch topology by specifying the CPU
1542 * connections and external port labels of a switch.
1544 * @typedef {Object<string, Object|Array>} SwitchTopology
1545 * @memberof LuCI.network
1547 * @property {Object<number, string>} netdevs
1548 * The `netdevs` property points to an object describing the CPU port
1549 * connections of the switch. The numeric key of the enclosed object is
1550 * the port number, the value contains the Linux network device name the
1551 * port is hardwired to.
1553 * @property {Array<Object<string, boolean|number|string>>} ports
1554 * The `ports` property points to an array describing the populated
1555 * ports of the switch in the external label order. Each array item is
1556 * an object containg the following keys:
1557 * - `num` - the internal switch port number
1558 * - `label` - the label of the port, e.g. `LAN 1` or `CPU (eth0)`
1559 * - `device` - the connected Linux network device name (CPU ports only)
1560 * - `tagged` - a boolean indicating whether the port must be tagged to
1561 * function (CPU ports only)
1565 * Returns the topologies of all swconfig switches found on the system.
1567 * @returns {Promise<Object<string, LuCI.network.SwitchTopology>>}
1568 * Returns a promise resolving to an object containing the topologies
1569 * of each switch. The object keys correspond to the name of the switches
1570 * such as `switch0`, the values are
1571 * {@link LuCI.network.SwitchTopology SwitchTopology} objects describing
1574 getSwitchTopologies: function() {
1575 return initNetworkState().then(function() {
1576 return _state
.switches
;
1581 instantiateNetwork: function(name
, proto
) {
1585 proto
= (proto
== null ? uci
.get('network', name
, 'proto') : proto
);
1587 var protoClass
= _protocols
[proto
] || Protocol
;
1588 return new protoClass(name
);
1592 instantiateDevice: function(name
, network
, extend
) {
1594 return new (Device
.extend(extend
))(name
, network
);
1596 return new Device(name
, network
);
1600 instantiateWifiDevice: function(radioname
, radiostate
) {
1601 return new WifiDevice(radioname
, radiostate
);
1605 instantiateWifiNetwork: function(sid
, radioname
, radiostate
, netid
, netstate
, hostapd
) {
1606 return new WifiNetwork(sid
, radioname
, radiostate
, netid
, netstate
, hostapd
);
1610 lookupWifiNetwork: function(netname
) {
1611 var sid
, res
, netid
, radioname
, radiostate
, netstate
;
1613 sid
= getWifiSidByNetid(netname
);
1616 res
= getWifiStateBySid(sid
);
1618 radioname
= res
? res
[0] : null;
1619 radiostate
= res
? res
[1] : null;
1620 netstate
= res
? res
[2] : null;
1623 res
= getWifiStateByIfname(netname
);
1627 radiostate
= res
[1];
1629 sid
= netstate
.section
;
1630 netid
= L
.toArray(getWifiNetidBySid(sid
))[0];
1633 res
= getWifiStateBySid(netname
);
1637 radiostate
= res
[1];
1640 netid
= L
.toArray(getWifiNetidBySid(sid
))[0];
1643 res
= getWifiNetidBySid(netname
);
1654 return this.instantiateWifiNetwork(sid
|| netname
, radioname
,
1655 radiostate
, netid
, netstate
,
1656 netstate
? _state
.hostapd
[netstate
.ifname
] : null);
1660 * Obtains the the network device name of the given object.
1662 * @param {LuCI.network.Protocol|LuCI.network.Device|LuCI.network.WifiDevice|LuCI.network.WifiNetwork|string} obj
1663 * The object to get the device name from.
1665 * @returns {null|string}
1666 * Returns a string containing the device name or `null` if the given
1667 * object could not be converted to a name.
1669 getIfnameOf: function(obj
) {
1670 return ifnameOf(obj
);
1674 * Queries the internal DSL modem type from board information.
1676 * @returns {Promise<null|string>}
1677 * Returns a promise resolving to the type of the internal modem
1678 * (e.g. `vdsl`) or to `null` if no internal modem is present.
1680 getDSLModemType: function() {
1681 return initNetworkState().then(function() {
1682 return _state
.hasDSLModem
? _state
.hasDSLModem
.type
: null;
1687 * Queries aggregated information about known hosts.
1689 * This function aggregates information from various sources such as
1690 * DHCP lease databases, ARP and IPv6 neighbour entries, wireless
1691 * association list etc. and returns a {@link LuCI.network.Hosts Hosts}
1692 * class instance describing the found hosts.
1694 * @returns {Promise<LuCI.network.Hosts>}
1695 * Returns a `Hosts` instance describing host known on the system.
1697 getHostHints: function() {
1698 return initNetworkState().then(function() {
1699 return new Hosts(_state
.hosts
);
1706 * @memberof LuCI.network
1710 * The `LuCI.network.Hosts` class encapsulates host information aggregated
1711 * from multiple sources and provides convenience functions to access the
1712 * host information by different criteria.
1714 Hosts
= baseclass
.extend(/** @lends LuCI.network.Hosts.prototype */ {
1715 __init__: function(hosts
) {
1720 * Lookup the hostname associated with the given MAC address.
1722 * @param {string} mac
1723 * The MAC address to lookup.
1725 * @returns {null|string}
1726 * Returns the hostname associated with the given MAC or `null` if
1727 * no matching host could be found or if no hostname is known for
1728 * the corresponding host.
1730 getHostnameByMACAddr: function(mac
) {
1731 return this.hosts
[mac
] ? this.hosts
[mac
].name
: null;
1735 * Lookup the IPv4 address associated with the given MAC address.
1737 * @param {string} mac
1738 * The MAC address to lookup.
1740 * @returns {null|string}
1741 * Returns the IPv4 address associated with the given MAC or `null` if
1742 * no matching host could be found or if no IPv4 address is known for
1743 * the corresponding host.
1745 getIPAddrByMACAddr: function(mac
) {
1746 return this.hosts
[mac
] ? this.hosts
[mac
].ipv4
: null;
1750 * Lookup the IPv6 address associated with the given MAC address.
1752 * @param {string} mac
1753 * The MAC address to lookup.
1755 * @returns {null|string}
1756 * Returns the IPv6 address associated with the given MAC or `null` if
1757 * no matching host could be found or if no IPv6 address is known for
1758 * the corresponding host.
1760 getIP6AddrByMACAddr: function(mac
) {
1761 return this.hosts
[mac
] ? this.hosts
[mac
].ipv6
: null;
1765 * Lookup the hostname associated with the given IPv4 address.
1767 * @param {string} ipaddr
1768 * The IPv4 address to lookup.
1770 * @returns {null|string}
1771 * Returns the hostname associated with the given IPv4 or `null` if
1772 * no matching host could be found or if no hostname is known for
1773 * the corresponding host.
1775 getHostnameByIPAddr: function(ipaddr
) {
1776 for (var mac
in this.hosts
)
1777 if (this.hosts
[mac
].ipv4
== ipaddr
&& this.hosts
[mac
].name
!= null)
1778 return this.hosts
[mac
].name
;
1783 * Lookup the MAC address associated with the given IPv4 address.
1785 * @param {string} ipaddr
1786 * The IPv4 address to lookup.
1788 * @returns {null|string}
1789 * Returns the MAC address associated with the given IPv4 or `null` if
1790 * no matching host could be found or if no MAC address is known for
1791 * the corresponding host.
1793 getMACAddrByIPAddr: function(ipaddr
) {
1794 for (var mac
in this.hosts
)
1795 if (this.hosts
[mac
].ipv4
== ipaddr
)
1801 * Lookup the hostname associated with the given IPv6 address.
1803 * @param {string} ipaddr
1804 * The IPv6 address to lookup.
1806 * @returns {null|string}
1807 * Returns the hostname associated with the given IPv6 or `null` if
1808 * no matching host could be found or if no hostname is known for
1809 * the corresponding host.
1811 getHostnameByIP6Addr: function(ip6addr
) {
1812 for (var mac
in this.hosts
)
1813 if (this.hosts
[mac
].ipv6
== ip6addr
&& this.hosts
[mac
].name
!= null)
1814 return this.hosts
[mac
].name
;
1819 * Lookup the MAC address associated with the given IPv6 address.
1821 * @param {string} ipaddr
1822 * The IPv6 address to lookup.
1824 * @returns {null|string}
1825 * Returns the MAC address associated with the given IPv6 or `null` if
1826 * no matching host could be found or if no MAC address is known for
1827 * the corresponding host.
1829 getMACAddrByIP6Addr: function(ip6addr
) {
1830 for (var mac
in this.hosts
)
1831 if (this.hosts
[mac
].ipv6
== ip6addr
)
1837 * Return an array of (MAC address, name hint) tuples sorted by
1840 * @param {boolean} [preferIp6=false]
1841 * Whether to prefer IPv6 addresses (`true`) or IPv4 addresses (`false`)
1842 * as name hint when no hostname is known for a specific MAC address.
1844 * @returns {Array<Array<string>>}
1845 * Returns an array of arrays containing a name hint for each found
1846 * MAC address on the system. The array is sorted ascending by MAC.
1848 * Each item of the resulting array is a two element array with the
1849 * MAC being the first element and the name hint being the second
1850 * element. The name hint is either the hostname, an IPv4 or an IPv6
1851 * address related to the MAC address.
1853 * If no hostname but both IPv4 and IPv6 addresses are known, the
1854 * `preferIP6` flag specifies whether the IPv6 or the IPv4 address
1857 getMACHints: function(preferIp6
) {
1859 for (var mac
in this.hosts
) {
1860 var hint
= this.hosts
[mac
].name
||
1861 this.hosts
[mac
][preferIp6
? 'ipv6' : 'ipv4'] ||
1862 this.hosts
[mac
][preferIp6
? 'ipv4' : 'ipv6'];
1864 rv
.push([mac
, hint
]);
1866 return rv
.sort(function(a
, b
) { return a
[0] > b
[0] });
1872 * @memberof LuCI.network
1876 * The `Network.Protocol` class serves as base for protocol specific
1877 * subclasses which describe logical UCI networks defined by `config
1878 * interface` sections in `/etc/config/network`.
1880 Protocol
= baseclass
.extend(/** @lends LuCI.network.Protocol.prototype */ {
1881 __init__: function(name
) {
1885 _get: function(opt
) {
1886 var val
= uci
.get('network', this.sid
, opt
);
1888 if (Array
.isArray(val
))
1889 return val
.join(' ');
1894 _ubus: function(field
) {
1895 for (var i
= 0; i
< _state
.ifaces
.length
; i
++) {
1896 if (_state
.ifaces
[i
].interface != this.sid
)
1899 return (field
!= null ? _state
.ifaces
[i
][field
] : _state
.ifaces
[i
]);
1904 * Read the given UCI option value of this network.
1906 * @param {string} opt
1907 * The UCI option name to read.
1909 * @returns {null|string|string[]}
1910 * Returns the UCI option value or `null` if the requested option is
1913 get: function(opt
) {
1914 return uci
.get('network', this.sid
, opt
);
1918 * Set the given UCI option of this network to the given value.
1920 * @param {string} opt
1921 * The name of the UCI option to set.
1923 * @param {null|string|string[]} val
1924 * The value to set or `null` to remove the given option from the
1927 set: function(opt
, val
) {
1928 return uci
.set('network', this.sid
, opt
, val
);
1932 * Get the associared Linux network device of this network.
1934 * @returns {null|string}
1935 * Returns the name of the associated network device or `null` if
1936 * it could not be determined.
1938 getIfname: function() {
1941 if (this.isFloating())
1942 ifname
= this._ubus('l3_device');
1944 ifname
= this._ubus('device') || this._ubus('l3_device');
1949 var res
= getWifiNetidByNetname(this.sid
);
1950 return (res
!= null ? res
[0] : null);
1954 * Get the name of this network protocol class.
1956 * This function will be overwritten by subclasses created by
1957 * {@link LuCI.network#registerProtocol Network.registerProtocol()}.
1961 * Returns the name of the network protocol implementation, e.g.
1962 * `static` or `dhcp`.
1964 getProtocol: function() {
1969 * Return a human readable description for the protcol, such as
1970 * `Static address` or `DHCP client`.
1972 * This function should be overwritten by subclasses.
1976 * Returns the description string.
1978 getI18n: function() {
1979 switch (this.getProtocol()) {
1980 case 'none': return _('Unmanaged');
1981 case 'static': return _('Static address');
1982 case 'dhcp': return _('DHCP client');
1983 default: return _('Unknown');
1988 * Get the type of the underlying interface.
1990 * This function actually is a convenience wrapper around
1991 * `proto.get("type")` and is mainly used by other `LuCI.network` code
1992 * to check whether the interface is declared as bridge in UCI.
1994 * @returns {null|string}
1995 * Returns the value of the `type` option of the associated logical
1996 * interface or `null` if no `type` option is set.
1998 getType: function() {
1999 return this._get('type');
2003 * Get the name of the associated logical interface.
2006 * Returns the logical interface name, such as `lan` or `wan`.
2008 getName: function() {
2013 * Get the uptime of the logical interface.
2016 * Returns the uptime of the associated interface in seconds.
2018 getUptime: function() {
2019 return this._ubus('uptime') || 0;
2023 * Get the logical interface expiry time in seconds.
2025 * For protocols that have a concept of a lease, such as DHCP or
2026 * DHCPv6, this function returns the remaining time in seconds
2027 * until the lease expires.
2030 * Returns the amount of seconds until the lease expires or `-1`
2031 * if it isn't applicable to the associated protocol.
2033 getExpiry: function() {
2034 var u
= this._ubus('uptime'),
2035 d
= this._ubus('data');
2037 if (typeof(u
) == 'number' && d
!= null &&
2038 typeof(d
) == 'object' && typeof(d
.leasetime
) == 'number') {
2039 var r
= d
.leasetime
- (u
% d
.leasetime
);
2040 return (r
> 0 ? r
: 0);
2047 * Get the metric value of the logical interface.
2050 * Returns the current metric value used for device and network
2051 * routes spawned by the associated logical interface.
2053 getMetric: function() {
2054 return this._ubus('metric') || 0;
2058 * Get the requested firewall zone name of the logical interface.
2060 * Some protocol implementations request a specific firewall zone
2061 * to trigger inclusion of their resulting network devices into the
2062 * firewall rule set.
2064 * @returns {null|string}
2065 * Returns the requested firewall zone name as published in the
2066 * `ubus` runtime information or `null` if the remote protocol
2067 * handler didn't request a zone.
2069 getZoneName: function() {
2070 var d
= this._ubus('data');
2072 if (L
.isObject(d
) && typeof(d
.zone
) == 'string')
2079 * Query the first (primary) IPv4 address of the logical interface.
2081 * @returns {null|string}
2082 * Returns the primary IPv4 address registered by the protocol handler
2083 * or `null` if no IPv4 addresses were set.
2085 getIPAddr: function() {
2086 var addrs
= this._ubus('ipv4-address');
2087 return ((Array
.isArray(addrs
) && addrs
.length
) ? addrs
[0].address
: null);
2091 * Query all IPv4 addresses of the logical interface.
2093 * @returns {string[]}
2094 * Returns an array of IPv4 addresses in CIDR notation which have been
2095 * registered by the protocol handler. The order of the resulting array
2096 * follows the order of the addresses in `ubus` runtime information.
2098 getIPAddrs: function() {
2099 var addrs
= this._ubus('ipv4-address'),
2102 if (Array
.isArray(addrs
))
2103 for (var i
= 0; i
< addrs
.length
; i
++)
2104 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2110 * Query the first (primary) IPv4 netmask of the logical interface.
2112 * @returns {null|string}
2113 * Returns the netmask of the primary IPv4 address registered by the
2114 * protocol handler or `null` if no IPv4 addresses were set.
2116 getNetmask: function() {
2117 var addrs
= this._ubus('ipv4-address');
2118 if (Array
.isArray(addrs
) && addrs
.length
)
2119 return prefixToMask(addrs
[0].mask
, false);
2123 * Query the gateway (nexthop) of the default route associated with
2124 * this logical interface.
2127 * Returns a string containing the IPv4 nexthop address of the associated
2128 * default route or `null` if no default route was found.
2130 getGatewayAddr: function() {
2131 var routes
= this._ubus('route');
2133 if (Array
.isArray(routes
))
2134 for (var i
= 0; i
< routes
.length
; i
++)
2135 if (typeof(routes
[i
]) == 'object' &&
2136 routes
[i
].target
== '0.0.0.0' &&
2137 routes
[i
].mask
== 0)
2138 return routes
[i
].nexthop
;
2144 * Query the IPv4 DNS servers associated with the logical interface.
2146 * @returns {string[]}
2147 * Returns an array of IPv4 DNS servers registered by the remote
2150 getDNSAddrs: function() {
2151 var addrs
= this._ubus('dns-server'),
2154 if (Array
.isArray(addrs
))
2155 for (var i
= 0; i
< addrs
.length
; i
++)
2156 if (!/:/.test(addrs
[i
]))
2163 * Query the first (primary) IPv6 address of the logical interface.
2165 * @returns {null|string}
2166 * Returns the primary IPv6 address registered by the protocol handler
2167 * in CIDR notation or `null` if no IPv6 addresses were set.
2169 getIP6Addr: function() {
2170 var addrs
= this._ubus('ipv6-address');
2172 if (Array
.isArray(addrs
) && L
.isObject(addrs
[0]))
2173 return '%s/%d'.format(addrs
[0].address
, addrs
[0].mask
);
2175 addrs
= this._ubus('ipv6-prefix-assignment');
2177 if (Array
.isArray(addrs
) && L
.isObject(addrs
[0]) && L
.isObject(addrs
[0]['local-address']))
2178 return '%s/%d'.format(addrs
[0]['local-address'].address
, addrs
[0]['local-address'].mask
);
2184 * Query all IPv6 addresses of the logical interface.
2186 * @returns {string[]}
2187 * Returns an array of IPv6 addresses in CIDR notation which have been
2188 * registered by the protocol handler. The order of the resulting array
2189 * follows the order of the addresses in `ubus` runtime information.
2191 getIP6Addrs: function() {
2192 var addrs
= this._ubus('ipv6-address'),
2195 if (Array
.isArray(addrs
))
2196 for (var i
= 0; i
< addrs
.length
; i
++)
2197 if (L
.isObject(addrs
[i
]))
2198 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2200 addrs
= this._ubus('ipv6-prefix-assignment');
2202 if (Array
.isArray(addrs
))
2203 for (var i
= 0; i
< addrs
.length
; i
++)
2204 if (L
.isObject(addrs
[i
]) && L
.isObject(addrs
[i
]['local-address']))
2205 rv
.push('%s/%d'.format(addrs
[i
]['local-address'].address
, addrs
[i
]['local-address'].mask
));
2211 * Query the gateway (nexthop) of the IPv6 default route associated with
2212 * this logical interface.
2215 * Returns a string containing the IPv6 nexthop address of the associated
2216 * default route or `null` if no default route was found.
2218 getGateway6Addr: function() {
2219 var routes
= this._ubus('route');
2221 if (Array
.isArray(routes
))
2222 for (var i
= 0; i
< routes
.length
; i
++)
2223 if (typeof(routes
[i
]) == 'object' &&
2224 routes
[i
].target
== '::' &&
2225 routes
[i
].mask
== 0)
2226 return routes
[i
].nexthop
;
2232 * Query the IPv6 DNS servers associated with the logical interface.
2234 * @returns {string[]}
2235 * Returns an array of IPv6 DNS servers registered by the remote
2238 getDNS6Addrs: function() {
2239 var addrs
= this._ubus('dns-server'),
2242 if (Array
.isArray(addrs
))
2243 for (var i
= 0; i
< addrs
.length
; i
++)
2244 if (/:/.test(addrs
[i
]))
2251 * Query the routed IPv6 prefix associated with the logical interface.
2253 * @returns {null|string}
2254 * Returns the routed IPv6 prefix registered by the remote protocol
2255 * handler or `null` if no prefix is present.
2257 getIP6Prefix: function() {
2258 var prefixes
= this._ubus('ipv6-prefix');
2260 if (Array
.isArray(prefixes
) && L
.isObject(prefixes
[0]))
2261 return '%s/%d'.format(prefixes
[0].address
, prefixes
[0].mask
);
2267 * Query interface error messages published in `ubus` runtime state.
2269 * Interface errors are emitted by remote protocol handlers if the setup
2270 * of the underlying logical interface failed, e.g. due to bad
2271 * configuration or network connectivity issues.
2273 * This function will translate the found error codes to human readable
2274 * messages using the descriptions registered by
2275 * {@link LuCI.network#registerErrorCode Network.registerErrorCode()}
2276 * and fall back to `"Unknown error (%s)"` where `%s` is replaced by the
2277 * error code in case no translation can be found.
2279 * @returns {string[]}
2280 * Returns an array of translated interface error messages.
2282 getErrors: function() {
2283 var errors
= this._ubus('errors'),
2286 if (Array
.isArray(errors
)) {
2287 for (var i
= 0; i
< errors
.length
; i
++) {
2288 if (!L
.isObject(errors
[i
]) || typeof(errors
[i
].code
) != 'string')
2292 rv
.push(proto_errors
[errors
[i
].code
] || _('Unknown error (%s)').format(errors
[i
].code
));
2300 * Checks whether the underlying logical interface is declared as bridge.
2302 * @returns {boolean}
2303 * Returns `true` when the interface is declared with `option type bridge`
2304 * and when the associated protocol implementation is not marked virtual
2305 * or `false` when the logical interface is no bridge.
2307 isBridge: function() {
2308 return (!this.isVirtual() && this.getType() == 'bridge');
2312 * Get the name of the opkg package providing the protocol functionality.
2314 * This function should be overwritten by protocol specific subclasses.
2319 * Returns the name of the opkg package required for the protocol to
2320 * function, e.g. `odhcp6c` for the `dhcpv6` prototocol.
2322 getOpkgPackage: function() {
2327 * Check function for the protocol handler if a new interface is createable.
2329 * This function should be overwritten by protocol specific subclasses.
2333 * @param {string} ifname
2334 * The name of the interface to be created.
2336 * @returns {Promise<void>}
2337 * Returns a promise resolving if new interface is createable, else
2338 * rejects with an error message string.
2340 isCreateable: function(ifname
) {
2341 return Promise
.resolve(null);
2345 * Checks whether the protocol functionality is installed.
2347 * This function exists for compatibility with old code, it always
2353 * @returns {boolean}
2354 * Returns `true` if the protocol support is installed, else `false`.
2356 isInstalled: function() {
2361 * Checks whether this protocol is "virtual".
2363 * A "virtual" protocol is a protocol which spawns its own interfaces
2364 * on demand instead of using existing physical interfaces.
2366 * Examples for virtual protocols are `6in4` which `gre` spawn tunnel
2367 * network device on startup, examples for non-virtual protcols are
2368 * `dhcp` or `static` which apply IP configuration to existing interfaces.
2370 * This function should be overwritten by subclasses.
2372 * @returns {boolean}
2373 * Returns a boolean indicating whether the underlying protocol spawns
2374 * dynamic interfaces (`true`) or not (`false`).
2376 isVirtual: function() {
2381 * Checks whether this protocol is "floating".
2383 * A "floating" protocol is a protocol which spawns its own interfaces
2384 * on demand, like a virtual one but which relies on an existinf lower
2385 * level interface to initiate the connection.
2387 * An example for such a protocol is "pppoe".
2389 * This function exists for backwards compatibility with older code
2390 * but should not be used anymore.
2393 * @returns {boolean}
2394 * Returns a boolean indicating whether this protocol is floating (`true`)
2397 isFloating: function() {
2402 * Checks whether this logical interface is dynamic.
2404 * A dynamic interface is an interface which has been created at runtime,
2405 * e.g. as sub-interface of another interface, but which is not backed by
2406 * any user configuration. Such dynamic interfaces cannot be edited but
2407 * only brought down or restarted.
2409 * @returns {boolean}
2410 * Returns a boolean indicating whether this interface is dynamic (`true`)
2413 isDynamic: function() {
2414 return (this._ubus('dynamic') == true);
2418 * Checks whether this interface is an alias interface.
2420 * Alias interfaces are interfaces layering on top of another interface
2421 * and are denoted by a special `@interfacename` notation in the
2422 * underlying `ifname` option.
2424 * @returns {null|string}
2425 * Returns the name of the parent interface if this logical interface
2426 * is an alias or `null` if it is not an alias interface.
2428 isAlias: function() {
2429 var ifnames
= L
.toArray(uci
.get('network', this.sid
, 'ifname')),
2432 for (var i
= 0; i
< ifnames
.length
; i
++)
2433 if (ifnames
[i
].charAt(0) == '@')
2434 parent
= ifnames
[i
].substr(1);
2435 else if (parent
!= null)
2442 * Checks whether this logical interface is "empty", meaning that ut
2443 * has no network devices attached.
2445 * @returns {boolean}
2446 * Returns `true` if this logical interface is empty, else `false`.
2448 isEmpty: function() {
2449 if (this.isFloating())
2453 ifname
= this._get('ifname');
2455 if (ifname
!= null && ifname
.match(/\S+/))
2458 if (empty
== true && getWifiNetidBySid(this.sid
) != null)
2465 * Checks whether this logical interface is configured and running.
2467 * @returns {boolean}
2468 * Returns `true` when the interface is active or `false` when it is not.
2471 return (this._ubus('up') == true);
2475 * Add the given network device to the logical interface.
2477 * @param {LuCI.network.Protocol|LuCI.network.Device|LuCI.network.WifiDevice|LuCI.network.WifiNetwork|string} device
2478 * The object or device name to add to the logical interface. In case the
2479 * given argument is not a string, it is resolved though the
2480 * {@link LuCI.network#getIfnameOf Network.getIfnameOf()} function.
2482 * @returns {boolean}
2483 * Returns `true` if the device name has been added or `false` if any
2484 * argument was invalid, if the device was already part of the logical
2485 * interface or if the logical interface is virtual.
2487 addDevice: function(ifname
) {
2488 ifname
= ifnameOf(ifname
);
2490 if (ifname
== null || this.isFloating())
2493 var wif
= getWifiSidByIfname(ifname
);
2496 return appendValue('wireless', wif
, 'network', this.sid
);
2498 return appendValue('network', this.sid
, 'ifname', ifname
);
2502 * Remove the given network device from the logical interface.
2504 * @param {LuCI.network.Protocol|LuCI.network.Device|LuCI.network.WifiDevice|LuCI.network.WifiNetwork|string} device
2505 * The object or device name to remove from the logical interface. In case
2506 * the given argument is not a string, it is resolved though the
2507 * {@link LuCI.network#getIfnameOf Network.getIfnameOf()} function.
2509 * @returns {boolean}
2510 * Returns `true` if the device name has been added or `false` if any
2511 * argument was invalid, if the device was already part of the logical
2512 * interface or if the logical interface is virtual.
2514 deleteDevice: function(ifname
) {
2517 ifname
= ifnameOf(ifname
);
2519 if (ifname
== null || this.isFloating())
2522 var wif
= getWifiSidByIfname(ifname
);
2525 rv
= removeValue('wireless', wif
, 'network', this.sid
);
2527 if (removeValue('network', this.sid
, 'ifname', ifname
))
2534 * Returns the Linux network device associated with this logical
2537 * @returns {LuCI.network.Device}
2538 * Returns a `Network.Device` class instance representing the
2539 * expected Linux network device according to the configuration.
2541 getDevice: function() {
2542 if (this.isVirtual()) {
2543 var ifname
= '%s-%s'.format(this.getProtocol(), this.sid
);
2544 _state
.isTunnel
[this.getProtocol() + '-' + this.sid
] = true;
2545 return Network
.prototype.instantiateDevice(ifname
, this);
2547 else if (this.isBridge()) {
2548 var ifname
= 'br-%s'.format(this.sid
);
2549 _state
.isBridge
[ifname
] = true;
2550 return new Device(ifname
, this);
2553 var ifnames
= L
.toArray(uci
.get('network', this.sid
, 'ifname'));
2555 for (var i
= 0; i
< ifnames
.length
; i
++) {
2556 var m
= ifnames
[i
].match(/^([^:/]+)/);
2557 return ((m
&& m
[1]) ? Network
.prototype.instantiateDevice(m
[1], this) : null);
2560 ifname
= getWifiNetidByNetname(this.sid
);
2562 return (ifname
!= null ? Network
.prototype.instantiateDevice(ifname
[0], this) : null);
2567 * Returns the layer 2 linux network device currently associated
2568 * with this logical interface.
2570 * @returns {LuCI.network.Device}
2571 * Returns a `Network.Device` class instance representing the Linux
2572 * network device currently associated with the logical interface.
2574 getL2Device: function() {
2575 var ifname
= this._ubus('device');
2576 return (ifname
!= null ? Network
.prototype.instantiateDevice(ifname
, this) : null);
2580 * Returns the layer 3 linux network device currently associated
2581 * with this logical interface.
2583 * @returns {LuCI.network.Device}
2584 * Returns a `Network.Device` class instance representing the Linux
2585 * network device currently associated with the logical interface.
2587 getL3Device: function() {
2588 var ifname
= this._ubus('l3_device');
2589 return (ifname
!= null ? Network
.prototype.instantiateDevice(ifname
, this) : null);
2593 * Returns a list of network sub-devices associated with this logical
2596 * @returns {null|Array<LuCI.network.Device>}
2597 * Returns an array of of `Network.Device` class instances representing
2598 * the sub-devices attached to this logical interface or `null` if the
2599 * logical interface does not support sub-devices, e.g. because it is
2600 * virtual and not a bridge.
2602 getDevices: function() {
2605 if (!this.isBridge() && !(this.isVirtual() && !this.isFloating()))
2608 var ifnames
= L
.toArray(uci
.get('network', this.sid
, 'ifname'));
2610 for (var i
= 0; i
< ifnames
.length
; i
++) {
2611 if (ifnames
[i
].charAt(0) == '@')
2614 var m
= ifnames
[i
].match(/^([^:/]+)/);
2616 rv
.push(Network
.prototype.instantiateDevice(m
[1], this));
2619 var uciWifiIfaces
= uci
.sections('wireless', 'wifi-iface');
2621 for (var i
= 0; i
< uciWifiIfaces
.length
; i
++) {
2622 if (typeof(uciWifiIfaces
[i
].device
) != 'string')
2625 var networks
= L
.toArray(uciWifiIfaces
[i
].network
);
2627 for (var j
= 0; j
< networks
.length
; j
++) {
2628 if (networks
[j
] != this.sid
)
2631 var netid
= getWifiNetidBySid(uciWifiIfaces
[i
]['.name']);
2634 rv
.push(Network
.prototype.instantiateDevice(netid
[0], this));
2638 rv
.sort(deviceSort
);
2644 * Checks whether this logical interface contains the given device
2647 * @param {LuCI.network.Protocol|LuCI.network.Device|LuCI.network.WifiDevice|LuCI.network.WifiNetwork|string} device
2648 * The object or device name to check. In case the given argument is not
2649 * a string, it is resolved though the
2650 * {@link LuCI.network#getIfnameOf Network.getIfnameOf()} function.
2652 * @returns {boolean}
2653 * Returns `true` when this logical interface contains the given network
2654 * device or `false` if not.
2656 containsDevice: function(ifname
) {
2657 ifname
= ifnameOf(ifname
);
2661 else if (this.isVirtual() && '%s-%s'.format(this.getProtocol(), this.sid
) == ifname
)
2663 else if (this.isBridge() && 'br-%s'.format(this.sid
) == ifname
)
2666 var ifnames
= L
.toArray(uci
.get('network', this.sid
, 'ifname'));
2668 for (var i
= 0; i
< ifnames
.length
; i
++) {
2669 var m
= ifnames
[i
].match(/^([^:/]+)/);
2670 if (m
!= null && m
[1] == ifname
)
2674 var wif
= getWifiSidByIfname(ifname
);
2677 var networks
= L
.toArray(uci
.get('wireless', wif
, 'network'));
2679 for (var i
= 0; i
< networks
.length
; i
++)
2680 if (networks
[i
] == this.sid
)
2688 * Cleanup related configuration entries.
2690 * This function will be invoked if an interface is about to be removed
2691 * from the configuration and is responsible for performing any required
2692 * cleanup tasks, such as unsetting uci entries in related configurations.
2694 * It should be overwritten by protocol specific subclasses.
2698 * @returns {*|Promise<*>}
2699 * This function may return a promise which is awaited before the rest of
2700 * the configuration is removed. Any non-promise return value and any
2701 * resolved promise value is ignored. If the returned promise is rejected,
2702 * the interface removal will be aborted.
2704 deleteConfiguration: function() {}
2709 * @memberof LuCI.network
2713 * A `Network.Device` class instance represents an underlying Linux network
2714 * device and allows querying device details such as packet statistics or MTU.
2716 Device
= baseclass
.extend(/** @lends LuCI.network.Device.prototype */ {
2717 __init__: function(ifname
, network
) {
2718 var wif
= getWifiSidByIfname(ifname
);
2721 var res
= getWifiStateBySid(wif
) || [],
2722 netid
= getWifiNetidBySid(wif
) || [];
2724 this.wif
= new WifiNetwork(wif
, res
[0], res
[1], netid
[0], res
[2], { ifname
: ifname
});
2725 this.ifname
= this.wif
.getIfname();
2728 this.ifname
= this.ifname
|| ifname
;
2729 this.dev
= _state
.netdevs
[this.ifname
];
2730 this.network
= network
;
2733 _devstate: function(/* ... */) {
2736 for (var i
= 0; i
< arguments
.length
; i
++)
2738 rv
= rv
[arguments
[i
]];
2746 * Get the name of the network device.
2749 * Returns the name of the device, e.g. `eth0` or `wlan0`.
2751 getName: function() {
2752 return (this.wif
!= null ? this.wif
.getIfname() : this.ifname
);
2756 * Get the MAC address of the device.
2758 * @returns {null|string}
2759 * Returns the MAC address of the device or `null` if not applicable,
2760 * e.g. for non-ethernet tunnel devices.
2762 getMAC: function() {
2763 var mac
= this._devstate('macaddr');
2764 return mac
? mac
.toUpperCase() : null;
2768 * Get the MTU of the device.
2771 * Returns the MTU of the device.
2773 getMTU: function() {
2774 return this._devstate('mtu');
2778 * Get the IPv4 addresses configured on the device.
2780 * @returns {string[]}
2781 * Returns an array of IPv4 address strings.
2783 getIPAddrs: function() {
2784 var addrs
= this._devstate('ipaddrs');
2785 return (Array
.isArray(addrs
) ? addrs
: []);
2789 * Get the IPv6 addresses configured on the device.
2791 * @returns {string[]}
2792 * Returns an array of IPv6 address strings.
2794 getIP6Addrs: function() {
2795 var addrs
= this._devstate('ip6addrs');
2796 return (Array
.isArray(addrs
) ? addrs
: []);
2800 * Get the type of the device..
2803 * Returns a string describing the type of the network device:
2804 * - `alias` if it is an abstract alias device (`@` notation)
2805 * - `wifi` if it is a wireless interface (e.g. `wlan0`)
2806 * - `bridge` if it is a bridge device (e.g. `br-lan`)
2807 * - `tunnel` if it is a tun or tap device (e.g. `tun0`)
2808 * - `vlan` if it is a vlan device (e.g. `eth0.1`)
2809 * - `switch` if it is a switch device (e.g.`eth1` connected to switch0)
2810 * - `ethernet` for all other device types
2812 getType: function() {
2813 if (this.ifname
!= null && this.ifname
.charAt(0) == '@')
2815 else if (this.wif
!= null || isWifiIfname(this.ifname
))
2817 else if (_state
.isBridge
[this.ifname
])
2819 else if (_state
.isTunnel
[this.ifname
])
2821 else if (this.ifname
.indexOf('.') > -1)
2823 else if (_state
.isSwitch
[this.ifname
])
2830 * Get a short description string for the device.
2833 * Returns the device name for non-wifi devices or a string containing
2834 * the operation mode and SSID for wifi devices.
2836 getShortName: function() {
2837 if (this.wif
!= null)
2838 return this.wif
.getShortName();
2844 * Get a long description string for the device.
2847 * Returns a string containing the type description and device name
2848 * for non-wifi devices or operation mode and ssid for wifi ones.
2850 getI18n: function() {
2851 if (this.wif
!= null) {
2852 return '%s: %s "%s"'.format(
2853 _('Wireless Network'),
2854 this.wif
.getActiveMode(),
2855 this.wif
.getActiveSSID() || this.wif
.getActiveBSSID() || this.wif
.getID() || '?');
2858 return '%s: "%s"'.format(this.getTypeI18n(), this.getName());
2862 * Get a string describing the device type.
2865 * Returns a string describing the type, e.g. "Wireless Adapter" or
2868 getTypeI18n: function() {
2869 switch (this.getType()) {
2871 return _('Alias Interface');
2874 return _('Wireless Adapter');
2880 return _('Ethernet Switch');
2883 return (_state
.isSwitch
[this.ifname
] ? _('Switch VLAN') : _('Software VLAN'));
2886 return _('Tunnel Interface');
2889 return _('Ethernet Adapter');
2894 * Get the associated bridge ports of the device.
2896 * @returns {null|Array<LuCI.network.Device>}
2897 * Returns an array of `Network.Device` instances representing the ports
2898 * (slave interfaces) of the bridge or `null` when this device isn't
2901 getPorts: function() {
2902 var br
= _state
.bridges
[this.ifname
],
2905 if (br
== null || !Array
.isArray(br
.ifnames
))
2908 for (var i
= 0; i
< br
.ifnames
.length
; i
++)
2909 rv
.push(Network
.prototype.instantiateDevice(br
.ifnames
[i
].name
));
2911 rv
.sort(deviceSort
);
2919 * @returns {null|string}
2920 * Returns the ID of this network bridge or `null` if this network
2921 * device is not a Linux bridge.
2923 getBridgeID: function() {
2924 var br
= _state
.bridges
[this.ifname
];
2925 return (br
!= null ? br
.id
: null);
2929 * Get the bridge STP setting
2931 * @returns {boolean}
2932 * Returns `true` when this device is a Linux bridge and has `stp`
2933 * enabled, else `false`.
2935 getBridgeSTP: function() {
2936 var br
= _state
.bridges
[this.ifname
];
2937 return (br
!= null ? !!br
.stp
: false);
2941 * Checks whether this device is up.
2943 * @returns {boolean}
2944 * Returns `true` when the associated device is running pr `false`
2945 * when it is down or absent.
2948 var up
= this._devstate('flags', 'up');
2951 up
= (this.getType() == 'alias');
2957 * Checks whether this device is a Linux bridge.
2959 * @returns {boolean}
2960 * Returns `true` when the network device is present and a Linux bridge,
2963 isBridge: function() {
2964 return (this.getType() == 'bridge');
2968 * Checks whether this device is part of a Linux bridge.
2970 * @returns {boolean}
2971 * Returns `true` when this network device is part of a bridge,
2974 isBridgePort: function() {
2975 return (this._devstate('bridge') != null);
2979 * Get the amount of transmitted bytes.
2982 * Returns the amount of bytes transmitted by the network device.
2984 getTXBytes: function() {
2985 var stat
= this._devstate('stats');
2986 return (stat
!= null ? stat
.tx_bytes
|| 0 : 0);
2990 * Get the amount of received bytes.
2993 * Returns the amount of bytes received by the network device.
2995 getRXBytes: function() {
2996 var stat
= this._devstate('stats');
2997 return (stat
!= null ? stat
.rx_bytes
|| 0 : 0);
3001 * Get the amount of transmitted packets.
3004 * Returns the amount of packets transmitted by the network device.
3006 getTXPackets: function() {
3007 var stat
= this._devstate('stats');
3008 return (stat
!= null ? stat
.tx_packets
|| 0 : 0);
3012 * Get the amount of received packets.
3015 * Returns the amount of packets received by the network device.
3017 getRXPackets: function() {
3018 var stat
= this._devstate('stats');
3019 return (stat
!= null ? stat
.rx_packets
|| 0 : 0);
3023 * Get the primary logical interface this device is assigned to.
3025 * @returns {null|LuCI.network.Protocol}
3026 * Returns a `Network.Protocol` instance representing the logical
3027 * interface this device is attached to or `null` if it is not
3028 * assigned to any logical interface.
3030 getNetwork: function() {
3031 return this.getNetworks()[0];
3035 * Get the logical interfaces this device is assigned to.
3037 * @returns {Array<LuCI.network.Protocol>}
3038 * Returns an array of `Network.Protocol` instances representing the
3039 * logical interfaces this device is assigned to.
3041 getNetworks: function() {
3042 if (this.networks
== null) {
3045 var networks
= enumerateNetworks
.apply(L
.network
);
3047 for (var i
= 0; i
< networks
.length
; i
++)
3048 if (networks
[i
].containsDevice(this.ifname
) || networks
[i
].getIfname() == this.ifname
)
3049 this.networks
.push(networks
[i
]);
3051 this.networks
.sort(networkSort
);
3054 return this.networks
;
3058 * Get the related wireless network this device is related to.
3060 * @returns {null|LuCI.network.WifiNetwork}
3061 * Returns a `Network.WifiNetwork` instance representing the wireless
3062 * network corresponding to this network device or `null` if this device
3063 * is not a wireless device.
3065 getWifiNetwork: function() {
3066 return (this.wif
!= null ? this.wif
: null);
3072 * @memberof LuCI.network
3076 * A `Network.WifiDevice` class instance represents a wireless radio device
3077 * present on the system and provides wireless capability information as
3078 * well as methods for enumerating related wireless networks.
3080 WifiDevice
= baseclass
.extend(/** @lends LuCI.network.WifiDevice.prototype */ {
3081 __init__: function(name
, radiostate
) {
3082 var uciWifiDevice
= uci
.get('wireless', name
);
3084 if (uciWifiDevice
!= null &&
3085 uciWifiDevice
['.type'] == 'wifi-device' &&
3086 uciWifiDevice
['.name'] != null) {
3087 this.sid
= uciWifiDevice
['.name'];
3090 this.sid
= this.sid
|| name
;
3098 ubus: function(/* ... */) {
3099 var v
= this._ubusdata
;
3101 for (var i
= 0; i
< arguments
.length
; i
++)
3103 v
= v
[arguments
[i
]];
3111 * Read the given UCI option value of this wireless device.
3113 * @param {string} opt
3114 * The UCI option name to read.
3116 * @returns {null|string|string[]}
3117 * Returns the UCI option value or `null` if the requested option is
3120 get: function(opt
) {
3121 return uci
.get('wireless', this.sid
, opt
);
3125 * Set the given UCI option of this network to the given value.
3127 * @param {string} opt
3128 * The name of the UCI option to set.
3130 * @param {null|string|string[]} val
3131 * The value to set or `null` to remove the given option from the
3134 set: function(opt
, value
) {
3135 return uci
.set('wireless', this.sid
, opt
, value
);
3139 * Checks whether this wireless radio is disabled.
3141 * @returns {boolean}
3142 * Returns `true` when the wireless radio is marked as disabled in `ubus`
3143 * runtime state or when the `disabled` option is set in the corresponding
3144 * UCI configuration.
3146 isDisabled: function() {
3147 return this.ubus('dev', 'disabled') || this.get('disabled') == '1';
3151 * Get the configuration name of this wireless radio.
3154 * Returns the UCI section name (e.g. `radio0`) of the corresponding
3155 * radio configuration which also serves as unique logical identifier
3156 * for the wireless phy.
3158 getName: function() {
3163 * Gets a list of supported hwmodes.
3165 * The hwmode values describe the frequency band and wireless standard
3166 * versions supported by the wireless phy.
3168 * @returns {string[]}
3169 * Returns an array of valid hwmode values for this radio. Currently
3170 * known mode values are:
3171 * - `a` - Legacy 802.11a mode, 5 GHz, up to 54 Mbit/s
3172 * - `b` - Legacy 802.11b mode, 2.4 GHz, up to 11 Mbit/s
3173 * - `g` - Legacy 802.11g mode, 2.4 GHz, up to 54 Mbit/s
3174 * - `n` - IEEE 802.11n mode, 2.4 or 5 GHz, up to 600 Mbit/s
3175 * - `ac` - IEEE 802.11ac mode, 5 GHz, up to 6770 Mbit/s
3177 getHWModes: function() {
3178 var hwmodes
= this.ubus('dev', 'iwinfo', 'hwmodes');
3179 return Array
.isArray(hwmodes
) ? hwmodes
: [ 'b', 'g' ];
3183 * Gets a list of supported htmodes.
3185 * The htmode values describe the wide-frequency options supported by
3188 * @returns {string[]}
3189 * Returns an array of valid htmode values for this radio. Currently
3190 * known mode values are:
3191 * - `HT20` - applicable to IEEE 802.11n, 20 MHz wide channels
3192 * - `HT40` - applicable to IEEE 802.11n, 40 MHz wide channels
3193 * - `VHT20` - applicable to IEEE 802.11ac, 20 MHz wide channels
3194 * - `VHT40` - applicable to IEEE 802.11ac, 40 MHz wide channels
3195 * - `VHT80` - applicable to IEEE 802.11ac, 80 MHz wide channels
3196 * - `VHT160` - applicable to IEEE 802.11ac, 160 MHz wide channels
3198 getHTModes: function() {
3199 var htmodes
= this.ubus('dev', 'iwinfo', 'htmodes');
3200 return (Array
.isArray(htmodes
) && htmodes
.length
) ? htmodes
: null;
3204 * Get a string describing the wireless radio hardware.
3207 * Returns the description string.
3209 getI18n: function() {
3210 var hw
= this.ubus('dev', 'iwinfo', 'hardware'),
3211 type
= L
.isObject(hw
) ? hw
.name
: null;
3213 if (this.ubus('dev', 'iwinfo', 'type') == 'wl')
3216 var hwmodes
= this.getHWModes(),
3219 hwmodes
.sort(function(a
, b
) {
3220 return (a
.length
!= b
.length
? a
.length
> b
.length
: a
> b
);
3223 modestr
= hwmodes
.join('');
3225 return '%s 802.11%s Wireless Controller (%s)'.format(type
|| 'Generic', modestr
, this.getName());
3229 * A wireless scan result object describes a neighbouring wireless
3230 * network found in the vincinity.
3232 * @typedef {Object<string, number|string|LuCI.network.WifiEncryption>} WifiScanResult
3233 * @memberof LuCI.network
3235 * @property {string} ssid
3236 * The SSID / Mesh ID of the network.
3238 * @property {string} bssid
3239 * The BSSID if the network.
3241 * @property {string} mode
3242 * The operation mode of the network (`Master`, `Ad-Hoc`, `Mesh Point`).
3244 * @property {number} channel
3245 * The wireless channel of the network.
3247 * @property {number} signal
3248 * The received signal strength of the network in dBm.
3250 * @property {number} quality
3251 * The numeric quality level of the signal, can be used in conjunction
3252 * with `quality_max` to calculate a quality percentage.
3254 * @property {number} quality_max
3255 * The maximum possible quality level of the signal, can be used in
3256 * conjunction with `quality` to calculate a quality percentage.
3258 * @property {LuCI.network.WifiEncryption} encryption
3259 * The encryption used by the wireless network.
3263 * Trigger a wireless scan on this radio device and obtain a list of
3266 * @returns {Promise<Array<LuCI.network.WifiScanResult>>}
3267 * Returns a promise resolving to an array of scan result objects
3268 * describing the networks found in the vincinity.
3270 getScanList: function() {
3271 return callIwinfoScan(this.sid
);
3275 * Check whether the wireless radio is marked as up in the `ubus`
3278 * @returns {boolean}
3279 * Returns `true` when the radio device is up, else `false`.
3282 if (L
.isObject(_state
.radios
[this.sid
]))
3283 return (_state
.radios
[this.sid
].up
== true);
3289 * Get the wifi network of the given name belonging to this radio device
3291 * @param {string} network
3292 * The name of the wireless network to lookup. This may be either an uci
3293 * configuration section ID, a network ID in the form `radio#.network#`
3294 * or a Linux network device name like `wlan0` which is resolved to the
3295 * corresponding configuration section through `ubus` runtime information.
3297 * @returns {Promise<LuCI.network.WifiNetwork>}
3298 * Returns a promise resolving to a `Network.WifiNetwork` instance
3299 * representing the wireless network and rejecting with `null` if
3300 * the given network could not be found or is not associated with
3301 * this radio device.
3303 getWifiNetwork: function(network
) {
3304 return Network
.prototype.getWifiNetwork(network
).then(L
.bind(function(networkInstance
) {
3305 var uciWifiIface
= (networkInstance
.sid
? uci
.get('wireless', networkInstance
.sid
) : null);
3307 if (uciWifiIface
== null || uciWifiIface
['.type'] != 'wifi-iface' || uciWifiIface
.device
!= this.sid
)
3308 return Promise
.reject();
3310 return networkInstance
;
3315 * Get all wireless networks associated with this wireless radio device.
3317 * @returns {Promise<Array<LuCI.network.WifiNetwork>>}
3318 * Returns a promise resolving to an array of `Network.WifiNetwork`
3319 * instances respresenting the wireless networks associated with this
3322 getWifiNetworks: function() {
3323 return Network
.prototype.getWifiNetworks().then(L
.bind(function(networks
) {
3326 for (var i
= 0; i
< networks
.length
; i
++)
3327 if (networks
[i
].getWifiDeviceName() == this.getName())
3328 rv
.push(networks
[i
]);
3335 * Adds a new wireless network associated with this radio device to the
3336 * configuration and sets its options to the provided values.
3338 * @param {Object<string, string|string[]>} [options]
3339 * The options to set for the newly added wireless network.
3341 * @returns {Promise<null|LuCI.network.WifiNetwork>}
3342 * Returns a promise resolving to a `WifiNetwork` instance describing
3343 * the newly added wireless network or `null` if the given options
3346 addWifiNetwork: function(options
) {
3347 if (!L
.isObject(options
))
3350 options
.device
= this.sid
;
3352 return Network
.prototype.addWifiNetwork(options
);
3356 * Deletes the wireless network with the given name associated with this
3359 * @param {string} network
3360 * The name of the wireless network to lookup. This may be either an uci
3361 * configuration section ID, a network ID in the form `radio#.network#`
3362 * or a Linux network device name like `wlan0` which is resolved to the
3363 * corresponding configuration section through `ubus` runtime information.
3365 * @returns {Promise<boolean>}
3366 * Returns a promise resolving to `true` when the wireless network was
3367 * successfully deleted from the configuration or `false` when the given
3368 * network could not be found or if the found network was not associated
3369 * with this wireless radio device.
3371 deleteWifiNetwork: function(network
) {
3374 if (network
instanceof WifiNetwork
) {
3378 var uciWifiIface
= uci
.get('wireless', network
);
3380 if (uciWifiIface
== null || uciWifiIface
['.type'] != 'wifi-iface')
3381 sid
= getWifiSidByIfname(network
);
3384 if (sid
== null || uci
.get('wireless', sid
, 'device') != this.sid
)
3385 return Promise
.resolve(false);
3387 uci
.delete('wireless', network
);
3389 return Promise
.resolve(true);
3395 * @memberof LuCI.network
3399 * A `Network.WifiNetwork` instance represents a wireless network (vif)
3400 * configured on top of a radio device and provides functions for querying
3401 * the runtime state of the network. Most radio devices support multiple
3402 * such networks in parallel.
3404 WifiNetwork
= baseclass
.extend(/** @lends LuCI.network.WifiNetwork.prototype */ {
3405 __init__: function(sid
, radioname
, radiostate
, netid
, netstate
, hostapd
) {
3416 ubus: function(/* ... */) {
3417 var v
= this._ubusdata
;
3419 for (var i
= 0; i
< arguments
.length
; i
++)
3421 v
= v
[arguments
[i
]];
3429 * Read the given UCI option value of this wireless network.
3431 * @param {string} opt
3432 * The UCI option name to read.
3434 * @returns {null|string|string[]}
3435 * Returns the UCI option value or `null` if the requested option is
3438 get: function(opt
) {
3439 return uci
.get('wireless', this.sid
, opt
);
3443 * Set the given UCI option of this network to the given value.
3445 * @param {string} opt
3446 * The name of the UCI option to set.
3448 * @param {null|string|string[]} val
3449 * The value to set or `null` to remove the given option from the
3452 set: function(opt
, value
) {
3453 return uci
.set('wireless', this.sid
, opt
, value
);
3457 * Checks whether this wireless network is disabled.
3459 * @returns {boolean}
3460 * Returns `true` when the wireless radio is marked as disabled in `ubus`
3461 * runtime state or when the `disabled` option is set in the corresponding
3462 * UCI configuration.
3464 isDisabled: function() {
3465 return this.ubus('dev', 'disabled') || this.get('disabled') == '1';
3469 * Get the configured operation mode of the wireless network.
3472 * Returns the configured operation mode. Possible values are:
3473 * - `ap` - Master (Access Point) mode
3474 * - `sta` - Station (client) mode
3475 * - `adhoc` - Ad-Hoc (IBSS) mode
3476 * - `mesh` - Mesh (IEEE 802.11s) mode
3477 * - `monitor` - Monitor mode
3479 getMode: function() {
3480 return this.ubus('net', 'config', 'mode') || this.get('mode') || 'ap';
3484 * Get the configured SSID of the wireless network.
3486 * @returns {null|string}
3487 * Returns the configured SSID value or `null` when this network is
3490 getSSID: function() {
3491 if (this.getMode() == 'mesh')
3494 return this.ubus('net', 'config', 'ssid') || this.get('ssid');
3498 * Get the configured Mesh ID of the wireless network.
3500 * @returns {null|string}
3501 * Returns the configured mesh ID value or `null` when this network
3502 * is not in mesh mode.
3504 getMeshID: function() {
3505 if (this.getMode() != 'mesh')
3508 return this.ubus('net', 'config', 'mesh_id') || this.get('mesh_id');
3512 * Get the configured BSSID of the wireless network.
3514 * @returns {null|string}
3515 * Returns the BSSID value or `null` if none has been specified.
3517 getBSSID: function() {
3518 return this.ubus('net', 'config', 'bssid') || this.get('bssid');
3522 * Get the names of the logical interfaces this wireless network is
3525 * @returns {string[]}
3526 * Returns an array of logical interface names.
3528 getNetworkNames: function() {
3529 return L
.toArray(this.ubus('net', 'config', 'network') || this.get('network'));
3533 * Get the internal network ID of this wireless network.
3535 * The network ID is a LuCI specific identifer in the form
3536 * `radio#.network#` to identify wireless networks by their corresponding
3537 * radio and network index numbers.
3540 * Returns the LuCI specific network ID.
3547 * Get the configuration ID of this wireless network.
3550 * Returns the corresponding UCI section ID of the network.
3552 getName: function() {
3557 * Get the Linux network device name.
3559 * @returns {null|string}
3560 * Returns the current Linux network device name as resolved from
3561 * `ubus` runtime information or `null` if this network has no
3562 * associated network device, e.g. when not configured or up.
3564 getIfname: function() {
3565 var ifname
= this.ubus('net', 'ifname') || this.ubus('net', 'iwinfo', 'ifname');
3567 if (ifname
== null || ifname
.match(/^(wifi|radio)\d/))
3568 ifname
= this.netid
;
3574 * Get the Linux VLAN network device names.
3576 * @returns {string[]}
3577 * Returns the current Linux VLAN network device name as resolved
3578 * from `ubus` runtime information or empty array if this network
3579 * has no associated VLAN network devices.
3581 getVlanIfnames: function() {
3582 var vlans
= L
.toArray(this.ubus('net', 'vlans')),
3585 for (var i
= 0; i
< vlans
.length
; i
++)
3586 ifnames
.push(vlans
[i
]['ifname']);
3592 * Get the name of the corresponding wifi radio device.
3594 * @returns {null|string}
3595 * Returns the name of the radio device this network is configured on
3596 * or `null` if it cannot be determined.
3598 getWifiDeviceName: function() {
3599 return this.ubus('radio') || this.get('device');
3603 * Get the corresponding wifi radio device.
3605 * @returns {null|LuCI.network.WifiDevice}
3606 * Returns a `Network.WifiDevice` instance representing the corresponding
3607 * wifi radio device or `null` if the related radio device could not be
3610 getWifiDevice: function() {
3611 var radioname
= this.getWifiDeviceName();
3613 if (radioname
== null)
3614 return Promise
.reject();
3616 return Network
.prototype.getWifiDevice(radioname
);
3620 * Check whether the radio network is up.
3622 * This function actually queries the up state of the related radio
3623 * device and assumes this network to be up as well when the parent
3624 * radio is up. This is due to the fact that OpenWrt does not control
3625 * virtual interfaces individually but within one common hostapd
3628 * @returns {boolean}
3629 * Returns `true` when the network is up, else `false`.
3632 var device
= this.getDevice();
3637 return device
.isUp();
3641 * Query the current operation mode from runtime information.
3644 * Returns the human readable mode name as reported by `ubus` runtime
3645 * state. Possible returned values are:
3657 getActiveMode: function() {
3658 var mode
= this.ubus('net', 'iwinfo', 'mode') || this.ubus('net', 'config', 'mode') || this.get('mode') || 'ap';
3661 case 'ap': return 'Master';
3662 case 'sta': return 'Client';
3663 case 'adhoc': return 'Ad-Hoc';
3664 case 'mesh': return 'Mesh';
3665 case 'monitor': return 'Monitor';
3666 default: return mode
;
3671 * Query the current operation mode from runtime information as
3672 * translated string.
3675 * Returns the translated, human readable mode name as reported by
3676 *`ubus` runtime state.
3678 getActiveModeI18n: function() {
3679 var mode
= this.getActiveMode();
3682 case 'Master': return _('Master');
3683 case 'Client': return _('Client');
3684 case 'Ad-Hoc': return _('Ad-Hoc');
3685 case 'Mash': return _('Mesh');
3686 case 'Monitor': return _('Monitor');
3687 default: return mode
;
3692 * Query the current SSID from runtime information.
3695 * Returns the current SSID or Mesh ID as reported by `ubus` runtime
3698 getActiveSSID: function() {
3699 return this.ubus('net', 'iwinfo', 'ssid') || this.ubus('net', 'config', 'ssid') || this.get('ssid');
3703 * Query the current BSSID from runtime information.
3706 * Returns the current BSSID or Mesh ID as reported by `ubus` runtime
3709 getActiveBSSID: function() {
3710 return this.ubus('net', 'iwinfo', 'bssid') || this.ubus('net', 'config', 'bssid') || this.get('bssid');
3714 * Query the current encryption settings from runtime information.
3717 * Returns a string describing the current encryption or `-` if the the
3718 * encryption state could not be found in `ubus` runtime information.
3720 getActiveEncryption: function() {
3721 return formatWifiEncryption(this.ubus('net', 'iwinfo', 'encryption')) || '-';
3725 * A wireless peer entry describes the properties of a remote wireless
3726 * peer associated with a local network.
3728 * @typedef {Object<string, boolean|number|string|LuCI.network.WifiRateEntry>} WifiPeerEntry
3729 * @memberof LuCI.network
3731 * @property {string} mac
3732 * The MAC address (BSSID).
3734 * @property {number} signal
3735 * The received signal strength.
3737 * @property {number} [signal_avg]
3738 * The average signal strength if supported by the driver.
3740 * @property {number} [noise]
3741 * The current noise floor of the radio. May be `0` or absent if not
3742 * supported by the driver.
3744 * @property {number} inactive
3745 * The amount of milliseconds the peer has been inactive, e.g. due
3748 * @property {number} connected_time
3749 * The amount of milliseconds the peer is associated to this network.
3751 * @property {number} [thr]
3752 * The estimated throughput of the peer, May be `0` or absent if not
3753 * supported by the driver.
3755 * @property {boolean} authorized
3756 * Specifies whether the peer is authorized to associate to this network.
3758 * @property {boolean} authenticated
3759 * Specifies whether the peer completed authentication to this network.
3761 * @property {string} preamble
3762 * The preamble mode used by the peer. May be `long` or `short`.
3764 * @property {boolean} wme
3765 * Specifies whether the peer supports WME/WMM capabilities.
3767 * @property {boolean} mfp
3768 * Specifies whether management frame protection is active.
3770 * @property {boolean} tdls
3771 * Specifies whether TDLS is active.
3773 * @property {number} [mesh llid]
3774 * The mesh LLID, may be `0` or absent if not applicable or supported
3777 * @property {number} [mesh plid]
3778 * The mesh PLID, may be `0` or absent if not applicable or supported
3781 * @property {string} [mesh plink]
3782 * The mesh peer link state description, may be an empty string (`''`)
3783 * or absent if not applicable or supported by the driver.
3785 * The following states are known:
3795 * @property {number} [mesh local PS]
3796 * The local powersafe mode for the peer link, may be an empty
3797 * string (`''`) or absent if not applicable or supported by
3800 * The following modes are known:
3801 * - `ACTIVE` (no power save)
3806 * @property {number} [mesh peer PS]
3807 * The remote powersafe mode for the peer link, may be an empty
3808 * string (`''`) or absent if not applicable or supported by
3811 * The following modes are known:
3812 * - `ACTIVE` (no power save)
3817 * @property {number} [mesh non-peer PS]
3818 * The powersafe mode for all non-peer neigbours, may be an empty
3819 * string (`''`) or absent if not applicable or supported by the driver.
3821 * The following modes are known:
3822 * - `ACTIVE` (no power save)
3827 * @property {LuCI.network.WifiRateEntry} rx
3828 * Describes the receiving wireless rate from the peer.
3830 * @property {LuCI.network.WifiRateEntry} tx
3831 * Describes the transmitting wireless rate to the peer.
3835 * A wireless rate entry describes the properties of a wireless
3836 * transmission rate to or from a peer.
3838 * @typedef {Object<string, boolean|number>} WifiRateEntry
3839 * @memberof LuCI.network
3841 * @property {number} [drop_misc]
3842 * The amount of received misc. packages that have been dropped, e.g.
3843 * due to corruption or missing authentication. Only applicable to
3846 * @property {number} packets
3847 * The amount of packets that have been received or sent.
3849 * @property {number} bytes
3850 * The amount of bytes that have been received or sent.
3852 * @property {number} [failed]
3853 * The amount of failed tranmission attempts. Only applicable to
3856 * @property {number} [retries]
3857 * The amount of retried transmissions. Only applicable to transmit
3860 * @property {boolean} is_ht
3861 * Specifies whether this rate is an HT (IEEE 802.11n) rate.
3863 * @property {boolean} is_vht
3864 * Specifies whether this rate is an VHT (IEEE 802.11ac) rate.
3866 * @property {number} mhz
3867 * The channel width in MHz used for the transmission.
3869 * @property {number} rate
3870 * The bitrate in bit/s of the transmission.
3872 * @property {number} [mcs]
3873 * The MCS index of the used transmission rate. Only applicable to
3876 * @property {number} [40mhz]
3877 * Specifies whether the tranmission rate used 40MHz wide channel.
3878 * Only applicable to HT or VHT rates.
3880 * Note: this option exists for backwards compatibility only and its
3881 * use is discouraged. The `mhz` field should be used instead to
3882 * determine the channel width.
3884 * @property {boolean} [short_gi]
3885 * Specifies whether a short guard interval is used for the transmission.
3886 * Only applicable to HT or VHT rates.
3888 * @property {number} [nss]
3889 * Specifies the number of spatial streams used by the transmission.
3890 * Only applicable to VHT rates.
3894 * Fetch the list of associated peers.
3896 * @returns {Promise<Array<LuCI.network.WifiPeerEntry>>}
3897 * Returns a promise resolving to an array of wireless peers associated
3898 * with this network.
3900 getAssocList: function() {
3902 var ifnames
= [ this.getIfname() ].concat(this.getVlanIfnames());
3904 for (var i
= 0; i
< ifnames
.length
; i
++)
3905 tasks
.push(callIwinfoAssoclist(ifnames
[i
]));
3907 return Promise
.all(tasks
).then(function(values
) {
3908 return Array
.prototype.concat
.apply([], values
);
3913 * Query the current operating frequency of the wireless network.
3915 * @returns {null|string}
3916 * Returns the current operating frequency of the network from `ubus`
3917 * runtime information in GHz or `null` if the information is not
3920 getFrequency: function() {
3921 var freq
= this.ubus('net', 'iwinfo', 'frequency');
3923 if (freq
!= null && freq
> 0)
3924 return '%.03f'.format(freq
/ 1000);
3930 * Query the current average bitrate of all peers associated to this
3933 * @returns {null|number}
3934 * Returns the average bit rate among all peers associated to the network
3935 * as reported by `ubus` runtime information or `null` if the information
3938 getBitRate: function() {
3939 var rate
= this.ubus('net', 'iwinfo', 'bitrate');
3941 if (rate
!= null && rate
> 0)
3942 return (rate
/ 1000);
3948 * Query the current wireless channel.
3950 * @returns {null|number}
3951 * Returns the wireless channel as reported by `ubus` runtime information
3952 * or `null` if it cannot be determined.
3954 getChannel: function() {
3955 return this.ubus('net', 'iwinfo', 'channel') || this.ubus('dev', 'config', 'channel') || this.get('channel');
3959 * Query the current wireless signal.
3961 * @returns {null|number}
3962 * Returns the wireless signal in dBm as reported by `ubus` runtime
3963 * information or `null` if it cannot be determined.
3965 getSignal: function() {
3966 return this.ubus('net', 'iwinfo', 'signal') || 0;
3970 * Query the current radio noise floor.
3973 * Returns the radio noise floor in dBm as reported by `ubus` runtime
3974 * information or `0` if it cannot be determined.
3976 getNoise: function() {
3977 return this.ubus('net', 'iwinfo', 'noise') || 0;
3981 * Query the current country code.
3984 * Returns the wireless country code as reported by `ubus` runtime
3985 * information or `00` if it cannot be determined.
3987 getCountryCode: function() {
3988 return this.ubus('net', 'iwinfo', 'country') || this.ubus('dev', 'config', 'country') || '00';
3992 * Query the current radio TX power.
3994 * @returns {null|number}
3995 * Returns the wireless network transmit power in dBm as reported by
3996 * `ubus` runtime information or `null` if it cannot be determined.
3998 getTXPower: function() {
3999 return this.ubus('net', 'iwinfo', 'txpower');
4003 * Query the radio TX power offset.
4005 * Some wireless radios have a fixed power offset, e.g. due to the
4006 * use of external amplifiers.
4009 * Returns the wireless network transmit power offset in dBm as reported
4010 * by `ubus` runtime information or `0` if there is no offset, or if it
4011 * cannot be determined.
4013 getTXPowerOffset: function() {
4014 return this.ubus('net', 'iwinfo', 'txpower_offset') || 0;
4018 * Calculate the current signal.
4022 * Returns the calculated signal level, which is the difference between
4023 * noise and signal (SNR), divided by 5.
4025 getSignalLevel: function(signal
, noise
) {
4026 if (this.getActiveBSSID() == '00:00:00:00:00:00')
4029 signal
= signal
|| this.getSignal();
4030 noise
= noise
|| this.getNoise();
4032 if (signal
< 0 && noise
< 0) {
4033 var snr
= -1 * (noise
- signal
);
4034 return Math
.floor(snr
/ 5);
4041 * Calculate the current signal quality percentage.
4044 * Returns the calculated signal quality in percent. The value is
4045 * calculated from the `quality` and `quality_max` indicators reported
4046 * by `ubus` runtime state.
4048 getSignalPercent: function() {
4049 var qc
= this.ubus('net', 'iwinfo', 'quality') || 0,
4050 qm
= this.ubus('net', 'iwinfo', 'quality_max') || 0;
4052 if (qc
> 0 && qm
> 0)
4053 return Math
.floor((100 / qm
) * qc
);
4059 * Get a short description string for this wireless network.
4062 * Returns a string describing this network, consisting of the
4063 * active operation mode, followed by either the SSID, BSSID or
4064 * internal network ID, depending on which information is available.
4066 getShortName: function() {
4067 return '%s "%s"'.format(
4068 this.getActiveModeI18n(),
4069 this.getActiveSSID() || this.getActiveBSSID() || this.getID());
4073 * Get a description string for this wireless network.
4076 * Returns a string describing this network, consisting of the
4077 * term `Wireless Network`, followed by the active operation mode,
4078 * the SSID, BSSID or internal network ID and the Linux network device
4079 * name, depending on which information is available.
4081 getI18n: function() {
4082 return '%s: %s "%s" (%s)'.format(
4083 _('Wireless Network'),
4084 this.getActiveModeI18n(),
4085 this.getActiveSSID() || this.getActiveBSSID() || this.getID(),
4090 * Get the primary logical interface this wireless network is attached to.
4092 * @returns {null|LuCI.network.Protocol}
4093 * Returns a `Network.Protocol` instance representing the logical
4094 * interface or `null` if this network is not attached to any logical
4097 getNetwork: function() {
4098 return this.getNetworks()[0];
4102 * Get the logical interfaces this wireless network is attached to.
4104 * @returns {Array<LuCI.network.Protocol>}
4105 * Returns an array of `Network.Protocol` instances representing the
4106 * logical interfaces this wireless network is attached to.
4108 getNetworks: function() {
4109 var networkNames
= this.getNetworkNames(),
4112 for (var i
= 0; i
< networkNames
.length
; i
++) {
4113 var uciInterface
= uci
.get('network', networkNames
[i
]);
4115 if (uciInterface
== null || uciInterface
['.type'] != 'interface')
4118 networks
.push(Network
.prototype.instantiateNetwork(networkNames
[i
]));
4121 networks
.sort(networkSort
);
4127 * Get the associated Linux network device.
4129 * @returns {LuCI.network.Device}
4130 * Returns a `Network.Device` instance representing the Linux network
4131 * device associted with this wireless network.
4133 getDevice: function() {
4134 return Network
.prototype.instantiateDevice(this.getIfname());
4138 * Check whether this wifi network supports deauthenticating clients.
4140 * @returns {boolean}
4141 * Returns `true` when this wifi network instance supports forcibly
4142 * deauthenticating clients, otherwise `false`.
4144 isClientDisconnectSupported: function() {
4145 return L
.isObject(this.ubus('hostapd', 'del_client'));
4149 * Forcibly disconnect the given client from the wireless network.
4151 * @param {string} mac
4152 * The MAC address of the client to disconnect.
4154 * @param {boolean} [deauth=false]
4155 * Specifies whether to deauthenticate (`true`) or disassociate (`false`)
4158 * @param {number} [reason=1]
4159 * Specifies the IEEE 802.11 reason code to disassoc/deauth the client
4160 * with. Default is `1` which corresponds to `Unspecified reason`.
4162 * @param {number} [ban_time=0]
4163 * Specifies the amount of milliseconds to ban the client from
4164 * reconnecting. By default, no ban time is set which allows the client
4165 * to reassociate / reauthenticate immediately.
4167 * @returns {Promise<number>}
4168 * Returns a promise resolving to the underlying ubus call result code
4169 * which is typically `0`, even for not existing MAC addresses.
4170 * The promise might reject with an error in case invalid arguments
4173 disconnectClient: function(mac
, deauth
, reason
, ban_time
) {
4174 if (reason
== null || reason
== 0)
4180 return rpc
.declare({
4181 object
: 'hostapd.%s'.format(this.getIfname()),
4182 method
: 'del_client',
4183 params
: [ 'addr', 'deauth', 'reason', 'ban_time' ]
4184 })(mac
, deauth
, reason
, ban_time
);