summaryrefslogtreecommitdiff
path: root/python
diff options
context:
space:
mode:
authorAdam Smith <adamsmith@yzguy.io>2026-10-08 01:20:09 +0000
committerChristian Breunig <christian@breunig.cc>2026-11-07 22:19:52 +0100
commit9babe4468dec43d2df20488bacd3877d77c42b35 (patch)
tree5e2b7e9114411a9e5a17efdecbd83a68bcf087b6 /python
parentd6902e6423ec78b5b99d96b6427ebee771ea6c38 (diff)
downloadvyos-1x-9babe4468dec43d2df20488bacd3877d77c42b35.tar.gz
vyos-1x-9babe4468dec43d2df20488bacd3877d77c42b35.zip
wwan: T9388: apply a static bearer's address/gateway/DNS directly
QMI raw-ip modems get their address, gateway and DNS from ModemManager as a "static" bearer instead of over a DHCP(v6) or Router Advertisement exchange, so "address dhcp", "address dhcpv6" and "ipv6 address autoconf" never produced a usable config and only worked for IPv4 by accident. Check the interface's connected bearer first. If its method for the family is static, apply it directly; if it is dhcp, or there is no bearer yet, fall through to the existing DHCP(v6) client / kernel SLAAC unchanged. - Address and DNS are applied from the bearer. DNS is registered with vyos-hostsd under the same dhcp-<if>/dhcpv6-<if> tags a real client uses. A DHCP(v6) client which was started while the bearer was still missing, including one which keeps restarting, is stopped before the settings are applied. - The default route is rendered into FRR as a tag 210 static route, the same way a DHCP one is. WWANIf records the gateway of the bearer in /run/vyos-wwan, which the new get_wwan_router() filter reads, and a new block in staticd.frr.j2 fed by get_wwan_interfaces() renders the IPv4 and IPv6 default routes. Distance, no-default-route and VRFs behave as for DHCP, also for an interface without "address dhcp". frrender notices a gateway change, and WWANIf reconciles FRR with vyos-frr-render.py whenever the recorded gateway changes, the way the dhclient lease hook does, so op-mode reconnect is covered as well. The state is written atomically, as the renderer reads it concurrently. - The address installed from the bearer is recorded in /run/vyos-wwan too. It is removed on reconnect, when the family is no longer configured and when the interface goes away, and nothing else on the interface is ever touched. - vyos-netlinkd applies the bearer again after it re-dials a lost session, as the new session can come back with a different address or gateway. A DHCP client used to pick that up on its own. What a previous session left behind is dropped for a family the new one does not supply, the configured DHCP(v6) client or SLAAC is started for it as a commit would, and an incomplete result is retried on the following reconcile passes for a while. - The bearer is picked by its connected status rather than bearers[0], and its config is polled briefly with wait_for() until it is no longer missing or a placeholder, since it can be populated slightly after the bearer reports connected.
Diffstat (limited to 'python')
-rw-r--r--python/vyos/configdict.py46
-rw-r--r--python/vyos/frrender.py56
-rw-r--r--python/vyos/ifconfig/wwan.py295
-rwxr-xr-xpython/vyos/template.py9
-rw-r--r--python/vyos/utils/wwan.py67
5 files changed, 467 insertions, 6 deletions
diff --git a/python/vyos/configdict.py b/python/vyos/configdict.py
index 8c311616c..0fc3a179b 100644
--- a/python/vyos/configdict.py
+++ b/python/vyos/configdict.py
@@ -480,6 +480,52 @@ def get_pppoe_interfaces(conf, vrf=None):
return pppoe_interfaces
+
+def get_wwan_interfaces(conf, vrf=None):
+ """Common helper function to retrieve all WWAN interfaces from the current
+ CLI session that can get an address from the bearer of their modem and
+ thus contribute a default route."""
+ wwan_interfaces = {}
+ conf.set_level([]) # required for list_nodes()
+ for ifname in conf.list_nodes(['interfaces', 'wwan']):
+ # always reset config level, as get_interface_dict() will alter it
+ conf.set_level([])
+ _, ifconfig = get_interface_dict(conf, ['interfaces', 'wwan'], ifname)
+
+ if 'disable' in ifconfig:
+ continue
+
+ options = {}
+ address = ifconfig.get('address', [])
+ if 'dhcp' in address:
+ options.update({'ipv4': {}})
+ if (
+ 'dhcpv6' in address
+ or dict_search('ipv6.address.autoconf', ifconfig) is not None
+ ):
+ options.update({'ipv6': {}})
+ if not options:
+ continue
+
+ # get_interface_dict() drops dhcp_options unless "address dhcp" is
+ # configured, but the distance applies to the IPv6 route as well
+ from vyos.xml_ref import default_value
+
+ path = ['interfaces', 'wwan', ifname, 'dhcp-options', 'default-route-distance']
+ tmp = conf.return_value(path) if conf.exists(path) else default_value(path)
+ if tmp is not None:
+ options.update({'default_route_distance': tmp})
+ if dict_search('dhcp_options.no_default_route', ifconfig) is not None:
+ options.update({'no_default_route': {}})
+ if 'vrf' in ifconfig:
+ if vrf == ifconfig['vrf']:
+ wwan_interfaces.update({ifname: options})
+ else:
+ if vrf is None:
+ wwan_interfaces.update({ifname: options})
+
+ return wwan_interfaces
+
def get_interface_dict(config, base, ifname='', recursive_defaults=True, with_pki=False):
"""
Common utility function to retrieve and mangle the interfaces configuration
diff --git a/python/vyos/frrender.py b/python/vyos/frrender.py
index 275316e4a..8685d5a9b 100644
--- a/python/vyos/frrender.py
+++ b/python/vyos/frrender.py
@@ -32,6 +32,7 @@ from vyos.config import Config
from vyos.config import config_dict_merge
from vyos.configdict import get_dhcp_interfaces
from vyos.configdict import get_pppoe_interfaces
+from vyos.configdict import get_wwan_interfaces
from vyos.defaults import frr_debug_enable
from vyos.utils.dict import dict_search
from vyos.utils.dict import dict_set_nested
@@ -39,6 +40,7 @@ from vyos.utils.file import read_file
from vyos.utils.file import write_file
from vyos.utils.process import rc_cmd
from vyos.template import get_dhcp_router
+from vyos.template import get_wwan_router
from vyos.template import render_to_string
from vyos import ConfigError
@@ -577,7 +579,7 @@ def get_frrender_dict(conf: Config, argv=None) -> dict:
no_tag_node_value_mangle=True)
dict.update({'static' : static})
elif conf.exists_effective(static_cli_path):
- # Use a copy - static.dhcp/static.pppoe below may be merged in,
+ # Use a copy - static.dhcp/static.pppoe/static.wwan below may be merged in,
# and deleted_protocol is shared by reference with other protocols
dict.update({'static' : deleted_protocol.copy()})
@@ -600,10 +602,14 @@ def get_frrender_dict(conf: Config, argv=None) -> dict:
tmp = get_pppoe_interfaces(conf)
if tmp: dict_set_nested('static.pppoe', tmp, dict)
+ tmp = get_wwan_interfaces(conf)
+ if tmp:
+ dict_set_nested('static.wwan', tmp, dict)
+
# T6991/T9054: "protocols static" may have been deleted while a DHCP or
# PPPoE interface still contributes a default route - in that case the
# static section must still be rendered, so drop the deletion marker
- if 'static' in dict and ('dhcp' in dict['static'] or 'pppoe' in dict['static']):
+ if 'static' in dict and any(k in dict['static'] for k in ('dhcp', 'pppoe', 'wwan')):
dict['static'].pop('deleted', None)
# keep a re-usable list of dependent VRFs
@@ -741,7 +747,7 @@ def get_frrender_dict(conf: Config, argv=None) -> dict:
no_tag_node_value_mangle=True)
dict_set_nested(f'{protocol_dict_path}.static', static, vrf)
elif conf.exists_effective(static_vrf_path):
- # Use a copy - static.dhcp/static.pppoe below may be merged in,
+ # Use a copy - static.dhcp/static.pppoe/static.wwan below may be merged in,
# and deleted_protocol is shared by reference with other protocols
dict_set_nested(f'{protocol_dict_path}.static', deleted_protocol.copy(), vrf)
@@ -752,12 +758,16 @@ def get_frrender_dict(conf: Config, argv=None) -> dict:
tmp = get_pppoe_interfaces(conf, vrf_name)
if tmp: dict_set_nested(f'name.{vrf_name}.protocols.static.pppoe', tmp, vrf)
+ tmp = get_wwan_interfaces(conf, vrf_name)
+ if tmp:
+ dict_set_nested(f'name.{vrf_name}.protocols.static.wwan', tmp, vrf)
+
# T6991/T9054: "protocols static" may have been deleted while a
# DHCP or PPPoE interface still contributes a default route - in
# that case the static section must still be rendered, so drop
# the deletion marker
static_dict = dict_search(f'{protocol_dict_path}.static', vrf)
- if static_dict and ('dhcp' in static_dict or 'pppoe' in static_dict):
+ if static_dict and any(k in static_dict for k in ('dhcp', 'pppoe', 'wwan')):
static_dict.pop('deleted', None)
vrf_vni_path = ['vrf', 'name', vrf_name, 'vni']
@@ -856,10 +866,31 @@ def get_dhcp_route_interfaces(config_dict) -> set:
return interfaces
+
+def get_wwan_route_interfaces(config_dict) -> set:
+ """Collect all WWAN interfaces whose default route is derived from the
+ gateway of their bearer, which is read by the "get_wwan_router" Jinja
+ filter and thus changes independently of the CLI configuration.
+ """
+ interfaces = set()
+ if not isinstance(config_dict, dict):
+ return interfaces
+
+ static = config_dict.get('static')
+ if isinstance(static, dict):
+ interfaces.update(static.get('wwan', {}))
+ for vrf_name in dict_search('vrf.name', config_dict) or {}:
+ static = dict_search(f'vrf.name.{vrf_name}.protocols.static', config_dict)
+ if isinstance(static, dict):
+ interfaces.update(static.get('wwan', {}))
+
+ return interfaces
+
class FRRender:
# Configuration of the last successful apply(), see generate()
cached_config_dict = {}
cached_dhcp_gateways = {}
+ cached_wwan_gateways = {}
def __init__(self):
self._frr_conf = frr_config_file
# Configuration rendered by generate(), which apply() has not
@@ -885,6 +916,14 @@ class FRRender:
for interface in get_dhcp_route_interfaces(config_dict)
}
+ wwan_gateways = {
+ interface: (
+ get_wwan_router(interface, 'ipv4'),
+ get_wwan_router(interface, 'ipv6'),
+ )
+ for interface in get_wwan_route_interfaces(config_dict)
+ }
+
# A render which did not reach apply() must not count as applied
self._pending = None
@@ -894,6 +933,7 @@ class FRRender:
if (
self.cached_config_dict == config_dict
and self.cached_dhcp_gateways == dhcp_gateways
+ and self.cached_wwan_gateways == wwan_gateways
and read_file(self._frr_conf, None)
== read_file(frr_applied_config_file, None)
):
@@ -1043,7 +1083,7 @@ class FRRender:
# Only apply() makes this the cached configuration. If FRR does not
# take it, the next commit must render and apply it again instead of
# reporting no changes (T9442).
- self._pending = (config_dict, dhcp_gateways)
+ self._pending = (config_dict, dhcp_gateways, wwan_gateways)
return True
def apply(self, count_max=5):
@@ -1096,4 +1136,8 @@ class FRRender:
# FRR runs the rendered configuration now, remember it for the change
# detection of generate()
if pending is not None:
- self.cached_config_dict, self.cached_dhcp_gateways = pending
+ (
+ self.cached_config_dict,
+ self.cached_dhcp_gateways,
+ self.cached_wwan_gateways,
+ ) = pending
diff --git a/python/vyos/ifconfig/wwan.py b/python/vyos/ifconfig/wwan.py
index 83a92639f..2904a124a 100644
--- a/python/vyos/ifconfig/wwan.py
+++ b/python/vyos/ifconfig/wwan.py
@@ -13,7 +13,19 @@
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see <http://www.gnu.org/licenses/>.
+from json import loads
+
from vyos.ifconfig.interface import Interface
+from vyos.utils.dict import dict_search
+from vyos.utils.misc import wait_for
+from vyos.utils.network import is_intf_addr_assigned
+from vyos.utils.process import cmdl
+from vyos.utils.process import is_systemd_service_active
+from vyos.utils.wwan import get_bearer_address
+from vyos.utils.wwan import get_bearer_router
+from vyos.utils.wwan import modem_index
+from vyos.utils.wwan import set_bearer_address
+from vyos.utils.wwan import set_bearer_router
@Interface.register
class WWANIf(Interface):
@@ -30,6 +42,138 @@ class WWANIf(Interface):
# we cannot create this interface as it is managed by the Kernel
pass
+ def _get_active_bearer(self):
+ """Return the mmcli --output-json dict for this interface's
+ connected ModemManager bearer, or None. Matches on status.connected
+ rather than bearers[0], since a stale disconnected bearer can
+ linger alongside the current one."""
+ modem = modem_index(self.ifname)
+ if modem is None:
+ return None
+ try:
+ modem_info = loads(cmdl(['mmcli', '--modem', modem, '--output-json']))
+ except (OSError, ValueError):
+ return None
+ bearers = dict_search('modem.generic.bearers', modem_info) or []
+ for bearer_path in bearers:
+ bearer_id = bearer_path.rsplit('/', 1)[-1]
+ try:
+ bearer = loads(cmdl(['mmcli', '--bearer', bearer_id, '--output-json']))
+ except (OSError, ValueError):
+ continue
+ if dict_search('bearer.status.connected', bearer) == 'yes':
+ return bearer
+ return None
+
+ def _wait_for_bearer_method(self, family):
+ # A bearer can report "connected" before its ipv4-config/ipv6-config
+ # is populated over D-Bus - retry briefly rather than mistaking that
+ # delay for "no static config".
+ result = {}
+
+ def _ready():
+ result['bearer'] = self._get_active_bearer()
+ result['method'] = (
+ dict_search(f'bearer.{family}-config.method', result['bearer'])
+ if result['bearer']
+ else None
+ )
+ return result['method'] not in (None, '', '--')
+
+ wait_for(_ready, interval=0.5, timeout=5)
+ return result['bearer'], result['method']
+
+ def add_addr(self, addr: str, vrf_changed: bool = False) -> bool:
+ if addr not in ('dhcp', 'dhcpv6'):
+ return super().add_addr(addr, vrf_changed=vrf_changed)
+
+ family = 'ipv4' if addr == 'dhcp' else 'ipv6'
+
+ bearer, method = self._wait_for_bearer_method(family)
+
+ if method in (None, '', '--', 'dhcp'):
+ self._forget_bearer(family)
+ return super().add_addr(addr, vrf_changed=vrf_changed)
+
+ # method == 'static' (the common case for QMI raw-ip modems): apply
+ # the bearer's own address/gateway/DNS directly, since a DHCP(v6)
+ # client would never get a reply from it.
+ return self._apply_bearer_address(bearer, family)
+
+ def set_ipv6_autoconf(self, autoconf):
+ if autoconf == '0':
+ result = super().set_ipv6_autoconf(autoconf)
+ # Called with '0' on every commit where autoconf isn't
+ # configured, not just on disable - skip the sweep if dhcpv6
+ # owns the address instead, which cleans up after itself.
+ if 'dhcpv6' not in (self.config.get('address') or []):
+ self._forget_bearer('ipv6')
+ return result
+
+ # Same idea as add_addr(): a modem resolving IPv6 over the air sends
+ # no RA traffic for the kernel to autoconf from, so apply the
+ # bearer's result directly. Falls through unchanged for a modem that
+ # genuinely needs host-side SLAAC (e.g. Intel XMM-based).
+ bearer, method = self._wait_for_bearer_method('ipv6')
+
+ if method in (None, '', '--', 'dhcp'):
+ self._forget_bearer('ipv6')
+ return super().set_ipv6_autoconf(autoconf)
+
+ return self._apply_bearer_address(bearer, 'ipv6')
+
+ def reapply_bearer(self, config):
+ """Re-apply a static bearer's config after the session was re-dialled,
+ as the new session can come back with a different address or gateway.
+ What the previous session left behind is dropped for a family the new
+ one does not supply (yet) or hands to a DHCP(v6) client, and the
+ configured DHCP(v6) client or SLAAC is started for it as a commit
+ does. Returns True once every configured family is settled, False if
+ the settings of one are still missing and the caller should try
+ again."""
+ self.config = config
+ address = config.get('address') or []
+ families = []
+ if 'dhcp' in address:
+ families.append('ipv4')
+ if (
+ 'dhcpv6' in address
+ or dict_search('ipv6.address.autoconf', config) is not None
+ ):
+ families.append('ipv6')
+ complete = True
+ for family in families:
+ bearer, method = self._wait_for_bearer_method(family)
+ if method not in (None, '', '--', 'dhcp'):
+ if not self._apply_bearer_address(bearer, family):
+ self._forget_bearer(family)
+ complete = False
+ continue
+ self._forget_bearer(family)
+ self._apply_fallback(family)
+ if method != 'dhcp':
+ complete = False
+ return complete
+
+ def del_addr(self, addr: str) -> bool:
+ if addr not in ('dhcp', 'dhcpv6'):
+ return super().del_addr(addr)
+
+ # Let a real DHCP(v6) client release its lease and clean up its own
+ # tag first; only then sweep anything a static bearer applied,
+ # since at most one of the two ever had the address.
+ result = super().del_addr(addr)
+ family = 'ipv4' if addr == 'dhcp' else 'ipv6'
+ # Called on every commit where dhcpv6 isn't configured. With autoconf
+ # the bearer is owned by set_ipv6_autoconf() and must stay.
+ if (
+ family == 'ipv6'
+ and dict_search('ipv6.address.autoconf', self.config) is not None
+ ):
+ return result
+ self._forget_bearer(family)
+ return result
+
def remove(self):
"""
Remove interface from config. Removing the interface deconfigures all
@@ -45,4 +189,155 @@ class WWANIf(Interface):
# will remain visible for the operating system.
self.set_admin_state('down')
+ # flush_addrs() clears the addresses but bypasses del_addr(), so it
+ # never runs the vyos-hostsd tag cleanup a static bearer needs.
+ self._clear_bearer_address('ipv4')
+ self._clear_bearer_address('ipv6')
+
super().remove()
+
+ def _apply_bearer_address(self, bearer, family) -> bool:
+ prefix = f'bearer.{family}-config'
+ address = dict_search(f'{prefix}.address', bearer)
+ plen = dict_search(f'{prefix}.prefix', bearer)
+ if not address or not plen:
+ return False
+ cidr = f'{address}/{plen}'
+
+ # A DHCP(v6) client started while the bearer was still missing would
+ # keep running next to the settings applied here
+ self._stop_address_client(family)
+
+ # A reconnect can negotiate a different address, and there's no
+ # config-tree entry for a bearer's address to diff against - remove
+ # the one applied from the previous bearer, and only that one.
+ previous = get_bearer_address(self.ifname, family)
+ if previous and previous != cidr:
+ self.del_addr(previous)
+
+ if not is_intf_addr_assigned(self.ifname, cidr):
+ tmp = ['ip', 'addr', 'add', cidr, 'dev', self.ifname]
+ if family == 'ipv4':
+ tmp += ['brd', '+']
+ self._cmdl(tmp)
+ self._addr.append(cidr)
+
+ set_bearer_address(self.ifname, family, cidr)
+ self._set_bearer_router(family, bearer)
+ self._apply_bearer_dns(bearer, family)
+ return True
+
+ def _apply_fallback(self, family):
+ # What a commit does for a family without a static bearer
+ if family == 'ipv4':
+ super().add_addr('dhcp')
+ elif 'dhcpv6' in (self.config.get('address') or []):
+ super().add_addr('dhcpv6')
+ else:
+ super().set_ipv6_autoconf('1')
+
+ def _forget_bearer(self, family):
+ # Only when a static bearer left something behind: the DNS tag is
+ # shared with a real DHCP(v6) client, whose servers are not ours to drop
+ if get_bearer_address(self.ifname, family) or get_bearer_router(
+ self.ifname, family
+ ):
+ self._clear_bearer_address(family)
+
+ def _set_bearer_router(self, family, bearer):
+ router = (
+ dict_search(f'bearer.{family}-config.gateway', bearer) if bearer else None
+ )
+ router = None if router == '--' else router
+ if router == get_bearer_router(self.ifname, family):
+ return None
+ set_bearer_router(self.ifname, family, router)
+ # The default route is rendered from the gateway, so FRR is reconciled
+ # the way a DHCP lease event does it. Not every caller is a commit
+ # with a render of its own at the end, e.g. op-mode reconnect.
+ try:
+ cmdl(
+ [
+ 'systemd-run',
+ '--no-block',
+ '--collect',
+ '--quiet',
+ '/usr/libexec/vyos/vyos-frr-render.py',
+ '--after-commit',
+ ]
+ )
+ except OSError:
+ pass
+
+ def _stop_address_client(self, family):
+ if family == 'ipv4':
+ unit = f'dhclient@{self.ifname}.service'
+ elif dict_search('dhcpv6_options.pd', self.config):
+ # DHCPv6-PD is requested through the same client and stays
+ return None
+ else:
+ unit = f'dhcp6c@{self.ifname}.service'
+
+ # A client which cannot get a lease keeps restarting and is never
+ # "active", which stop_systemd_unit() would leave alone
+ state = cmdl(['systemctl', 'show', '--value', '-p', 'ActiveState', unit])
+ if state not in ('active', 'activating', 'reloading'):
+ return None
+ try:
+ cmdl(['systemctl', 'stop', unit])
+ except OSError:
+ pass
+ if family == 'ipv4':
+ self.set_dhcp(False)
+ else:
+ self.set_dhcpv6(False)
+
+ def _apply_bearer_dns(self, bearer, family):
+ # A current mmcli --output-json reports this as a JSON list under a
+ # single 'dns' key rather than the older separate dns1/dns2/dns3
+ # keys - fall back to those for an older ModemManager.
+ dns = dict_search(f'bearer.{family}-config.dns', bearer)
+ if isinstance(dns, list):
+ servers = [s for s in dns if s and s != '--']
+ else:
+ servers = []
+ for key in ('dns1', 'dns2', 'dns3'):
+ value = dict_search(f'bearer.{family}-config.{key}', bearer)
+ if value and value != '--':
+ servers.append(value)
+ self._set_hostsd_name_servers(family, servers)
+
+ def _clear_bearer_address(self, family):
+ cidr = get_bearer_address(self.ifname, family)
+ if cidr:
+ if is_intf_addr_assigned(self.ifname, cidr):
+ self._cmdl(['ip', 'addr', 'del', cidr, 'dev', self.ifname])
+ if cidr in self._addr:
+ self._addr.remove(cidr)
+ set_bearer_address(self.ifname, family, None)
+ self._set_bearer_router(family, None)
+ self._set_hostsd_name_servers(family, None)
+
+ def _set_hostsd_name_servers(self, family, servers):
+ """servers=None deletes the tag's nameservers without replacing them
+ (teardown); servers=[] or a populated list replaces them (apply).
+ Uses the same vyos-hostsd tags a real DHCP(v6) client would
+ ("dhcp-<ifname>" / "dhcpv6-<ifname>", see 04-vyos-resolvconf and
+ dhcp6c-script.j2), not a WWAN-specific one, so an operator's
+ `set system name-server <ifname>` trust config works unchanged
+ either way."""
+ if not is_systemd_service_active('vyos-hostsd'):
+ return
+ # Imported here as it pulls in zmq, which no other ifconfig class needs
+ from vyos.hostsd_client import Client as hostsd_client
+ from vyos.hostsd_client import VyOSHostsdError
+
+ tag = f'dhcp-{self.ifname}' if family == 'ipv4' else f'dhcpv6-{self.ifname}'
+ try:
+ hc = hostsd_client()
+ hc.delete_name_servers([tag])
+ if servers:
+ hc.add_name_servers({tag: servers})
+ hc.apply()
+ except VyOSHostsdError:
+ pass
diff --git a/python/vyos/template.py b/python/vyos/template.py
index 6323657ed..934beecd1 100755
--- a/python/vyos/template.py
+++ b/python/vyos/template.py
@@ -454,6 +454,15 @@ def get_dhcp_router(interface):
address = address.split()[0]
return address
+
+@register_filter('get_wwan_router')
+def get_wwan_router(interface, family):
+ """Default router of the static bearer of a WWAN interface for the given
+ address family ("ipv4" or "ipv6"), or None if it does not have one."""
+ from vyos.utils.wwan import get_bearer_router
+
+ return get_bearer_router(interface, family)
+
@register_filter('natural_sort')
def natural_sort(iterable):
import re
diff --git a/python/vyos/utils/wwan.py b/python/vyos/utils/wwan.py
index 7b7c31d02..e42adea16 100644
--- a/python/vyos/utils/wwan.py
+++ b/python/vyos/utils/wwan.py
@@ -24,6 +24,7 @@ would have done.
"""
import os
+import tempfile
from time import sleep
@@ -190,6 +191,72 @@ def connect_options(config: dict) -> str:
return options
+# What WWANIf applied from the static bearer of an interface, per address
+# family: its gateway, for the FRR renderer to build the default route from, and
+# the address it installed, so only that one is ever removed again. Same /run
+# directory as above.
+bearer_state_dir = admin_disconnect_dir
+
+
+def _bearer_state_file(ifname: str, family: str, key: str) -> str:
+ return os.path.join(bearer_state_dir, f'{ifname}.{family}-{key}')
+
+
+def _set_bearer_state(ifname: str, family: str, key: str, value) -> None:
+ path = _bearer_state_file(ifname, family, key)
+ if not value:
+ try:
+ os.unlink(path)
+ except FileNotFoundError:
+ pass
+ return None
+ os.makedirs(bearer_state_dir, exist_ok=True)
+ # The FRR renderer reads this while it is being written, so a reader
+ # must never see a truncated or partial value
+ fd, tmp_path = tempfile.mkstemp(dir=bearer_state_dir, prefix='.tmp-')
+ try:
+ with os.fdopen(fd, 'w') as f:
+ f.write(value)
+ os.chmod(tmp_path, 0o644)
+ os.replace(tmp_path, path)
+ except BaseException:
+ try:
+ os.unlink(tmp_path)
+ except FileNotFoundError:
+ pass
+ raise
+
+
+def _get_bearer_state(ifname: str, family: str, key: str):
+ try:
+ with open(_bearer_state_file(ifname, family, key)) as f:
+ return f.read().strip() or None
+ except FileNotFoundError:
+ return None
+
+
+def set_bearer_router(ifname: str, family: str, router) -> None:
+ """Record the gateway of the static bearer of a WWAN interface, or forget
+ it when router is empty - the bearer is gone or does not have one"""
+ _set_bearer_state(ifname, family, 'router', router)
+
+
+def get_bearer_router(ifname: str, family: str):
+ """Return the recorded gateway of a static bearer, or None"""
+ return _get_bearer_state(ifname, family, 'router')
+
+
+def set_bearer_address(ifname: str, family: str, address) -> None:
+ """Record the address (CIDR) installed from the static bearer of a WWAN
+ interface, or forget it when address is empty"""
+ _set_bearer_state(ifname, family, 'address', address)
+
+
+def get_bearer_address(ifname: str, family: str):
+ """Return the recorded address (CIDR) installed from a static bearer"""
+ return _get_bearer_state(ifname, family, 'address')
+
+
def _admin_disconnect_marker(ifname: str) -> str:
return os.path.join(admin_disconnect_dir, f'{ifname}.disconnected')