From 3213dfaaaa464fbce4a533f4bda6596fd77ffc62 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 12 Nov 2026 19:05:48 +0100 Subject: [PATCH] fix(wan): read the uplink from the gateway's status page (#29) get_wan_status built its answer from WanIp, WanAccessType, SystemUpTime, MaxUpstream and MaxDownstream in getBasicInformation. A VMG4005-B50A sends none of them there, so every gateway's uplink read as down, with no address and no sync rate; get_nat_translations built inside_global from the same WanIp and reported ":". Both now read the DAL's cardpage_status. A bridge has no WAN address of its own, so it is connected when its DSL line is in sync (a DslChannelInfo entry with Status "Up"); a router is connected when a WAN interface that is not IP_Bridged is up with an address. The sync rates are those of the channels in sync, added up for bonded lines; a channel out of sync keeps its last rates, which are not reported. A translation without a WAN address goes to 0.0.0.0, and without enabled port forwards the status page is not read at all. The tests read the recorded, anonymised status page of a VMG4005-B50A bridge whose line was not in sync; the in-sync and router states are derived from it. Closes #29 --- CHANGELOG.md | 13 + README.md | 2 +- napalm_zyxel/parsers.py | 89 ++++- napalm_zyxel/zyxel_driver.py | 40 +- ...vmg4005-b50a-ABQA.3.1-cardpage_status.json | 357 ++++++++++++++++++ tests/test_wan_status.py | 192 ++++++++++ tests/test_zyxel.py | 7 - 7 files changed, 672 insertions(+), 28 deletions(-) create mode 100644 tests/fixtures/vmg4005-b50a-ABQA.3.1-cardpage_status.json create mode 100644 tests/test_wan_status.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f331bb..515d8f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,19 @@ All notable changes to this driver. The format follows 3.12 venv no longer has. ### Fixed +- `get_wan_status()` reports the gateway's uplink as the gateway does (#29). It read + `WanIp`, `WanAccessType`, `SystemUpTime`, `MaxUpstream` and `MaxDownstream` from + `getBasicInformation`, which a VMG4005-B50A does not send them in, and reported + every uplink as down, with no address and no sync rate. It now reads the DAL's + `cardpage_status`: a bridge is connected when its DSL line is in sync and has no + external address of its own; a router is connected when a WAN interface that is + not a bridge is up with an address, which is then `external_ip`. `link_status` is + `"Up"` while the DSL line is in sync, the sync rates are those of the channels in + sync (added up for bonded lines), and `connection_type` is `"DSL"` for a bridge, + the WAN's encapsulation (`"PPPoE"`, `"IPoE"`) for a router. Byte counters are not + read and stay `0`. +- `get_nat_translations()` translates to the gateway's WAN address from the same page, + and to `0.0.0.0` when it has none; it reported `":"` (#29). - `get_hosts()`, `get_arp_table()` and `get_port_forwards()` report what the gateway has (#25). They parsed the DAL's answer without decrypting it, found none of their keys in the sealed envelope and reported nothing, on every gateway; the Wi-Fi diff --git a/README.md b/README.md index 8d10057..3abd927 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ with driver("192.0.2.1", "admin", "secret", optional_args={"use_tls": True}) as | `get_facts` | basic device information | | `get_interfaces`, `get_interfaces_ip` | basic device information (WAN, LAN, Wi-Fi) | | `get_arp_table` | derived from the active LAN hosts | -| `get_wan_status` | basic device information | +| `get_wan_status` | DAL `cardpage_status`: the DSL line and the WAN interfaces | | `get_hosts` | DAL `lanhosts`, else the DHCP page | | `get_port_forwards`, `get_nat_translations` | DAL `nat`, else the status page | | `get_wireless_clients`, `get_ssids`, `get_radio_status` | DAL, else the wireless page | diff --git a/napalm_zyxel/parsers.py b/napalm_zyxel/parsers.py index a54faea..5e60cdb 100644 --- a/napalm_zyxel/parsers.py +++ b/napalm_zyxel/parsers.py @@ -4,7 +4,7 @@ from __future__ import annotations from typing import Any -from napalm_device_types.models import HostDict, PortForwardDict +from napalm_device_types.models import HostDict, PortForwardDict, WANStatusDict #: The name ``lanhosts`` gives a host the gateway has no name for. _UNKNOWN_HOST = "Unknown" @@ -60,3 +60,90 @@ def port_forwards(objects: list[dict[str, Any]]) -> list[PortForwardDict]: forward["remote_host"] = str(rule["OriginatingIpAddress"]) forwards.append(forward) return forwards + + +def _channels_in_sync(page: dict[str, Any]) -> list[dict[str, Any]]: + """The DSL channels of a ``cardpage_status`` page that are in sync.""" + return [ + channel + for channel in page.get("DslChannelInfo") or [] + if isinstance(channel, dict) and channel.get("Status") == "Up" + ] + + +def _routed_wans(page: dict[str, Any]) -> list[dict[str, Any]]: + """The enabled WAN interfaces of a ``cardpage_status`` page that are not bridges.""" + return [ + entry + for entry in page.get("WanLanInfo") or [] + if isinstance(entry, dict) + and entry.get("X_ZYXEL_Type") == "WAN" + and entry.get("Enable") + and entry.get("X_ZYXEL_ConnectionType") != "IP_Bridged" + ] + + +def _address(entry: dict[str, Any]) -> str: + """The first enabled IPv4 address of a ``WanLanInfo`` entry, else ``""``.""" + for addr in entry.get("IPv4Address") or []: + if isinstance(addr, dict) and addr.get("Enable") and addr.get("IPAddress"): + return str(addr["IPAddress"]) + return "" + + +def _connected_wan(page: dict[str, Any]) -> dict[str, Any] | None: + """The routed WAN interface that is up with an address, if there is one.""" + for entry in _routed_wans(page): + if entry.get("Status") == "Up" and _address(entry): + return entry + return None + + +def wan_address(page: dict[str, Any]) -> str: + """The gateway's own WAN address on a ``cardpage_status`` page; ``""`` for a bridge + or a router whose WAN is not up.""" + wan = _connected_wan(page) + return _address(wan) if wan is not None else "" + + +def _seconds(value: Any) -> int: + """*value* as a number of seconds; ``0`` (unknown) when it is not a number.""" + text = str(value if value is not None else "").strip() + return int(text) if text.isdigit() else 0 + + +def _uplink(page: dict[str, Any], channels: list[dict[str, Any]]) -> tuple[bool, str, int]: + """Whether the uplink is connected, its type and how long it has been up.""" + routed = _routed_wans(page) + if not routed: # a bridge: the DSL line is the uplink + uptime = _seconds(channels[0].get("DSLUpTime")) if channels else 0 + return bool(channels), "DSL", uptime + wan = _connected_wan(page) + connection_type = str(routed[0].get("Encapsulation") or "") + if wan is None: + return False, connection_type, 0 + return True, connection_type, _seconds(wan.get("X_ZYXEL_UpTime")) + + +def wan_status(page: dict[str, Any]) -> WANStatusDict: + """The uplink of a ``cardpage_status`` page. + + A router (a WAN interface that is not ``IP_Bridged``) is connected when such an + interface is up with an address. A bridge has no WAN address of its own: it is + connected when its DSL line is in sync. The sync rates (kbit/s) are those of the + channels in sync, added up for bonded lines; a channel out of sync keeps the rates + of its last sync, which are not reported. + """ + channels = _channels_in_sync(page) + connected, connection_type, uptime = _uplink(page, channels) + return { + "connection_type": connection_type, + "is_connected": connected, + "external_ip": wan_address(page), + "uptime": uptime, + "bytes_sent": 0, + "bytes_received": 0, + "max_bitrate_up": sum(int(c.get("UpstreamCurrRate") or 0) for c in channels), + "max_bitrate_down": sum(int(c.get("DownstreamCurrRate") or 0) for c in channels), + "link_status": "Up" if channels else "Down", + } diff --git a/napalm_zyxel/zyxel_driver.py b/napalm_zyxel/zyxel_driver.py index eff1988..90520b2 100644 --- a/napalm_zyxel/zyxel_driver.py +++ b/napalm_zyxel/zyxel_driver.py @@ -45,6 +45,10 @@ _SESSION_REFUSED = (401, 403) _T = TypeVar("_T") +#: The inside-global address of a port forward when the gateway has no WAN address +#: (an address reported, not one bound to). +_ANY_ADDRESS = "0.0.0.0" # nosec B104 + _PING_UNSUPPORTED = "Not supported on Zyxel VMG: the DAL does not report ping replies" @@ -629,20 +633,13 @@ class ZyxelVMGDriver(ResidentialGatewayDriver): pass def get_wan_status(self) -> WANStatusDict: - """Return WAN connection status from cached device info.""" - info = self._device_info or {} - wan_ip = info.get("WanIp", "") - return { - "connection_type": info.get("WanAccessType", "VDSL"), - "is_connected": bool(wan_ip), - "external_ip": wan_ip, - "uptime": int(info.get("SystemUpTime", 0) or 0), - "bytes_sent": 0, - "bytes_received": 0, - "max_bitrate_up": int(info.get("MaxUpstream", 0) or 0) // 1000, - "max_bitrate_down": int(info.get("MaxDownstream", 0) or 0) // 1000, - "link_status": "Up" if wan_ip else "Down", - } + """The uplink as the gateway's status page (``cardpage_status``) reports it (#29). + + A bridge is connected when its DSL line is in sync and has no external address; + a router is connected when its WAN interface is up with an address. Byte + counters are not read: 0. + """ + return parsers.wan_status(self._status_page()) def get_port_forwards(self) -> list[PortForwardDict]: """The gateway's port forwards (DAL ``nat``), else the status page's.""" @@ -705,12 +702,17 @@ class ZyxelVMGDriver(ResidentialGatewayDriver): return hosts def get_nat_translations(self) -> list[NATTranslationDict]: - """Return NAT translations derived from enabled port forwards.""" - wan_ip = (self._device_info or {}).get("WanIp", "") + """The enabled port forwards as translations to the gateway's WAN address. + + Without a WAN address of its own (a bridge, or a WAN that is down) the + translation is to any address, ``0.0.0.0``. + """ + forwards = [forward for forward in self.get_port_forwards() if forward["enabled"]] + if not forwards: + return [] + wan_ip = parsers.wan_address(self._status_page()) or _ANY_ADDRESS translations: list[NATTranslationDict] = [] - for forward in self.get_port_forwards(): - if not forward["enabled"]: - continue + for forward in forwards: translations.append( { "protocol": forward["protocol"].lower(), diff --git a/tests/fixtures/vmg4005-b50a-ABQA.3.1-cardpage_status.json b/tests/fixtures/vmg4005-b50a-ABQA.3.1-cardpage_status.json new file mode 100644 index 0000000..bec6db2 --- /dev/null +++ b/tests/fixtures/vmg4005-b50a-ABQA.3.1-cardpage_status.json @@ -0,0 +1,357 @@ +{ + "result": "ZCFG_SUCCESS", + "ReplyMsg": "DeviceSource", + "ReplyMsgMultiLang": "", + "Object": [ + { + "WanLanInfo": [ + { + "Enable": true, + "IpIfacePath": "IP.Interface.1", + "wanIdx": 1, + "BindToIntfGrp": false, + "X_ZYXEL_Type": "LAN", + "Encapsulation": "", + "MACAddress": "6c:4f:89:00:00:50", + "LowerlayerUp": "", + "pppConnectionStatus": "", + "wanpppIdx": 0, + "DHCPtr181Path": "Device.DHCPv4.Server.Pool.1", + "Status": "Up", + "X_ZYXEL_ConnectionType": "IP_Routed", + "X_ZYXEL_SrvName": "Default", + "Name": "LAN", + "Type": "Normal", + "IPv4Enable": true, + "IPv6Enable": false, + "X_ZYXEL_IfName": "br0", + "X_ZYXEL_UpTime": 13554113, + "IPv6Origin": "DelegateFromWan", + "IPv6PrefixDelegateWAN": "Default", + "X_ZYXEL_DefaultGatewayIface": false, + "X_ZYXEL_IPv6LocalAddress": "fe80::6e4f:89ff:fe00:50", + "IPv4Address": [ + { + "Enable": true, + "Alias": "", + "IPAddress": "192.0.2.1", + "SubnetMask": "255.255.255.248", + "Status": "Enabled", + "AddressingType": "Static", + "X_ZYXEL_IfName": "", + "X_ZYXEL_Alias": false, + "X_ZYXEL_Dhcp4Subnet_Ref": "", + "ipIfaceIdx": 1 + } + ], + "IPv6Address": [], + "IPv6Prefix": [], + "v4Gateway": "192.0.2.2", + "dnsv4Server": [], + "dnsv6Server": [], + "rtinfoIntf": [], + "ipoeConnectionUpTime": 13554213, + "BridgingBrPath": "Bridging.Bridge.1", + "Group_WAN_IpIface": "", + "DHCPStatus": "Disable", + "Gateway": "", + "LeaseTime": 0, + "LeaseTimeRemaining": 0, + "DHCPoption42Enable": false, + "DHCPoption43Enable": false, + "DHCPoption60Enable": false, + "DHCPoption42Value": "", + "DHCPoption43Value": "", + "DHCPoption60Value": "" + }, + { + "Enable": true, + "IpIfacePath": "IP.Interface.2", + "wanIdx": 2, + "BindToIntfGrp": false, + "X_ZYXEL_Type": "WAN", + "Encapsulation": "IPoE", + "MACAddress": "", + "LowerlayerUp": "", + "pppConnectionStatus": "", + "wanpppIdx": 0, + "DHCPtr181Path": "", + "X_ZYXEL_ConnectionType": "IP_Bridged", + "X_ZYXEL_SrvName": "Bridge_ATM", + "Name": "WAN", + "Type": "Normal", + "IPv4Enable": false, + "IPv6Enable": false, + "X_ZYXEL_IfName": "atm0.1", + "IPv6Origin": "", + "IPv6PrefixDelegateWAN": "Default", + "X_ZYXEL_DefaultGatewayIface": false, + "X_ZYXEL_IPv6LocalAddress": "", + "IPv4Address": [], + "IPv6Address": [], + "IPv6Prefix": [], + "dnsv4Server": [], + "dnsv6Server": [], + "rtinfoIntf": [], + "ipoeConnectionUpTime": 0, + "LinkType": "ATM", + "DHCPStatus": "Disable", + "Gateway": "", + "LeaseTime": 0, + "LeaseTimeRemaining": 0, + "DHCPoption42Enable": false, + "DHCPoption43Enable": false, + "DHCPoption60Enable": false, + "DHCPoption42Value": "", + "DHCPoption43Value": "", + "DHCPoption60Value": "" + }, + { + "Enable": true, + "IpIfacePath": "IP.Interface.3", + "wanIdx": 3, + "BindToIntfGrp": false, + "X_ZYXEL_Type": "WAN", + "Encapsulation": "IPoE", + "MACAddress": "", + "LowerlayerUp": "", + "pppConnectionStatus": "", + "wanpppIdx": 0, + "DHCPtr181Path": "", + "Status": "LowerLayerDown", + "X_ZYXEL_ConnectionType": "IP_Bridged", + "X_ZYXEL_SrvName": "Bridge_PTM", + "Name": "WAN", + "Type": "Normal", + "IPv4Enable": false, + "IPv6Enable": false, + "X_ZYXEL_IfName": "ptm0.2", + "X_ZYXEL_UpTime": 0, + "IPv6Origin": "", + "IPv6PrefixDelegateWAN": "Default", + "X_ZYXEL_DefaultGatewayIface": false, + "X_ZYXEL_IPv6LocalAddress": "", + "IPv4Address": [], + "IPv6Address": [], + "IPv6Prefix": [], + "dnsv4Server": [], + "dnsv6Server": [], + "rtinfoIntf": [], + "ipoeConnectionUpTime": 0, + "LinkType": "PTM", + "DHCPStatus": "Disable", + "Gateway": "", + "LeaseTime": 0, + "LeaseTimeRemaining": 0, + "DHCPoption42Enable": false, + "DHCPoption43Enable": false, + "DHCPoption60Enable": false, + "DHCPoption42Value": "", + "DHCPoption43Value": "", + "DHCPoption60Value": "" + } + ], + "DeviceInfo": { + "Manufacturer": "ZYXEL", + "ManufacturerOUI": "6C4F89", + "FixManufacturerOUI": "", + "ModelName": "VMG4005-B50A", + "Description": "VDSL2 17a Bonding and 35b Single Line Bridge", + "ProductClass": "VMG4005-B50A", + "SerialNumber": "S000Y00000001", + "HardwareVersion": "VMG4005-B50A", + "SoftwareVersion": "V5.17(ABQA.3.1)C0", + "AdditionalHardwareVersion": "", + "AdditionalSoftwareVersion": "", + "ProvisioningCode": "", + "X_ZYXEL_ProvisioningCodeIntf": "", + "X_ZYXEL_ProvisioningKey": "", + "X_ZYXEL_GponSerialNumber": "", + "X_ZYXEL_Ploam_Password": "", + "UpTime": 13554213, + "FirstUseDate": "0001-01-01T00:00:00Z", + "VendorConfigFileNumberOfEntries": 0, + "SupportedDataModelNumberOfEntries": 0, + "ProcessorNumberOfEntries": 0, + "VendorLogFileNumberOfEntries": 0, + "LocationNumberOfEntries": 0, + "BootVersion": "", + "WiFiDriverVersion": "", + "DSLVersion": "" + }, + "LanPortInfo": { + "LanMac": "6c:4f:89:00:00:53", + "ethPortExist": false + }, + "Dhcp4SerPoolInfo": { + "Enable": false, + "X_ZYXEL_SetEnable": false, + "X_ZYXEL_AutoReserveLanIp": false, + "Status": "Enabled", + "Alias": "", + "Order": 1, + "Interface": "IP.Interface.1", + "VendorClassID": "", + "VendorClassIDExclude": false, + "VendorClassIDMode": "", + "ClientID": "", + "ClientIDExclude": false, + "UserClassID": "", + "ChaddrExclude": false, + "Chaddr": "", + "ChaddrMask": "", + "MinAddress": "192.0.2.2", + "MaxAddress": "192.0.2.254", + "ReservedAddresses": "", + "SubnetMask": "255.255.255.0", + "DNSServers": "192.0.2.1", + "X_ZYXEL_ServerConfigurable": true, + "X_ZYXEL_DNS_Type": "DNS Proxy", + "DomainName": "", + "IPRouters": "", + "LeaseTime": 86400, + "X_ZYXEL_STB_VENDORID": "", + "X_ZYXEL_STB_URL": "", + "X_ZYXEL_STB_PrCode": "", + "X_ZYXEL_STB_URL_subcode": 1, + "X_ZYXEL_STB_PrCode_subcode": 2, + "StaticAddressNumberOfEntries": 0, + "OptionNumberOfEntries": 0, + "ClientNumberOfEntries": 0 + }, + "LanInfo": [ + { + "Enable": true, + "Status": "Up", + "Alias": "", + "Name": "eth1", + "LastChange": 13554195, + "LowerLayers": "", + "Upstream": false, + "MACAddress": "6c:4f:89:00:00:53", + "IntfEnable": true, + "IntfStatus": "Up", + "MaxBitRate": 1000, + "DuplexMode": "Full", + "EEECapability": false, + "EEEEnable": true, + "X_ZYXEL_DuplexMode": "Auto", + "X_ZYXEL_MaxBitRate": -1, + "X_ZYXEL_LanPort": "LAN1", + "X_ZYXEL_SFP": false, + "X_ZYXEL_SwitchToWAN": false, + "X_ZYXEL_Upstream": false, + "X_ZYXEL_UpTime": 13554195, + "X_ZYXEL_LastChangeTime": 18 + } + ], + "DslChannelInfo": [ + { + "Enable": true, + "Status": "Down", + "Alias": "", + "Name": "", + "LastChange": 0, + "LowerLayers": "DSL.Line.1", + "LinkEncapsulationSupported": "G.992.3_Annex_K_ATM", + "LinkEncapsulationUsed": "G.992.3_Annex_K_ATM", + "LPATH": 0, + "INTLVDEPTH": 0, + "INTLVBLOCK": 0, + "ActualInterleavingDelay": 0, + "ACTINP": 0, + "INPREPORT": false, + "NFEC": 0, + "RFEC": 0, + "LSYMB": 0, + "UpstreamCurrRate": 0, + "DownstreamCurrRate": 0, + "DSLUpTime": "", + "X_ZYXEL_BondingLineNumber": 0 + }, + { + "Enable": true, + "Status": "LowerLayerDown", + "Alias": "", + "Name": "", + "LastChange": 0, + "LowerLayers": "DSL.Line.1", + "LinkEncapsulationSupported": "G.992.3_Annex_K_PTM", + "LinkEncapsulationUsed": "G.992.3_Annex_K_PTM", + "LPATH": 0, + "INTLVDEPTH": 0, + "INTLVBLOCK": 0, + "ActualInterleavingDelay": 0, + "ACTINP": 0, + "INPREPORT": false, + "NFEC": 0, + "RFEC": 0, + "LSYMB": 0, + "UpstreamCurrRate": 0, + "DownstreamCurrRate": 0, + "DSLUpTime": "", + "X_ZYXEL_BondingLineNumber": 0 + }, + { + "Enable": true, + "Status": "Down", + "Alias": "", + "Name": "", + "LastChange": 0, + "LowerLayers": "DSL.Line.2", + "LinkEncapsulationSupported": "G.992.3_Annex_K_ATM", + "LinkEncapsulationUsed": "G.992.3_Annex_K_ATM", + "LPATH": 0, + "INTLVDEPTH": 0, + "INTLVBLOCK": 0, + "ActualInterleavingDelay": 0, + "ACTINP": 0, + "INPREPORT": false, + "NFEC": 0, + "RFEC": 0, + "LSYMB": 0, + "UpstreamCurrRate": 0, + "DownstreamCurrRate": 0, + "DSLUpTime": "", + "X_ZYXEL_BondingLineNumber": 1 + }, + { + "Enable": true, + "Status": "LowerLayerDown", + "Alias": "", + "Name": "", + "LastChange": 0, + "LowerLayers": "DSL.Line.2", + "LinkEncapsulationSupported": "G.992.3_Annex_K_PTM", + "LinkEncapsulationUsed": "G.992.3_Annex_K_PTM", + "LPATH": 0, + "INTLVDEPTH": 0, + "INTLVBLOCK": 0, + "ActualInterleavingDelay": 0, + "ACTINP": 0, + "INPREPORT": false, + "NFEC": 0, + "RFEC": 0, + "LSYMB": 0, + "UpstreamCurrRate": 45875, + "DownstreamCurrRate": 274098, + "DSLUpTime": "", + "X_ZYXEL_BondingLineNumber": 1 + } + ], + "OptIntfInfo": [], + "GponStatsInfo": { + "RxPowerSignal": "0", + "TxPowerSignal": "0", + "Temperature": "0", + "SFP_Vendor": "", + "SFP_Model": "", + "SFP_Serial": "", + "SFP_Presence": false + }, + "WanType": "", + "WanRate_RX": "", + "WanRate_TX": "" + } + ] +} diff --git a/tests/test_wan_status.py b/tests/test_wan_status.py new file mode 100644 index 0000000..e59c3a2 --- /dev/null +++ b/tests/test_wan_status.py @@ -0,0 +1,192 @@ +"""The uplink's state is the gateway's own: the DSL line and the WAN interfaces (#29). + +``get_wan_status`` built its answer from ``WanIp``, ``WanAccessType``, +``SystemUpTime``, ``MaxUpstream`` and ``MaxDownstream`` in ``getBasicInformation``. +A VMG4005-B50A sends none of them there, so every gateway's uplink read as down, +with no address and no sync rate, whatever its line did. ``get_nat_translations`` +built ``inside_global`` from the same ``WanIp`` and reported ``":"``. + +The line state is in the DAL's ``cardpage_status``: ``DslChannelInfo[]`` (a channel +whose ``Status`` is ``Up`` is in sync; its rates are in kbit/s) and the +``WanLanInfo[]`` entries of ``X_ZYXEL_Type`` ``WAN``. A bridge has no WAN address +of its own: there, connected means the DSL line is in sync. + +``STATUS`` is that answer from a VMG4005-B50A bridge whose line was not in sync +when it was recorded (``tests/gateway.py``). The other states change it the way +TR-181 and the recorded fields describe them: they were not recorded. +""" + +from __future__ import annotations + +import copy +from typing import Any + +import pytest + +from tests.gateway import dal, driver, fixture, requested, response + +STATUS = fixture("cardpage_status") +PTM_LINE_2 = 3 # DslChannelInfo: the channel that carries the recorded sync rates + + +def _status( + channels: dict[int, dict[str, Any]] | None = None, wan: dict[str, Any] | None = None +) -> dict[str, Any]: + """The recorded status page with *channels* (index: changes) and *wan* (changes to + the ``ptm0.2`` WAN interface) applied.""" + answer = copy.deepcopy(STATUS) + page = answer["Object"][0] + for index, changes in (channels or {}).items(): + page["DslChannelInfo"][index].update(changes) + for entry in page["WanLanInfo"]: + if entry["X_ZYXEL_IfName"] == "ptm0.2": + entry.update(wan or {}) + return answer + + +IN_SYNC = _status({PTM_LINE_2: {"Status": "Up"}}, {"Status": "Up"}) + +ROUTED = { + "X_ZYXEL_ConnectionType": "IP_Routed", + "Encapsulation": "PPPoE", + "Status": "Up", + "X_ZYXEL_UpTime": 7200, + "IPv4Address": [ + { + "Enable": True, + "IPAddress": "203.0.113.10", + "SubnetMask": "255.255.255.255", + "Status": "Enabled", + } + ], +} + + +def _wan(answer: dict[str, Any]) -> Any: + return driver({dal("cardpage_status"): answer}).get_wan_status() + + +# --- a bridge ----------------------------------------------------------------------------- + + +def test_a_bridge_whose_line_is_not_in_sync_is_down(): + assert _wan(STATUS) == { + "connection_type": "DSL", + "is_connected": False, + "external_ip": "", + "uptime": 0, + "bytes_sent": 0, + "bytes_received": 0, + "max_bitrate_up": 0, + "max_bitrate_down": 0, + "link_status": "Down", + } + + +def test_a_bridge_whose_line_is_in_sync_is_connected(): + status = _wan(IN_SYNC) + assert (status["is_connected"], status["link_status"]) == (True, "Up") + assert status["external_ip"] == "" # a bridge has no WAN address + + +def test_the_sync_rates_are_the_channels_in_kbit_per_second(): + status = _wan(IN_SYNC) + assert (status["max_bitrate_up"], status["max_bitrate_down"]) == (45875, 274098) + + +def test_the_rates_of_a_line_out_of_sync_are_not_reported(): + """The recorded channel keeps the rates of its last sync while it is down.""" + status = _wan(STATUS) + assert (status["max_bitrate_up"], status["max_bitrate_down"]) == (0, 0) + + +def test_bonded_lines_add_up(): + rates = {"UpstreamCurrRate": 40000, "DownstreamCurrRate": 100000} + answer = _status({1: {"Status": "Up", **rates}, PTM_LINE_2: {"Status": "Up"}}) + status = _wan(answer) + assert (status["max_bitrate_up"], status["max_bitrate_down"]) == (85875, 374098) + + +def test_the_line_uptime_is_reported_when_the_gateway_gives_one(): + answer = _status({PTM_LINE_2: {"Status": "Up", "DSLUpTime": "5400"}}) + assert _wan(answer)["uptime"] == 5400 + + +def test_a_line_uptime_that_is_not_a_number_is_unknown(): + answer = _status({PTM_LINE_2: {"Status": "Up", "DSLUpTime": ""}}) + assert _wan(answer)["uptime"] == 0 + + +# --- a router ----------------------------------------------------------------------------- + + +def test_a_router_with_a_wan_address_is_connected_with_it(): + status = _wan(_status({PTM_LINE_2: {"Status": "Up"}}, ROUTED)) + assert status["is_connected"] is True + assert status["external_ip"] == "203.0.113.10" + assert status["connection_type"] == "PPPoE" + assert status["uptime"] == 7200 + + +def test_a_router_whose_line_is_in_sync_but_its_wan_down_is_not_connected(): + wan = {**ROUTED, "Status": "Down", "IPv4Address": []} + status = _wan(_status({PTM_LINE_2: {"Status": "Up"}}, wan)) + assert (status["is_connected"], status["link_status"]) == (False, "Up") + assert status["external_ip"] == "" + + +def test_a_disabled_wan_address_is_not_the_external_one(): + addresses = [{**ROUTED["IPv4Address"][0], "Enable": False}] + status = _wan(_status({PTM_LINE_2: {"Status": "Up"}}, {**ROUTED, "IPv4Address": addresses})) + assert (status["is_connected"], status["external_ip"]) == (False, "") + + +# --- reading ------------------------------------------------------------------------------ + + +def test_basic_information_is_not_read_for_it(): + drv = driver({dal("cardpage_status"): IN_SYNC}) + drv._device_info = {**fixture("getBasicInformation"), "WanIp": "198.51.100.1"} + assert drv.get_wan_status()["external_ip"] == "" + + +def test_get_wan_status_raises_when_the_status_page_cannot_be_read(): + with pytest.raises(RuntimeError, match="cardpage_status"): + _wan(response(500)) # type: ignore[arg-type] + + +# --- NAT translations --------------------------------------------------------------------- + +RULE = { + "Enable": True, + "Protocol": "TCP", + "Description": "web", + "ExternalPortStart": 8443, + "InternalPortStart": 443, + "InternalClient": "192.0.2.3", +} + + +def _nat_driver(status: Any) -> Any: + return driver( + {dal("nat"): {**fixture("nat"), "Object": [RULE]}, dal("cardpage_status"): status} + ) + + +def test_a_translation_is_to_the_wan_address(): + status = _status({PTM_LINE_2: {"Status": "Up"}}, ROUTED) + nat = _nat_driver(status).get_nat_translations() + assert [(t["inside_local"], t["inside_global"]) for t in nat] == [ + ("192.0.2.3:443", "203.0.113.10:8443") + ] + + +def test_without_a_wan_address_a_translation_is_to_any_address(): + nat = _nat_driver(STATUS).get_nat_translations() + assert [t["inside_global"] for t in nat] == ["0.0.0.0:8443"] + + +def test_without_port_forwards_the_status_page_is_not_read(): + drv = driver({dal("nat"): fixture("nat")}) + assert drv.get_nat_translations() == [] + assert requested(drv) == ["http://192.0.2.1:80/cgi-bin/DAL?oid=nat"] diff --git a/tests/test_zyxel.py b/tests/test_zyxel.py index a5caf7a..6447e5d 100644 --- a/tests/test_zyxel.py +++ b/tests/test_zyxel.py @@ -188,13 +188,6 @@ class TestZyxelVMGDriver: assert facts["fqdn"] == "ZyxelVMG.home" assert facts["uptime"] == 1234567 - def test_get_wan_status(self): - self._setup_mocked_http() - status = self.driver.get_wan_status() - assert status["is_connected"] is True - assert status["external_ip"] == "85.2.34.56" - assert status["connection_type"] == "VDSL" - def test_get_port_forwards_empty(self): self._setup_mocked_http() self.driver._session.get.side_effect = None