Commit be06ea0794 for frr
commit be06ea0794ed96a733398015fb341e76ba05c81a
Author: Yufan Zhou <zyivon1019@gmail.com>
Date: Tue Dec 1 18:34:10 2026 -0800
tests: check that ORF REMOVE deletes only the specified entry
Two raw BGP peers install the same two Address Prefix ORF entries on
r1. One of them then sends a REMOVE for seq 10: only that entry may
go, seq 20 must stay. The other peer is the control and keeps both
entries.
Signed-off-by: Yufan Zhou <zyivon1019@gmail.com>
diff --git a/tests/topotests/bgp_orf_remove/__init__.py b/tests/topotests/bgp_orf_remove/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/topotests/bgp_orf_remove/r1/frr.conf b/tests/topotests/bgp_orf_remove/r1/frr.conf
new file mode 100644
index 0000000000..0ddd2398b5
--- /dev/null
+++ b/tests/topotests/bgp_orf_remove/r1/frr.conf
@@ -0,0 +1,26 @@
+!
+interface lo
+ ip address 10.10.10.1/32
+ ip address 10.10.10.2/32
+!
+interface r1-eth0
+ ip address 10.0.0.1/24
+!
+debug bgp neighbor-events
+!
+router bgp 65001
+ bgp router-id 10.0.0.1
+ no bgp ebgp-requires-policy
+ bgp log-neighbor-changes
+ neighbor 10.0.0.2 remote-as 65002
+ neighbor 10.0.0.2 passive
+ neighbor 10.0.0.3 remote-as 65003
+ neighbor 10.0.0.3 passive
+ address-family ipv4 unicast
+ redistribute connected
+ neighbor 10.0.0.2 activate
+ neighbor 10.0.0.2 capability orf prefix-list receive
+ neighbor 10.0.0.3 activate
+ neighbor 10.0.0.3 capability orf prefix-list receive
+ exit-address-family
+!
diff --git a/tests/topotests/bgp_orf_remove/rawpeer.py b/tests/topotests/bgp_orf_remove/rawpeer.py
new file mode 100644
index 0000000000..5685ae57fa
--- /dev/null
+++ b/tests/topotests/bgp_orf_remove/rawpeer.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: ISC
+#
+# Copyright (c) 2026 by
+# Yufan Zhou <zyivon1019@gmail.com>
+#
+"""Minimal raw BGP speaker that sends Prefix ORF ADD and REMOVE entries."""
+
+import argparse
+import socket
+import struct
+import sys
+import threading
+import time
+
+MARKER = b"\xff" * 16
+OPEN = 1
+KEEPALIVE = 4
+ROUTE_REFRESH = 5
+ORF_TYPE_PREFIX = 64
+WHEN_IMMEDIATE = 1
+ADD_PERMIT = 0x00
+# RFC 5291 section 4: Action is the two most significant bits.
+# ADD=0, REMOVE=1, REMOVE-ALL=2, hence REMOVE permits encode as 0x40.
+REMOVE_PERMIT = 0x40
+PREFIX1 = "10.10.10.1"
+PREFIX2 = "10.10.10.2"
+
+
+def log(message):
+ print(message, flush=True)
+
+
+def packet(kind, body=b""):
+ return MARKER + struct.pack("!HB", 19 + len(body), kind) + body
+
+
+def open_packet(local_as, local_ip):
+ # Route Refresh, IPv4-unicast MP, and Prefix ORF in send mode. Do not
+ # advertise Enhanced Route Refresh: this test exercises only subtype 0.
+ refresh_cap = struct.pack("!BB", 2, 0)
+ mp_cap = struct.pack("!BBHBB", 1, 4, 1, 0, 1)
+ orf_value = struct.pack("!HBBBBB", 1, 0, 1, 1, ORF_TYPE_PREFIX, 2)
+ orf_cap = struct.pack("!BB", 3, len(orf_value)) + orf_value
+ capabilities = refresh_cap + mp_cap + orf_cap
+ optional = struct.pack("!BB", 2, len(capabilities)) + capabilities
+ bgp_id = struct.unpack("!I", socket.inet_aton(local_ip))[0]
+ body = struct.pack("!BHHIB", 4, local_as, 30, bgp_id, len(optional))
+ return packet(OPEN, body + optional)
+
+
+def orf_entry(common, sequence, address):
+ # Address Prefix ORF (RFC 5292): sequence, minlen, maxlen, length, prefix.
+ return struct.pack("!BIBBB", common, sequence, 0, 0, 32) + socket.inet_aton(address)
+
+
+def orf_refresh(entries):
+ payload = b"".join(entries)
+ body = (
+ struct.pack("!HBBBBH", 1, 0, 1, WHEN_IMMEDIATE, ORF_TYPE_PREFIX, len(payload))
+ + payload
+ )
+ return packet(ROUTE_REFRESH, body)
+
+
+class Session:
+ def __init__(self, args):
+ self.args = args
+ self.sock = None
+ self.lock = threading.Lock()
+
+ def close(self):
+ if self.sock is not None:
+ self.sock.close()
+ self.sock = None
+
+ def send(self, data):
+ # The keepalive thread and the main thread share the socket.
+ with self.lock:
+ self.sock.sendall(data)
+
+ def _read_exact(self, length):
+ data = b""
+ while len(data) < length:
+ chunk = self.sock.recv(length - len(data))
+ if not chunk:
+ raise EOFError("peer closed TCP connection")
+ data += chunk
+ return data
+
+ def recv_message(self):
+ header = self._read_exact(19)
+ if header[:16] != MARKER:
+ raise RuntimeError("bad BGP marker")
+ length, kind = struct.unpack("!HB", header[16:19])
+ if length < 19 or length > 4096:
+ raise RuntimeError("invalid BGP message length %d" % length)
+ return kind, self._read_exact(length - 19)
+
+ def establish_once(self):
+ self.sock = socket.create_connection((self.args.peer_ip, 179), timeout=5)
+ self.sock.settimeout(10)
+ self.sock.sendall(open_packet(self.args.local_as, self.args.local_ip))
+ kind, body = self.recv_message()
+ if kind != OPEN:
+ raise RuntimeError(
+ "expected OPEN, got type=%d body=%s" % (kind, body.hex())
+ )
+ self.sock.sendall(packet(KEEPALIVE))
+ while True:
+ kind, body = self.recv_message()
+ if kind == KEEPALIVE:
+ return
+ if kind == 3:
+ raise RuntimeError("OPEN rejected: %s" % body.hex())
+
+ def establish(self):
+ deadline = time.time() + 90
+ while True:
+ try:
+ self.establish_once()
+ log("ESTABLISHED=%s" % self.args.mode)
+ return
+ except (OSError, EOFError, RuntimeError) as error:
+ self.close()
+ if time.time() >= deadline:
+ raise
+ log("handshake retry: %s" % error)
+ time.sleep(1)
+
+ def keepalive_forever(self):
+ # Hold time is 30 seconds. Keep the session up even while the main
+ # thread is blocked waiting for the trigger on stdin.
+ while True:
+ time.sleep(10)
+ self.send(packet(KEEPALIVE))
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--mode", choices=["control", "remove"], required=True)
+ parser.add_argument("--local-ip", required=True)
+ parser.add_argument("--peer-ip", default="10.0.0.1")
+ parser.add_argument("--local-as", type=int, required=True)
+ args = parser.parse_args()
+
+ session = Session(args)
+ session.establish()
+ threading.Thread(target=session.keepalive_forever, daemon=True).start()
+
+ add = orf_refresh(
+ [
+ orf_entry(ADD_PERMIT, 10, PREFIX1),
+ orf_entry(ADD_PERMIT, 20, PREFIX2),
+ ]
+ )
+ log("ADD_HEX=" + add.hex())
+ session.send(add)
+ log("ADDED=%s" % args.mode)
+
+ if args.mode == "remove":
+ # The topotest first verifies that both entries are installed. This
+ # prevents a final empty list from being mistaken for REMOVE processing.
+ command = sys.stdin.readline()
+ if not command:
+ raise RuntimeError("stdin closed before REMOVE trigger")
+ remove = orf_refresh([orf_entry(REMOVE_PERMIT, 10, PREFIX1)])
+ log("REMOVE_HEX=" + remove.hex())
+ session.send(remove)
+ log("REMOVED=standard-0x40")
+
+ log("READY=%s" % args.mode)
+ while True:
+ time.sleep(3600)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/topotests/bgp_orf_remove/test_bgp_orf_remove.py b/tests/topotests/bgp_orf_remove/test_bgp_orf_remove.py
new file mode 100644
index 0000000000..6e0cad2d2b
--- /dev/null
+++ b/tests/topotests/bgp_orf_remove/test_bgp_orf_remove.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: ISC
+#
+# Copyright (c) 2026 by
+# Yufan Zhou <zyivon1019@gmail.com>
+#
+"""Prefix ORF REMOVE must delete only the specified entry.
+
+Two raw peers install the same two Address Prefix ORF entries on r1. One
+of them then sends a standard REMOVE (Action=1, 0x40) for seq 10. Only that
+entry may be removed; seq 20 must stay.
+"""
+
+import json
+import os
+import subprocess
+import sys
+
+import pytest
+
+from lib import topotest
+from lib.topogen import Topogen, get_topogen
+
+CWD = os.path.dirname(os.path.realpath(__file__))
+PEERS = {
+ "control": {"ip": "10.0.0.2", "asn": 65002},
+ "remove": {"ip": "10.0.0.3", "asn": 65003},
+}
+PROCESSES = {}
+LOGS = {}
+PREFIX1 = "10.10.10.1/32"
+PREFIX2 = "10.10.10.2/32"
+
+pytestmark = [pytest.mark.bgpd]
+
+
+def build_topo(tgen):
+ r1 = tgen.add_router("r1")
+ switch = tgen.add_switch("s1")
+ switch.add_link(r1)
+ for name, settings in PEERS.items():
+ peer = tgen.add_host(name, "%s/24" % settings["ip"], "via 10.0.0.1")
+ switch.add_link(peer)
+
+
+def setup_module(mod):
+ tgen = Topogen(build_topo, mod.__name__)
+ tgen.start_topology()
+ router = tgen.gears["r1"]
+ router.load_frr_config(os.path.join(CWD, "r1/frr.conf"))
+ router.start()
+
+ for name, settings in PEERS.items():
+ peer = tgen.gears[name]
+ log_path = os.path.join(peer.logdir, name, "rawpeer.log")
+ os.makedirs(os.path.dirname(log_path), exist_ok=True)
+ LOGS[name] = log_path
+ PROCESSES[name] = peer.popen(
+ [
+ "python3",
+ os.path.join(CWD, "rawpeer.py"),
+ "--mode",
+ name,
+ "--local-ip",
+ settings["ip"],
+ "--local-as",
+ str(settings["asn"]),
+ ],
+ stdin=subprocess.PIPE,
+ stdout=open(log_path, "w"),
+ stderr=subprocess.STDOUT,
+ )
+
+
+def teardown_module(mod):
+ for process in PROCESSES.values():
+ if process.poll() is None:
+ process.terminate()
+ process.wait()
+ get_topogen().stop_topology()
+
+
+def wait_for_log(name, marker):
+ def _check():
+ if not os.path.exists(LOGS[name]):
+ return "log does not exist"
+ with open(LOGS[name], "r") as handle:
+ text = handle.read()
+ if marker in text:
+ return None
+ process = PROCESSES[name]
+ if process.poll() is not None:
+ return "raw peer exited with %s; log=%s" % (process.returncode, text)
+ return "waiting for %s; log=%s" % (marker, text)
+
+ _, result = topotest.run_and_expect(_check, None, count=120, wait=0.5)
+ assert result is None, result
+
+
+def orf_text(router, name):
+ return router.vtysh_cmd(
+ "show bgp ipv4 unicast neighbors %s orf-prefix-list" % PEERS[name]["ip"]
+ )
+
+
+def wait_for_entries(router, name, prefixes):
+ def _check():
+ output = orf_text(router, name)
+ missing = [prefix for prefix in prefixes if prefix not in output]
+ if not missing:
+ return None
+ return "missing %s; output=%s" % (missing, output)
+
+ _, result = topotest.run_and_expect(_check, None, count=60, wait=0.5)
+ assert result is None, result
+
+
+def session_state(router, name):
+ output = json.loads(
+ router.vtysh_cmd("show bgp neighbors %s json" % PEERS[name]["ip"])
+ )
+ return output.get(PEERS[name]["ip"], {}).get("bgpState")
+
+
+def trigger(name, command):
+ PROCESSES[name].stdin.write(command + "\n")
+ PROCESSES[name].stdin.flush()
+
+
+def test_standard_remove_deletes_only_selected_entry():
+ """Two-entry ORF must survive a standard REMOVE with its second entry."""
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+ router = tgen.gears["r1"]
+
+ # Normal-retention control: the same two ADDs without a subsequent REMOVE.
+ wait_for_log("control", "READY=control")
+ wait_for_entries(router, "control", [PREFIX1, PREFIX2])
+ initial_control = orf_text(router, "control")
+
+ # Prove the experimental ORF contains both entries before triggering REMOVE.
+ wait_for_log("remove", "ADDED=remove")
+ wait_for_entries(router, "remove", [PREFIX1, PREFIX2])
+ initial_remove = orf_text(router, "remove")
+ print("ORF_BEFORE_REMOVE remove=%r control=%r" % (initial_remove, initial_control))
+ trigger("remove", "remove")
+ wait_for_log("remove", "REMOVED=standard-0x40")
+
+ # Wait until seq 10 has actually been processed, then inspect the same
+ # snapshot. RFC 5291 section 6 requires only the specified entry to go.
+ def _remove_processed():
+ output = orf_text(router, "remove")
+ if PREFIX1 in output:
+ return "REMOVE has not taken effect; output=%s" % output
+ return None
+
+ _, result = topotest.run_and_expect(_remove_processed, None, count=60, wait=0.5)
+ assert result is None, result
+ observed = orf_text(router, "remove")
+ control = orf_text(router, "control")
+ state = session_state(router, "remove")
+ print(
+ "ORF_AFTER_REMOVE observed=%r control=%r session=%s "
+ "removed_seq10_present=%s retained_seq20_present=%s"
+ % (
+ observed,
+ control,
+ state,
+ PREFIX1 in observed,
+ PREFIX2 in observed,
+ )
+ )
+
+ # Establish all validity/control facts before the RFC assertion, so a real
+ # implementation mismatch cannot hide the initial state or session health.
+ assert PREFIX1 not in observed, observed
+ assert PREFIX1 in control and PREFIX2 in control, control
+ assert state == "Established", state
+ assert PREFIX2 in observed, (
+ "RFC5291 REMOVE(0x40) seq 10 must retain seq 20; FRR output=%s" % observed
+ )
+
+
+if __name__ == "__main__":
+ args = ["-s"] + sys.argv[1:]
+ sys.exit(pytest.main(args))