7 CONNECT_FAILED
: _('Connection attempt failed'),
8 INVALID_ADDRESS
: _('IP address is invalid'),
9 INVALID_GATEWAY
: _('Gateway address is invalid'),
10 INVALID_LOCAL_ADDRESS
: _('Local IP address is invalid'),
11 MISSING_ADDRESS
: _('IP address is missing'),
12 MISSING_PEER_ADDRESS
: _('Peer address is missing'),
13 NO_DEVICE
: _('Network device is not present'),
14 NO_IFACE
: _('Unable to determine device name'),
15 NO_IFNAME
: _('Unable to determine device name'),
16 NO_WAN_ADDRESS
: _('Unable to determine external IP address'),
17 NO_WAN_LINK
: _('Unable to determine upstream interface'),
18 PEER_RESOLVE_FAIL
: _('Unable to resolve peer host name'),
19 PIN_FAILED
: _('PIN code rejected')
22 var iface_patterns_ignore
= [
38 var iface_patterns_wireless
= [
45 var iface_patterns_virtual
= [ ];
47 var callLuciNetworkDevices
= rpc
.declare({
49 method
: 'getNetworkDevices',
53 var callLuciWirelessDevices
= rpc
.declare({
55 method
: 'getWirelessDevices',
59 var callLuciBoardJSON
= rpc
.declare({
61 method
: 'getBoardJSON'
64 var callLuciHostHints
= rpc
.declare({
66 method
: 'getHostHints',
70 var callIwinfoAssoclist
= rpc
.declare({
73 params
: [ 'device', 'mac' ],
74 expect
: { results
: [] }
77 var callIwinfoScan
= rpc
.declare({
82 expect
: { results
: [] }
85 var callNetworkInterfaceDump
= rpc
.declare({
86 object
: 'network.interface',
88 expect
: { 'interface': [] }
91 var callNetworkProtoHandlers
= rpc
.declare({
93 method
: 'get_proto_handlers',
102 function getProtocolHandlers(cache
) {
103 return callNetworkProtoHandlers().then(function(protos
) {
104 /* Register "none" protocol */
105 if (!protos
.hasOwnProperty('none'))
106 Object
.assign(protos
, { none
: { no_device
: false } });
108 /* Hack: emulate relayd protocol */
109 if (!protos
.hasOwnProperty('relay'))
110 Object
.assign(protos
, { relay
: { no_device
: true } });
112 Object
.assign(_protospecs
, protos
);
114 return Promise
.all(Object
.keys(protos
).map(function(p
) {
115 return Promise
.resolve(L
.require('protocol.%s'.format(p
))).catch(function(err
) {
116 if (L
.isObject(err
) && err
.name
!= 'NetworkError')
119 })).then(function() {
122 }).catch(function() {
127 function getWifiStateBySid(sid
) {
128 var s
= uci
.get('wireless', sid
);
130 if (s
!= null && s
['.type'] == 'wifi-iface') {
131 for (var radioname
in _state
.radios
) {
132 for (var i
= 0; i
< _state
.radios
[radioname
].interfaces
.length
; i
++) {
133 var netstate
= _state
.radios
[radioname
].interfaces
[i
];
135 if (typeof(netstate
.section
) != 'string')
138 var s2
= uci
.get('wireless', netstate
.section
);
140 if (s2
!= null && s
['.type'] == s2
['.type'] && s
['.name'] == s2
['.name']) {
141 if (s2
['.anonymous'] == false && netstate
.section
.charAt(0) == '@')
144 return [ radioname
, _state
.radios
[radioname
], netstate
];
153 function getWifiStateByIfname(ifname
) {
154 for (var radioname
in _state
.radios
) {
155 for (var i
= 0; i
< _state
.radios
[radioname
].interfaces
.length
; i
++) {
156 var netstate
= _state
.radios
[radioname
].interfaces
[i
];
158 if (typeof(netstate
.ifname
) != 'string')
161 if (netstate
.ifname
== ifname
)
162 return [ radioname
, _state
.radios
[radioname
], netstate
];
169 function isWifiIfname(ifname
) {
170 for (var i
= 0; i
< iface_patterns_wireless
.length
; i
++)
171 if (iface_patterns_wireless
[i
].test(ifname
))
177 function getWifiSidByNetid(netid
) {
178 var m
= /^(\w+)\.network(\d+)$/.exec(netid
);
180 var sections
= uci
.sections('wireless', 'wifi-iface');
181 for (var i
= 0, n
= 0; i
< sections
.length
; i
++) {
182 if (sections
[i
].device
!= m
[1])
186 return sections
[i
]['.name'];
193 function getWifiSidByIfname(ifname
) {
194 var sid
= getWifiSidByNetid(ifname
);
199 var res
= getWifiStateByIfname(ifname
);
201 if (res
!= null && L
.isObject(res
[2]) && typeof(res
[2].section
) == 'string')
202 return res
[2].section
;
207 function getWifiNetidBySid(sid
) {
208 var s
= uci
.get('wireless', sid
);
209 if (s
!= null && s
['.type'] == 'wifi-iface') {
210 var radioname
= s
.device
;
211 if (typeof(s
.device
) == 'string') {
212 var i
= 0, netid
= null, sections
= uci
.sections('wireless', 'wifi-iface');
213 for (var i
= 0, n
= 0; i
< sections
.length
; i
++) {
214 if (sections
[i
].device
!= s
.device
)
219 if (sections
[i
]['.name'] != s
['.name'])
222 return [ '%s.network%d'.format(s
.device
, n
), s
.device
];
231 function getWifiNetidByNetname(name
) {
232 var sections
= uci
.sections('wireless', 'wifi-iface');
233 for (var i
= 0; i
< sections
.length
; i
++) {
234 if (typeof(sections
[i
].network
) != 'string')
237 var nets
= sections
[i
].network
.split(/\s+/);
238 for (var j
= 0; j
< nets
.length
; j
++) {
242 return getWifiNetidBySid(sections
[i
]['.name']);
249 function isVirtualIfname(ifname
) {
250 for (var i
= 0; i
< iface_patterns_virtual
.length
; i
++)
251 if (iface_patterns_virtual
[i
].test(ifname
))
257 function isIgnoredIfname(ifname
) {
258 for (var i
= 0; i
< iface_patterns_ignore
.length
; i
++)
259 if (iface_patterns_ignore
[i
].test(ifname
))
265 function appendValue(config
, section
, option
, value
) {
266 var values
= uci
.get(config
, section
, option
),
267 isArray
= Array
.isArray(values
),
270 if (isArray
== false)
271 values
= L
.toArray(values
);
273 if (values
.indexOf(value
) == -1) {
278 uci
.set(config
, section
, option
, isArray
? values
: values
.join(' '));
283 function removeValue(config
, section
, option
, value
) {
284 var values
= uci
.get(config
, section
, option
),
285 isArray
= Array
.isArray(values
),
288 if (isArray
== false)
289 values
= L
.toArray(values
);
291 for (var i
= values
.length
- 1; i
>= 0; i
--) {
292 if (values
[i
] == value
) {
298 if (values
.length
> 0)
299 uci
.set(config
, section
, option
, isArray
? values
: values
.join(' '));
301 uci
.unset(config
, section
, option
);
306 function prefixToMask(bits
, v6
) {
307 var w
= v6
? 128 : 32,
313 for (var i
= 0; i
< w
/ 16; i
++) {
314 var b
= Math
.min(16, bits
);
315 m
.push((0xffff << (16 - b
)) & 0xffff);
320 return String
.prototype.format
.apply('%x:%x:%x:%x:%x:%x:%x:%x', m
).replace(/:0(?::0)+$/, '::');
322 return '%d.%d.%d.%d'.format(m
[0] >>> 8, m
[0] & 0xff, m
[1] >>> 8, m
[1] & 0xff);
325 function maskToPrefix(mask
, v6
) {
326 var m
= v6
? validation
.parseIPv6(mask
) : validation
.parseIPv4(mask
);
333 for (var i
= 0, z
= false; i
< m
.length
; i
++) {
336 while (!z
&& (m
[i
] & (v6
? 0x8000 : 0x80))) {
337 m
[i
] = (m
[i
] << 1) & (v6
? 0xffff : 0xff);
348 function initNetworkState(refresh
) {
349 if (_state
== null || refresh
) {
350 _init
= _init
|| Promise
.all([
351 L
.resolveDefault(callNetworkInterfaceDump(), []),
352 L
.resolveDefault(callLuciBoardJSON(), {}),
353 L
.resolveDefault(callLuciNetworkDevices(), {}),
354 L
.resolveDefault(callLuciWirelessDevices(), {}),
355 L
.resolveDefault(callLuciHostHints(), {}),
356 getProtocolHandlers(),
357 uci
.load(['network', 'wireless', 'luci'])
358 ]).then(function(data
) {
359 var netifd_ifaces
= data
[0],
360 board_json
= data
[1],
364 isTunnel
: {}, isBridge
: {}, isSwitch
: {}, isWifi
: {},
365 ifaces
: netifd_ifaces
, radios
: data
[3], hosts
: data
[4],
366 netdevs
: {}, bridges
: {}, switches
: {}, hostapd
: {}
369 for (var name
in luci_devs
) {
370 var dev
= luci_devs
[name
];
372 if (isVirtualIfname(name
))
373 s
.isTunnel
[name
] = true;
375 if (!s
.isTunnel
[name
] && isIgnoredIfname(name
))
378 s
.netdevs
[name
] = s
.netdevs
[name
] || {
388 wireless
: dev
.wireless
,
393 if (Array
.isArray(dev
.ipaddrs
))
394 for (var i
= 0; i
< dev
.ipaddrs
.length
; i
++)
395 s
.netdevs
[name
].ipaddrs
.push(dev
.ipaddrs
[i
].address
+ '/' + dev
.ipaddrs
[i
].netmask
);
397 if (Array
.isArray(dev
.ip6addrs
))
398 for (var i
= 0; i
< dev
.ip6addrs
.length
; i
++)
399 s
.netdevs
[name
].ip6addrs
.push(dev
.ip6addrs
[i
].address
+ '/' + dev
.ip6addrs
[i
].netmask
);
402 for (var name
in luci_devs
) {
403 var dev
= luci_devs
[name
];
415 for (var i
= 0; dev
.ports
&& i
< dev
.ports
.length
; i
++) {
416 var subdev
= s
.netdevs
[dev
.ports
[i
]];
421 b
.ifnames
.push(subdev
);
426 s
.isBridge
[name
] = true;
429 if (L
.isObject(board_json
.switch)) {
430 for (var switchname
in board_json
.switch) {
431 var layout
= board_json
.switch[switchname
],
438 if (L
.isObject(layout
) && Array
.isArray(layout
.ports
)) {
439 for (var i
= 0, port
; (port
= layout
.ports
[i
]) != null; i
++) {
440 if (typeof(port
) == 'object' && typeof(port
.num
) == 'number' &&
441 (typeof(port
.role
) == 'string' || typeof(port
.device
) == 'string')) {
444 role
: port
.role
|| 'cpu',
445 index
: (port
.index
!= null) ? port
.index
: port
.num
448 if (port
.device
!= null) {
449 spec
.device
= port
.device
;
450 spec
.tagged
= spec
.need_tag
;
451 netdevs
[port
.num
] = port
.device
;
456 if (port
.role
!= null)
457 nports
[port
.role
] = (nports
[port
.role
] || 0) + 1;
461 ports
.sort(function(a
, b
) {
462 if (a
.role
!= b
.role
)
463 return (a
.role
< b
.role
) ? -1 : 1;
465 return (a
.index
- b
.index
);
468 for (var i
= 0, port
; (port
= ports
[i
]) != null; i
++) {
469 if (port
.role
!= role
) {
475 port
.label
= 'CPU (%s)'.format(port
.device
);
476 else if (nports
[role
] > 1)
477 port
.label
= '%s %d'.format(role
.toUpperCase(), pnum
++);
479 port
.label
= role
.toUpperCase();
485 s
.switches
[switchname
] = {
493 if (L
.isObject(board_json
.dsl
) && L
.isObject(board_json
.dsl
.modem
)) {
494 s
.hasDSLModem
= board_json
.dsl
.modem
;
501 if (L
.isObject(s
.radios
))
502 for (var radio
in s
.radios
)
503 if (L
.isObject(s
.radios
[radio
]) && Array
.isArray(s
.radios
[radio
].interfaces
))
504 for (var i
= 0; i
< s
.radios
[radio
].interfaces
.length
; i
++)
505 if (L
.isObject(s
.radios
[radio
].interfaces
[i
]) && s
.radios
[radio
].interfaces
[i
].ifname
)
506 objects
.push('hostapd.%s'.format(s
.radios
[radio
].interfaces
[i
].ifname
));
508 return (objects
.length
? L
.resolveDefault(rpc
.list
.apply(rpc
, objects
), {}) : Promise
.resolve({})).then(function(res
) {
510 var m
= k
.match(/^hostapd\.(.+)$/);
512 s
.hostapd
[m
[1]] = res
[k
];
520 return (_state
!= null ? Promise
.resolve(_state
) : _init
);
523 function ifnameOf(obj
) {
524 if (obj
instanceof Protocol
)
525 return obj
.getIfname();
526 else if (obj
instanceof Device
)
527 return obj
.getName();
528 else if (obj
instanceof WifiDevice
)
529 return obj
.getName();
530 else if (obj
instanceof WifiNetwork
)
531 return obj
.getIfname();
532 else if (typeof(obj
) == 'string')
533 return obj
.replace(/:.+$/, '');
538 function networkSort(a
, b
) {
539 return a
.getName() > b
.getName();
542 function deviceSort(a
, b
) {
543 var typeWeigth
= { wifi
: 2, alias
: 3 },
544 weightA
= typeWeigth
[a
.getType()] || 1,
545 weightB
= typeWeigth
[b
.getType()] || 1;
547 if (weightA
!= weightB
)
548 return weightA
- weightB
;
550 return a
.getName() > b
.getName();
553 function formatWifiEncryption(enc
) {
554 if (!L
.isObject(enc
))
560 var ciphers
= Array
.isArray(enc
.ciphers
)
561 ? enc
.ciphers
.map(function(c
) { return c
.toUpperCase() }) : [ 'NONE' ];
563 if (Array
.isArray(enc
.wep
)) {
564 var has_open
= false,
567 for (var i
= 0; i
< enc
.wep
.length
; i
++)
568 if (enc
.wep
[i
] == 'open')
570 else if (enc
.wep
[i
] == 'shared')
573 if (has_open
&& has_shared
)
574 return 'WEP Open/Shared (%s)'.format(ciphers
.join(', '));
576 return 'WEP Open System (%s)'.format(ciphers
.join(', '));
578 return 'WEP Shared Auth (%s)'.format(ciphers
.join(', '));
583 if (Array
.isArray(enc
.wpa
)) {
585 suites
= Array
.isArray(enc
.authentication
)
586 ? enc
.authentication
.map(function(a
) { return a
.toUpperCase() }) : [ 'NONE' ];
588 for (var i
= 0; i
< enc
.wpa
.length
; i
++)
589 switch (enc
.wpa
[i
]) {
591 versions
.push('WPA');
595 versions
.push('WPA%d'.format(enc
.wpa
[i
]));
599 if (versions
.length
> 1)
600 return 'mixed %s %s (%s)'.format(versions
.join('/'), suites
.join(', '), ciphers
.join(', '));
602 return '%s %s (%s)'.format(versions
[0], suites
.join(', '), ciphers
.join(', '));
608 function enumerateNetworks() {
609 var uciInterfaces
= uci
.sections('network', 'interface'),
612 for (var i
= 0; i
< uciInterfaces
.length
; i
++)
613 networks
[uciInterfaces
[i
]['.name']] = this.instantiateNetwork(uciInterfaces
[i
]['.name']);
615 for (var i
= 0; i
< _state
.ifaces
.length
; i
++)
616 if (networks
[_state
.ifaces
[i
].interface] == null)
617 networks
[_state
.ifaces
[i
].interface] =
618 this.instantiateNetwork(_state
.ifaces
[i
].interface, _state
.ifaces
[i
].proto
);
622 for (var network
in networks
)
623 if (networks
.hasOwnProperty(network
))
624 rv
.push(networks
[network
]);
626 rv
.sort(networkSort
);
632 var Hosts
, Network
, Protocol
, Device
, WifiDevice
, WifiNetwork
;
640 * The `LuCI.Network` class combines data from multiple `ubus` apis to
641 * provide an abstraction of the current network configuration state.
643 * It provides methods to enumerate interfaces and devices, to query
644 * current configuration details and to manipulate settings.
646 Network
= L
.Class
.extend(/** @lends LuCI.Network.prototype */ {
648 * Converts the given prefix size in bits to a netmask.
652 * @param {number} bits
653 * The prefix size in bits.
655 * @param {boolean} [v6=false]
656 * Whether to convert the bits value into an IPv4 netmask (`false`) or
657 * an IPv6 netmask (`true`).
659 * @returns {null|string}
660 * Returns a string containing the netmask corresponding to the bit count
661 * or `null` when the given amount of bits exceeds the maximum possible
662 * value of `32` for IPv4 or `128` for IPv6.
664 prefixToMask
: prefixToMask
,
667 * Converts the given netmask to a prefix size in bits.
671 * @param {string} netmask
672 * The netmask to convert into a bit count.
674 * @param {boolean} [v6=false]
675 * Whether to parse the given netmask as IPv4 (`false`) or IPv6 (`true`)
678 * @returns {null|number}
679 * Returns the number of prefix bits contained in the netmask or `null`
680 * if the given netmask value was invalid.
682 maskToPrefix
: maskToPrefix
,
685 * An encryption entry describes active wireless encryption settings
686 * such as the used key management protocols, active ciphers and
689 * @typedef {Object<string, boolean|Array<number|string>>} LuCI.Network.WifiEncryption
690 * @memberof LuCI.Network
692 * @property {boolean} enabled
693 * Specifies whether any kind of encryption, such as `WEP` or `WPA` is
694 * enabled. If set to `false`, then no encryption is active and the
695 * corresponding network is open.
697 * @property {string[]} [wep]
698 * When the `wep` property exists, the network uses WEP encryption.
699 * In this case, the property is set to an array of active WEP modes
700 * which might be either `open`, `shared` or both.
702 * @property {number[]} [wpa]
703 * When the `wpa` property exists, the network uses WPA security.
704 * In this case, the property is set to an array containing the WPA
705 * protocol versions used, e.g. `[ 1, 2 ]` for WPA/WPA2 mixed mode or
706 * `[ 3 ]` for WPA3-SAE.
708 * @property {string[]} [authentication]
709 * The `authentication` property only applies to WPA encryption and
710 * is defined when the `wpa` property is set as well. It points to
711 * an array of active authentication suites used by the network, e.g.
712 * `[ "psk" ]` for a WPA(2)-PSK network or `[ "psk", "sae" ]` for
713 * mixed WPA2-PSK/WPA3-SAE encryption.
715 * @property {string[]} [ciphers]
716 * If either WEP or WPA encryption is active, then the `ciphers`
717 * property will be set to an array describing the active encryption
718 * ciphers used by the network, e.g. `[ "tkip", "ccmp" ]` for a
719 * WPA/WPA2-PSK mixed network or `[ "wep-40", "wep-104" ]` for an
724 * Converts a given {@link LuCI.Network.WifiEncryption encryption entry}
725 * into a human readable string such as `mixed WPA/WPA2 PSK (TKIP, CCMP)`
726 * or `WPA3 SAE (CCMP)`.
730 * @param {LuCI.Network.WifiEncryption} encryption
731 * The wireless encryption entry to convert.
733 * @returns {null|string}
734 * Returns the description string for the given encryption entry or
735 * `null` if the given entry was invalid.
737 formatWifiEncryption
: formatWifiEncryption
,
740 * Flushes the local network state cache and fetches updated information
741 * from the remote `ubus` apis.
743 * @returns {Promise<Object>}
744 * Returns a promise resolving to the internal network state object.
746 flushCache: function() {
747 initNetworkState(true);
752 * Instantiates the given {@link LuCI.Network.Protocol Protocol} backend,
753 * optionally using the given network name.
755 * @param {string} protoname
756 * The protocol backend to use, e.g. `static` or `dhcp`.
758 * @param {string} [netname=__dummy__]
759 * The network name to use for the instantiated protocol. This should be
760 * usually set to one of the interfaces described in /etc/config/network
761 * but it is allowed to omit it, e.g. to query protocol capabilities
762 * without the need for an existing interface.
764 * @returns {null|LuCI.Network.Protocol}
765 * Returns the instantiated protocol backend class or `null` if the given
766 * protocol isn't known.
768 getProtocol: function(protoname
, netname
) {
769 var v
= _protocols
[protoname
];
771 return new v(netname
|| '__dummy__');
777 * Obtains instances of all known {@link LuCI.Network.Protocol Protocol}
780 * @returns {Array<LuCI.Network.Protocol>}
781 * Returns an array of protocol class instances.
783 getProtocols: function() {
786 for (var protoname
in _protocols
)
787 rv
.push(new _protocols
[protoname
]('__dummy__'));
793 * Registers a new {@link LuCI.Network.Protocol Protocol} subclass
794 * with the given methods and returns the resulting subclass value.
796 * This functions internally calls
797 * {@link LuCI.Class.extend Class.extend()} on the `Network.Protocol`
800 * @param {string} protoname
801 * The name of the new protocol to register.
803 * @param {Object<string, *>} methods
804 * The member methods and values of the new `Protocol` subclass to
805 * be passed to {@link LuCI.Class.extend Class.extend()}.
807 * @returns {LuCI.Network.Protocol}
808 * Returns the new `Protocol` subclass.
810 registerProtocol: function(protoname
, methods
) {
811 var spec
= L
.isObject(_protospecs
) ? _protospecs
[protoname
] : null;
812 var proto
= Protocol
.extend(Object
.assign({
813 getI18n: function() {
817 isFloating: function() {
821 isVirtual: function() {
822 return (L
.isObject(spec
) && spec
.no_device
== true);
825 renderFormOptions: function(section
) {
829 __init__: function(name
) {
833 getProtocol: function() {
838 _protocols
[protoname
] = proto
;
844 * Registers a new regular expression pattern to recognize
845 * virtual interfaces.
847 * @param {RegExp} pat
848 * A `RegExp` instance to match a virtual interface name
849 * such as `6in4-wan` or `tun0`.
851 registerPatternVirtual: function(pat
) {
852 iface_patterns_virtual
.push(pat
);
856 * Registers a new human readable translation string for a `Protocol`
859 * @param {string} code
860 * The `ubus` protocol error code to register a translation for, e.g.
863 * @param {string} message
864 * The message to use as translation for the given protocol error code.
867 * Returns `true` if the error code description has been added or `false`
868 * if either the arguments were invalid or if there already was a
869 * description for the given code.
871 registerErrorCode: function(code
, message
) {
872 if (typeof(code
) == 'string' &&
873 typeof(message
) == 'string' &&
874 !proto_errors
.hasOwnProperty(code
)) {
875 proto_errors
[code
] = message
;
883 * Adds a new network of the given name and update it with the given
886 * If a network with the given name already exist but is empty, then
887 * this function will update its option, otherwise it will do nothing.
889 * @param {string} name
890 * The name of the network to add. Must be in the format `[a-zA-Z0-9_]+`.
892 * @param {Object<string, string|string[]>} [options]
893 * An object of uci option values to set on the new network or to
894 * update in an existing, empty network.
896 * @returns {Promise<null|LuCI.Network.Protocol>}
897 * Returns a promise resolving to the `Protocol` subclass instance
898 * describing the added network or resolving to `null` if the name
899 * was invalid or if a non-empty network of the given name already
902 addNetwork: function(name
, options
) {
903 return this.getNetwork(name
).then(L
.bind(function(existingNetwork
) {
904 if (name
!= null && /^[a-zA-Z0-9_]+$/.test(name
) && existingNetwork
== null) {
905 var sid
= uci
.add('network', 'interface', name
);
908 if (L
.isObject(options
))
909 for (var key
in options
)
910 if (options
.hasOwnProperty(key
))
911 uci
.set('network', sid
, key
, options
[key
]);
913 return this.instantiateNetwork(sid
);
916 else if (existingNetwork
!= null && existingNetwork
.isEmpty()) {
917 if (L
.isObject(options
))
918 for (var key
in options
)
919 if (options
.hasOwnProperty(key
))
920 existingNetwork
.set(key
, options
[key
]);
922 return existingNetwork
;
928 * Get a {@link LuCI.Network.Protocol Protocol} instance describing
929 * the network with the given name.
931 * @param {string} name
932 * The logical interface name of the network get, e.g. `lan` or `wan`.
934 * @returns {Promise<null|LuCI.Network.Protocol>}
935 * Returns a promise resolving to a
936 * {@link LuCI.Network.Protocol Protocol} subclass instance describing
937 * the network or `null` if the network did not exist.
939 getNetwork: function(name
) {
940 return initNetworkState().then(L
.bind(function() {
941 var section
= (name
!= null) ? uci
.get('network', name
) : null;
943 if (section
!= null && section
['.type'] == 'interface') {
944 return this.instantiateNetwork(name
);
946 else if (name
!= null) {
947 for (var i
= 0; i
< _state
.ifaces
.length
; i
++)
948 if (_state
.ifaces
[i
].interface == name
)
949 return this.instantiateNetwork(name
, _state
.ifaces
[i
].proto
);
957 * Gets an array containing all known networks.
959 * @returns {Promise<Array<LuCI.Network.Protocol>>}
960 * Returns a promise resolving to a name-sorted array of
961 * {@link LuCI.Network.Protocol Protocol} subclass instances
962 * describing all known networks.
964 getNetworks: function() {
965 return initNetworkState().then(L
.bind(enumerateNetworks
, this));
969 * Deletes the given network and its references from the network and
970 * firewall configuration.
972 * @param {string} name
973 * The name of the network to delete.
975 * @returns {Promise<boolean>}
976 * Returns a promise resolving to either `true` if the network and
977 * references to it were successfully deleted from the configuration or
978 * `false` if the given network could not be found.
980 deleteNetwork: function(name
) {
981 var requireFirewall
= Promise
.resolve(L
.require('firewall')).catch(function() {});
983 return Promise
.all([ requireFirewall
, initNetworkState() ]).then(function() {
984 var uciInterface
= uci
.get('network', name
);
986 if (uciInterface
!= null && uciInterface
['.type'] == 'interface') {
987 uci
.remove('network', name
);
989 uci
.sections('luci', 'ifstate', function(s
) {
990 if (s
.interface == name
)
991 uci
.remove('luci', s
['.name']);
994 uci
.sections('network', 'alias', function(s
) {
995 if (s
.interface == name
)
996 uci
.remove('network', s
['.name']);
999 uci
.sections('network', 'route', function(s
) {
1000 if (s
.interface == name
)
1001 uci
.remove('network', s
['.name']);
1004 uci
.sections('network', 'route6', function(s
) {
1005 if (s
.interface == name
)
1006 uci
.remove('network', s
['.name']);
1009 uci
.sections('wireless', 'wifi-iface', function(s
) {
1010 var networks
= L
.toArray(s
.network
).filter(function(network
) { return network
!= name
});
1012 if (networks
.length
> 0)
1013 uci
.set('wireless', s
['.name'], 'network', networks
.join(' '));
1015 uci
.unset('wireless', s
['.name'], 'network');
1019 return L
.firewall
.deleteNetwork(name
).then(function() { return true });
1029 * Rename the given network and its references to a new name.
1031 * @param {string} oldName
1032 * The current name of the network.
1034 * @param {string} newName
1035 * The name to rename the network to, must be in the format
1038 * @returns {Promise<boolean>}
1039 * Returns a promise resolving to either `true` if the network was
1040 * successfully renamed or `false` if the new name was invalid, if
1041 * a network with the new name already exists or if the network to
1042 * rename could not be found.
1044 renameNetwork: function(oldName
, newName
) {
1045 return initNetworkState().then(function() {
1046 if (newName
== null || !/^[a-zA-Z0-9_]+$/.test(newName
) || uci
.get('network', newName
) != null)
1049 var oldNetwork
= uci
.get('network', oldName
);
1051 if (oldNetwork
== null || oldNetwork
['.type'] != 'interface')
1054 var sid
= uci
.add('network', 'interface', newName
);
1056 for (var key
in oldNetwork
)
1057 if (oldNetwork
.hasOwnProperty(key
) && key
.charAt(0) != '.')
1058 uci
.set('network', sid
, key
, oldNetwork
[key
]);
1060 uci
.sections('luci', 'ifstate', function(s
) {
1061 if (s
.interface == oldName
)
1062 uci
.set('luci', s
['.name'], 'interface', newName
);
1065 uci
.sections('network', 'alias', function(s
) {
1066 if (s
.interface == oldName
)
1067 uci
.set('network', s
['.name'], 'interface', newName
);
1070 uci
.sections('network', 'route', function(s
) {
1071 if (s
.interface == oldName
)
1072 uci
.set('network', s
['.name'], 'interface', newName
);
1075 uci
.sections('network', 'route6', function(s
) {
1076 if (s
.interface == oldName
)
1077 uci
.set('network', s
['.name'], 'interface', newName
);
1080 uci
.sections('wireless', 'wifi-iface', function(s
) {
1081 var networks
= L
.toArray(s
.network
).map(function(network
) { return (network
== oldName
? newName
: network
) });
1083 if (networks
.length
> 0)
1084 uci
.set('wireless', s
['.name'], 'network', networks
.join(' '));
1087 uci
.remove('network', oldName
);
1094 * Get a {@link LuCI.Network.Device Device} instance describing the
1095 * given network device.
1097 * @param {string} name
1098 * The name of the network device to get, e.g. `eth0` or `br-lan`.
1100 * @returns {Promise<null|LuCI.Network.Device>}
1101 * Returns a promise resolving to the `Device` instance describing
1102 * the network device or `null` if the given device name could not
1105 getDevice: function(name
) {
1106 return initNetworkState().then(L
.bind(function() {
1110 if (_state
.netdevs
.hasOwnProperty(name
) || isWifiIfname(name
))
1111 return this.instantiateDevice(name
);
1113 var netid
= getWifiNetidBySid(name
);
1115 return this.instantiateDevice(netid
[0]);
1122 * Get a sorted list of all found network devices.
1124 * @returns {Promise<Array<LuCI.Network.Device>>}
1125 * Returns a promise resolving to a sorted array of `Device` class
1126 * instances describing the network devices found on the system.
1128 getDevices: function() {
1129 return initNetworkState().then(L
.bind(function() {
1132 /* find simple devices */
1133 var uciInterfaces
= uci
.sections('network', 'interface');
1134 for (var i
= 0; i
< uciInterfaces
.length
; i
++) {
1135 var ifnames
= L
.toArray(uciInterfaces
[i
].ifname
);
1137 for (var j
= 0; j
< ifnames
.length
; j
++) {
1138 if (ifnames
[j
].charAt(0) == '@')
1141 if (isIgnoredIfname(ifnames
[j
]) || isVirtualIfname(ifnames
[j
]) || isWifiIfname(ifnames
[j
]))
1144 devices
[ifnames
[j
]] = this.instantiateDevice(ifnames
[j
]);
1148 for (var ifname
in _state
.netdevs
) {
1149 if (devices
.hasOwnProperty(ifname
))
1152 if (isIgnoredIfname(ifname
) || isWifiIfname(ifname
))
1155 if (_state
.netdevs
[ifname
].wireless
)
1158 devices
[ifname
] = this.instantiateDevice(ifname
);
1161 /* find VLAN devices */
1162 var uciSwitchVLANs
= uci
.sections('network', 'switch_vlan');
1163 for (var i
= 0; i
< uciSwitchVLANs
.length
; i
++) {
1164 if (typeof(uciSwitchVLANs
[i
].ports
) != 'string' ||
1165 typeof(uciSwitchVLANs
[i
].device
) != 'string' ||
1166 !_state
.switches
.hasOwnProperty(uciSwitchVLANs
[i
].device
))
1169 var ports
= uciSwitchVLANs
[i
].ports
.split(/\s+/);
1170 for (var j
= 0; j
< ports
.length
; j
++) {
1171 var m
= ports
[j
].match(/^(\d+)([tu]?)$/);
1175 var netdev
= _state
.switches
[uciSwitchVLANs
[i
].device
].netdevs
[m
[1]];
1179 if (!devices
.hasOwnProperty(netdev
))
1180 devices
[netdev
] = this.instantiateDevice(netdev
);
1182 _state
.isSwitch
[netdev
] = true;
1187 var vid
= uciSwitchVLANs
[i
].vid
|| uciSwitchVLANs
[i
].vlan
;
1188 vid
= (vid
!= null ? +vid
: null);
1190 if (vid
== null || vid
< 0 || vid
> 4095)
1193 var vlandev
= '%s.%d'.format(netdev
, vid
);
1195 if (!devices
.hasOwnProperty(vlandev
))
1196 devices
[vlandev
] = this.instantiateDevice(vlandev
);
1198 _state
.isSwitch
[vlandev
] = true;
1202 /* find wireless interfaces */
1203 var uciWifiIfaces
= uci
.sections('wireless', 'wifi-iface'),
1206 for (var i
= 0; i
< uciWifiIfaces
.length
; i
++) {
1207 if (typeof(uciWifiIfaces
[i
].device
) != 'string')
1210 networkCount
[uciWifiIfaces
[i
].device
] = (networkCount
[uciWifiIfaces
[i
].device
] || 0) + 1;
1212 var netid
= '%s.network%d'.format(uciWifiIfaces
[i
].device
, networkCount
[uciWifiIfaces
[i
].device
]);
1214 devices
[netid
] = this.instantiateDevice(netid
);
1219 for (var netdev
in devices
)
1220 if (devices
.hasOwnProperty(netdev
))
1221 rv
.push(devices
[netdev
]);
1223 rv
.sort(deviceSort
);
1230 * Test if a given network device name is in the list of patterns for
1231 * device names to ignore.
1233 * Ignored device names are usually Linux network devices which are
1234 * spawned implicitly by kernel modules such as `tunl0` or `hwsim0`
1235 * and which are unsuitable for use in network configuration.
1237 * @param {string} name
1238 * The device name to test.
1240 * @returns {boolean}
1241 * Returns `true` if the given name is in the ignore pattern list,
1242 * else returns `false`.
1244 isIgnoredDevice: function(name
) {
1245 return isIgnoredIfname(name
);
1249 * Get a {@link LuCI.Network.WifiDevice WifiDevice} instance describing
1250 * the given wireless radio.
1252 * @param {string} devname
1253 * The configuration name of the wireless radio to lookup, e.g. `radio0`
1254 * for the first mac80211 phy on the system.
1256 * @returns {Promise<null|LuCI.Network.WifiDevice>}
1257 * Returns a promise resolving to the `WifiDevice` instance describing
1258 * the underlying radio device or `null` if the wireless radio could not
1261 getWifiDevice: function(devname
) {
1262 return initNetworkState().then(L
.bind(function() {
1263 var existingDevice
= uci
.get('wireless', devname
);
1265 if (existingDevice
== null || existingDevice
['.type'] != 'wifi-device')
1268 return this.instantiateWifiDevice(devname
, _state
.radios
[devname
] || {});
1273 * Obtain a list of all configured radio devices.
1275 * @returns {Promise<Array<LuCI.Network.WifiDevice>>}
1276 * Returns a promise resolving to an array of `WifiDevice` instances
1277 * describing the wireless radios configured in the system.
1278 * The order of the array corresponds to the order of the radios in
1279 * the configuration.
1281 getWifiDevices: function() {
1282 return initNetworkState().then(L
.bind(function() {
1283 var uciWifiDevices
= uci
.sections('wireless', 'wifi-device'),
1286 for (var i
= 0; i
< uciWifiDevices
.length
; i
++) {
1287 var devname
= uciWifiDevices
[i
]['.name'];
1288 rv
.push(this.instantiateWifiDevice(devname
, _state
.radios
[devname
] || {}));
1296 * Get a {@link LuCI.Network.WifiNetwork WifiNetwork} instance describing
1297 * the given wireless network.
1299 * @param {string} netname
1300 * The name of the wireless network to lookup. This may be either an uci
1301 * configuration section ID, a network ID in the form `radio#.network#`
1302 * or a Linux network device name like `wlan0` which is resolved to the
1303 * corresponding configuration section through `ubus` runtime information.
1305 * @returns {Promise<null|LuCI.Network.WifiNetwork>}
1306 * Returns a promise resolving to the `WifiNetwork` instance describing
1307 * the wireless network or `null` if the corresponding network could not
1310 getWifiNetwork: function(netname
) {
1311 return initNetworkState()
1312 .then(L
.bind(this.lookupWifiNetwork
, this, netname
));
1316 * Get an array of all {@link LuCI.Network.WifiNetwork WifiNetwork}
1317 * instances describing the wireless networks present on the system.
1319 * @returns {Promise<Array<LuCI.Network.WifiNetwork>>}
1320 * Returns a promise resolving to an array of `WifiNetwork` instances
1321 * describing the wireless networks. The array will be empty if no networks
1324 getWifiNetworks: function() {
1325 return initNetworkState().then(L
.bind(function() {
1326 var wifiIfaces
= uci
.sections('wireless', 'wifi-iface'),
1329 for (var i
= 0; i
< wifiIfaces
.length
; i
++)
1330 rv
.push(this.lookupWifiNetwork(wifiIfaces
[i
]['.name']));
1332 rv
.sort(function(a
, b
) {
1333 return (a
.getID() > b
.getID());
1341 * Adds a new wireless network to the configuration and sets its options
1342 * to the provided values.
1344 * @param {Object<string, string|string[]>} options
1345 * The options to set for the newly added wireless network. This object
1346 * must at least contain a `device` property which is set to the radio
1347 * name the new network belongs to.
1349 * @returns {Promise<null|LuCI.Network.WifiNetwork>}
1350 * Returns a promise resolving to a `WifiNetwork` instance describing
1351 * the newly added wireless network or `null` if the given options
1352 * were invalid or if the associated radio device could not be found.
1354 addWifiNetwork: function(options
) {
1355 return initNetworkState().then(L
.bind(function() {
1356 if (options
== null ||
1357 typeof(options
) != 'object' ||
1358 typeof(options
.device
) != 'string')
1361 var existingDevice
= uci
.get('wireless', options
.device
);
1362 if (existingDevice
== null || existingDevice
['.type'] != 'wifi-device')
1365 /* XXX: need to add a named section (wifinet#) here */
1366 var sid
= uci
.add('wireless', 'wifi-iface');
1367 for (var key
in options
)
1368 if (options
.hasOwnProperty(key
))
1369 uci
.set('wireless', sid
, key
, options
[key
]);
1371 var radioname
= existingDevice
['.name'],
1372 netid
= getWifiNetidBySid(sid
) || [];
1374 return this.instantiateWifiNetwork(sid
, radioname
, _state
.radios
[radioname
], netid
[0], null);
1379 * Deletes the given wireless network from the configuration.
1381 * @param {string} netname
1382 * The name of the network to remove. This may be either a
1383 * network ID in the form `radio#.network#` or a Linux network device
1384 * name like `wlan0` which is resolved to the corresponding configuration
1385 * section through `ubus` runtime information.
1387 * @returns {Promise<boolean>}
1388 * Returns a promise resolving to `true` if the wireless network has been
1389 * successfully deleted from the configuration or `false` if it could not
1392 deleteWifiNetwork: function(netname
) {
1393 return initNetworkState().then(L
.bind(function() {
1394 var sid
= getWifiSidByIfname(netname
);
1399 uci
.remove('wireless', sid
);
1405 getStatusByRoute: function(addr
, mask
) {
1406 return initNetworkState().then(L
.bind(function() {
1409 for (var i
= 0; i
< _state
.ifaces
.length
; i
++) {
1410 if (!Array
.isArray(_state
.ifaces
[i
].route
))
1413 for (var j
= 0; j
< _state
.ifaces
[i
].route
.length
; j
++) {
1414 if (typeof(_state
.ifaces
[i
].route
[j
]) != 'object' ||
1415 typeof(_state
.ifaces
[i
].route
[j
].target
) != 'string' ||
1416 typeof(_state
.ifaces
[i
].route
[j
].mask
) != 'number')
1419 if (_state
.ifaces
[i
].route
[j
].table
)
1422 if (_state
.ifaces
[i
].route
[j
].target
!= addr
||
1423 _state
.ifaces
[i
].route
[j
].mask
!= mask
)
1426 rv
.push(_state
.ifaces
[i
]);
1435 getStatusByAddress: function(addr
) {
1436 return initNetworkState().then(L
.bind(function() {
1439 for (var i
= 0; i
< _state
.ifaces
.length
; i
++) {
1440 if (Array
.isArray(_state
.ifaces
[i
]['ipv4-address']))
1441 for (var j
= 0; j
< _state
.ifaces
[i
]['ipv4-address'].length
; j
++)
1442 if (typeof(_state
.ifaces
[i
]['ipv4-address'][j
]) == 'object' &&
1443 _state
.ifaces
[i
]['ipv4-address'][j
].address
== addr
)
1444 return _state
.ifaces
[i
];
1446 if (Array
.isArray(_state
.ifaces
[i
]['ipv6-address']))
1447 for (var j
= 0; j
< _state
.ifaces
[i
]['ipv6-address'].length
; j
++)
1448 if (typeof(_state
.ifaces
[i
]['ipv6-address'][j
]) == 'object' &&
1449 _state
.ifaces
[i
]['ipv6-address'][j
].address
== addr
)
1450 return _state
.ifaces
[i
];
1452 if (Array
.isArray(_state
.ifaces
[i
]['ipv6-prefix-assignment']))
1453 for (var j
= 0; j
< _state
.ifaces
[i
]['ipv6-prefix-assignment'].length
; j
++)
1454 if (typeof(_state
.ifaces
[i
]['ipv6-prefix-assignment'][j
]) == 'object' &&
1455 typeof(_state
.ifaces
[i
]['ipv6-prefix-assignment'][j
]['local-address']) == 'object' &&
1456 _state
.ifaces
[i
]['ipv6-prefix-assignment'][j
]['local-address'].address
== addr
)
1457 return _state
.ifaces
[i
];
1465 * Get IPv4 wan networks.
1467 * This function looks up all networks having a default `0.0.0.0/0` route
1468 * and returns them as array.
1470 * @returns {Promise<Array<LuCI.Network.Protocol>>}
1471 * Returns a promise resolving to an array of `Protocol` subclass
1472 * instances describing the found default route interfaces.
1474 getWANNetworks: function() {
1475 return this.getStatusByRoute('0.0.0.0', 0).then(L
.bind(function(statuses
) {
1476 var rv
= [], seen
= {};
1478 for (var i
= 0; i
< statuses
.length
; i
++) {
1479 if (!seen
.hasOwnProperty(statuses
[i
].interface)) {
1480 rv
.push(this.instantiateNetwork(statuses
[i
].interface, statuses
[i
].proto
));
1481 seen
[statuses
[i
].interface] = true;
1490 * Get IPv6 wan networks.
1492 * This function looks up all networks having a default `::/0` route
1493 * and returns them as array.
1495 * @returns {Promise<Array<LuCI.Network.Protocol>>}
1496 * Returns a promise resolving to an array of `Protocol` subclass
1497 * instances describing the found IPv6 default route interfaces.
1499 getWAN6Networks: function() {
1500 return this.getStatusByRoute('::', 0).then(L
.bind(function(statuses
) {
1501 var rv
= [], seen
= {};
1503 for (var i
= 0; i
< statuses
.length
; i
++) {
1504 if (!seen
.hasOwnProperty(statuses
[i
].interface)) {
1505 rv
.push(this.instantiateNetwork(statuses
[i
].interface, statuses
[i
].proto
));
1506 seen
[statuses
[i
].interface] = true;
1515 * Describes an swconfig switch topology by specifying the CPU
1516 * connections and external port labels of a switch.
1518 * @typedef {Object<string, Object|Array>} SwitchTopology
1519 * @memberof LuCI.Network
1521 * @property {Object<number, string>} netdevs
1522 * The `netdevs` property points to an object describing the CPU port
1523 * connections of the switch. The numeric key of the enclosed object is
1524 * the port number, the value contains the Linux network device name the
1525 * port is hardwired to.
1527 * @property {Array<Object<string, boolean|number|string>>} ports
1528 * The `ports` property points to an array describing the populated
1529 * ports of the switch in the external label order. Each array item is
1530 * an object containg the following keys:
1531 * - `num` - the internal switch port number
1532 * - `label` - the label of the port, e.g. `LAN 1` or `CPU (eth0)`
1533 * - `device` - the connected Linux network device name (CPU ports only)
1534 * - `tagged` - a boolean indicating whether the port must be tagged to
1535 * function (CPU ports only)
1539 * Returns the topologies of all swconfig switches found on the system.
1541 * @returns {Promise<Object<string, LuCI.Network.SwitchTopology>>}
1542 * Returns a promise resolving to an object containing the topologies
1543 * of each switch. The object keys correspond to the name of the switches
1544 * such as `switch0`, the values are
1545 * {@link LuCI.Network.SwitchTopology SwitchTopology} objects describing
1548 getSwitchTopologies: function() {
1549 return initNetworkState().then(function() {
1550 return _state
.switches
;
1555 instantiateNetwork: function(name
, proto
) {
1559 proto
= (proto
== null ? uci
.get('network', name
, 'proto') : proto
);
1561 var protoClass
= _protocols
[proto
] || Protocol
;
1562 return new protoClass(name
);
1566 instantiateDevice: function(name
, network
, extend
) {
1568 return new (Device
.extend(extend
))(name
, network
);
1570 return new Device(name
, network
);
1574 instantiateWifiDevice: function(radioname
, radiostate
) {
1575 return new WifiDevice(radioname
, radiostate
);
1579 instantiateWifiNetwork: function(sid
, radioname
, radiostate
, netid
, netstate
, hostapd
) {
1580 return new WifiNetwork(sid
, radioname
, radiostate
, netid
, netstate
, hostapd
);
1584 lookupWifiNetwork: function(netname
) {
1585 var sid
, res
, netid
, radioname
, radiostate
, netstate
;
1587 sid
= getWifiSidByNetid(netname
);
1590 res
= getWifiStateBySid(sid
);
1592 radioname
= res
? res
[0] : null;
1593 radiostate
= res
? res
[1] : null;
1594 netstate
= res
? res
[2] : null;
1597 res
= getWifiStateByIfname(netname
);
1601 radiostate
= res
[1];
1603 sid
= netstate
.section
;
1604 netid
= L
.toArray(getWifiNetidBySid(sid
))[0];
1607 res
= getWifiStateBySid(netname
);
1611 radiostate
= res
[1];
1614 netid
= L
.toArray(getWifiNetidBySid(sid
))[0];
1617 res
= getWifiNetidBySid(netname
);
1628 return this.instantiateWifiNetwork(sid
|| netname
, radioname
,
1629 radiostate
, netid
, netstate
,
1630 netstate
? _state
.hostapd
[netstate
.ifname
] : null);
1634 * Obtains the the network device name of the given object.
1636 * @param {LuCI.Network.Protocol|LuCI.Network.Device|LuCI.Network.WifiDevice|LuCI.Network.WifiNetwork|string} obj
1637 * The object to get the device name from.
1639 * @returns {null|string}
1640 * Returns a string containing the device name or `null` if the given
1641 * object could not be converted to a name.
1643 getIfnameOf: function(obj
) {
1644 return ifnameOf(obj
);
1648 * Queries the internal DSL modem type from board information.
1650 * @returns {Promise<null|string>}
1651 * Returns a promise resolving to the type of the internal modem
1652 * (e.g. `vdsl`) or to `null` if no internal modem is present.
1654 getDSLModemType: function() {
1655 return initNetworkState().then(function() {
1656 return _state
.hasDSLModem
? _state
.hasDSLModem
.type
: null;
1661 * Queries aggregated information about known hosts.
1663 * This function aggregates information from various sources such as
1664 * DHCP lease databases, ARP and IPv6 neighbour entries, wireless
1665 * association list etc. and returns a {@link LuCI.Network.Hosts Hosts}
1666 * class instance describing the found hosts.
1668 * @returns {Promise<LuCI.Network.Hosts>}
1669 * Returns a `Hosts` instance describing host known on the system.
1671 getHostHints: function() {
1672 return initNetworkState().then(function() {
1673 return new Hosts(_state
.hosts
);
1680 * @memberof LuCI.Network
1684 * The `LuCI.Network.Hosts` class encapsulates host information aggregated
1685 * from multiple sources and provides convenience functions to access the
1686 * host information by different criteria.
1688 Hosts
= L
.Class
.extend(/** @lends LuCI.Network.Hosts.prototype */ {
1689 __init__: function(hosts
) {
1694 * Lookup the hostname associated with the given MAC address.
1696 * @param {string} mac
1697 * The MAC address to lookup.
1699 * @returns {null|string}
1700 * Returns the hostname associated with the given MAC or `null` if
1701 * no matching host could be found or if no hostname is known for
1702 * the corresponding host.
1704 getHostnameByMACAddr: function(mac
) {
1705 return this.hosts
[mac
] ? this.hosts
[mac
].name
: null;
1709 * Lookup the IPv4 address associated with the given MAC address.
1711 * @param {string} mac
1712 * The MAC address to lookup.
1714 * @returns {null|string}
1715 * Returns the IPv4 address associated with the given MAC or `null` if
1716 * no matching host could be found or if no IPv4 address is known for
1717 * the corresponding host.
1719 getIPAddrByMACAddr: function(mac
) {
1720 return this.hosts
[mac
] ? this.hosts
[mac
].ipv4
: null;
1724 * Lookup the IPv6 address associated with the given MAC address.
1726 * @param {string} mac
1727 * The MAC address to lookup.
1729 * @returns {null|string}
1730 * Returns the IPv6 address associated with the given MAC or `null` if
1731 * no matching host could be found or if no IPv6 address is known for
1732 * the corresponding host.
1734 getIP6AddrByMACAddr: function(mac
) {
1735 return this.hosts
[mac
] ? this.hosts
[mac
].ipv6
: null;
1739 * Lookup the hostname associated with the given IPv4 address.
1741 * @param {string} ipaddr
1742 * The IPv4 address to lookup.
1744 * @returns {null|string}
1745 * Returns the hostname associated with the given IPv4 or `null` if
1746 * no matching host could be found or if no hostname is known for
1747 * the corresponding host.
1749 getHostnameByIPAddr: function(ipaddr
) {
1750 for (var mac
in this.hosts
)
1751 if (this.hosts
[mac
].ipv4
== ipaddr
&& this.hosts
[mac
].name
!= null)
1752 return this.hosts
[mac
].name
;
1757 * Lookup the MAC address associated with the given IPv4 address.
1759 * @param {string} ipaddr
1760 * The IPv4 address to lookup.
1762 * @returns {null|string}
1763 * Returns the MAC address associated with the given IPv4 or `null` if
1764 * no matching host could be found or if no MAC address is known for
1765 * the corresponding host.
1767 getMACAddrByIPAddr: function(ipaddr
) {
1768 for (var mac
in this.hosts
)
1769 if (this.hosts
[mac
].ipv4
== ipaddr
)
1775 * Lookup the hostname associated with the given IPv6 address.
1777 * @param {string} ipaddr
1778 * The IPv6 address to lookup.
1780 * @returns {null|string}
1781 * Returns the hostname associated with the given IPv6 or `null` if
1782 * no matching host could be found or if no hostname is known for
1783 * the corresponding host.
1785 getHostnameByIP6Addr: function(ip6addr
) {
1786 for (var mac
in this.hosts
)
1787 if (this.hosts
[mac
].ipv6
== ip6addr
&& this.hosts
[mac
].name
!= null)
1788 return this.hosts
[mac
].name
;
1793 * Lookup the MAC address associated with the given IPv6 address.
1795 * @param {string} ipaddr
1796 * The IPv6 address to lookup.
1798 * @returns {null|string}
1799 * Returns the MAC address associated with the given IPv6 or `null` if
1800 * no matching host could be found or if no MAC address is known for
1801 * the corresponding host.
1803 getMACAddrByIP6Addr: function(ip6addr
) {
1804 for (var mac
in this.hosts
)
1805 if (this.hosts
[mac
].ipv6
== ip6addr
)
1811 * Return an array of (MAC address, name hint) tuples sorted by
1814 * @param {boolean} [preferIp6=false]
1815 * Whether to prefer IPv6 addresses (`true`) or IPv4 addresses (`false`)
1816 * as name hint when no hostname is known for a specific MAC address.
1818 * @returns {Array<Array<string>>}
1819 * Returns an array of arrays containing a name hint for each found
1820 * MAC address on the system. The array is sorted ascending by MAC.
1822 * Each item of the resulting array is a two element array with the
1823 * MAC being the first element and the name hint being the second
1824 * element. The name hint is either the hostname, an IPv4 or an IPv6
1825 * address related to the MAC address.
1827 * If no hostname but both IPv4 and IPv6 addresses are known, the
1828 * `preferIP6` flag specifies whether the IPv6 or the IPv4 address
1831 getMACHints: function(preferIp6
) {
1833 for (var mac
in this.hosts
) {
1834 var hint
= this.hosts
[mac
].name
||
1835 this.hosts
[mac
][preferIp6
? 'ipv6' : 'ipv4'] ||
1836 this.hosts
[mac
][preferIp6
? 'ipv4' : 'ipv6'];
1838 rv
.push([mac
, hint
]);
1840 return rv
.sort(function(a
, b
) { return a
[0] > b
[0] });
1846 * @memberof LuCI.Network
1850 * The `Network.Protocol` class serves as base for protocol specific
1851 * subclasses which describe logical UCI networks defined by `config
1852 * interface` sections in `/etc/config/network`.
1854 Protocol
= L
.Class
.extend(/** @lends LuCI.Network.Protocol.prototype */ {
1855 __init__: function(name
) {
1859 _get: function(opt
) {
1860 var val
= uci
.get('network', this.sid
, opt
);
1862 if (Array
.isArray(val
))
1863 return val
.join(' ');
1868 _ubus: function(field
) {
1869 for (var i
= 0; i
< _state
.ifaces
.length
; i
++) {
1870 if (_state
.ifaces
[i
].interface != this.sid
)
1873 return (field
!= null ? _state
.ifaces
[i
][field
] : _state
.ifaces
[i
]);
1878 * Read the given UCI option value of this network.
1880 * @param {string} opt
1881 * The UCI option name to read.
1883 * @returns {null|string|string[]}
1884 * Returns the UCI option value or `null` if the requested option is
1887 get: function(opt
) {
1888 return uci
.get('network', this.sid
, opt
);
1892 * Set the given UCI option of this network to the given value.
1894 * @param {string} opt
1895 * The name of the UCI option to set.
1897 * @param {null|string|string[]} val
1898 * The value to set or `null` to remove the given option from the
1901 set: function(opt
, val
) {
1902 return uci
.set('network', this.sid
, opt
, val
);
1906 * Get the associared Linux network device of this network.
1908 * @returns {null|string}
1909 * Returns the name of the associated network device or `null` if
1910 * it could not be determined.
1912 getIfname: function() {
1915 if (this.isFloating())
1916 ifname
= this._ubus('l3_device');
1918 ifname
= this._ubus('device') || this._ubus('l3_device');
1923 var res
= getWifiNetidByNetname(this.sid
);
1924 return (res
!= null ? res
[0] : null);
1928 * Get the name of this network protocol class.
1930 * This function will be overwritten by subclasses created by
1931 * {@link LuCI.Network#registerProtocol Network.registerProtocol()}.
1935 * Returns the name of the network protocol implementation, e.g.
1936 * `static` or `dhcp`.
1938 getProtocol: function() {
1943 * Return a human readable description for the protcol, such as
1944 * `Static address` or `DHCP client`.
1946 * This function should be overwritten by subclasses.
1950 * Returns the description string.
1952 getI18n: function() {
1953 switch (this.getProtocol()) {
1954 case 'none': return _('Unmanaged');
1955 case 'static': return _('Static address');
1956 case 'dhcp': return _('DHCP client');
1957 default: return _('Unknown');
1962 * Get the type of the underlying interface.
1964 * This function actually is a convenience wrapper around
1965 * `proto.get("type")` and is mainly used by other `LuCI.Network` code
1966 * to check whether the interface is declared as bridge in UCI.
1968 * @returns {null|string}
1969 * Returns the value of the `type` option of the associated logical
1970 * interface or `null` if no `type` option is set.
1972 getType: function() {
1973 return this._get('type');
1977 * Get the name of the associated logical interface.
1980 * Returns the logical interface name, such as `lan` or `wan`.
1982 getName: function() {
1987 * Get the uptime of the logical interface.
1990 * Returns the uptime of the associated interface in seconds.
1992 getUptime: function() {
1993 return this._ubus('uptime') || 0;
1997 * Get the logical interface expiry time in seconds.
1999 * For protocols that have a concept of a lease, such as DHCP or
2000 * DHCPv6, this function returns the remaining time in seconds
2001 * until the lease expires.
2004 * Returns the amount of seconds until the lease expires or `-1`
2005 * if it isn't applicable to the associated protocol.
2007 getExpiry: function() {
2008 var u
= this._ubus('uptime'),
2009 d
= this._ubus('data');
2011 if (typeof(u
) == 'number' && d
!= null &&
2012 typeof(d
) == 'object' && typeof(d
.leasetime
) == 'number') {
2013 var r
= d
.leasetime
- (u
% d
.leasetime
);
2014 return (r
> 0 ? r
: 0);
2021 * Get the metric value of the logical interface.
2024 * Returns the current metric value used for device and network
2025 * routes spawned by the associated logical interface.
2027 getMetric: function() {
2028 return this._ubus('metric') || 0;
2032 * Get the requested firewall zone name of the logical interface.
2034 * Some protocol implementations request a specific firewall zone
2035 * to trigger inclusion of their resulting network devices into the
2036 * firewall rule set.
2038 * @returns {null|string}
2039 * Returns the requested firewall zone name as published in the
2040 * `ubus` runtime information or `null` if the remote protocol
2041 * handler didn't request a zone.
2043 getZoneName: function() {
2044 var d
= this._ubus('data');
2046 if (L
.isObject(d
) && typeof(d
.zone
) == 'string')
2053 * Query the first (primary) IPv4 address of the logical interface.
2055 * @returns {null|string}
2056 * Returns the primary IPv4 address registered by the protocol handler
2057 * or `null` if no IPv4 addresses were set.
2059 getIPAddr: function() {
2060 var addrs
= this._ubus('ipv4-address');
2061 return ((Array
.isArray(addrs
) && addrs
.length
) ? addrs
[0].address
: null);
2065 * Query all IPv4 addresses of the logical interface.
2067 * @returns {string[]}
2068 * Returns an array of IPv4 addresses in CIDR notation which have been
2069 * registered by the protocol handler. The order of the resulting array
2070 * follows the order of the addresses in `ubus` runtime information.
2072 getIPAddrs: function() {
2073 var addrs
= this._ubus('ipv4-address'),
2076 if (Array
.isArray(addrs
))
2077 for (var i
= 0; i
< addrs
.length
; i
++)
2078 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2084 * Query the first (primary) IPv4 netmask of the logical interface.
2086 * @returns {null|string}
2087 * Returns the netmask of the primary IPv4 address registered by the
2088 * protocol handler or `null` if no IPv4 addresses were set.
2090 getNetmask: function() {
2091 var addrs
= this._ubus('ipv4-address');
2092 if (Array
.isArray(addrs
) && addrs
.length
)
2093 return prefixToMask(addrs
[0].mask
, false);
2097 * Query the gateway (nexthop) of the default route associated with
2098 * this logical interface.
2101 * Returns a string containing the IPv4 nexthop address of the associated
2102 * default route or `null` if no default route was found.
2104 getGatewayAddr: function() {
2105 var routes
= this._ubus('route');
2107 if (Array
.isArray(routes
))
2108 for (var i
= 0; i
< routes
.length
; i
++)
2109 if (typeof(routes
[i
]) == 'object' &&
2110 routes
[i
].target
== '0.0.0.0' &&
2111 routes
[i
].mask
== 0)
2112 return routes
[i
].nexthop
;
2118 * Query the IPv4 DNS servers associated with the logical interface.
2120 * @returns {string[]}
2121 * Returns an array of IPv4 DNS servers registered by the remote
2124 getDNSAddrs: function() {
2125 var addrs
= this._ubus('dns-server'),
2128 if (Array
.isArray(addrs
))
2129 for (var i
= 0; i
< addrs
.length
; i
++)
2130 if (!/:/.test(addrs
[i
]))
2137 * Query the first (primary) IPv6 address of the logical interface.
2139 * @returns {null|string}
2140 * Returns the primary IPv6 address registered by the protocol handler
2141 * in CIDR notation or `null` if no IPv6 addresses were set.
2143 getIP6Addr: function() {
2144 var addrs
= this._ubus('ipv6-address');
2146 if (Array
.isArray(addrs
) && L
.isObject(addrs
[0]))
2147 return '%s/%d'.format(addrs
[0].address
, addrs
[0].mask
);
2149 addrs
= this._ubus('ipv6-prefix-assignment');
2151 if (Array
.isArray(addrs
) && L
.isObject(addrs
[0]) && L
.isObject(addrs
[0]['local-address']))
2152 return '%s/%d'.format(addrs
[0]['local-address'].address
, addrs
[0]['local-address'].mask
);
2158 * Query all IPv6 addresses of the logical interface.
2160 * @returns {string[]}
2161 * Returns an array of IPv6 addresses in CIDR notation which have been
2162 * registered by the protocol handler. The order of the resulting array
2163 * follows the order of the addresses in `ubus` runtime information.
2165 getIP6Addrs: function() {
2166 var addrs
= this._ubus('ipv6-address'),
2169 if (Array
.isArray(addrs
))
2170 for (var i
= 0; i
< addrs
.length
; i
++)
2171 if (L
.isObject(addrs
[i
]))
2172 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2174 addrs
= this._ubus('ipv6-prefix-assignment');
2176 if (Array
.isArray(addrs
))
2177 for (var i
= 0; i
< addrs
.length
; i
++)
2178 if (L
.isObject(addrs
[i
]) && L
.isObject(addrs
[i
]['local-address']))
2179 rv
.push('%s/%d'.format(addrs
[i
]['local-address'].address
, addrs
[i
]['local-address'].mask
));
2185 * Query the gateway (nexthop) of the IPv6 default route associated with
2186 * this logical interface.
2189 * Returns a string containing the IPv6 nexthop address of the associated
2190 * default route or `null` if no default route was found.
2192 getGateway6Addr: function() {
2193 var routes
= this._ubus('route');
2195 if (Array
.isArray(routes
))
2196 for (var i
= 0; i
< routes
.length
; i
++)
2197 if (typeof(routes
[i
]) == 'object' &&
2198 routes
[i
].target
== '::' &&
2199 routes
[i
].mask
== 0)
2200 return routes
[i
].nexthop
;
2206 * Query the IPv6 DNS servers associated with the logical interface.
2208 * @returns {string[]}
2209 * Returns an array of IPv6 DNS servers registered by the remote
2212 getDNS6Addrs: function() {
2213 var addrs
= this._ubus('dns-server'),
2216 if (Array
.isArray(addrs
))
2217 for (var i
= 0; i
< addrs
.length
; i
++)
2218 if (/:/.test(addrs
[i
]))
2225 * Query the routed IPv6 prefix associated with the logical interface.
2227 * @returns {null|string}
2228 * Returns the routed IPv6 prefix registered by the remote protocol
2229 * handler or `null` if no prefix is present.
2231 getIP6Prefix: function() {
2232 var prefixes
= this._ubus('ipv6-prefix');
2234 if (Array
.isArray(prefixes
) && L
.isObject(prefixes
[0]))
2235 return '%s/%d'.format(prefixes
[0].address
, prefixes
[0].mask
);
2241 * Query interface error messages published in `ubus` runtime state.
2243 * Interface errors are emitted by remote protocol handlers if the setup
2244 * of the underlying logical interface failed, e.g. due to bad
2245 * configuration or network connectivity issues.
2247 * This function will translate the found error codes to human readable
2248 * messages using the descriptions registered by
2249 * {@link LuCI.Network#registerErrorCode Network.registerErrorCode()}
2250 * and fall back to `"Unknown error (%s)"` where `%s` is replaced by the
2251 * error code in case no translation can be found.
2253 * @returns {string[]}
2254 * Returns an array of translated interface error messages.
2256 getErrors: function() {
2257 var errors
= this._ubus('errors'),
2260 if (Array
.isArray(errors
)) {
2261 for (var i
= 0; i
< errors
.length
; i
++) {
2262 if (!L
.isObject(errors
[i
]) || typeof(errors
[i
].code
) != 'string')
2266 rv
.push(proto_errors
[errors
[i
].code
] || _('Unknown error (%s)').format(errors
[i
].code
));
2274 * Checks whether the underlying logical interface is declared as bridge.
2276 * @returns {boolean}
2277 * Returns `true` when the interface is declared with `option type bridge`
2278 * and when the associated protocol implementation is not marked virtual
2279 * or `false` when the logical interface is no bridge.
2281 isBridge: function() {
2282 return (!this.isVirtual() && this.getType() == 'bridge');
2286 * Get the name of the opkg package providing the protocol functionality.
2288 * This function should be overwritten by protocol specific subclasses.
2293 * Returns the name of the opkg package required for the protocol to
2294 * function, e.g. `odhcp6c` for the `dhcpv6` prototocol.
2296 getOpkgPackage: function() {
2301 * Checks whether the protocol functionality is installed.
2303 * This function exists for compatibility with old code, it always
2309 * @returns {boolean}
2310 * Returns `true` if the protocol support is installed, else `false`.
2312 isInstalled: function() {
2317 * Checks whether this protocol is "virtual".
2319 * A "virtual" protocol is a protocol which spawns its own interfaces
2320 * on demand instead of using existing physical interfaces.
2322 * Examples for virtual protocols are `6in4` which `gre` spawn tunnel
2323 * network device on startup, examples for non-virtual protcols are
2324 * `dhcp` or `static` which apply IP configuration to existing interfaces.
2326 * This function should be overwritten by subclasses.
2328 * @returns {boolean}
2329 * Returns a boolean indicating whether the underlying protocol spawns
2330 * dynamic interfaces (`true`) or not (`false`).
2332 isVirtual: function() {
2337 * Checks whether this protocol is "floating".
2339 * A "floating" protocol is a protocol which spawns its own interfaces
2340 * on demand, like a virtual one but which relies on an existinf lower
2341 * level interface to initiate the connection.
2343 * An example for such a protocol is "pppoe".
2345 * This function exists for backwards compatibility with older code
2346 * but should not be used anymore.
2349 * @returns {boolean}
2350 * Returns a boolean indicating whether this protocol is floating (`true`)
2353 isFloating: function() {
2358 * Checks whether this logical interface is dynamic.
2360 * A dynamic interface is an interface which has been created at runtime,
2361 * e.g. as sub-interface of another interface, but which is not backed by
2362 * any user configuration. Such dynamic interfaces cannot be edited but
2363 * only brought down or restarted.
2365 * @returns {boolean}
2366 * Returns a boolean indicating whether this interface is dynamic (`true`)
2369 isDynamic: function() {
2370 return (this._ubus('dynamic') == true);
2374 * Checks whether this interface is an alias interface.
2376 * Alias interfaces are interfaces layering on top of another interface
2377 * and are denoted by a special `@interfacename` notation in the
2378 * underlying `ifname` option.
2380 * @returns {null|string}
2381 * Returns the name of the parent interface if this logical interface
2382 * is an alias or `null` if it is not an alias interface.
2384 isAlias: function() {
2385 var ifnames
= L
.toArray(uci
.get('network', this.sid
, 'ifname')),
2388 for (var i
= 0; i
< ifnames
.length
; i
++)
2389 if (ifnames
[i
].charAt(0) == '@')
2390 parent
= ifnames
[i
].substr(1);
2391 else if (parent
!= null)
2398 * Checks whether this logical interface is "empty", meaning that ut
2399 * has no network devices attached.
2401 * @returns {boolean}
2402 * Returns `true` if this logical interface is empty, else `false`.
2404 isEmpty: function() {
2405 if (this.isFloating())
2409 ifname
= this._get('ifname');
2411 if (ifname
!= null && ifname
.match(/\S+/))
2414 if (empty
== true && getWifiNetidBySid(this.sid
) != null)
2421 * Checks whether this logical interface is configured and running.
2423 * @returns {boolean}
2424 * Returns `true` when the interface is active or `false` when it is not.
2427 return (this._ubus('up') == true);
2431 * Add the given network device to the logical interface.
2433 * @param {LuCI.Network.Protocol|LuCI.Network.Device|LuCI.Network.WifiDevice|LuCI.Network.WifiNetwork|string} device
2434 * The object or device name to add to the logical interface. In case the
2435 * given argument is not a string, it is resolved though the
2436 * {@link LuCI.Network#getIfnameOf Network.getIfnameOf()} function.
2438 * @returns {boolean}
2439 * Returns `true` if the device name has been added or `false` if any
2440 * argument was invalid, if the device was already part of the logical
2441 * interface or if the logical interface is virtual.
2443 addDevice: function(ifname
) {
2444 ifname
= ifnameOf(ifname
);
2446 if (ifname
== null || this.isFloating())
2449 var wif
= getWifiSidByIfname(ifname
);
2452 return appendValue('wireless', wif
, 'network', this.sid
);
2454 return appendValue('network', this.sid
, 'ifname', ifname
);
2458 * Remove the given network device from the logical interface.
2460 * @param {LuCI.Network.Protocol|LuCI.Network.Device|LuCI.Network.WifiDevice|LuCI.Network.WifiNetwork|string} device
2461 * The object or device name to remove from the logical interface. In case
2462 * the given argument is not a string, it is resolved though the
2463 * {@link LuCI.Network#getIfnameOf Network.getIfnameOf()} function.
2465 * @returns {boolean}
2466 * Returns `true` if the device name has been added or `false` if any
2467 * argument was invalid, if the device was already part of the logical
2468 * interface or if the logical interface is virtual.
2470 deleteDevice: function(ifname
) {
2473 ifname
= ifnameOf(ifname
);
2475 if (ifname
== null || this.isFloating())
2478 var wif
= getWifiSidByIfname(ifname
);
2481 rv
= removeValue('wireless', wif
, 'network', this.sid
);
2483 if (removeValue('network', this.sid
, 'ifname', ifname
))
2490 * Returns the Linux network device associated with this logical
2493 * @returns {LuCI.Network.Device}
2494 * Returns a `Network.Device` class instance representing the
2495 * expected Linux network device according to the configuration.
2497 getDevice: function() {
2498 if (this.isVirtual()) {
2499 var ifname
= '%s-%s'.format(this.getProtocol(), this.sid
);
2500 _state
.isTunnel
[this.getProtocol() + '-' + this.sid
] = true;
2501 return L
.network
.instantiateDevice(ifname
, this);
2503 else if (this.isBridge()) {
2504 var ifname
= 'br-%s'.format(this.sid
);
2505 _state
.isBridge
[ifname
] = true;
2506 return new Device(ifname
, this);
2509 var ifnames
= L
.toArray(uci
.get('network', this.sid
, 'ifname'));
2511 for (var i
= 0; i
< ifnames
.length
; i
++) {
2512 var m
= ifnames
[i
].match(/^([^:/]+)/);
2513 return ((m
&& m
[1]) ? L
.network
.instantiateDevice(m
[1], this) : null);
2516 ifname
= getWifiNetidByNetname(this.sid
);
2518 return (ifname
!= null ? L
.network
.instantiateDevice(ifname
[0], this) : null);
2523 * Returns the layer 2 linux network device currently associated
2524 * with this logical interface.
2526 * @returns {LuCI.Network.Device}
2527 * Returns a `Network.Device` class instance representing the Linux
2528 * network device currently associated with the logical interface.
2530 getL2Device: function() {
2531 var ifname
= this._ubus('device');
2532 return (ifname
!= null ? L
.network
.instantiateDevice(ifname
, this) : null);
2536 * Returns the layer 3 linux network device currently associated
2537 * with this logical interface.
2539 * @returns {LuCI.Network.Device}
2540 * Returns a `Network.Device` class instance representing the Linux
2541 * network device currently associated with the logical interface.
2543 getL3Device: function() {
2544 var ifname
= this._ubus('l3_device');
2545 return (ifname
!= null ? L
.network
.instantiateDevice(ifname
, this) : null);
2549 * Returns a list of network sub-devices associated with this logical
2552 * @returns {null|Array<LuCI.Network.Device>}
2553 * Returns an array of of `Network.Device` class instances representing
2554 * the sub-devices attached to this logical interface or `null` if the
2555 * logical interface does not support sub-devices, e.g. because it is
2556 * virtual and not a bridge.
2558 getDevices: function() {
2561 if (!this.isBridge() && !(this.isVirtual() && !this.isFloating()))
2564 var ifnames
= L
.toArray(uci
.get('network', this.sid
, 'ifname'));
2566 for (var i
= 0; i
< ifnames
.length
; i
++) {
2567 if (ifnames
[i
].charAt(0) == '@')
2570 var m
= ifnames
[i
].match(/^([^:/]+)/);
2572 rv
.push(L
.network
.instantiateDevice(m
[1], this));
2575 var uciWifiIfaces
= uci
.sections('wireless', 'wifi-iface');
2577 for (var i
= 0; i
< uciWifiIfaces
.length
; i
++) {
2578 if (typeof(uciWifiIfaces
[i
].device
) != 'string')
2581 var networks
= L
.toArray(uciWifiIfaces
[i
].network
);
2583 for (var j
= 0; j
< networks
.length
; j
++) {
2584 if (networks
[j
] != this.sid
)
2587 var netid
= getWifiNetidBySid(uciWifiIfaces
[i
]['.name']);
2590 rv
.push(L
.network
.instantiateDevice(netid
[0], this));
2594 rv
.sort(deviceSort
);
2600 * Checks whether this logical interface contains the given device
2603 * @param {LuCI.Network.Protocol|LuCI.Network.Device|LuCI.Network.WifiDevice|LuCI.Network.WifiNetwork|string} device
2604 * The object or device name to check. In case the given argument is not
2605 * a string, it is resolved though the
2606 * {@link LuCI.Network#getIfnameOf Network.getIfnameOf()} function.
2608 * @returns {boolean}
2609 * Returns `true` when this logical interface contains the given network
2610 * device or `false` if not.
2612 containsDevice: function(ifname
) {
2613 ifname
= ifnameOf(ifname
);
2617 else if (this.isVirtual() && '%s-%s'.format(this.getProtocol(), this.sid
) == ifname
)
2619 else if (this.isBridge() && 'br-%s'.format(this.sid
) == ifname
)
2622 var ifnames
= L
.toArray(uci
.get('network', this.sid
, 'ifname'));
2624 for (var i
= 0; i
< ifnames
.length
; i
++) {
2625 var m
= ifnames
[i
].match(/^([^:/]+)/);
2626 if (m
!= null && m
[1] == ifname
)
2630 var wif
= getWifiSidByIfname(ifname
);
2633 var networks
= L
.toArray(uci
.get('wireless', wif
, 'network'));
2635 for (var i
= 0; i
< networks
.length
; i
++)
2636 if (networks
[i
] == this.sid
)
2646 * @memberof LuCI.Network
2650 * A `Network.Device` class instance represents an underlying Linux network
2651 * device and allows querying device details such as packet statistics or MTU.
2653 Device
= L
.Class
.extend(/** @lends LuCI.Network.Device.prototype */ {
2654 __init__: function(ifname
, network
) {
2655 var wif
= getWifiSidByIfname(ifname
);
2658 var res
= getWifiStateBySid(wif
) || [],
2659 netid
= getWifiNetidBySid(wif
) || [];
2661 this.wif
= new WifiNetwork(wif
, res
[0], res
[1], netid
[0], res
[2], { ifname
: ifname
});
2662 this.ifname
= this.wif
.getIfname();
2665 this.ifname
= this.ifname
|| ifname
;
2666 this.dev
= _state
.netdevs
[this.ifname
];
2667 this.network
= network
;
2670 _devstate: function(/* ... */) {
2673 for (var i
= 0; i
< arguments
.length
; i
++)
2675 rv
= rv
[arguments
[i
]];
2683 * Get the name of the network device.
2686 * Returns the name of the device, e.g. `eth0` or `wlan0`.
2688 getName: function() {
2689 return (this.wif
!= null ? this.wif
.getIfname() : this.ifname
);
2693 * Get the MAC address of the device.
2695 * @returns {null|string}
2696 * Returns the MAC address of the device or `null` if not applicable,
2697 * e.g. for non-ethernet tunnel devices.
2699 getMAC: function() {
2700 var mac
= this._devstate('macaddr');
2701 return mac
? mac
.toUpperCase() : null;
2705 * Get the MTU of the device.
2708 * Returns the MTU of the device.
2710 getMTU: function() {
2711 return this._devstate('mtu');
2715 * Get the IPv4 addresses configured on the device.
2717 * @returns {string[]}
2718 * Returns an array of IPv4 address strings.
2720 getIPAddrs: function() {
2721 var addrs
= this._devstate('ipaddrs');
2722 return (Array
.isArray(addrs
) ? addrs
: []);
2726 * Get the IPv6 addresses configured on the device.
2728 * @returns {string[]}
2729 * Returns an array of IPv6 address strings.
2731 getIP6Addrs: function() {
2732 var addrs
= this._devstate('ip6addrs');
2733 return (Array
.isArray(addrs
) ? addrs
: []);
2737 * Get the type of the device..
2740 * Returns a string describing the type of the network device:
2741 * - `alias` if it is an abstract alias device (`@` notation)
2742 * - `wifi` if it is a wireless interface (e.g. `wlan0`)
2743 * - `bridge` if it is a bridge device (e.g. `br-lan`)
2744 * - `tunnel` if it is a tun or tap device (e.g. `tun0`)
2745 * - `vlan` if it is a vlan device (e.g. `eth0.1`)
2746 * - `switch` if it is a switch device (e.g.`eth1` connected to switch0)
2747 * - `ethernet` for all other device types
2749 getType: function() {
2750 if (this.ifname
!= null && this.ifname
.charAt(0) == '@')
2752 else if (this.wif
!= null || isWifiIfname(this.ifname
))
2754 else if (_state
.isBridge
[this.ifname
])
2756 else if (_state
.isTunnel
[this.ifname
])
2758 else if (this.ifname
.indexOf('.') > -1)
2760 else if (_state
.isSwitch
[this.ifname
])
2767 * Get a short description string for the device.
2770 * Returns the device name for non-wifi devices or a string containing
2771 * the operation mode and SSID for wifi devices.
2773 getShortName: function() {
2774 if (this.wif
!= null)
2775 return this.wif
.getShortName();
2781 * Get a long description string for the device.
2784 * Returns a string containing the type description and device name
2785 * for non-wifi devices or operation mode and ssid for wifi ones.
2787 getI18n: function() {
2788 if (this.wif
!= null) {
2789 return '%s: %s "%s"'.format(
2790 _('Wireless Network'),
2791 this.wif
.getActiveMode(),
2792 this.wif
.getActiveSSID() || this.wif
.getActiveBSSID() || this.wif
.getID() || '?');
2795 return '%s: "%s"'.format(this.getTypeI18n(), this.getName());
2799 * Get a string describing the device type.
2802 * Returns a string describing the type, e.g. "Wireless Adapter" or
2805 getTypeI18n: function() {
2806 switch (this.getType()) {
2808 return _('Alias Interface');
2811 return _('Wireless Adapter');
2817 return _('Ethernet Switch');
2820 return (_state
.isSwitch
[this.ifname
] ? _('Switch VLAN') : _('Software VLAN'));
2823 return _('Tunnel Interface');
2826 return _('Ethernet Adapter');
2831 * Get the associated bridge ports of the device.
2833 * @returns {null|Array<LuCI.Network.Device>}
2834 * Returns an array of `Network.Device` instances representing the ports
2835 * (slave interfaces) of the bridge or `null` when this device isn't
2838 getPorts: function() {
2839 var br
= _state
.bridges
[this.ifname
],
2842 if (br
== null || !Array
.isArray(br
.ifnames
))
2845 for (var i
= 0; i
< br
.ifnames
.length
; i
++)
2846 rv
.push(L
.network
.instantiateDevice(br
.ifnames
[i
].name
));
2848 rv
.sort(deviceSort
);
2856 * @returns {null|string}
2857 * Returns the ID of this network bridge or `null` if this network
2858 * device is not a Linux bridge.
2860 getBridgeID: function() {
2861 var br
= _state
.bridges
[this.ifname
];
2862 return (br
!= null ? br
.id
: null);
2866 * Get the bridge STP setting
2868 * @returns {boolean}
2869 * Returns `true` when this device is a Linux bridge and has `stp`
2870 * enabled, else `false`.
2872 getBridgeSTP: function() {
2873 var br
= _state
.bridges
[this.ifname
];
2874 return (br
!= null ? !!br
.stp
: false);
2878 * Checks whether this device is up.
2880 * @returns {boolean}
2881 * Returns `true` when the associated device is running pr `false`
2882 * when it is down or absent.
2885 var up
= this._devstate('flags', 'up');
2888 up
= (this.getType() == 'alias');
2894 * Checks whether this device is a Linux bridge.
2896 * @returns {boolean}
2897 * Returns `true` when the network device is present and a Linux bridge,
2900 isBridge: function() {
2901 return (this.getType() == 'bridge');
2905 * Checks whether this device is part of a Linux bridge.
2907 * @returns {boolean}
2908 * Returns `true` when this network device is part of a bridge,
2911 isBridgePort: function() {
2912 return (this._devstate('bridge') != null);
2916 * Get the amount of transmitted bytes.
2919 * Returns the amount of bytes transmitted by the network device.
2921 getTXBytes: function() {
2922 var stat
= this._devstate('stats');
2923 return (stat
!= null ? stat
.tx_bytes
|| 0 : 0);
2927 * Get the amount of received bytes.
2930 * Returns the amount of bytes received by the network device.
2932 getRXBytes: function() {
2933 var stat
= this._devstate('stats');
2934 return (stat
!= null ? stat
.rx_bytes
|| 0 : 0);
2938 * Get the amount of transmitted packets.
2941 * Returns the amount of packets transmitted by the network device.
2943 getTXPackets: function() {
2944 var stat
= this._devstate('stats');
2945 return (stat
!= null ? stat
.tx_packets
|| 0 : 0);
2949 * Get the amount of received packets.
2952 * Returns the amount of packets received by the network device.
2954 getRXPackets: function() {
2955 var stat
= this._devstate('stats');
2956 return (stat
!= null ? stat
.rx_packets
|| 0 : 0);
2960 * Get the primary logical interface this device is assigned to.
2962 * @returns {null|LuCI.Network.Protocol}
2963 * Returns a `Network.Protocol` instance representing the logical
2964 * interface this device is attached to or `null` if it is not
2965 * assigned to any logical interface.
2967 getNetwork: function() {
2968 return this.getNetworks()[0];
2972 * Get the logical interfaces this device is assigned to.
2974 * @returns {Array<LuCI.Network.Protocol>}
2975 * Returns an array of `Network.Protocol` instances representing the
2976 * logical interfaces this device is assigned to.
2978 getNetworks: function() {
2979 if (this.networks
== null) {
2982 var networks
= enumerateNetworks
.apply(L
.network
);
2984 for (var i
= 0; i
< networks
.length
; i
++)
2985 if (networks
[i
].containsDevice(this.ifname
) || networks
[i
].getIfname() == this.ifname
)
2986 this.networks
.push(networks
[i
]);
2988 this.networks
.sort(networkSort
);
2991 return this.networks
;
2995 * Get the related wireless network this device is related to.
2997 * @returns {null|LuCI.Network.WifiNetwork}
2998 * Returns a `Network.WifiNetwork` instance representing the wireless
2999 * network corresponding to this network device or `null` if this device
3000 * is not a wireless device.
3002 getWifiNetwork: function() {
3003 return (this.wif
!= null ? this.wif
: null);
3009 * @memberof LuCI.Network
3013 * A `Network.WifiDevice` class instance represents a wireless radio device
3014 * present on the system and provides wireless capability information as
3015 * well as methods for enumerating related wireless networks.
3017 WifiDevice
= L
.Class
.extend(/** @lends LuCI.Network.WifiDevice.prototype */ {
3018 __init__: function(name
, radiostate
) {
3019 var uciWifiDevice
= uci
.get('wireless', name
);
3021 if (uciWifiDevice
!= null &&
3022 uciWifiDevice
['.type'] == 'wifi-device' &&
3023 uciWifiDevice
['.name'] != null) {
3024 this.sid
= uciWifiDevice
['.name'];
3027 this.sid
= this.sid
|| name
;
3035 ubus: function(/* ... */) {
3036 var v
= this._ubusdata
;
3038 for (var i
= 0; i
< arguments
.length
; i
++)
3040 v
= v
[arguments
[i
]];
3048 * Read the given UCI option value of this wireless device.
3050 * @param {string} opt
3051 * The UCI option name to read.
3053 * @returns {null|string|string[]}
3054 * Returns the UCI option value or `null` if the requested option is
3057 get: function(opt
) {
3058 return uci
.get('wireless', this.sid
, opt
);
3062 * Set the given UCI option of this network to the given value.
3064 * @param {string} opt
3065 * The name of the UCI option to set.
3067 * @param {null|string|string[]} val
3068 * The value to set or `null` to remove the given option from the
3071 set: function(opt
, value
) {
3072 return uci
.set('wireless', this.sid
, opt
, value
);
3076 * Checks whether this wireless radio is disabled.
3078 * @returns {boolean}
3079 * Returns `true` when the wireless radio is marked as disabled in `ubus`
3080 * runtime state or when the `disabled` option is set in the corresponding
3081 * UCI configuration.
3083 isDisabled: function() {
3084 return this.ubus('dev', 'disabled') || this.get('disabled') == '1';
3088 * Get the configuration name of this wireless radio.
3091 * Returns the UCI section name (e.g. `radio0`) of the corresponding
3092 * radio configuration which also serves as unique logical identifier
3093 * for the wireless phy.
3095 getName: function() {
3100 * Gets a list of supported hwmodes.
3102 * The hwmode values describe the frequency band and wireless standard
3103 * versions supported by the wireless phy.
3105 * @returns {string[]}
3106 * Returns an array of valid hwmode values for this radio. Currently
3107 * known mode values are:
3108 * - `a` - Legacy 802.11a mode, 5 GHz, up to 54 Mbit/s
3109 * - `b` - Legacy 802.11b mode, 2.4 GHz, up to 11 Mbit/s
3110 * - `g` - Legacy 802.11g mode, 2.4 GHz, up to 54 Mbit/s
3111 * - `n` - IEEE 802.11n mode, 2.4 or 5 GHz, up to 600 Mbit/s
3112 * - `ac` - IEEE 802.11ac mode, 5 GHz, up to 6770 Mbit/s
3114 getHWModes: function() {
3115 var hwmodes
= this.ubus('dev', 'iwinfo', 'hwmodes');
3116 return Array
.isArray(hwmodes
) ? hwmodes
: [ 'b', 'g' ];
3120 * Gets a list of supported htmodes.
3122 * The htmode values describe the wide-frequency options supported by
3125 * @returns {string[]}
3126 * Returns an array of valid htmode values for this radio. Currently
3127 * known mode values are:
3128 * - `HT20` - applicable to IEEE 802.11n, 20 MHz wide channels
3129 * - `HT40` - applicable to IEEE 802.11n, 40 MHz wide channels
3130 * - `VHT20` - applicable to IEEE 802.11ac, 20 MHz wide channels
3131 * - `VHT40` - applicable to IEEE 802.11ac, 40 MHz wide channels
3132 * - `VHT80` - applicable to IEEE 802.11ac, 80 MHz wide channels
3133 * - `VHT160` - applicable to IEEE 802.11ac, 160 MHz wide channels
3135 getHTModes: function() {
3136 var htmodes
= this.ubus('dev', 'iwinfo', 'htmodes');
3137 return (Array
.isArray(htmodes
) && htmodes
.length
) ? htmodes
: null;
3141 * Get a string describing the wireless radio hardware.
3144 * Returns the description string.
3146 getI18n: function() {
3147 var hw
= this.ubus('dev', 'iwinfo', 'hardware'),
3148 type
= L
.isObject(hw
) ? hw
.name
: null;
3150 if (this.ubus('dev', 'iwinfo', 'type') == 'wl')
3153 var hwmodes
= this.getHWModes(),
3156 hwmodes
.sort(function(a
, b
) {
3157 return (a
.length
!= b
.length
? a
.length
> b
.length
: a
> b
);
3160 modestr
= hwmodes
.join('');
3162 return '%s 802.11%s Wireless Controller (%s)'.format(type
|| 'Generic', modestr
, this.getName());
3166 * A wireless scan result object describes a neighbouring wireless
3167 * network found in the vincinity.
3169 * @typedef {Object<string, number|string|LuCI.Network.WifiEncryption>} WifiScanResult
3170 * @memberof LuCI.Network
3172 * @property {string} ssid
3173 * The SSID / Mesh ID of the network.
3175 * @property {string} bssid
3176 * The BSSID if the network.
3178 * @property {string} mode
3179 * The operation mode of the network (`Master`, `Ad-Hoc`, `Mesh Point`).
3181 * @property {number} channel
3182 * The wireless channel of the network.
3184 * @property {number} signal
3185 * The received signal strength of the network in dBm.
3187 * @property {number} quality
3188 * The numeric quality level of the signal, can be used in conjunction
3189 * with `quality_max` to calculate a quality percentage.
3191 * @property {number} quality_max
3192 * The maximum possible quality level of the signal, can be used in
3193 * conjunction with `quality` to calculate a quality percentage.
3195 * @property {LuCI.Network.WifiEncryption} encryption
3196 * The encryption used by the wireless network.
3200 * Trigger a wireless scan on this radio device and obtain a list of
3203 * @returns {Promise<Array<LuCI.Network.WifiScanResult>>}
3204 * Returns a promise resolving to an array of scan result objects
3205 * describing the networks found in the vincinity.
3207 getScanList: function() {
3208 return callIwinfoScan(this.sid
);
3212 * Check whether the wireless radio is marked as up in the `ubus`
3215 * @returns {boolean}
3216 * Returns `true` when the radio device is up, else `false`.
3219 if (L
.isObject(_state
.radios
[this.sid
]))
3220 return (_state
.radios
[this.sid
].up
== true);
3226 * Get the wifi network of the given name belonging to this radio device
3228 * @param {string} network
3229 * The name of the wireless network to lookup. This may be either an uci
3230 * configuration section ID, a network ID in the form `radio#.network#`
3231 * or a Linux network device name like `wlan0` which is resolved to the
3232 * corresponding configuration section through `ubus` runtime information.
3234 * @returns {Promise<LuCI.Network.WifiNetwork>}
3235 * Returns a promise resolving to a `Network.WifiNetwork` instance
3236 * representing the wireless network and rejecting with `null` if
3237 * the given network could not be found or is not associated with
3238 * this radio device.
3240 getWifiNetwork: function(network
) {
3241 return L
.network
.getWifiNetwork(network
).then(L
.bind(function(networkInstance
) {
3242 var uciWifiIface
= (networkInstance
.sid
? uci
.get('wireless', networkInstance
.sid
) : null);
3244 if (uciWifiIface
== null || uciWifiIface
['.type'] != 'wifi-iface' || uciWifiIface
.device
!= this.sid
)
3245 return Promise
.reject();
3247 return networkInstance
;
3252 * Get all wireless networks associated with this wireless radio device.
3254 * @returns {Promise<Array<LuCI.Network.WifiNetwork>>}
3255 * Returns a promise resolving to an array of `Network.WifiNetwork`
3256 * instances respresenting the wireless networks associated with this
3259 getWifiNetworks: function() {
3260 return L
.network
.getWifiNetworks().then(L
.bind(function(networks
) {
3263 for (var i
= 0; i
< networks
.length
; i
++)
3264 if (networks
[i
].getWifiDeviceName() == this.getName())
3265 rv
.push(networks
[i
]);
3272 * Adds a new wireless network associated with this radio device to the
3273 * configuration and sets its options to the provided values.
3275 * @param {Object<string, string|string[]>} [options]
3276 * The options to set for the newly added wireless network.
3278 * @returns {Promise<null|LuCI.Network.WifiNetwork>}
3279 * Returns a promise resolving to a `WifiNetwork` instance describing
3280 * the newly added wireless network or `null` if the given options
3283 addWifiNetwork: function(options
) {
3284 if (!L
.isObject(options
))
3287 options
.device
= this.sid
;
3289 return L
.network
.addWifiNetwork(options
);
3293 * Deletes the wireless network with the given name associated with this
3296 * @param {string} network
3297 * The name of the wireless network to lookup. This may be either an uci
3298 * configuration section ID, a network ID in the form `radio#.network#`
3299 * or a Linux network device name like `wlan0` which is resolved to the
3300 * corresponding configuration section through `ubus` runtime information.
3302 * @returns {Promise<boolean>}
3303 * Returns a promise resolving to `true` when the wireless network was
3304 * successfully deleted from the configuration or `false` when the given
3305 * network could not be found or if the found network was not associated
3306 * with this wireless radio device.
3308 deleteWifiNetwork: function(network
) {
3311 if (network
instanceof WifiNetwork
) {
3315 var uciWifiIface
= uci
.get('wireless', network
);
3317 if (uciWifiIface
== null || uciWifiIface
['.type'] != 'wifi-iface')
3318 sid
= getWifiSidByIfname(network
);
3321 if (sid
== null || uci
.get('wireless', sid
, 'device') != this.sid
)
3322 return Promise
.resolve(false);
3324 uci
.delete('wireless', network
);
3326 return Promise
.resolve(true);
3332 * @memberof LuCI.Network
3336 * A `Network.WifiNetwork` instance represents a wireless network (vif)
3337 * configured on top of a radio device and provides functions for querying
3338 * the runtime state of the network. Most radio devices support multiple
3339 * such networks in parallel.
3341 WifiNetwork
= L
.Class
.extend(/** @lends LuCI.Network.WifiNetwork.prototype */ {
3342 __init__: function(sid
, radioname
, radiostate
, netid
, netstate
, hostapd
) {
3353 ubus: function(/* ... */) {
3354 var v
= this._ubusdata
;
3356 for (var i
= 0; i
< arguments
.length
; i
++)
3358 v
= v
[arguments
[i
]];
3366 * Read the given UCI option value of this wireless network.
3368 * @param {string} opt
3369 * The UCI option name to read.
3371 * @returns {null|string|string[]}
3372 * Returns the UCI option value or `null` if the requested option is
3375 get: function(opt
) {
3376 return uci
.get('wireless', this.sid
, opt
);
3380 * Set the given UCI option of this network to the given value.
3382 * @param {string} opt
3383 * The name of the UCI option to set.
3385 * @param {null|string|string[]} val
3386 * The value to set or `null` to remove the given option from the
3389 set: function(opt
, value
) {
3390 return uci
.set('wireless', this.sid
, opt
, value
);
3394 * Checks whether this wireless network is disabled.
3396 * @returns {boolean}
3397 * Returns `true` when the wireless radio is marked as disabled in `ubus`
3398 * runtime state or when the `disabled` option is set in the corresponding
3399 * UCI configuration.
3401 isDisabled: function() {
3402 return this.ubus('dev', 'disabled') || this.get('disabled') == '1';
3406 * Get the configured operation mode of the wireless network.
3409 * Returns the configured operation mode. Possible values are:
3410 * - `ap` - Master (Access Point) mode
3411 * - `sta` - Station (client) mode
3412 * - `adhoc` - Ad-Hoc (IBSS) mode
3413 * - `mesh` - Mesh (IEEE 802.11s) mode
3414 * - `monitor` - Monitor mode
3416 getMode: function() {
3417 return this.ubus('net', 'config', 'mode') || this.get('mode') || 'ap';
3421 * Get the configured SSID of the wireless network.
3423 * @returns {null|string}
3424 * Returns the configured SSID value or `null` when this network is
3427 getSSID: function() {
3428 if (this.getMode() == 'mesh')
3431 return this.ubus('net', 'config', 'ssid') || this.get('ssid');
3435 * Get the configured Mesh ID of the wireless network.
3437 * @returns {null|string}
3438 * Returns the configured mesh ID value or `null` when this network
3439 * is not in mesh mode.
3441 getMeshID: function() {
3442 if (this.getMode() != 'mesh')
3445 return this.ubus('net', 'config', 'mesh_id') || this.get('mesh_id');
3449 * Get the configured BSSID of the wireless network.
3451 * @returns {null|string}
3452 * Returns the BSSID value or `null` if none has been specified.
3454 getBSSID: function() {
3455 return this.ubus('net', 'config', 'bssid') || this.get('bssid');
3459 * Get the names of the logical interfaces this wireless network is
3462 * @returns {string[]}
3463 * Returns an array of logical interface names.
3465 getNetworkNames: function() {
3466 return L
.toArray(this.ubus('net', 'config', 'network') || this.get('network'));
3470 * Get the internal network ID of this wireless network.
3472 * The network ID is a LuCI specific identifer in the form
3473 * `radio#.network#` to identify wireless networks by their corresponding
3474 * radio and network index numbers.
3477 * Returns the LuCI specific network ID.
3484 * Get the configuration ID of this wireless network.
3487 * Returns the corresponding UCI section ID of the network.
3489 getName: function() {
3494 * Get the Linux network device name.
3496 * @returns {null|string}
3497 * Returns the current Linux network device name as resolved from
3498 * `ubus` runtime information or `null` if this network has no
3499 * associated network device, e.g. when not configured or up.
3501 getIfname: function() {
3502 var ifname
= this.ubus('net', 'ifname') || this.ubus('net', 'iwinfo', 'ifname');
3504 if (ifname
== null || ifname
.match(/^(wifi|radio)\d/))
3505 ifname
= this.netid
;
3511 * Get the name of the corresponding wifi radio device.
3513 * @returns {null|string}
3514 * Returns the name of the radio device this network is configured on
3515 * or `null` if it cannot be determined.
3517 getWifiDeviceName: function() {
3518 return this.ubus('radio') || this.get('device');
3522 * Get the corresponding wifi radio device.
3524 * @returns {null|LuCI.Network.WifiDevice}
3525 * Returns a `Network.WifiDevice` instance representing the corresponding
3526 * wifi radio device or `null` if the related radio device could not be
3529 getWifiDevice: function() {
3530 var radioname
= this.getWifiDeviceName();
3532 if (radioname
== null)
3533 return Promise
.reject();
3535 return L
.network
.getWifiDevice(radioname
);
3539 * Check whether the radio network is up.
3541 * This function actually queries the up state of the related radio
3542 * device and assumes this network to be up as well when the parent
3543 * radio is up. This is due to the fact that OpenWrt does not control
3544 * virtual interfaces individually but within one common hostapd
3547 * @returns {boolean}
3548 * Returns `true` when the network is up, else `false`.
3551 var device
= this.getDevice();
3556 return device
.isUp();
3560 * Query the current operation mode from runtime information.
3563 * Returns the human readable mode name as reported by `ubus` runtime
3564 * state. Possible returned values are:
3576 getActiveMode: function() {
3577 var mode
= this.ubus('net', 'iwinfo', 'mode') || this.ubus('net', 'config', 'mode') || this.get('mode') || 'ap';
3580 case 'ap': return 'Master';
3581 case 'sta': return 'Client';
3582 case 'adhoc': return 'Ad-Hoc';
3583 case 'mesh': return 'Mesh';
3584 case 'monitor': return 'Monitor';
3585 default: return mode
;
3590 * Query the current operation mode from runtime information as
3591 * translated string.
3594 * Returns the translated, human readable mode name as reported by
3595 *`ubus` runtime state.
3597 getActiveModeI18n: function() {
3598 var mode
= this.getActiveMode();
3601 case 'Master': return _('Master');
3602 case 'Client': return _('Client');
3603 case 'Ad-Hoc': return _('Ad-Hoc');
3604 case 'Mash': return _('Mesh');
3605 case 'Monitor': return _('Monitor');
3606 default: return mode
;
3611 * Query the current SSID from runtime information.
3614 * Returns the current SSID or Mesh ID as reported by `ubus` runtime
3617 getActiveSSID: function() {
3618 return this.ubus('net', 'iwinfo', 'ssid') || this.ubus('net', 'config', 'ssid') || this.get('ssid');
3622 * Query the current BSSID from runtime information.
3625 * Returns the current BSSID or Mesh ID as reported by `ubus` runtime
3628 getActiveBSSID: function() {
3629 return this.ubus('net', 'iwinfo', 'bssid') || this.ubus('net', 'config', 'bssid') || this.get('bssid');
3633 * Query the current encryption settings from runtime information.
3636 * Returns a string describing the current encryption or `-` if the the
3637 * encryption state could not be found in `ubus` runtime information.
3639 getActiveEncryption: function() {
3640 return formatWifiEncryption(this.ubus('net', 'iwinfo', 'encryption')) || '-';
3644 * A wireless peer entry describes the properties of a remote wireless
3645 * peer associated with a local network.
3647 * @typedef {Object<string, boolean|number|string|LuCI.Network.WifiRateEntry>} WifiPeerEntry
3648 * @memberof LuCI.Network
3650 * @property {string} mac
3651 * The MAC address (BSSID).
3653 * @property {number} signal
3654 * The received signal strength.
3656 * @property {number} [signal_avg]
3657 * The average signal strength if supported by the driver.
3659 * @property {number} [noise]
3660 * The current noise floor of the radio. May be `0` or absent if not
3661 * supported by the driver.
3663 * @property {number} inactive
3664 * The amount of milliseconds the peer has been inactive, e.g. due
3667 * @property {number} connected_time
3668 * The amount of milliseconds the peer is associated to this network.
3670 * @property {number} [thr]
3671 * The estimated throughput of the peer, May be `0` or absent if not
3672 * supported by the driver.
3674 * @property {boolean} authorized
3675 * Specifies whether the peer is authorized to associate to this network.
3677 * @property {boolean} authenticated
3678 * Specifies whether the peer completed authentication to this network.
3680 * @property {string} preamble
3681 * The preamble mode used by the peer. May be `long` or `short`.
3683 * @property {boolean} wme
3684 * Specifies whether the peer supports WME/WMM capabilities.
3686 * @property {boolean} mfp
3687 * Specifies whether management frame protection is active.
3689 * @property {boolean} tdls
3690 * Specifies whether TDLS is active.
3692 * @property {number} [mesh llid]
3693 * The mesh LLID, may be `0` or absent if not applicable or supported
3696 * @property {number} [mesh plid]
3697 * The mesh PLID, may be `0` or absent if not applicable or supported
3700 * @property {string} [mesh plink]
3701 * The mesh peer link state description, may be an empty string (`''`)
3702 * or absent if not applicable or supported by the driver.
3704 * The following states are known:
3714 * @property {number} [mesh local PS]
3715 * The local powersafe mode for the peer link, may be an empty
3716 * string (`''`) or absent if not applicable or supported by
3719 * The following modes are known:
3720 * - `ACTIVE` (no power save)
3725 * @property {number} [mesh peer PS]
3726 * The remote powersafe mode for the peer link, may be an empty
3727 * string (`''`) or absent if not applicable or supported by
3730 * The following modes are known:
3731 * - `ACTIVE` (no power save)
3736 * @property {number} [mesh non-peer PS]
3737 * The powersafe mode for all non-peer neigbours, may be an empty
3738 * string (`''`) or absent if not applicable or supported by the driver.
3740 * The following modes are known:
3741 * - `ACTIVE` (no power save)
3746 * @property {LuCI.Network.WifiRateEntry} rx
3747 * Describes the receiving wireless rate from the peer.
3749 * @property {LuCI.Network.WifiRateEntry} tx
3750 * Describes the transmitting wireless rate to the peer.
3754 * A wireless rate entry describes the properties of a wireless
3755 * transmission rate to or from a peer.
3757 * @typedef {Object<string, boolean|number>} WifiRateEntry
3758 * @memberof LuCI.Network
3760 * @property {number} [drop_misc]
3761 * The amount of received misc. packages that have been dropped, e.g.
3762 * due to corruption or missing authentication. Only applicable to
3765 * @property {number} packets
3766 * The amount of packets that have been received or sent.
3768 * @property {number} bytes
3769 * The amount of bytes that have been received or sent.
3771 * @property {number} [failed]
3772 * The amount of failed tranmission attempts. Only applicable to
3775 * @property {number} [retries]
3776 * The amount of retried transmissions. Only applicable to transmit
3779 * @property {boolean} is_ht
3780 * Specifies whether this rate is an HT (IEEE 802.11n) rate.
3782 * @property {boolean} is_vht
3783 * Specifies whether this rate is an VHT (IEEE 802.11ac) rate.
3785 * @property {number} mhz
3786 * The channel width in MHz used for the transmission.
3788 * @property {number} rate
3789 * The bitrate in bit/s of the transmission.
3791 * @property {number} [mcs]
3792 * The MCS index of the used transmission rate. Only applicable to
3795 * @property {number} [40mhz]
3796 * Specifies whether the tranmission rate used 40MHz wide channel.
3797 * Only applicable to HT or VHT rates.
3799 * Note: this option exists for backwards compatibility only and its
3800 * use is discouraged. The `mhz` field should be used instead to
3801 * determine the channel width.
3803 * @property {boolean} [short_gi]
3804 * Specifies whether a short guard interval is used for the transmission.
3805 * Only applicable to HT or VHT rates.
3807 * @property {number} [nss]
3808 * Specifies the number of spatial streams used by the transmission.
3809 * Only applicable to VHT rates.
3813 * Fetch the list of associated peers.
3815 * @returns {Promise<Array<LuCI.Network.WifiPeerEntry>>}
3816 * Returns a promise resolving to an array of wireless peers associated
3817 * with this network.
3819 getAssocList: function() {
3820 return callIwinfoAssoclist(this.getIfname());
3824 * Query the current operating frequency of the wireless network.
3826 * @returns {null|string}
3827 * Returns the current operating frequency of the network from `ubus`
3828 * runtime information in GHz or `null` if the information is not
3831 getFrequency: function() {
3832 var freq
= this.ubus('net', 'iwinfo', 'frequency');
3834 if (freq
!= null && freq
> 0)
3835 return '%.03f'.format(freq
/ 1000);
3841 * Query the current average bitrate of all peers associated to this
3844 * @returns {null|number}
3845 * Returns the average bit rate among all peers associated to the network
3846 * as reported by `ubus` runtime information or `null` if the information
3849 getBitRate: function() {
3850 var rate
= this.ubus('net', 'iwinfo', 'bitrate');
3852 if (rate
!= null && rate
> 0)
3853 return (rate
/ 1000);
3859 * Query the current wireless channel.
3861 * @returns {null|number}
3862 * Returns the wireless channel as reported by `ubus` runtime information
3863 * or `null` if it cannot be determined.
3865 getChannel: function() {
3866 return this.ubus('net', 'iwinfo', 'channel') || this.ubus('dev', 'config', 'channel') || this.get('channel');
3870 * Query the current wireless signal.
3872 * @returns {null|number}
3873 * Returns the wireless signal in dBm as reported by `ubus` runtime
3874 * information or `null` if it cannot be determined.
3876 getSignal: function() {
3877 return this.ubus('net', 'iwinfo', 'signal') || 0;
3881 * Query the current radio noise floor.
3884 * Returns the radio noise floor in dBm as reported by `ubus` runtime
3885 * information or `0` if it cannot be determined.
3887 getNoise: function() {
3888 return this.ubus('net', 'iwinfo', 'noise') || 0;
3892 * Query the current country code.
3895 * Returns the wireless country code as reported by `ubus` runtime
3896 * information or `00` if it cannot be determined.
3898 getCountryCode: function() {
3899 return this.ubus('net', 'iwinfo', 'country') || this.ubus('dev', 'config', 'country') || '00';
3903 * Query the current radio TX power.
3905 * @returns {null|number}
3906 * Returns the wireless network transmit power in dBm as reported by
3907 * `ubus` runtime information or `null` if it cannot be determined.
3909 getTXPower: function() {
3910 return this.ubus('net', 'iwinfo', 'txpower');
3914 * Query the radio TX power offset.
3916 * Some wireless radios have a fixed power offset, e.g. due to the
3917 * use of external amplifiers.
3920 * Returns the wireless network transmit power offset in dBm as reported
3921 * by `ubus` runtime information or `0` if there is no offset, or if it
3922 * cannot be determined.
3924 getTXPowerOffset: function() {
3925 return this.ubus('net', 'iwinfo', 'txpower_offset') || 0;
3929 * Calculate the current signal.
3933 * Returns the calculated signal level, which is the difference between
3934 * noise and signal (SNR), divided by 5.
3936 getSignalLevel: function(signal
, noise
) {
3937 if (this.getActiveBSSID() == '00:00:00:00:00:00')
3940 signal
= signal
|| this.getSignal();
3941 noise
= noise
|| this.getNoise();
3943 if (signal
< 0 && noise
< 0) {
3944 var snr
= -1 * (noise
- signal
);
3945 return Math
.floor(snr
/ 5);
3952 * Calculate the current signal quality percentage.
3955 * Returns the calculated signal quality in percent. The value is
3956 * calculated from the `quality` and `quality_max` indicators reported
3957 * by `ubus` runtime state.
3959 getSignalPercent: function() {
3960 var qc
= this.ubus('net', 'iwinfo', 'quality') || 0,
3961 qm
= this.ubus('net', 'iwinfo', 'quality_max') || 0;
3963 if (qc
> 0 && qm
> 0)
3964 return Math
.floor((100 / qm
) * qc
);
3970 * Get a short description string for this wireless network.
3973 * Returns a string describing this network, consisting of the
3974 * active operation mode, followed by either the SSID, BSSID or
3975 * internal network ID, depending on which information is available.
3977 getShortName: function() {
3978 return '%s "%s"'.format(
3979 this.getActiveModeI18n(),
3980 this.getActiveSSID() || this.getActiveBSSID() || this.getID());
3984 * Get a description string for this wireless network.
3987 * Returns a string describing this network, consisting of the
3988 * term `Wireless Network`, followed by the active operation mode,
3989 * the SSID, BSSID or internal network ID and the Linux network device
3990 * name, depending on which information is available.
3992 getI18n: function() {
3993 return '%s: %s "%s" (%s)'.format(
3994 _('Wireless Network'),
3995 this.getActiveModeI18n(),
3996 this.getActiveSSID() || this.getActiveBSSID() || this.getID(),
4001 * Get the primary logical interface this wireless network is attached to.
4003 * @returns {null|LuCI.Network.Protocol}
4004 * Returns a `Network.Protocol` instance representing the logical
4005 * interface or `null` if this network is not attached to any logical
4008 getNetwork: function() {
4009 return this.getNetworks()[0];
4013 * Get the logical interfaces this wireless network is attached to.
4015 * @returns {Array<LuCI.Network.Protocol>}
4016 * Returns an array of `Network.Protocol` instances representing the
4017 * logical interfaces this wireless network is attached to.
4019 getNetworks: function() {
4020 var networkNames
= this.getNetworkNames(),
4023 for (var i
= 0; i
< networkNames
.length
; i
++) {
4024 var uciInterface
= uci
.get('network', networkNames
[i
]);
4026 if (uciInterface
== null || uciInterface
['.type'] != 'interface')
4029 networks
.push(L
.network
.instantiateNetwork(networkNames
[i
]));
4032 networks
.sort(networkSort
);
4038 * Get the associated Linux network device.
4040 * @returns {LuCI.Network.Device}
4041 * Returns a `Network.Device` instance representing the Linux network
4042 * device associted with this wireless network.
4044 getDevice: function() {
4045 return L
.network
.instantiateDevice(this.getIfname());
4049 * Check whether this wifi network supports deauthenticating clients.
4051 * @returns {boolean}
4052 * Returns `true` when this wifi network instance supports forcibly
4053 * deauthenticating clients, otherwise `false`.
4055 isClientDisconnectSupported: function() {
4056 return L
.isObject(this.ubus('hostapd', 'del_client'));
4060 * Forcibly disconnect the given client from the wireless network.
4062 * @param {string} mac
4063 * The MAC address of the client to disconnect.
4065 * @param {boolean} [deauth=false]
4066 * Specifies whether to deauthenticate (`true`) or disassociate (`false`)
4069 * @param {number} [reason=1]
4070 * Specifies the IEEE 802.11 reason code to disassoc/deauth the client
4071 * with. Default is `1` which corresponds to `Unspecified reason`.
4073 * @param {number} [ban_time=0]
4074 * Specifies the amount of milliseconds to ban the client from
4075 * reconnecting. By default, no ban time is set which allows the client
4076 * to reassociate / reauthenticate immediately.
4078 * @returns {Promise<number>}
4079 * Returns a promise resolving to the underlying ubus call result code
4080 * which is typically `0`, even for not existing MAC addresses.
4081 * The promise might reject with an error in case invalid arguments
4084 disconnectClient: function(mac
, deauth
, reason
, ban_time
) {
4085 if (reason
== null || reason
== 0)
4091 return rpc
.declare({
4092 object
: 'hostapd.%s'.format(this.getIfname()),
4093 method
: 'del_client',
4094 params
: [ 'addr', 'deauth', 'reason', 'ban_time' ]
4095 })(mac
, deauth
, reason
, ban_time
);