c79022968ccc99132ab83285e40716f1f8b63dd4
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() {}),
982 network
= this.instantiateNetwork(name
);
984 return Promise
.all([ requireFirewall
, initNetworkState() ]).then(function() {
985 var uciInterface
= uci
.get('network', name
);
987 if (uciInterface
!= null && uciInterface
['.type'] == 'interface') {
988 return Promise
.resolve(network
? network
.deleteConfiguration() : null).then(function() {
989 uci
.remove('network', name
);
991 uci
.sections('luci', 'ifstate', function(s
) {
992 if (s
.interface == name
)
993 uci
.remove('luci', s
['.name']);
996 uci
.sections('network', 'alias', function(s
) {
997 if (s
.interface == name
)
998 uci
.remove('network', s
['.name']);
1001 uci
.sections('network', 'route', function(s
) {
1002 if (s
.interface == name
)
1003 uci
.remove('network', s
['.name']);
1006 uci
.sections('network', 'route6', function(s
) {
1007 if (s
.interface == name
)
1008 uci
.remove('network', s
['.name']);
1011 uci
.sections('wireless', 'wifi-iface', function(s
) {
1012 var networks
= L
.toArray(s
.network
).filter(function(network
) { return network
!= name
});
1014 if (networks
.length
> 0)
1015 uci
.set('wireless', s
['.name'], 'network', networks
.join(' '));
1017 uci
.unset('wireless', s
['.name'], 'network');
1021 return L
.firewall
.deleteNetwork(name
).then(function() { return true });
1024 }).catch(function() {
1034 * Rename the given network and its references to a new name.
1036 * @param {string} oldName
1037 * The current name of the network.
1039 * @param {string} newName
1040 * The name to rename the network to, must be in the format
1043 * @returns {Promise<boolean>}
1044 * Returns a promise resolving to either `true` if the network was
1045 * successfully renamed or `false` if the new name was invalid, if
1046 * a network with the new name already exists or if the network to
1047 * rename could not be found.
1049 renameNetwork: function(oldName
, newName
) {
1050 return initNetworkState().then(function() {
1051 if (newName
== null || !/^[a-zA-Z0-9_]+$/.test(newName
) || uci
.get('network', newName
) != null)
1054 var oldNetwork
= uci
.get('network', oldName
);
1056 if (oldNetwork
== null || oldNetwork
['.type'] != 'interface')
1059 var sid
= uci
.add('network', 'interface', newName
);
1061 for (var key
in oldNetwork
)
1062 if (oldNetwork
.hasOwnProperty(key
) && key
.charAt(0) != '.')
1063 uci
.set('network', sid
, key
, oldNetwork
[key
]);
1065 uci
.sections('luci', 'ifstate', function(s
) {
1066 if (s
.interface == oldName
)
1067 uci
.set('luci', s
['.name'], 'interface', newName
);
1070 uci
.sections('network', 'alias', function(s
) {
1071 if (s
.interface == oldName
)
1072 uci
.set('network', s
['.name'], 'interface', newName
);
1075 uci
.sections('network', 'route', function(s
) {
1076 if (s
.interface == oldName
)
1077 uci
.set('network', s
['.name'], 'interface', newName
);
1080 uci
.sections('network', 'route6', function(s
) {
1081 if (s
.interface == oldName
)
1082 uci
.set('network', s
['.name'], 'interface', newName
);
1085 uci
.sections('wireless', 'wifi-iface', function(s
) {
1086 var networks
= L
.toArray(s
.network
).map(function(network
) { return (network
== oldName
? newName
: network
) });
1088 if (networks
.length
> 0)
1089 uci
.set('wireless', s
['.name'], 'network', networks
.join(' '));
1092 uci
.remove('network', oldName
);
1099 * Get a {@link LuCI.Network.Device Device} instance describing the
1100 * given network device.
1102 * @param {string} name
1103 * The name of the network device to get, e.g. `eth0` or `br-lan`.
1105 * @returns {Promise<null|LuCI.Network.Device>}
1106 * Returns a promise resolving to the `Device` instance describing
1107 * the network device or `null` if the given device name could not
1110 getDevice: function(name
) {
1111 return initNetworkState().then(L
.bind(function() {
1115 if (_state
.netdevs
.hasOwnProperty(name
) || isWifiIfname(name
))
1116 return this.instantiateDevice(name
);
1118 var netid
= getWifiNetidBySid(name
);
1120 return this.instantiateDevice(netid
[0]);
1127 * Get a sorted list of all found network devices.
1129 * @returns {Promise<Array<LuCI.Network.Device>>}
1130 * Returns a promise resolving to a sorted array of `Device` class
1131 * instances describing the network devices found on the system.
1133 getDevices: function() {
1134 return initNetworkState().then(L
.bind(function() {
1137 /* find simple devices */
1138 var uciInterfaces
= uci
.sections('network', 'interface');
1139 for (var i
= 0; i
< uciInterfaces
.length
; i
++) {
1140 var ifnames
= L
.toArray(uciInterfaces
[i
].ifname
);
1142 for (var j
= 0; j
< ifnames
.length
; j
++) {
1143 if (ifnames
[j
].charAt(0) == '@')
1146 if (isIgnoredIfname(ifnames
[j
]) || isVirtualIfname(ifnames
[j
]) || isWifiIfname(ifnames
[j
]))
1149 devices
[ifnames
[j
]] = this.instantiateDevice(ifnames
[j
]);
1153 for (var ifname
in _state
.netdevs
) {
1154 if (devices
.hasOwnProperty(ifname
))
1157 if (isIgnoredIfname(ifname
) || isWifiIfname(ifname
))
1160 if (_state
.netdevs
[ifname
].wireless
)
1163 devices
[ifname
] = this.instantiateDevice(ifname
);
1166 /* find VLAN devices */
1167 var uciSwitchVLANs
= uci
.sections('network', 'switch_vlan');
1168 for (var i
= 0; i
< uciSwitchVLANs
.length
; i
++) {
1169 if (typeof(uciSwitchVLANs
[i
].ports
) != 'string' ||
1170 typeof(uciSwitchVLANs
[i
].device
) != 'string' ||
1171 !_state
.switches
.hasOwnProperty(uciSwitchVLANs
[i
].device
))
1174 var ports
= uciSwitchVLANs
[i
].ports
.split(/\s+/);
1175 for (var j
= 0; j
< ports
.length
; j
++) {
1176 var m
= ports
[j
].match(/^(\d+)([tu]?)$/);
1180 var netdev
= _state
.switches
[uciSwitchVLANs
[i
].device
].netdevs
[m
[1]];
1184 if (!devices
.hasOwnProperty(netdev
))
1185 devices
[netdev
] = this.instantiateDevice(netdev
);
1187 _state
.isSwitch
[netdev
] = true;
1192 var vid
= uciSwitchVLANs
[i
].vid
|| uciSwitchVLANs
[i
].vlan
;
1193 vid
= (vid
!= null ? +vid
: null);
1195 if (vid
== null || vid
< 0 || vid
> 4095)
1198 var vlandev
= '%s.%d'.format(netdev
, vid
);
1200 if (!devices
.hasOwnProperty(vlandev
))
1201 devices
[vlandev
] = this.instantiateDevice(vlandev
);
1203 _state
.isSwitch
[vlandev
] = true;
1207 /* find wireless interfaces */
1208 var uciWifiIfaces
= uci
.sections('wireless', 'wifi-iface'),
1211 for (var i
= 0; i
< uciWifiIfaces
.length
; i
++) {
1212 if (typeof(uciWifiIfaces
[i
].device
) != 'string')
1215 networkCount
[uciWifiIfaces
[i
].device
] = (networkCount
[uciWifiIfaces
[i
].device
] || 0) + 1;
1217 var netid
= '%s.network%d'.format(uciWifiIfaces
[i
].device
, networkCount
[uciWifiIfaces
[i
].device
]);
1219 devices
[netid
] = this.instantiateDevice(netid
);
1224 for (var netdev
in devices
)
1225 if (devices
.hasOwnProperty(netdev
))
1226 rv
.push(devices
[netdev
]);
1228 rv
.sort(deviceSort
);
1235 * Test if a given network device name is in the list of patterns for
1236 * device names to ignore.
1238 * Ignored device names are usually Linux network devices which are
1239 * spawned implicitly by kernel modules such as `tunl0` or `hwsim0`
1240 * and which are unsuitable for use in network configuration.
1242 * @param {string} name
1243 * The device name to test.
1245 * @returns {boolean}
1246 * Returns `true` if the given name is in the ignore pattern list,
1247 * else returns `false`.
1249 isIgnoredDevice: function(name
) {
1250 return isIgnoredIfname(name
);
1254 * Get a {@link LuCI.Network.WifiDevice WifiDevice} instance describing
1255 * the given wireless radio.
1257 * @param {string} devname
1258 * The configuration name of the wireless radio to lookup, e.g. `radio0`
1259 * for the first mac80211 phy on the system.
1261 * @returns {Promise<null|LuCI.Network.WifiDevice>}
1262 * Returns a promise resolving to the `WifiDevice` instance describing
1263 * the underlying radio device or `null` if the wireless radio could not
1266 getWifiDevice: function(devname
) {
1267 return initNetworkState().then(L
.bind(function() {
1268 var existingDevice
= uci
.get('wireless', devname
);
1270 if (existingDevice
== null || existingDevice
['.type'] != 'wifi-device')
1273 return this.instantiateWifiDevice(devname
, _state
.radios
[devname
] || {});
1278 * Obtain a list of all configured radio devices.
1280 * @returns {Promise<Array<LuCI.Network.WifiDevice>>}
1281 * Returns a promise resolving to an array of `WifiDevice` instances
1282 * describing the wireless radios configured in the system.
1283 * The order of the array corresponds to the order of the radios in
1284 * the configuration.
1286 getWifiDevices: function() {
1287 return initNetworkState().then(L
.bind(function() {
1288 var uciWifiDevices
= uci
.sections('wireless', 'wifi-device'),
1291 for (var i
= 0; i
< uciWifiDevices
.length
; i
++) {
1292 var devname
= uciWifiDevices
[i
]['.name'];
1293 rv
.push(this.instantiateWifiDevice(devname
, _state
.radios
[devname
] || {}));
1301 * Get a {@link LuCI.Network.WifiNetwork WifiNetwork} instance describing
1302 * the given wireless network.
1304 * @param {string} netname
1305 * The name of the wireless network to lookup. This may be either an uci
1306 * configuration section ID, a network ID in the form `radio#.network#`
1307 * or a Linux network device name like `wlan0` which is resolved to the
1308 * corresponding configuration section through `ubus` runtime information.
1310 * @returns {Promise<null|LuCI.Network.WifiNetwork>}
1311 * Returns a promise resolving to the `WifiNetwork` instance describing
1312 * the wireless network or `null` if the corresponding network could not
1315 getWifiNetwork: function(netname
) {
1316 return initNetworkState()
1317 .then(L
.bind(this.lookupWifiNetwork
, this, netname
));
1321 * Get an array of all {@link LuCI.Network.WifiNetwork WifiNetwork}
1322 * instances describing the wireless networks present on the system.
1324 * @returns {Promise<Array<LuCI.Network.WifiNetwork>>}
1325 * Returns a promise resolving to an array of `WifiNetwork` instances
1326 * describing the wireless networks. The array will be empty if no networks
1329 getWifiNetworks: function() {
1330 return initNetworkState().then(L
.bind(function() {
1331 var wifiIfaces
= uci
.sections('wireless', 'wifi-iface'),
1334 for (var i
= 0; i
< wifiIfaces
.length
; i
++)
1335 rv
.push(this.lookupWifiNetwork(wifiIfaces
[i
]['.name']));
1337 rv
.sort(function(a
, b
) {
1338 return (a
.getID() > b
.getID());
1346 * Adds a new wireless network to the configuration and sets its options
1347 * to the provided values.
1349 * @param {Object<string, string|string[]>} options
1350 * The options to set for the newly added wireless network. This object
1351 * must at least contain a `device` property which is set to the radio
1352 * name the new network belongs to.
1354 * @returns {Promise<null|LuCI.Network.WifiNetwork>}
1355 * Returns a promise resolving to a `WifiNetwork` instance describing
1356 * the newly added wireless network or `null` if the given options
1357 * were invalid or if the associated radio device could not be found.
1359 addWifiNetwork: function(options
) {
1360 return initNetworkState().then(L
.bind(function() {
1361 if (options
== null ||
1362 typeof(options
) != 'object' ||
1363 typeof(options
.device
) != 'string')
1366 var existingDevice
= uci
.get('wireless', options
.device
);
1367 if (existingDevice
== null || existingDevice
['.type'] != 'wifi-device')
1370 /* XXX: need to add a named section (wifinet#) here */
1371 var sid
= uci
.add('wireless', 'wifi-iface');
1372 for (var key
in options
)
1373 if (options
.hasOwnProperty(key
))
1374 uci
.set('wireless', sid
, key
, options
[key
]);
1376 var radioname
= existingDevice
['.name'],
1377 netid
= getWifiNetidBySid(sid
) || [];
1379 return this.instantiateWifiNetwork(sid
, radioname
, _state
.radios
[radioname
], netid
[0], null);
1384 * Deletes the given wireless network from the configuration.
1386 * @param {string} netname
1387 * The name of the network to remove. This may be either a
1388 * network ID in the form `radio#.network#` or a Linux network device
1389 * name like `wlan0` which is resolved to the corresponding configuration
1390 * section through `ubus` runtime information.
1392 * @returns {Promise<boolean>}
1393 * Returns a promise resolving to `true` if the wireless network has been
1394 * successfully deleted from the configuration or `false` if it could not
1397 deleteWifiNetwork: function(netname
) {
1398 return initNetworkState().then(L
.bind(function() {
1399 var sid
= getWifiSidByIfname(netname
);
1404 uci
.remove('wireless', sid
);
1410 getStatusByRoute: function(addr
, mask
) {
1411 return initNetworkState().then(L
.bind(function() {
1414 for (var i
= 0; i
< _state
.ifaces
.length
; i
++) {
1415 if (!Array
.isArray(_state
.ifaces
[i
].route
))
1418 for (var j
= 0; j
< _state
.ifaces
[i
].route
.length
; j
++) {
1419 if (typeof(_state
.ifaces
[i
].route
[j
]) != 'object' ||
1420 typeof(_state
.ifaces
[i
].route
[j
].target
) != 'string' ||
1421 typeof(_state
.ifaces
[i
].route
[j
].mask
) != 'number')
1424 if (_state
.ifaces
[i
].route
[j
].table
)
1427 if (_state
.ifaces
[i
].route
[j
].target
!= addr
||
1428 _state
.ifaces
[i
].route
[j
].mask
!= mask
)
1431 rv
.push(_state
.ifaces
[i
]);
1440 getStatusByAddress: function(addr
) {
1441 return initNetworkState().then(L
.bind(function() {
1444 for (var i
= 0; i
< _state
.ifaces
.length
; i
++) {
1445 if (Array
.isArray(_state
.ifaces
[i
]['ipv4-address']))
1446 for (var j
= 0; j
< _state
.ifaces
[i
]['ipv4-address'].length
; j
++)
1447 if (typeof(_state
.ifaces
[i
]['ipv4-address'][j
]) == 'object' &&
1448 _state
.ifaces
[i
]['ipv4-address'][j
].address
== addr
)
1449 return _state
.ifaces
[i
];
1451 if (Array
.isArray(_state
.ifaces
[i
]['ipv6-address']))
1452 for (var j
= 0; j
< _state
.ifaces
[i
]['ipv6-address'].length
; j
++)
1453 if (typeof(_state
.ifaces
[i
]['ipv6-address'][j
]) == 'object' &&
1454 _state
.ifaces
[i
]['ipv6-address'][j
].address
== addr
)
1455 return _state
.ifaces
[i
];
1457 if (Array
.isArray(_state
.ifaces
[i
]['ipv6-prefix-assignment']))
1458 for (var j
= 0; j
< _state
.ifaces
[i
]['ipv6-prefix-assignment'].length
; j
++)
1459 if (typeof(_state
.ifaces
[i
]['ipv6-prefix-assignment'][j
]) == 'object' &&
1460 typeof(_state
.ifaces
[i
]['ipv6-prefix-assignment'][j
]['local-address']) == 'object' &&
1461 _state
.ifaces
[i
]['ipv6-prefix-assignment'][j
]['local-address'].address
== addr
)
1462 return _state
.ifaces
[i
];
1470 * Get IPv4 wan networks.
1472 * This function looks up all networks having a default `0.0.0.0/0` route
1473 * and returns them as array.
1475 * @returns {Promise<Array<LuCI.Network.Protocol>>}
1476 * Returns a promise resolving to an array of `Protocol` subclass
1477 * instances describing the found default route interfaces.
1479 getWANNetworks: function() {
1480 return this.getStatusByRoute('0.0.0.0', 0).then(L
.bind(function(statuses
) {
1481 var rv
= [], seen
= {};
1483 for (var i
= 0; i
< statuses
.length
; i
++) {
1484 if (!seen
.hasOwnProperty(statuses
[i
].interface)) {
1485 rv
.push(this.instantiateNetwork(statuses
[i
].interface, statuses
[i
].proto
));
1486 seen
[statuses
[i
].interface] = true;
1495 * Get IPv6 wan networks.
1497 * This function looks up all networks having a default `::/0` route
1498 * and returns them as array.
1500 * @returns {Promise<Array<LuCI.Network.Protocol>>}
1501 * Returns a promise resolving to an array of `Protocol` subclass
1502 * instances describing the found IPv6 default route interfaces.
1504 getWAN6Networks: function() {
1505 return this.getStatusByRoute('::', 0).then(L
.bind(function(statuses
) {
1506 var rv
= [], seen
= {};
1508 for (var i
= 0; i
< statuses
.length
; i
++) {
1509 if (!seen
.hasOwnProperty(statuses
[i
].interface)) {
1510 rv
.push(this.instantiateNetwork(statuses
[i
].interface, statuses
[i
].proto
));
1511 seen
[statuses
[i
].interface] = true;
1520 * Describes an swconfig switch topology by specifying the CPU
1521 * connections and external port labels of a switch.
1523 * @typedef {Object<string, Object|Array>} SwitchTopology
1524 * @memberof LuCI.Network
1526 * @property {Object<number, string>} netdevs
1527 * The `netdevs` property points to an object describing the CPU port
1528 * connections of the switch. The numeric key of the enclosed object is
1529 * the port number, the value contains the Linux network device name the
1530 * port is hardwired to.
1532 * @property {Array<Object<string, boolean|number|string>>} ports
1533 * The `ports` property points to an array describing the populated
1534 * ports of the switch in the external label order. Each array item is
1535 * an object containg the following keys:
1536 * - `num` - the internal switch port number
1537 * - `label` - the label of the port, e.g. `LAN 1` or `CPU (eth0)`
1538 * - `device` - the connected Linux network device name (CPU ports only)
1539 * - `tagged` - a boolean indicating whether the port must be tagged to
1540 * function (CPU ports only)
1544 * Returns the topologies of all swconfig switches found on the system.
1546 * @returns {Promise<Object<string, LuCI.Network.SwitchTopology>>}
1547 * Returns a promise resolving to an object containing the topologies
1548 * of each switch. The object keys correspond to the name of the switches
1549 * such as `switch0`, the values are
1550 * {@link LuCI.Network.SwitchTopology SwitchTopology} objects describing
1553 getSwitchTopologies: function() {
1554 return initNetworkState().then(function() {
1555 return _state
.switches
;
1560 instantiateNetwork: function(name
, proto
) {
1564 proto
= (proto
== null ? uci
.get('network', name
, 'proto') : proto
);
1566 var protoClass
= _protocols
[proto
] || Protocol
;
1567 return new protoClass(name
);
1571 instantiateDevice: function(name
, network
, extend
) {
1573 return new (Device
.extend(extend
))(name
, network
);
1575 return new Device(name
, network
);
1579 instantiateWifiDevice: function(radioname
, radiostate
) {
1580 return new WifiDevice(radioname
, radiostate
);
1584 instantiateWifiNetwork: function(sid
, radioname
, radiostate
, netid
, netstate
, hostapd
) {
1585 return new WifiNetwork(sid
, radioname
, radiostate
, netid
, netstate
, hostapd
);
1589 lookupWifiNetwork: function(netname
) {
1590 var sid
, res
, netid
, radioname
, radiostate
, netstate
;
1592 sid
= getWifiSidByNetid(netname
);
1595 res
= getWifiStateBySid(sid
);
1597 radioname
= res
? res
[0] : null;
1598 radiostate
= res
? res
[1] : null;
1599 netstate
= res
? res
[2] : null;
1602 res
= getWifiStateByIfname(netname
);
1606 radiostate
= res
[1];
1608 sid
= netstate
.section
;
1609 netid
= L
.toArray(getWifiNetidBySid(sid
))[0];
1612 res
= getWifiStateBySid(netname
);
1616 radiostate
= res
[1];
1619 netid
= L
.toArray(getWifiNetidBySid(sid
))[0];
1622 res
= getWifiNetidBySid(netname
);
1633 return this.instantiateWifiNetwork(sid
|| netname
, radioname
,
1634 radiostate
, netid
, netstate
,
1635 netstate
? _state
.hostapd
[netstate
.ifname
] : null);
1639 * Obtains the the network device name of the given object.
1641 * @param {LuCI.Network.Protocol|LuCI.Network.Device|LuCI.Network.WifiDevice|LuCI.Network.WifiNetwork|string} obj
1642 * The object to get the device name from.
1644 * @returns {null|string}
1645 * Returns a string containing the device name or `null` if the given
1646 * object could not be converted to a name.
1648 getIfnameOf: function(obj
) {
1649 return ifnameOf(obj
);
1653 * Queries the internal DSL modem type from board information.
1655 * @returns {Promise<null|string>}
1656 * Returns a promise resolving to the type of the internal modem
1657 * (e.g. `vdsl`) or to `null` if no internal modem is present.
1659 getDSLModemType: function() {
1660 return initNetworkState().then(function() {
1661 return _state
.hasDSLModem
? _state
.hasDSLModem
.type
: null;
1666 * Queries aggregated information about known hosts.
1668 * This function aggregates information from various sources such as
1669 * DHCP lease databases, ARP and IPv6 neighbour entries, wireless
1670 * association list etc. and returns a {@link LuCI.Network.Hosts Hosts}
1671 * class instance describing the found hosts.
1673 * @returns {Promise<LuCI.Network.Hosts>}
1674 * Returns a `Hosts` instance describing host known on the system.
1676 getHostHints: function() {
1677 return initNetworkState().then(function() {
1678 return new Hosts(_state
.hosts
);
1685 * @memberof LuCI.Network
1689 * The `LuCI.Network.Hosts` class encapsulates host information aggregated
1690 * from multiple sources and provides convenience functions to access the
1691 * host information by different criteria.
1693 Hosts
= L
.Class
.extend(/** @lends LuCI.Network.Hosts.prototype */ {
1694 __init__: function(hosts
) {
1699 * Lookup the hostname associated with the given MAC address.
1701 * @param {string} mac
1702 * The MAC address to lookup.
1704 * @returns {null|string}
1705 * Returns the hostname associated with the given MAC or `null` if
1706 * no matching host could be found or if no hostname is known for
1707 * the corresponding host.
1709 getHostnameByMACAddr: function(mac
) {
1710 return this.hosts
[mac
] ? this.hosts
[mac
].name
: null;
1714 * Lookup the IPv4 address associated with the given MAC address.
1716 * @param {string} mac
1717 * The MAC address to lookup.
1719 * @returns {null|string}
1720 * Returns the IPv4 address associated with the given MAC or `null` if
1721 * no matching host could be found or if no IPv4 address is known for
1722 * the corresponding host.
1724 getIPAddrByMACAddr: function(mac
) {
1725 return this.hosts
[mac
] ? this.hosts
[mac
].ipv4
: null;
1729 * Lookup the IPv6 address associated with the given MAC address.
1731 * @param {string} mac
1732 * The MAC address to lookup.
1734 * @returns {null|string}
1735 * Returns the IPv6 address associated with the given MAC or `null` if
1736 * no matching host could be found or if no IPv6 address is known for
1737 * the corresponding host.
1739 getIP6AddrByMACAddr: function(mac
) {
1740 return this.hosts
[mac
] ? this.hosts
[mac
].ipv6
: null;
1744 * Lookup the hostname associated with the given IPv4 address.
1746 * @param {string} ipaddr
1747 * The IPv4 address to lookup.
1749 * @returns {null|string}
1750 * Returns the hostname associated with the given IPv4 or `null` if
1751 * no matching host could be found or if no hostname is known for
1752 * the corresponding host.
1754 getHostnameByIPAddr: function(ipaddr
) {
1755 for (var mac
in this.hosts
)
1756 if (this.hosts
[mac
].ipv4
== ipaddr
&& this.hosts
[mac
].name
!= null)
1757 return this.hosts
[mac
].name
;
1762 * Lookup the MAC address associated with the given IPv4 address.
1764 * @param {string} ipaddr
1765 * The IPv4 address to lookup.
1767 * @returns {null|string}
1768 * Returns the MAC address associated with the given IPv4 or `null` if
1769 * no matching host could be found or if no MAC address is known for
1770 * the corresponding host.
1772 getMACAddrByIPAddr: function(ipaddr
) {
1773 for (var mac
in this.hosts
)
1774 if (this.hosts
[mac
].ipv4
== ipaddr
)
1780 * Lookup the hostname associated with the given IPv6 address.
1782 * @param {string} ipaddr
1783 * The IPv6 address to lookup.
1785 * @returns {null|string}
1786 * Returns the hostname associated with the given IPv6 or `null` if
1787 * no matching host could be found or if no hostname is known for
1788 * the corresponding host.
1790 getHostnameByIP6Addr: function(ip6addr
) {
1791 for (var mac
in this.hosts
)
1792 if (this.hosts
[mac
].ipv6
== ip6addr
&& this.hosts
[mac
].name
!= null)
1793 return this.hosts
[mac
].name
;
1798 * Lookup the MAC address associated with the given IPv6 address.
1800 * @param {string} ipaddr
1801 * The IPv6 address to lookup.
1803 * @returns {null|string}
1804 * Returns the MAC address associated with the given IPv6 or `null` if
1805 * no matching host could be found or if no MAC address is known for
1806 * the corresponding host.
1808 getMACAddrByIP6Addr: function(ip6addr
) {
1809 for (var mac
in this.hosts
)
1810 if (this.hosts
[mac
].ipv6
== ip6addr
)
1816 * Return an array of (MAC address, name hint) tuples sorted by
1819 * @param {boolean} [preferIp6=false]
1820 * Whether to prefer IPv6 addresses (`true`) or IPv4 addresses (`false`)
1821 * as name hint when no hostname is known for a specific MAC address.
1823 * @returns {Array<Array<string>>}
1824 * Returns an array of arrays containing a name hint for each found
1825 * MAC address on the system. The array is sorted ascending by MAC.
1827 * Each item of the resulting array is a two element array with the
1828 * MAC being the first element and the name hint being the second
1829 * element. The name hint is either the hostname, an IPv4 or an IPv6
1830 * address related to the MAC address.
1832 * If no hostname but both IPv4 and IPv6 addresses are known, the
1833 * `preferIP6` flag specifies whether the IPv6 or the IPv4 address
1836 getMACHints: function(preferIp6
) {
1838 for (var mac
in this.hosts
) {
1839 var hint
= this.hosts
[mac
].name
||
1840 this.hosts
[mac
][preferIp6
? 'ipv6' : 'ipv4'] ||
1841 this.hosts
[mac
][preferIp6
? 'ipv4' : 'ipv6'];
1843 rv
.push([mac
, hint
]);
1845 return rv
.sort(function(a
, b
) { return a
[0] > b
[0] });
1851 * @memberof LuCI.Network
1855 * The `Network.Protocol` class serves as base for protocol specific
1856 * subclasses which describe logical UCI networks defined by `config
1857 * interface` sections in `/etc/config/network`.
1859 Protocol
= L
.Class
.extend(/** @lends LuCI.Network.Protocol.prototype */ {
1860 __init__: function(name
) {
1864 _get: function(opt
) {
1865 var val
= uci
.get('network', this.sid
, opt
);
1867 if (Array
.isArray(val
))
1868 return val
.join(' ');
1873 _ubus: function(field
) {
1874 for (var i
= 0; i
< _state
.ifaces
.length
; i
++) {
1875 if (_state
.ifaces
[i
].interface != this.sid
)
1878 return (field
!= null ? _state
.ifaces
[i
][field
] : _state
.ifaces
[i
]);
1883 * Read the given UCI option value of this network.
1885 * @param {string} opt
1886 * The UCI option name to read.
1888 * @returns {null|string|string[]}
1889 * Returns the UCI option value or `null` if the requested option is
1892 get: function(opt
) {
1893 return uci
.get('network', this.sid
, opt
);
1897 * Set the given UCI option of this network to the given value.
1899 * @param {string} opt
1900 * The name of the UCI option to set.
1902 * @param {null|string|string[]} val
1903 * The value to set or `null` to remove the given option from the
1906 set: function(opt
, val
) {
1907 return uci
.set('network', this.sid
, opt
, val
);
1911 * Get the associared Linux network device of this network.
1913 * @returns {null|string}
1914 * Returns the name of the associated network device or `null` if
1915 * it could not be determined.
1917 getIfname: function() {
1920 if (this.isFloating())
1921 ifname
= this._ubus('l3_device');
1923 ifname
= this._ubus('device') || this._ubus('l3_device');
1928 var res
= getWifiNetidByNetname(this.sid
);
1929 return (res
!= null ? res
[0] : null);
1933 * Get the name of this network protocol class.
1935 * This function will be overwritten by subclasses created by
1936 * {@link LuCI.Network#registerProtocol Network.registerProtocol()}.
1940 * Returns the name of the network protocol implementation, e.g.
1941 * `static` or `dhcp`.
1943 getProtocol: function() {
1948 * Return a human readable description for the protcol, such as
1949 * `Static address` or `DHCP client`.
1951 * This function should be overwritten by subclasses.
1955 * Returns the description string.
1957 getI18n: function() {
1958 switch (this.getProtocol()) {
1959 case 'none': return _('Unmanaged');
1960 case 'static': return _('Static address');
1961 case 'dhcp': return _('DHCP client');
1962 default: return _('Unknown');
1967 * Get the type of the underlying interface.
1969 * This function actually is a convenience wrapper around
1970 * `proto.get("type")` and is mainly used by other `LuCI.Network` code
1971 * to check whether the interface is declared as bridge in UCI.
1973 * @returns {null|string}
1974 * Returns the value of the `type` option of the associated logical
1975 * interface or `null` if no `type` option is set.
1977 getType: function() {
1978 return this._get('type');
1982 * Get the name of the associated logical interface.
1985 * Returns the logical interface name, such as `lan` or `wan`.
1987 getName: function() {
1992 * Get the uptime of the logical interface.
1995 * Returns the uptime of the associated interface in seconds.
1997 getUptime: function() {
1998 return this._ubus('uptime') || 0;
2002 * Get the logical interface expiry time in seconds.
2004 * For protocols that have a concept of a lease, such as DHCP or
2005 * DHCPv6, this function returns the remaining time in seconds
2006 * until the lease expires.
2009 * Returns the amount of seconds until the lease expires or `-1`
2010 * if it isn't applicable to the associated protocol.
2012 getExpiry: function() {
2013 var u
= this._ubus('uptime'),
2014 d
= this._ubus('data');
2016 if (typeof(u
) == 'number' && d
!= null &&
2017 typeof(d
) == 'object' && typeof(d
.leasetime
) == 'number') {
2018 var r
= d
.leasetime
- (u
% d
.leasetime
);
2019 return (r
> 0 ? r
: 0);
2026 * Get the metric value of the logical interface.
2029 * Returns the current metric value used for device and network
2030 * routes spawned by the associated logical interface.
2032 getMetric: function() {
2033 return this._ubus('metric') || 0;
2037 * Get the requested firewall zone name of the logical interface.
2039 * Some protocol implementations request a specific firewall zone
2040 * to trigger inclusion of their resulting network devices into the
2041 * firewall rule set.
2043 * @returns {null|string}
2044 * Returns the requested firewall zone name as published in the
2045 * `ubus` runtime information or `null` if the remote protocol
2046 * handler didn't request a zone.
2048 getZoneName: function() {
2049 var d
= this._ubus('data');
2051 if (L
.isObject(d
) && typeof(d
.zone
) == 'string')
2058 * Query the first (primary) IPv4 address of the logical interface.
2060 * @returns {null|string}
2061 * Returns the primary IPv4 address registered by the protocol handler
2062 * or `null` if no IPv4 addresses were set.
2064 getIPAddr: function() {
2065 var addrs
= this._ubus('ipv4-address');
2066 return ((Array
.isArray(addrs
) && addrs
.length
) ? addrs
[0].address
: null);
2070 * Query all IPv4 addresses of the logical interface.
2072 * @returns {string[]}
2073 * Returns an array of IPv4 addresses in CIDR notation which have been
2074 * registered by the protocol handler. The order of the resulting array
2075 * follows the order of the addresses in `ubus` runtime information.
2077 getIPAddrs: function() {
2078 var addrs
= this._ubus('ipv4-address'),
2081 if (Array
.isArray(addrs
))
2082 for (var i
= 0; i
< addrs
.length
; i
++)
2083 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2089 * Query the first (primary) IPv4 netmask of the logical interface.
2091 * @returns {null|string}
2092 * Returns the netmask of the primary IPv4 address registered by the
2093 * protocol handler or `null` if no IPv4 addresses were set.
2095 getNetmask: function() {
2096 var addrs
= this._ubus('ipv4-address');
2097 if (Array
.isArray(addrs
) && addrs
.length
)
2098 return prefixToMask(addrs
[0].mask
, false);
2102 * Query the gateway (nexthop) of the default route associated with
2103 * this logical interface.
2106 * Returns a string containing the IPv4 nexthop address of the associated
2107 * default route or `null` if no default route was found.
2109 getGatewayAddr: function() {
2110 var routes
= this._ubus('route');
2112 if (Array
.isArray(routes
))
2113 for (var i
= 0; i
< routes
.length
; i
++)
2114 if (typeof(routes
[i
]) == 'object' &&
2115 routes
[i
].target
== '0.0.0.0' &&
2116 routes
[i
].mask
== 0)
2117 return routes
[i
].nexthop
;
2123 * Query the IPv4 DNS servers associated with the logical interface.
2125 * @returns {string[]}
2126 * Returns an array of IPv4 DNS servers registered by the remote
2129 getDNSAddrs: function() {
2130 var addrs
= this._ubus('dns-server'),
2133 if (Array
.isArray(addrs
))
2134 for (var i
= 0; i
< addrs
.length
; i
++)
2135 if (!/:/.test(addrs
[i
]))
2142 * Query the first (primary) IPv6 address of the logical interface.
2144 * @returns {null|string}
2145 * Returns the primary IPv6 address registered by the protocol handler
2146 * in CIDR notation or `null` if no IPv6 addresses were set.
2148 getIP6Addr: function() {
2149 var addrs
= this._ubus('ipv6-address');
2151 if (Array
.isArray(addrs
) && L
.isObject(addrs
[0]))
2152 return '%s/%d'.format(addrs
[0].address
, addrs
[0].mask
);
2154 addrs
= this._ubus('ipv6-prefix-assignment');
2156 if (Array
.isArray(addrs
) && L
.isObject(addrs
[0]) && L
.isObject(addrs
[0]['local-address']))
2157 return '%s/%d'.format(addrs
[0]['local-address'].address
, addrs
[0]['local-address'].mask
);
2163 * Query all IPv6 addresses of the logical interface.
2165 * @returns {string[]}
2166 * Returns an array of IPv6 addresses in CIDR notation which have been
2167 * registered by the protocol handler. The order of the resulting array
2168 * follows the order of the addresses in `ubus` runtime information.
2170 getIP6Addrs: function() {
2171 var addrs
= this._ubus('ipv6-address'),
2174 if (Array
.isArray(addrs
))
2175 for (var i
= 0; i
< addrs
.length
; i
++)
2176 if (L
.isObject(addrs
[i
]))
2177 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2179 addrs
= this._ubus('ipv6-prefix-assignment');
2181 if (Array
.isArray(addrs
))
2182 for (var i
= 0; i
< addrs
.length
; i
++)
2183 if (L
.isObject(addrs
[i
]) && L
.isObject(addrs
[i
]['local-address']))
2184 rv
.push('%s/%d'.format(addrs
[i
]['local-address'].address
, addrs
[i
]['local-address'].mask
));
2190 * Query the gateway (nexthop) of the IPv6 default route associated with
2191 * this logical interface.
2194 * Returns a string containing the IPv6 nexthop address of the associated
2195 * default route or `null` if no default route was found.
2197 getGateway6Addr: function() {
2198 var routes
= this._ubus('route');
2200 if (Array
.isArray(routes
))
2201 for (var i
= 0; i
< routes
.length
; i
++)
2202 if (typeof(routes
[i
]) == 'object' &&
2203 routes
[i
].target
== '::' &&
2204 routes
[i
].mask
== 0)
2205 return routes
[i
].nexthop
;
2211 * Query the IPv6 DNS servers associated with the logical interface.
2213 * @returns {string[]}
2214 * Returns an array of IPv6 DNS servers registered by the remote
2217 getDNS6Addrs: function() {
2218 var addrs
= this._ubus('dns-server'),
2221 if (Array
.isArray(addrs
))
2222 for (var i
= 0; i
< addrs
.length
; i
++)
2223 if (/:/.test(addrs
[i
]))
2230 * Query the routed IPv6 prefix associated with the logical interface.
2232 * @returns {null|string}
2233 * Returns the routed IPv6 prefix registered by the remote protocol
2234 * handler or `null` if no prefix is present.
2236 getIP6Prefix: function() {
2237 var prefixes
= this._ubus('ipv6-prefix');
2239 if (Array
.isArray(prefixes
) && L
.isObject(prefixes
[0]))
2240 return '%s/%d'.format(prefixes
[0].address
, prefixes
[0].mask
);
2246 * Query interface error messages published in `ubus` runtime state.
2248 * Interface errors are emitted by remote protocol handlers if the setup
2249 * of the underlying logical interface failed, e.g. due to bad
2250 * configuration or network connectivity issues.
2252 * This function will translate the found error codes to human readable
2253 * messages using the descriptions registered by
2254 * {@link LuCI.Network#registerErrorCode Network.registerErrorCode()}
2255 * and fall back to `"Unknown error (%s)"` where `%s` is replaced by the
2256 * error code in case no translation can be found.
2258 * @returns {string[]}
2259 * Returns an array of translated interface error messages.
2261 getErrors: function() {
2262 var errors
= this._ubus('errors'),
2265 if (Array
.isArray(errors
)) {
2266 for (var i
= 0; i
< errors
.length
; i
++) {
2267 if (!L
.isObject(errors
[i
]) || typeof(errors
[i
].code
) != 'string')
2271 rv
.push(proto_errors
[errors
[i
].code
] || _('Unknown error (%s)').format(errors
[i
].code
));
2279 * Checks whether the underlying logical interface is declared as bridge.
2281 * @returns {boolean}
2282 * Returns `true` when the interface is declared with `option type bridge`
2283 * and when the associated protocol implementation is not marked virtual
2284 * or `false` when the logical interface is no bridge.
2286 isBridge: function() {
2287 return (!this.isVirtual() && this.getType() == 'bridge');
2291 * Get the name of the opkg package providing the protocol functionality.
2293 * This function should be overwritten by protocol specific subclasses.
2298 * Returns the name of the opkg package required for the protocol to
2299 * function, e.g. `odhcp6c` for the `dhcpv6` prototocol.
2301 getOpkgPackage: function() {
2306 * Check function for the protocol handler if a new interface is createable.
2308 * This function should be overwritten by protocol specific subclasses.
2312 * @param {string} ifname
2313 * The name of the interface to be created.
2315 * @returns {Promise<null|error message>}
2316 * Returns `null` if new interface is createable, else returns (error) message.
2318 isCreateable: function(ifname
) {
2319 return Promise
.resolve(null);
2323 * Checks whether the protocol functionality is installed.
2325 * This function exists for compatibility with old code, it always
2331 * @returns {boolean}
2332 * Returns `true` if the protocol support is installed, else `false`.
2334 isInstalled: function() {
2339 * Checks whether this protocol is "virtual".
2341 * A "virtual" protocol is a protocol which spawns its own interfaces
2342 * on demand instead of using existing physical interfaces.
2344 * Examples for virtual protocols are `6in4` which `gre` spawn tunnel
2345 * network device on startup, examples for non-virtual protcols are
2346 * `dhcp` or `static` which apply IP configuration to existing interfaces.
2348 * This function should be overwritten by subclasses.
2350 * @returns {boolean}
2351 * Returns a boolean indicating whether the underlying protocol spawns
2352 * dynamic interfaces (`true`) or not (`false`).
2354 isVirtual: function() {
2359 * Checks whether this protocol is "floating".
2361 * A "floating" protocol is a protocol which spawns its own interfaces
2362 * on demand, like a virtual one but which relies on an existinf lower
2363 * level interface to initiate the connection.
2365 * An example for such a protocol is "pppoe".
2367 * This function exists for backwards compatibility with older code
2368 * but should not be used anymore.
2371 * @returns {boolean}
2372 * Returns a boolean indicating whether this protocol is floating (`true`)
2375 isFloating: function() {
2380 * Checks whether this logical interface is dynamic.
2382 * A dynamic interface is an interface which has been created at runtime,
2383 * e.g. as sub-interface of another interface, but which is not backed by
2384 * any user configuration. Such dynamic interfaces cannot be edited but
2385 * only brought down or restarted.
2387 * @returns {boolean}
2388 * Returns a boolean indicating whether this interface is dynamic (`true`)
2391 isDynamic: function() {
2392 return (this._ubus('dynamic') == true);
2396 * Checks whether this interface is an alias interface.
2398 * Alias interfaces are interfaces layering on top of another interface
2399 * and are denoted by a special `@interfacename` notation in the
2400 * underlying `ifname` option.
2402 * @returns {null|string}
2403 * Returns the name of the parent interface if this logical interface
2404 * is an alias or `null` if it is not an alias interface.
2406 isAlias: function() {
2407 var ifnames
= L
.toArray(uci
.get('network', this.sid
, 'ifname')),
2410 for (var i
= 0; i
< ifnames
.length
; i
++)
2411 if (ifnames
[i
].charAt(0) == '@')
2412 parent
= ifnames
[i
].substr(1);
2413 else if (parent
!= null)
2420 * Checks whether this logical interface is "empty", meaning that ut
2421 * has no network devices attached.
2423 * @returns {boolean}
2424 * Returns `true` if this logical interface is empty, else `false`.
2426 isEmpty: function() {
2427 if (this.isFloating())
2431 ifname
= this._get('ifname');
2433 if (ifname
!= null && ifname
.match(/\S+/))
2436 if (empty
== true && getWifiNetidBySid(this.sid
) != null)
2443 * Checks whether this logical interface is configured and running.
2445 * @returns {boolean}
2446 * Returns `true` when the interface is active or `false` when it is not.
2449 return (this._ubus('up') == true);
2453 * Add the given network device to the logical interface.
2455 * @param {LuCI.Network.Protocol|LuCI.Network.Device|LuCI.Network.WifiDevice|LuCI.Network.WifiNetwork|string} device
2456 * The object or device name to add to the logical interface. In case the
2457 * given argument is not a string, it is resolved though the
2458 * {@link LuCI.Network#getIfnameOf Network.getIfnameOf()} function.
2460 * @returns {boolean}
2461 * Returns `true` if the device name has been added or `false` if any
2462 * argument was invalid, if the device was already part of the logical
2463 * interface or if the logical interface is virtual.
2465 addDevice: function(ifname
) {
2466 ifname
= ifnameOf(ifname
);
2468 if (ifname
== null || this.isFloating())
2471 var wif
= getWifiSidByIfname(ifname
);
2474 return appendValue('wireless', wif
, 'network', this.sid
);
2476 return appendValue('network', this.sid
, 'ifname', ifname
);
2480 * Remove the given network device from the logical interface.
2482 * @param {LuCI.Network.Protocol|LuCI.Network.Device|LuCI.Network.WifiDevice|LuCI.Network.WifiNetwork|string} device
2483 * The object or device name to remove from the logical interface. In case
2484 * the given argument is not a string, it is resolved though the
2485 * {@link LuCI.Network#getIfnameOf Network.getIfnameOf()} function.
2487 * @returns {boolean}
2488 * Returns `true` if the device name has been added or `false` if any
2489 * argument was invalid, if the device was already part of the logical
2490 * interface or if the logical interface is virtual.
2492 deleteDevice: function(ifname
) {
2495 ifname
= ifnameOf(ifname
);
2497 if (ifname
== null || this.isFloating())
2500 var wif
= getWifiSidByIfname(ifname
);
2503 rv
= removeValue('wireless', wif
, 'network', this.sid
);
2505 if (removeValue('network', this.sid
, 'ifname', ifname
))
2512 * Returns the Linux network device associated with this logical
2515 * @returns {LuCI.Network.Device}
2516 * Returns a `Network.Device` class instance representing the
2517 * expected Linux network device according to the configuration.
2519 getDevice: function() {
2520 if (this.isVirtual()) {
2521 var ifname
= '%s-%s'.format(this.getProtocol(), this.sid
);
2522 _state
.isTunnel
[this.getProtocol() + '-' + this.sid
] = true;
2523 return L
.network
.instantiateDevice(ifname
, this);
2525 else if (this.isBridge()) {
2526 var ifname
= 'br-%s'.format(this.sid
);
2527 _state
.isBridge
[ifname
] = true;
2528 return new Device(ifname
, this);
2531 var ifnames
= L
.toArray(uci
.get('network', this.sid
, 'ifname'));
2533 for (var i
= 0; i
< ifnames
.length
; i
++) {
2534 var m
= ifnames
[i
].match(/^([^:/]+)/);
2535 return ((m
&& m
[1]) ? L
.network
.instantiateDevice(m
[1], this) : null);
2538 ifname
= getWifiNetidByNetname(this.sid
);
2540 return (ifname
!= null ? L
.network
.instantiateDevice(ifname
[0], this) : null);
2545 * Returns the layer 2 linux network device currently associated
2546 * with this logical interface.
2548 * @returns {LuCI.Network.Device}
2549 * Returns a `Network.Device` class instance representing the Linux
2550 * network device currently associated with the logical interface.
2552 getL2Device: function() {
2553 var ifname
= this._ubus('device');
2554 return (ifname
!= null ? L
.network
.instantiateDevice(ifname
, this) : null);
2558 * Returns the layer 3 linux network device currently associated
2559 * with this logical interface.
2561 * @returns {LuCI.Network.Device}
2562 * Returns a `Network.Device` class instance representing the Linux
2563 * network device currently associated with the logical interface.
2565 getL3Device: function() {
2566 var ifname
= this._ubus('l3_device');
2567 return (ifname
!= null ? L
.network
.instantiateDevice(ifname
, this) : null);
2571 * Returns a list of network sub-devices associated with this logical
2574 * @returns {null|Array<LuCI.Network.Device>}
2575 * Returns an array of of `Network.Device` class instances representing
2576 * the sub-devices attached to this logical interface or `null` if the
2577 * logical interface does not support sub-devices, e.g. because it is
2578 * virtual and not a bridge.
2580 getDevices: function() {
2583 if (!this.isBridge() && !(this.isVirtual() && !this.isFloating()))
2586 var ifnames
= L
.toArray(uci
.get('network', this.sid
, 'ifname'));
2588 for (var i
= 0; i
< ifnames
.length
; i
++) {
2589 if (ifnames
[i
].charAt(0) == '@')
2592 var m
= ifnames
[i
].match(/^([^:/]+)/);
2594 rv
.push(L
.network
.instantiateDevice(m
[1], this));
2597 var uciWifiIfaces
= uci
.sections('wireless', 'wifi-iface');
2599 for (var i
= 0; i
< uciWifiIfaces
.length
; i
++) {
2600 if (typeof(uciWifiIfaces
[i
].device
) != 'string')
2603 var networks
= L
.toArray(uciWifiIfaces
[i
].network
);
2605 for (var j
= 0; j
< networks
.length
; j
++) {
2606 if (networks
[j
] != this.sid
)
2609 var netid
= getWifiNetidBySid(uciWifiIfaces
[i
]['.name']);
2612 rv
.push(L
.network
.instantiateDevice(netid
[0], this));
2616 rv
.sort(deviceSort
);
2622 * Checks whether this logical interface contains the given device
2625 * @param {LuCI.Network.Protocol|LuCI.Network.Device|LuCI.Network.WifiDevice|LuCI.Network.WifiNetwork|string} device
2626 * The object or device name to check. In case the given argument is not
2627 * a string, it is resolved though the
2628 * {@link LuCI.Network#getIfnameOf Network.getIfnameOf()} function.
2630 * @returns {boolean}
2631 * Returns `true` when this logical interface contains the given network
2632 * device or `false` if not.
2634 containsDevice: function(ifname
) {
2635 ifname
= ifnameOf(ifname
);
2639 else if (this.isVirtual() && '%s-%s'.format(this.getProtocol(), this.sid
) == ifname
)
2641 else if (this.isBridge() && 'br-%s'.format(this.sid
) == ifname
)
2644 var ifnames
= L
.toArray(uci
.get('network', this.sid
, 'ifname'));
2646 for (var i
= 0; i
< ifnames
.length
; i
++) {
2647 var m
= ifnames
[i
].match(/^([^:/]+)/);
2648 if (m
!= null && m
[1] == ifname
)
2652 var wif
= getWifiSidByIfname(ifname
);
2655 var networks
= L
.toArray(uci
.get('wireless', wif
, 'network'));
2657 for (var i
= 0; i
< networks
.length
; i
++)
2658 if (networks
[i
] == this.sid
)
2666 * Cleanup related configuration entries.
2668 * This function will be invoked if an interface is about to be removed
2669 * from the configuration and is responsible for performing any required
2670 * cleanup tasks, such as unsetting uci entries in related configurations.
2672 * It should be overwritten by protocol specific subclasses.
2676 * @returns {*|Promise<*>}
2677 * This function may return a promise which is awaited before the rest of
2678 * the configuration is removed. Any non-promise return value and any
2679 * resolved promise value is ignored. If the returned promise is rejected,
2680 * the interface removal will be aborted.
2682 deleteConfiguration: function() {}
2687 * @memberof LuCI.Network
2691 * A `Network.Device` class instance represents an underlying Linux network
2692 * device and allows querying device details such as packet statistics or MTU.
2694 Device
= L
.Class
.extend(/** @lends LuCI.Network.Device.prototype */ {
2695 __init__: function(ifname
, network
) {
2696 var wif
= getWifiSidByIfname(ifname
);
2699 var res
= getWifiStateBySid(wif
) || [],
2700 netid
= getWifiNetidBySid(wif
) || [];
2702 this.wif
= new WifiNetwork(wif
, res
[0], res
[1], netid
[0], res
[2], { ifname
: ifname
});
2703 this.ifname
= this.wif
.getIfname();
2706 this.ifname
= this.ifname
|| ifname
;
2707 this.dev
= _state
.netdevs
[this.ifname
];
2708 this.network
= network
;
2711 _devstate: function(/* ... */) {
2714 for (var i
= 0; i
< arguments
.length
; i
++)
2716 rv
= rv
[arguments
[i
]];
2724 * Get the name of the network device.
2727 * Returns the name of the device, e.g. `eth0` or `wlan0`.
2729 getName: function() {
2730 return (this.wif
!= null ? this.wif
.getIfname() : this.ifname
);
2734 * Get the MAC address of the device.
2736 * @returns {null|string}
2737 * Returns the MAC address of the device or `null` if not applicable,
2738 * e.g. for non-ethernet tunnel devices.
2740 getMAC: function() {
2741 var mac
= this._devstate('macaddr');
2742 return mac
? mac
.toUpperCase() : null;
2746 * Get the MTU of the device.
2749 * Returns the MTU of the device.
2751 getMTU: function() {
2752 return this._devstate('mtu');
2756 * Get the IPv4 addresses configured on the device.
2758 * @returns {string[]}
2759 * Returns an array of IPv4 address strings.
2761 getIPAddrs: function() {
2762 var addrs
= this._devstate('ipaddrs');
2763 return (Array
.isArray(addrs
) ? addrs
: []);
2767 * Get the IPv6 addresses configured on the device.
2769 * @returns {string[]}
2770 * Returns an array of IPv6 address strings.
2772 getIP6Addrs: function() {
2773 var addrs
= this._devstate('ip6addrs');
2774 return (Array
.isArray(addrs
) ? addrs
: []);
2778 * Get the type of the device..
2781 * Returns a string describing the type of the network device:
2782 * - `alias` if it is an abstract alias device (`@` notation)
2783 * - `wifi` if it is a wireless interface (e.g. `wlan0`)
2784 * - `bridge` if it is a bridge device (e.g. `br-lan`)
2785 * - `tunnel` if it is a tun or tap device (e.g. `tun0`)
2786 * - `vlan` if it is a vlan device (e.g. `eth0.1`)
2787 * - `switch` if it is a switch device (e.g.`eth1` connected to switch0)
2788 * - `ethernet` for all other device types
2790 getType: function() {
2791 if (this.ifname
!= null && this.ifname
.charAt(0) == '@')
2793 else if (this.wif
!= null || isWifiIfname(this.ifname
))
2795 else if (_state
.isBridge
[this.ifname
])
2797 else if (_state
.isTunnel
[this.ifname
])
2799 else if (this.ifname
.indexOf('.') > -1)
2801 else if (_state
.isSwitch
[this.ifname
])
2808 * Get a short description string for the device.
2811 * Returns the device name for non-wifi devices or a string containing
2812 * the operation mode and SSID for wifi devices.
2814 getShortName: function() {
2815 if (this.wif
!= null)
2816 return this.wif
.getShortName();
2822 * Get a long description string for the device.
2825 * Returns a string containing the type description and device name
2826 * for non-wifi devices or operation mode and ssid for wifi ones.
2828 getI18n: function() {
2829 if (this.wif
!= null) {
2830 return '%s: %s "%s"'.format(
2831 _('Wireless Network'),
2832 this.wif
.getActiveMode(),
2833 this.wif
.getActiveSSID() || this.wif
.getActiveBSSID() || this.wif
.getID() || '?');
2836 return '%s: "%s"'.format(this.getTypeI18n(), this.getName());
2840 * Get a string describing the device type.
2843 * Returns a string describing the type, e.g. "Wireless Adapter" or
2846 getTypeI18n: function() {
2847 switch (this.getType()) {
2849 return _('Alias Interface');
2852 return _('Wireless Adapter');
2858 return _('Ethernet Switch');
2861 return (_state
.isSwitch
[this.ifname
] ? _('Switch VLAN') : _('Software VLAN'));
2864 return _('Tunnel Interface');
2867 return _('Ethernet Adapter');
2872 * Get the associated bridge ports of the device.
2874 * @returns {null|Array<LuCI.Network.Device>}
2875 * Returns an array of `Network.Device` instances representing the ports
2876 * (slave interfaces) of the bridge or `null` when this device isn't
2879 getPorts: function() {
2880 var br
= _state
.bridges
[this.ifname
],
2883 if (br
== null || !Array
.isArray(br
.ifnames
))
2886 for (var i
= 0; i
< br
.ifnames
.length
; i
++)
2887 rv
.push(L
.network
.instantiateDevice(br
.ifnames
[i
].name
));
2889 rv
.sort(deviceSort
);
2897 * @returns {null|string}
2898 * Returns the ID of this network bridge or `null` if this network
2899 * device is not a Linux bridge.
2901 getBridgeID: function() {
2902 var br
= _state
.bridges
[this.ifname
];
2903 return (br
!= null ? br
.id
: null);
2907 * Get the bridge STP setting
2909 * @returns {boolean}
2910 * Returns `true` when this device is a Linux bridge and has `stp`
2911 * enabled, else `false`.
2913 getBridgeSTP: function() {
2914 var br
= _state
.bridges
[this.ifname
];
2915 return (br
!= null ? !!br
.stp
: false);
2919 * Checks whether this device is up.
2921 * @returns {boolean}
2922 * Returns `true` when the associated device is running pr `false`
2923 * when it is down or absent.
2926 var up
= this._devstate('flags', 'up');
2929 up
= (this.getType() == 'alias');
2935 * Checks whether this device is a Linux bridge.
2937 * @returns {boolean}
2938 * Returns `true` when the network device is present and a Linux bridge,
2941 isBridge: function() {
2942 return (this.getType() == 'bridge');
2946 * Checks whether this device is part of a Linux bridge.
2948 * @returns {boolean}
2949 * Returns `true` when this network device is part of a bridge,
2952 isBridgePort: function() {
2953 return (this._devstate('bridge') != null);
2957 * Get the amount of transmitted bytes.
2960 * Returns the amount of bytes transmitted by the network device.
2962 getTXBytes: function() {
2963 var stat
= this._devstate('stats');
2964 return (stat
!= null ? stat
.tx_bytes
|| 0 : 0);
2968 * Get the amount of received bytes.
2971 * Returns the amount of bytes received by the network device.
2973 getRXBytes: function() {
2974 var stat
= this._devstate('stats');
2975 return (stat
!= null ? stat
.rx_bytes
|| 0 : 0);
2979 * Get the amount of transmitted packets.
2982 * Returns the amount of packets transmitted by the network device.
2984 getTXPackets: function() {
2985 var stat
= this._devstate('stats');
2986 return (stat
!= null ? stat
.tx_packets
|| 0 : 0);
2990 * Get the amount of received packets.
2993 * Returns the amount of packets received by the network device.
2995 getRXPackets: function() {
2996 var stat
= this._devstate('stats');
2997 return (stat
!= null ? stat
.rx_packets
|| 0 : 0);
3001 * Get the primary logical interface this device is assigned to.
3003 * @returns {null|LuCI.Network.Protocol}
3004 * Returns a `Network.Protocol` instance representing the logical
3005 * interface this device is attached to or `null` if it is not
3006 * assigned to any logical interface.
3008 getNetwork: function() {
3009 return this.getNetworks()[0];
3013 * Get the logical interfaces this device is assigned to.
3015 * @returns {Array<LuCI.Network.Protocol>}
3016 * Returns an array of `Network.Protocol` instances representing the
3017 * logical interfaces this device is assigned to.
3019 getNetworks: function() {
3020 if (this.networks
== null) {
3023 var networks
= enumerateNetworks
.apply(L
.network
);
3025 for (var i
= 0; i
< networks
.length
; i
++)
3026 if (networks
[i
].containsDevice(this.ifname
) || networks
[i
].getIfname() == this.ifname
)
3027 this.networks
.push(networks
[i
]);
3029 this.networks
.sort(networkSort
);
3032 return this.networks
;
3036 * Get the related wireless network this device is related to.
3038 * @returns {null|LuCI.Network.WifiNetwork}
3039 * Returns a `Network.WifiNetwork` instance representing the wireless
3040 * network corresponding to this network device or `null` if this device
3041 * is not a wireless device.
3043 getWifiNetwork: function() {
3044 return (this.wif
!= null ? this.wif
: null);
3050 * @memberof LuCI.Network
3054 * A `Network.WifiDevice` class instance represents a wireless radio device
3055 * present on the system and provides wireless capability information as
3056 * well as methods for enumerating related wireless networks.
3058 WifiDevice
= L
.Class
.extend(/** @lends LuCI.Network.WifiDevice.prototype */ {
3059 __init__: function(name
, radiostate
) {
3060 var uciWifiDevice
= uci
.get('wireless', name
);
3062 if (uciWifiDevice
!= null &&
3063 uciWifiDevice
['.type'] == 'wifi-device' &&
3064 uciWifiDevice
['.name'] != null) {
3065 this.sid
= uciWifiDevice
['.name'];
3068 this.sid
= this.sid
|| name
;
3076 ubus: function(/* ... */) {
3077 var v
= this._ubusdata
;
3079 for (var i
= 0; i
< arguments
.length
; i
++)
3081 v
= v
[arguments
[i
]];
3089 * Read the given UCI option value of this wireless device.
3091 * @param {string} opt
3092 * The UCI option name to read.
3094 * @returns {null|string|string[]}
3095 * Returns the UCI option value or `null` if the requested option is
3098 get: function(opt
) {
3099 return uci
.get('wireless', this.sid
, opt
);
3103 * Set the given UCI option of this network to the given value.
3105 * @param {string} opt
3106 * The name of the UCI option to set.
3108 * @param {null|string|string[]} val
3109 * The value to set or `null` to remove the given option from the
3112 set: function(opt
, value
) {
3113 return uci
.set('wireless', this.sid
, opt
, value
);
3117 * Checks whether this wireless radio is disabled.
3119 * @returns {boolean}
3120 * Returns `true` when the wireless radio is marked as disabled in `ubus`
3121 * runtime state or when the `disabled` option is set in the corresponding
3122 * UCI configuration.
3124 isDisabled: function() {
3125 return this.ubus('dev', 'disabled') || this.get('disabled') == '1';
3129 * Get the configuration name of this wireless radio.
3132 * Returns the UCI section name (e.g. `radio0`) of the corresponding
3133 * radio configuration which also serves as unique logical identifier
3134 * for the wireless phy.
3136 getName: function() {
3141 * Gets a list of supported hwmodes.
3143 * The hwmode values describe the frequency band and wireless standard
3144 * versions supported by the wireless phy.
3146 * @returns {string[]}
3147 * Returns an array of valid hwmode values for this radio. Currently
3148 * known mode values are:
3149 * - `a` - Legacy 802.11a mode, 5 GHz, up to 54 Mbit/s
3150 * - `b` - Legacy 802.11b mode, 2.4 GHz, up to 11 Mbit/s
3151 * - `g` - Legacy 802.11g mode, 2.4 GHz, up to 54 Mbit/s
3152 * - `n` - IEEE 802.11n mode, 2.4 or 5 GHz, up to 600 Mbit/s
3153 * - `ac` - IEEE 802.11ac mode, 5 GHz, up to 6770 Mbit/s
3155 getHWModes: function() {
3156 var hwmodes
= this.ubus('dev', 'iwinfo', 'hwmodes');
3157 return Array
.isArray(hwmodes
) ? hwmodes
: [ 'b', 'g' ];
3161 * Gets a list of supported htmodes.
3163 * The htmode values describe the wide-frequency options supported by
3166 * @returns {string[]}
3167 * Returns an array of valid htmode values for this radio. Currently
3168 * known mode values are:
3169 * - `HT20` - applicable to IEEE 802.11n, 20 MHz wide channels
3170 * - `HT40` - applicable to IEEE 802.11n, 40 MHz wide channels
3171 * - `VHT20` - applicable to IEEE 802.11ac, 20 MHz wide channels
3172 * - `VHT40` - applicable to IEEE 802.11ac, 40 MHz wide channels
3173 * - `VHT80` - applicable to IEEE 802.11ac, 80 MHz wide channels
3174 * - `VHT160` - applicable to IEEE 802.11ac, 160 MHz wide channels
3176 getHTModes: function() {
3177 var htmodes
= this.ubus('dev', 'iwinfo', 'htmodes');
3178 return (Array
.isArray(htmodes
) && htmodes
.length
) ? htmodes
: null;
3182 * Get a string describing the wireless radio hardware.
3185 * Returns the description string.
3187 getI18n: function() {
3188 var hw
= this.ubus('dev', 'iwinfo', 'hardware'),
3189 type
= L
.isObject(hw
) ? hw
.name
: null;
3191 if (this.ubus('dev', 'iwinfo', 'type') == 'wl')
3194 var hwmodes
= this.getHWModes(),
3197 hwmodes
.sort(function(a
, b
) {
3198 return (a
.length
!= b
.length
? a
.length
> b
.length
: a
> b
);
3201 modestr
= hwmodes
.join('');
3203 return '%s 802.11%s Wireless Controller (%s)'.format(type
|| 'Generic', modestr
, this.getName());
3207 * A wireless scan result object describes a neighbouring wireless
3208 * network found in the vincinity.
3210 * @typedef {Object<string, number|string|LuCI.Network.WifiEncryption>} WifiScanResult
3211 * @memberof LuCI.Network
3213 * @property {string} ssid
3214 * The SSID / Mesh ID of the network.
3216 * @property {string} bssid
3217 * The BSSID if the network.
3219 * @property {string} mode
3220 * The operation mode of the network (`Master`, `Ad-Hoc`, `Mesh Point`).
3222 * @property {number} channel
3223 * The wireless channel of the network.
3225 * @property {number} signal
3226 * The received signal strength of the network in dBm.
3228 * @property {number} quality
3229 * The numeric quality level of the signal, can be used in conjunction
3230 * with `quality_max` to calculate a quality percentage.
3232 * @property {number} quality_max
3233 * The maximum possible quality level of the signal, can be used in
3234 * conjunction with `quality` to calculate a quality percentage.
3236 * @property {LuCI.Network.WifiEncryption} encryption
3237 * The encryption used by the wireless network.
3241 * Trigger a wireless scan on this radio device and obtain a list of
3244 * @returns {Promise<Array<LuCI.Network.WifiScanResult>>}
3245 * Returns a promise resolving to an array of scan result objects
3246 * describing the networks found in the vincinity.
3248 getScanList: function() {
3249 return callIwinfoScan(this.sid
);
3253 * Check whether the wireless radio is marked as up in the `ubus`
3256 * @returns {boolean}
3257 * Returns `true` when the radio device is up, else `false`.
3260 if (L
.isObject(_state
.radios
[this.sid
]))
3261 return (_state
.radios
[this.sid
].up
== true);
3267 * Get the wifi network of the given name belonging to this radio device
3269 * @param {string} network
3270 * The name of the wireless network to lookup. This may be either an uci
3271 * configuration section ID, a network ID in the form `radio#.network#`
3272 * or a Linux network device name like `wlan0` which is resolved to the
3273 * corresponding configuration section through `ubus` runtime information.
3275 * @returns {Promise<LuCI.Network.WifiNetwork>}
3276 * Returns a promise resolving to a `Network.WifiNetwork` instance
3277 * representing the wireless network and rejecting with `null` if
3278 * the given network could not be found or is not associated with
3279 * this radio device.
3281 getWifiNetwork: function(network
) {
3282 return L
.network
.getWifiNetwork(network
).then(L
.bind(function(networkInstance
) {
3283 var uciWifiIface
= (networkInstance
.sid
? uci
.get('wireless', networkInstance
.sid
) : null);
3285 if (uciWifiIface
== null || uciWifiIface
['.type'] != 'wifi-iface' || uciWifiIface
.device
!= this.sid
)
3286 return Promise
.reject();
3288 return networkInstance
;
3293 * Get all wireless networks associated with this wireless radio device.
3295 * @returns {Promise<Array<LuCI.Network.WifiNetwork>>}
3296 * Returns a promise resolving to an array of `Network.WifiNetwork`
3297 * instances respresenting the wireless networks associated with this
3300 getWifiNetworks: function() {
3301 return L
.network
.getWifiNetworks().then(L
.bind(function(networks
) {
3304 for (var i
= 0; i
< networks
.length
; i
++)
3305 if (networks
[i
].getWifiDeviceName() == this.getName())
3306 rv
.push(networks
[i
]);
3313 * Adds a new wireless network associated with this radio device to the
3314 * configuration and sets its options to the provided values.
3316 * @param {Object<string, string|string[]>} [options]
3317 * The options to set for the newly added wireless network.
3319 * @returns {Promise<null|LuCI.Network.WifiNetwork>}
3320 * Returns a promise resolving to a `WifiNetwork` instance describing
3321 * the newly added wireless network or `null` if the given options
3324 addWifiNetwork: function(options
) {
3325 if (!L
.isObject(options
))
3328 options
.device
= this.sid
;
3330 return L
.network
.addWifiNetwork(options
);
3334 * Deletes the wireless network with the given name associated with this
3337 * @param {string} network
3338 * The name of the wireless network to lookup. This may be either an uci
3339 * configuration section ID, a network ID in the form `radio#.network#`
3340 * or a Linux network device name like `wlan0` which is resolved to the
3341 * corresponding configuration section through `ubus` runtime information.
3343 * @returns {Promise<boolean>}
3344 * Returns a promise resolving to `true` when the wireless network was
3345 * successfully deleted from the configuration or `false` when the given
3346 * network could not be found or if the found network was not associated
3347 * with this wireless radio device.
3349 deleteWifiNetwork: function(network
) {
3352 if (network
instanceof WifiNetwork
) {
3356 var uciWifiIface
= uci
.get('wireless', network
);
3358 if (uciWifiIface
== null || uciWifiIface
['.type'] != 'wifi-iface')
3359 sid
= getWifiSidByIfname(network
);
3362 if (sid
== null || uci
.get('wireless', sid
, 'device') != this.sid
)
3363 return Promise
.resolve(false);
3365 uci
.delete('wireless', network
);
3367 return Promise
.resolve(true);
3373 * @memberof LuCI.Network
3377 * A `Network.WifiNetwork` instance represents a wireless network (vif)
3378 * configured on top of a radio device and provides functions for querying
3379 * the runtime state of the network. Most radio devices support multiple
3380 * such networks in parallel.
3382 WifiNetwork
= L
.Class
.extend(/** @lends LuCI.Network.WifiNetwork.prototype */ {
3383 __init__: function(sid
, radioname
, radiostate
, netid
, netstate
, hostapd
) {
3394 ubus: function(/* ... */) {
3395 var v
= this._ubusdata
;
3397 for (var i
= 0; i
< arguments
.length
; i
++)
3399 v
= v
[arguments
[i
]];
3407 * Read the given UCI option value of this wireless network.
3409 * @param {string} opt
3410 * The UCI option name to read.
3412 * @returns {null|string|string[]}
3413 * Returns the UCI option value or `null` if the requested option is
3416 get: function(opt
) {
3417 return uci
.get('wireless', this.sid
, opt
);
3421 * Set the given UCI option of this network to the given value.
3423 * @param {string} opt
3424 * The name of the UCI option to set.
3426 * @param {null|string|string[]} val
3427 * The value to set or `null` to remove the given option from the
3430 set: function(opt
, value
) {
3431 return uci
.set('wireless', this.sid
, opt
, value
);
3435 * Checks whether this wireless network is disabled.
3437 * @returns {boolean}
3438 * Returns `true` when the wireless radio is marked as disabled in `ubus`
3439 * runtime state or when the `disabled` option is set in the corresponding
3440 * UCI configuration.
3442 isDisabled: function() {
3443 return this.ubus('dev', 'disabled') || this.get('disabled') == '1';
3447 * Get the configured operation mode of the wireless network.
3450 * Returns the configured operation mode. Possible values are:
3451 * - `ap` - Master (Access Point) mode
3452 * - `sta` - Station (client) mode
3453 * - `adhoc` - Ad-Hoc (IBSS) mode
3454 * - `mesh` - Mesh (IEEE 802.11s) mode
3455 * - `monitor` - Monitor mode
3457 getMode: function() {
3458 return this.ubus('net', 'config', 'mode') || this.get('mode') || 'ap';
3462 * Get the configured SSID of the wireless network.
3464 * @returns {null|string}
3465 * Returns the configured SSID value or `null` when this network is
3468 getSSID: function() {
3469 if (this.getMode() == 'mesh')
3472 return this.ubus('net', 'config', 'ssid') || this.get('ssid');
3476 * Get the configured Mesh ID of the wireless network.
3478 * @returns {null|string}
3479 * Returns the configured mesh ID value or `null` when this network
3480 * is not in mesh mode.
3482 getMeshID: function() {
3483 if (this.getMode() != 'mesh')
3486 return this.ubus('net', 'config', 'mesh_id') || this.get('mesh_id');
3490 * Get the configured BSSID of the wireless network.
3492 * @returns {null|string}
3493 * Returns the BSSID value or `null` if none has been specified.
3495 getBSSID: function() {
3496 return this.ubus('net', 'config', 'bssid') || this.get('bssid');
3500 * Get the names of the logical interfaces this wireless network is
3503 * @returns {string[]}
3504 * Returns an array of logical interface names.
3506 getNetworkNames: function() {
3507 return L
.toArray(this.ubus('net', 'config', 'network') || this.get('network'));
3511 * Get the internal network ID of this wireless network.
3513 * The network ID is a LuCI specific identifer in the form
3514 * `radio#.network#` to identify wireless networks by their corresponding
3515 * radio and network index numbers.
3518 * Returns the LuCI specific network ID.
3525 * Get the configuration ID of this wireless network.
3528 * Returns the corresponding UCI section ID of the network.
3530 getName: function() {
3535 * Get the Linux network device name.
3537 * @returns {null|string}
3538 * Returns the current Linux network device name as resolved from
3539 * `ubus` runtime information or `null` if this network has no
3540 * associated network device, e.g. when not configured or up.
3542 getIfname: function() {
3543 var ifname
= this.ubus('net', 'ifname') || this.ubus('net', 'iwinfo', 'ifname');
3545 if (ifname
== null || ifname
.match(/^(wifi|radio)\d/))
3546 ifname
= this.netid
;
3552 * Get the name of the corresponding wifi radio device.
3554 * @returns {null|string}
3555 * Returns the name of the radio device this network is configured on
3556 * or `null` if it cannot be determined.
3558 getWifiDeviceName: function() {
3559 return this.ubus('radio') || this.get('device');
3563 * Get the corresponding wifi radio device.
3565 * @returns {null|LuCI.Network.WifiDevice}
3566 * Returns a `Network.WifiDevice` instance representing the corresponding
3567 * wifi radio device or `null` if the related radio device could not be
3570 getWifiDevice: function() {
3571 var radioname
= this.getWifiDeviceName();
3573 if (radioname
== null)
3574 return Promise
.reject();
3576 return L
.network
.getWifiDevice(radioname
);
3580 * Check whether the radio network is up.
3582 * This function actually queries the up state of the related radio
3583 * device and assumes this network to be up as well when the parent
3584 * radio is up. This is due to the fact that OpenWrt does not control
3585 * virtual interfaces individually but within one common hostapd
3588 * @returns {boolean}
3589 * Returns `true` when the network is up, else `false`.
3592 var device
= this.getDevice();
3597 return device
.isUp();
3601 * Query the current operation mode from runtime information.
3604 * Returns the human readable mode name as reported by `ubus` runtime
3605 * state. Possible returned values are:
3617 getActiveMode: function() {
3618 var mode
= this.ubus('net', 'iwinfo', 'mode') || this.ubus('net', 'config', 'mode') || this.get('mode') || 'ap';
3621 case 'ap': return 'Master';
3622 case 'sta': return 'Client';
3623 case 'adhoc': return 'Ad-Hoc';
3624 case 'mesh': return 'Mesh';
3625 case 'monitor': return 'Monitor';
3626 default: return mode
;
3631 * Query the current operation mode from runtime information as
3632 * translated string.
3635 * Returns the translated, human readable mode name as reported by
3636 *`ubus` runtime state.
3638 getActiveModeI18n: function() {
3639 var mode
= this.getActiveMode();
3642 case 'Master': return _('Master');
3643 case 'Client': return _('Client');
3644 case 'Ad-Hoc': return _('Ad-Hoc');
3645 case 'Mash': return _('Mesh');
3646 case 'Monitor': return _('Monitor');
3647 default: return mode
;
3652 * Query the current SSID from runtime information.
3655 * Returns the current SSID or Mesh ID as reported by `ubus` runtime
3658 getActiveSSID: function() {
3659 return this.ubus('net', 'iwinfo', 'ssid') || this.ubus('net', 'config', 'ssid') || this.get('ssid');
3663 * Query the current BSSID from runtime information.
3666 * Returns the current BSSID or Mesh ID as reported by `ubus` runtime
3669 getActiveBSSID: function() {
3670 return this.ubus('net', 'iwinfo', 'bssid') || this.ubus('net', 'config', 'bssid') || this.get('bssid');
3674 * Query the current encryption settings from runtime information.
3677 * Returns a string describing the current encryption or `-` if the the
3678 * encryption state could not be found in `ubus` runtime information.
3680 getActiveEncryption: function() {
3681 return formatWifiEncryption(this.ubus('net', 'iwinfo', 'encryption')) || '-';
3685 * A wireless peer entry describes the properties of a remote wireless
3686 * peer associated with a local network.
3688 * @typedef {Object<string, boolean|number|string|LuCI.Network.WifiRateEntry>} WifiPeerEntry
3689 * @memberof LuCI.Network
3691 * @property {string} mac
3692 * The MAC address (BSSID).
3694 * @property {number} signal
3695 * The received signal strength.
3697 * @property {number} [signal_avg]
3698 * The average signal strength if supported by the driver.
3700 * @property {number} [noise]
3701 * The current noise floor of the radio. May be `0` or absent if not
3702 * supported by the driver.
3704 * @property {number} inactive
3705 * The amount of milliseconds the peer has been inactive, e.g. due
3708 * @property {number} connected_time
3709 * The amount of milliseconds the peer is associated to this network.
3711 * @property {number} [thr]
3712 * The estimated throughput of the peer, May be `0` or absent if not
3713 * supported by the driver.
3715 * @property {boolean} authorized
3716 * Specifies whether the peer is authorized to associate to this network.
3718 * @property {boolean} authenticated
3719 * Specifies whether the peer completed authentication to this network.
3721 * @property {string} preamble
3722 * The preamble mode used by the peer. May be `long` or `short`.
3724 * @property {boolean} wme
3725 * Specifies whether the peer supports WME/WMM capabilities.
3727 * @property {boolean} mfp
3728 * Specifies whether management frame protection is active.
3730 * @property {boolean} tdls
3731 * Specifies whether TDLS is active.
3733 * @property {number} [mesh llid]
3734 * The mesh LLID, may be `0` or absent if not applicable or supported
3737 * @property {number} [mesh plid]
3738 * The mesh PLID, may be `0` or absent if not applicable or supported
3741 * @property {string} [mesh plink]
3742 * The mesh peer link state description, may be an empty string (`''`)
3743 * or absent if not applicable or supported by the driver.
3745 * The following states are known:
3755 * @property {number} [mesh local PS]
3756 * The local powersafe mode for the peer link, may be an empty
3757 * string (`''`) or absent if not applicable or supported by
3760 * The following modes are known:
3761 * - `ACTIVE` (no power save)
3766 * @property {number} [mesh peer PS]
3767 * The remote powersafe mode for the peer link, may be an empty
3768 * string (`''`) or absent if not applicable or supported by
3771 * The following modes are known:
3772 * - `ACTIVE` (no power save)
3777 * @property {number} [mesh non-peer PS]
3778 * The powersafe mode for all non-peer neigbours, may be an empty
3779 * string (`''`) or absent if not applicable or supported by the driver.
3781 * The following modes are known:
3782 * - `ACTIVE` (no power save)
3787 * @property {LuCI.Network.WifiRateEntry} rx
3788 * Describes the receiving wireless rate from the peer.
3790 * @property {LuCI.Network.WifiRateEntry} tx
3791 * Describes the transmitting wireless rate to the peer.
3795 * A wireless rate entry describes the properties of a wireless
3796 * transmission rate to or from a peer.
3798 * @typedef {Object<string, boolean|number>} WifiRateEntry
3799 * @memberof LuCI.Network
3801 * @property {number} [drop_misc]
3802 * The amount of received misc. packages that have been dropped, e.g.
3803 * due to corruption or missing authentication. Only applicable to
3806 * @property {number} packets
3807 * The amount of packets that have been received or sent.
3809 * @property {number} bytes
3810 * The amount of bytes that have been received or sent.
3812 * @property {number} [failed]
3813 * The amount of failed tranmission attempts. Only applicable to
3816 * @property {number} [retries]
3817 * The amount of retried transmissions. Only applicable to transmit
3820 * @property {boolean} is_ht
3821 * Specifies whether this rate is an HT (IEEE 802.11n) rate.
3823 * @property {boolean} is_vht
3824 * Specifies whether this rate is an VHT (IEEE 802.11ac) rate.
3826 * @property {number} mhz
3827 * The channel width in MHz used for the transmission.
3829 * @property {number} rate
3830 * The bitrate in bit/s of the transmission.
3832 * @property {number} [mcs]
3833 * The MCS index of the used transmission rate. Only applicable to
3836 * @property {number} [40mhz]
3837 * Specifies whether the tranmission rate used 40MHz wide channel.
3838 * Only applicable to HT or VHT rates.
3840 * Note: this option exists for backwards compatibility only and its
3841 * use is discouraged. The `mhz` field should be used instead to
3842 * determine the channel width.
3844 * @property {boolean} [short_gi]
3845 * Specifies whether a short guard interval is used for the transmission.
3846 * Only applicable to HT or VHT rates.
3848 * @property {number} [nss]
3849 * Specifies the number of spatial streams used by the transmission.
3850 * Only applicable to VHT rates.
3854 * Fetch the list of associated peers.
3856 * @returns {Promise<Array<LuCI.Network.WifiPeerEntry>>}
3857 * Returns a promise resolving to an array of wireless peers associated
3858 * with this network.
3860 getAssocList: function() {
3861 return callIwinfoAssoclist(this.getIfname());
3865 * Query the current operating frequency of the wireless network.
3867 * @returns {null|string}
3868 * Returns the current operating frequency of the network from `ubus`
3869 * runtime information in GHz or `null` if the information is not
3872 getFrequency: function() {
3873 var freq
= this.ubus('net', 'iwinfo', 'frequency');
3875 if (freq
!= null && freq
> 0)
3876 return '%.03f'.format(freq
/ 1000);
3882 * Query the current average bitrate of all peers associated to this
3885 * @returns {null|number}
3886 * Returns the average bit rate among all peers associated to the network
3887 * as reported by `ubus` runtime information or `null` if the information
3890 getBitRate: function() {
3891 var rate
= this.ubus('net', 'iwinfo', 'bitrate');
3893 if (rate
!= null && rate
> 0)
3894 return (rate
/ 1000);
3900 * Query the current wireless channel.
3902 * @returns {null|number}
3903 * Returns the wireless channel as reported by `ubus` runtime information
3904 * or `null` if it cannot be determined.
3906 getChannel: function() {
3907 return this.ubus('net', 'iwinfo', 'channel') || this.ubus('dev', 'config', 'channel') || this.get('channel');
3911 * Query the current wireless signal.
3913 * @returns {null|number}
3914 * Returns the wireless signal in dBm as reported by `ubus` runtime
3915 * information or `null` if it cannot be determined.
3917 getSignal: function() {
3918 return this.ubus('net', 'iwinfo', 'signal') || 0;
3922 * Query the current radio noise floor.
3925 * Returns the radio noise floor in dBm as reported by `ubus` runtime
3926 * information or `0` if it cannot be determined.
3928 getNoise: function() {
3929 return this.ubus('net', 'iwinfo', 'noise') || 0;
3933 * Query the current country code.
3936 * Returns the wireless country code as reported by `ubus` runtime
3937 * information or `00` if it cannot be determined.
3939 getCountryCode: function() {
3940 return this.ubus('net', 'iwinfo', 'country') || this.ubus('dev', 'config', 'country') || '00';
3944 * Query the current radio TX power.
3946 * @returns {null|number}
3947 * Returns the wireless network transmit power in dBm as reported by
3948 * `ubus` runtime information or `null` if it cannot be determined.
3950 getTXPower: function() {
3951 return this.ubus('net', 'iwinfo', 'txpower');
3955 * Query the radio TX power offset.
3957 * Some wireless radios have a fixed power offset, e.g. due to the
3958 * use of external amplifiers.
3961 * Returns the wireless network transmit power offset in dBm as reported
3962 * by `ubus` runtime information or `0` if there is no offset, or if it
3963 * cannot be determined.
3965 getTXPowerOffset: function() {
3966 return this.ubus('net', 'iwinfo', 'txpower_offset') || 0;
3970 * Calculate the current signal.
3974 * Returns the calculated signal level, which is the difference between
3975 * noise and signal (SNR), divided by 5.
3977 getSignalLevel: function(signal
, noise
) {
3978 if (this.getActiveBSSID() == '00:00:00:00:00:00')
3981 signal
= signal
|| this.getSignal();
3982 noise
= noise
|| this.getNoise();
3984 if (signal
< 0 && noise
< 0) {
3985 var snr
= -1 * (noise
- signal
);
3986 return Math
.floor(snr
/ 5);
3993 * Calculate the current signal quality percentage.
3996 * Returns the calculated signal quality in percent. The value is
3997 * calculated from the `quality` and `quality_max` indicators reported
3998 * by `ubus` runtime state.
4000 getSignalPercent: function() {
4001 var qc
= this.ubus('net', 'iwinfo', 'quality') || 0,
4002 qm
= this.ubus('net', 'iwinfo', 'quality_max') || 0;
4004 if (qc
> 0 && qm
> 0)
4005 return Math
.floor((100 / qm
) * qc
);
4011 * Get a short description string for this wireless network.
4014 * Returns a string describing this network, consisting of the
4015 * active operation mode, followed by either the SSID, BSSID or
4016 * internal network ID, depending on which information is available.
4018 getShortName: function() {
4019 return '%s "%s"'.format(
4020 this.getActiveModeI18n(),
4021 this.getActiveSSID() || this.getActiveBSSID() || this.getID());
4025 * Get a description string for this wireless network.
4028 * Returns a string describing this network, consisting of the
4029 * term `Wireless Network`, followed by the active operation mode,
4030 * the SSID, BSSID or internal network ID and the Linux network device
4031 * name, depending on which information is available.
4033 getI18n: function() {
4034 return '%s: %s "%s" (%s)'.format(
4035 _('Wireless Network'),
4036 this.getActiveModeI18n(),
4037 this.getActiveSSID() || this.getActiveBSSID() || this.getID(),
4042 * Get the primary logical interface this wireless network is attached to.
4044 * @returns {null|LuCI.Network.Protocol}
4045 * Returns a `Network.Protocol` instance representing the logical
4046 * interface or `null` if this network is not attached to any logical
4049 getNetwork: function() {
4050 return this.getNetworks()[0];
4054 * Get the logical interfaces this wireless network is attached to.
4056 * @returns {Array<LuCI.Network.Protocol>}
4057 * Returns an array of `Network.Protocol` instances representing the
4058 * logical interfaces this wireless network is attached to.
4060 getNetworks: function() {
4061 var networkNames
= this.getNetworkNames(),
4064 for (var i
= 0; i
< networkNames
.length
; i
++) {
4065 var uciInterface
= uci
.get('network', networkNames
[i
]);
4067 if (uciInterface
== null || uciInterface
['.type'] != 'interface')
4070 networks
.push(L
.network
.instantiateNetwork(networkNames
[i
]));
4073 networks
.sort(networkSort
);
4079 * Get the associated Linux network device.
4081 * @returns {LuCI.Network.Device}
4082 * Returns a `Network.Device` instance representing the Linux network
4083 * device associted with this wireless network.
4085 getDevice: function() {
4086 return L
.network
.instantiateDevice(this.getIfname());
4090 * Check whether this wifi network supports deauthenticating clients.
4092 * @returns {boolean}
4093 * Returns `true` when this wifi network instance supports forcibly
4094 * deauthenticating clients, otherwise `false`.
4096 isClientDisconnectSupported: function() {
4097 return L
.isObject(this.ubus('hostapd', 'del_client'));
4101 * Forcibly disconnect the given client from the wireless network.
4103 * @param {string} mac
4104 * The MAC address of the client to disconnect.
4106 * @param {boolean} [deauth=false]
4107 * Specifies whether to deauthenticate (`true`) or disassociate (`false`)
4110 * @param {number} [reason=1]
4111 * Specifies the IEEE 802.11 reason code to disassoc/deauth the client
4112 * with. Default is `1` which corresponds to `Unspecified reason`.
4114 * @param {number} [ban_time=0]
4115 * Specifies the amount of milliseconds to ban the client from
4116 * reconnecting. By default, no ban time is set which allows the client
4117 * to reassociate / reauthenticate immediately.
4119 * @returns {Promise<number>}
4120 * Returns a promise resolving to the underlying ubus call result code
4121 * which is typically `0`, even for not existing MAC addresses.
4122 * The promise might reject with an error in case invalid arguments
4125 disconnectClient: function(mac
, deauth
, reason
, ban_time
) {
4126 if (reason
== null || reason
== 0)
4132 return rpc
.declare({
4133 object
: 'hostapd.%s'.format(this.getIfname()),
4134 method
: 'del_client',
4135 params
: [ 'addr', 'deauth', 'reason', 'ban_time' ]
4136 })(mac
, deauth
, reason
, ban_time
);