Files
napalm-linux/napalm_linux/_routes.py
T
Christian Manivong ca65f007c1
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m17s
driver / test (3.13) (pull_request) Successful in 1m12s
driver / test (3.12) (pull_request) Successful in 1m18s
driver / lowest (pull_request) Successful in 37s
driver / build (pull_request) Successful in 40s
driver / security (pull_request) Successful in 1m25s
CI / driver (pull_request) Successful in 3m10s
driver / publish (pull_request) Skipped
fix(routes): read the address of a "via inet6" next hop
iproute2 prints an IPv4 route with an IPv6 next hop (RFC 8950, BGP
unnumbered) as "via inet6 fe80::1", and the next hop was read as the
literal "inet6". The family word after "via" is now skipped, for
multipath next hops as well.

With the address in place, get_route_to would have reported such a
route as ipv6, because it took the family from the next hop too. The
family is now the destination's alone. The test fixture is ip's output
(iproute2 6.1.0) recorded in a network namespace set up with these
routes.

Closes #65
2026-11-02 08:49:53 +01:00

107 lines
3.6 KiB
Python

"""Routes from ``ip route show``, one address family at a time."""
from __future__ import annotations
import re
from collections.abc import Iterator
from typing import NamedTuple
#: The command per family. ``ip -6 route show`` names its default route ``default``
#: as well, so only the command a line came from says which family it is (#6).
IP_ROUTE_COMMANDS = {"ipv4": "ip -4 route show", "ipv6": "ip -6 route show"}
_DEFAULT = {"ipv4": "0.0.0.0/0", "ipv6": "::/0"}
_HOST_PREFIX = {"ipv4": "/32", "ipv6": "/128"}
#: The route types ``ip route`` prints in front of the destination; a unicast route
#: carries none (#57).
_ROUTE_TYPES = frozenset(
{
"unicast",
"local",
"broadcast",
"anycast",
"multicast",
"blackhole",
"unreachable",
"prohibit",
"throw",
"nat",
"xresolve",
}
)
#: Route types that send nothing out of an interface: no next hop, and no outgoing
#: interface either, though IPv6 names ``lo`` for them.
_NO_FORWARDING = frozenset({"blackhole", "unreachable", "prohibit", "throw"})
#: The line a multipath route's next hops start with, one each, after the route.
_NEXTHOP = "nexthop"
#: ``via 192.0.2.1``, or with the gateway's family in front: ``via inet6 fe80::1`` for an
#: IPv4 route with an IPv6 next hop (RFC 8950, #65).
_VIA = re.compile(r"via\s+(?:inet6?\s+)?(\S+)")
_DEV = re.compile(r"dev\s+(\S+)")
_PROTO = re.compile(r"proto\s+(\S+)")
_METRIC = re.compile(r"metric\s+(\d+)")
class IpRoute(NamedTuple):
"""One route of ``ip route show``; a multipath route is one per next hop."""
network: str
proto: str
nexthop: str
iface: str
metric: int
route_type: str = "unicast"
@property
def attributes(self) -> dict[str, str]:
"""NAPALM's ``protocol_attributes`` for this route: its type, unless unicast."""
return {} if self.route_type == "unicast" else {"type": self.route_type}
def parse_ip_route(out: str, family: str) -> Iterator[IpRoute]:
"""The routes in *out*, the output of ``IP_ROUTE_COMMANDS[family]``."""
route = ""
hops: list[str] = []
for line in out.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if line.split(None, 1)[0] == _NEXTHOP:
hops.append(line)
continue
if route:
yield from _routes(route, hops, family)
route, hops = line, []
if route:
yield from _routes(route, hops, family)
def with_length(prefix: str) -> str:
"""*prefix* with a prefix length: a host route without one is ``/32`` or ``/128``
by the address's family (#64)."""
if "/" in prefix:
return prefix
return prefix + _HOST_PREFIX["ipv6" if ":" in prefix else "ipv4"]
def _routes(line: str, hops: list[str], family: str) -> Iterator[IpRoute]:
"""The route *line* with its multipath next-hop lines *hops*: one per next hop."""
words = line.split()
route_type = words.pop(0) if words[0] in _ROUTE_TYPES and len(words) > 1 else "unicast"
network = _DEFAULT[family] if words[0] == "default" else words[0]
if "/" not in network:
network += _HOST_PREFIX[family]
proto = _first(_PROTO, line) or "kernel"
metric = int(_first(_METRIC, line) or 0)
if route_type in _NO_FORWARDING:
yield IpRoute(network, proto, "", "", metric, route_type)
return
for hop in hops or [line]:
yield IpRoute(network, proto, _first(_VIA, hop), _first(_DEV, hop), metric, route_type)
def _first(pattern: re.Pattern[str], line: str) -> str:
match = pattern.search(line)
return match.group(1) if match else ""