#!/usr/bin/env python3 """First-run setup wizard for the OpenThread Border Router Umbrel app. Rendered by Umbrel's app template pass into server.py during install/update. Avoid shell-style environment variable markers in this source. """ import glob import html import os import re import socket import urllib.parse from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer PORT = int(os.environ.get("SETUP_PORT", "7586")) OTBR_WEB_PORT = os.environ.get("OTBR_WEB_PORT", "8080") OTBR_REST_PORT = os.environ.get("OTBR_REST_PORT", "8083") SETTINGS_FILE = "/data/settings.env" APPLIED_FILE = "/data/.applied" DEFAULTS = { "DEVICE": "", "BAUDRATE": "460800", "FLOW_CONTROL": "0", "BACKBONE_IF": "eth0", "FIREWALL": "1", "NAT64": "1", "AUTOFLASH_FIRMWARE": "0", } def list_serial_devices(): devices = [] for path in sorted(glob.glob("/dev/serial/by-id/*")): devices.append(path) for pattern in ("/dev/ttyACM*", "/dev/ttyUSB*"): for path in sorted(glob.glob(pattern)): if path not in devices: devices.append(path) return devices _VIRTUAL_IF_PREFIXES = ( "lo", "veth", "br-", "br0", "docker", "dind", "wpan", "tap", "tun", "trel", "virbr", "vmnet", "cni", "flannel", "kube", "ifb", "dummy", "wg", "zt", "tailscale", "sit", "gre", ) def detect_backbone_if(): try: with open("/proc/net/route") as fh: for line in fh.readlines()[1:]: fields = line.split() if len(fields) >= 2 and fields[1] == "00000000": return fields[0] except OSError: pass try: with open("/proc/net/ipv6_route") as fh: for line in fh: fields = line.split() if len(fields) >= 10 and fields[0] == "0" * 32 and fields[1] == "00": return fields[9] except OSError: pass for iface in sorted(glob.glob("/sys/class/net/*")): name = os.path.basename(iface) if name != "lo" and not name.startswith(_VIRTUAL_IF_PREFIXES): return name return "eth0" def list_interfaces(): names = [] for path in sorted(glob.glob("/sys/class/net/*")): name = os.path.basename(path) if name == "lo" or name.startswith(_VIRTUAL_IF_PREFIXES): continue names.append(name) default_if = detect_backbone_if() if default_if in names: names.remove(default_if) names.insert(0, default_if) return names def _read_int(path): try: with open(path) as fh: return int(fh.read().strip()) except (OSError, ValueError): return None def iface_has_global_ipv6(iface): try: with open("/proc/net/if_inet6") as fh: for line in fh: fields = line.split() if len(fields) >= 6 and fields[5] == iface and fields[3] == "00": return True except OSError: pass return False def has_default_ipv6_route(): try: with open("/proc/net/ipv6_route") as fh: for line in fh: fields = line.split() if len(fields) >= 2 and fields[0] == "0" * 32 and fields[1] == "00": return True except OSError: pass return False def ipv6_status(iface): host_enabled = _read_int("/proc/sys/net/ipv6/conf/all/disable_ipv6") == 0 iface_has_addr = iface_has_global_ipv6(iface) default_route = has_default_ipv6_route() return [ ( "IPv6 on the Umbrel host", host_enabled, "Kernel IPv6 is enabled." if host_enabled else "IPv6 is disabled on this host. Enable it in your Umbrel/OS " "network settings, then restart this app.", ), ( f"Global IPv6 address on '{iface}'", iface_has_addr, "A routable IPv6 address is present." if iface_has_addr else "No global IPv6 address found on this interface. Make sure " "you picked your LAN interface and that your router hands out IPv6.", ), ( "IPv6 from your router (default route)", default_route, "An IPv6 default route is present." if default_route else "No IPv6 default route. Enable IPv6 (SLAAC/DHCPv6) on your " "router. Thread/Matter need end-to-end IPv6 on your LAN.", ), ] def read_settings(): values = dict(DEFAULTS) values["CONFIGURED"] = "0" try: with open(SETTINGS_FILE) as fh: for line in fh: line = line.strip() if not line or line.startswith("#") or "=" not in line: continue key, _, val = line.partition("=") values[key.strip()] = val.strip() except OSError: pass return values def write_settings(values): lines = [ "# OpenThread Border Router settings — written by the setup wizard.", "# Re-run setup from the app to change these.", "", ] for key in DEFAULTS: lines.append(f"{key}={values.get(key, DEFAULTS[key])}") lines.append("CONFIGURED=1") lines.append("") os.makedirs(os.path.dirname(SETTINGS_FILE), exist_ok=True) tmp = SETTINGS_FILE + ".tmp" with open(tmp, "w") as fh: fh.write("\n".join(lines)) os.replace(tmp, SETTINGS_FILE) def is_configured(): return read_settings().get("CONFIGURED") == "1" def device_exists(path): return bool(path) and os.path.exists(path) def config_applied(): """True if the live border router was launched with the current settings (the entrypoint records them in APPLIED_FILE just before starting OTBR). False right after a reconfigure, while the restart is still pending.""" try: with open(SETTINGS_FILE) as f: current = f.read() with open(APPLIED_FILE) as f: applied = f.read() except OSError: return False return current == applied def otbr_running(): """True if the OTBR REST port is accepting connections (it only listens once otbr-agent has actually started, i.e. the radio came up).""" try: port = int(OTBR_REST_PORT) except ValueError: return False for family, addr in ( (socket.AF_INET, ("127.0.0.1", port)), (socket.AF_INET6, ("::1", port)), ): try: with socket.socket(family, socket.SOCK_STREAM) as s: s.settimeout(0.5) if s.connect_ex(addr) == 0: return True except OSError: pass return False _RE_DEVICE = re.compile( r"^/dev/(?:ttyACM[0-9]+|ttyUSB[0-9]+|serial/(?:by-id|by-path)/[A-Za-z0-9][A-Za-z0-9_.+,:=@-]{0,199})$" ) _RE_IFACE = re.compile(r"^[A-Za-z0-9._\-]{1,32}$") _RE_BAUD = re.compile(r"^[0-9]{3,7}$") _BOOLS = {"0", "1"} def validate_settings(values): if not values.get("DEVICE"): return "Please select or enter a serial device." if not _RE_DEVICE.match(values["DEVICE"]): return "Device path must be a USB serial radio path like /dev/ttyACM0, /dev/ttyUSB0, or /dev/serial/by-id/..." if not _RE_BAUD.match(values.get("BAUDRATE", "")): return "Baud rate must be a number (e.g. 460800)." if not _RE_IFACE.match(values.get("BACKBONE_IF", "")): return "Backbone interface must be a valid interface name (e.g. eth0)." for key in ("FLOW_CONTROL", "FIREWALL", "NAT64", "AUTOFLASH_FIRMWARE"): if values.get(key) not in _BOOLS: return "Invalid option value." return None ICON_SVG = """ """ PAGE = """
{esc(k)}{esc(values.get(k, ''))}No serial devices detected. Plug in your Thread radio " "dongle and reload, or enter the path manually.
" if not devices else "" ) interfaces = list_interfaces() if_opts = [] for name in interfaces: sel = " selected" if name == iface else "" if_opts.append(f'') if_manual_sel = " selected" if iface and iface not in interfaces else "" if_opts.append(f'') checks_html = render_ipv6_checks(iface) msg_html = ( f"First-run setup
{msg_html}Connect Home Assistant
In Home Assistant add the OpenThread Border Router integration and enter this REST API URL (it's an API, not a web page):
…
Or manage the Thread network directly in the OTBR dashboard:
Saving changes restarts the border router automatically to apply them.
{device} "
"isn't connected. Plug the radio in, or choose Reconfigure to pick "
"another device — the border router starts automatically once the "
"device is present."
)
else:
title = "Starting the border router…"
detail = (
"The border router is starting with your settings (this also happens "
"right after you reconfigure). It can take a minute — this page "
"refreshes automatically."
)
body = f"""
Setup
Cross-site request blocked.