From 307121ec2c6489cb8d5181ed3f91d34d74105796 Mon Sep 17 00:00:00 2001 From: Colin Date: Tue, 11 Jul 2023 01:18:47 +0000 Subject: [PATCH] sane_ssdp: cache the UPNP root device i could also cache the lan and wan... future work, i guess --- .../sane-scripts/src/lib/ssdp/sane_ssdp.py | 21 ++++++++++++++----- .../sane-scripts/src/sane-ip-port-forward | 2 +- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/pkgs/additional/sane-scripts/src/lib/ssdp/sane_ssdp.py b/pkgs/additional/sane-scripts/src/lib/ssdp/sane_ssdp.py index 5523fc40..b4e84a8f 100644 --- a/pkgs/additional/sane-scripts/src/lib/ssdp/sane_ssdp.py +++ b/pkgs/additional/sane-scripts/src/lib/ssdp/sane_ssdp.py @@ -31,6 +31,14 @@ class SsdpResponse: def location(self) -> str: return self.headers.get("LOCATION") +def get_cached_root_devices() -> list[str]: + try: + dev = open("/var/lib/uninsane/upnp.txt", "r").read() + except IOError: + return [] + else: + logger.debug("loaded cached UPNP root device", dev) + return [dev] def get_root_devices() -> list[str]: listener = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) @@ -91,12 +99,15 @@ def get_ips_from_location(location: str) -> tuple[str | None, str | None]: logger.info(f"got LAN = {lan} from {location}") return lan, wan -def get_any_wan() -> tuple[str, str, str] | None: +def get_any_wan(cached: bool = False) -> tuple[str, str, str] | None: """ return (location, LAN IP, WAN IP) for the first device seen which has a WAN IP """ - for location in get_root_devices(): - lan, wan = get_ips_from_location(location) - if lan and wan: - return location, lan, wan + sources = ([ get_cached_root_devices() ] if cached else []) \ + + [ get_root_devices() ] + for source in sources: + for location in source: + lan, wan = get_ips_from_location(location) + if lan and wan: + return location, lan, wan def forward_port(root_device: str, proto: str, port: int, lan_ip: str, reason: str = "", duration: int = 86400) -> None: args = [ diff --git a/pkgs/additional/sane-scripts/src/sane-ip-port-forward b/pkgs/additional/sane-scripts/src/sane-ip-port-forward index 17a3100d..c696679f 100755 --- a/pkgs/additional/sane-scripts/src/sane-ip-port-forward +++ b/pkgs/additional/sane-scripts/src/sane-ip-port-forward @@ -99,6 +99,6 @@ if __name__ == '__main__': print(e) sys.exit(1) - root_device, lan, _wan = get_any_wan() + root_device, lan, _wan = get_any_wan(cached=True) for (proto, port, reason) in forwards: forward_port(root_device, proto, port, lan_ip=lan, reason=reason, duration=duration)