#!/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 = """ OpenThread Border Router {head}
{icon}
{status_text}

OpenThread Border Router

{subtitle}
{topbtn}
{body}
""" def esc(value): return html.escape(str(value), quote=True) def _page(body, status_cls, status_text, subtitle, topbtn="", head=""): return PAGE.format( icon=ICON_SVG, body=body, status_cls=status_cls, status_text=status_text, subtitle=subtitle, topbtn=topbtn, head=head, ) def _settings_table(values): rows = "".join( f"{esc(k)}{esc(values.get(k, ''))}" for k in DEFAULTS ) return f'{rows}
' def _sel(values, key, option): return " selected" if values.get(key) == option else "" def render_ipv6_checks(iface): parts = [] for label, ok, detail in ipv6_status(iface): cls = "ok" if ok else "warn" mark = "✓" if ok else "!" parts.append( f"
{mark} {esc(label)}" f"
{esc(detail)}
" ) return "".join(parts) def render_wizard(values, message=""): devices = list_serial_devices() iface = values.get("BACKBONE_IF") or detect_backbone_if() selected_dev = values.get("DEVICE") or (devices[0] if devices else "") opts = [] for dev in devices: sel = " selected" if dev == selected_dev else "" opts.append(f'') manual_sel = " selected" if selected_dev and selected_dev not in devices else "" opts.append(f'') device_hint = ( "

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"
! {esc(message)}
" if message else "" ) body = f"""

First-run setup

{msg_html}
{device_hint}

IPv6 readiness

Thread and Matter require working IPv6 on your host and LAN.

{checks_html}

Options

""" return _page( body, status_cls="warn", status_text="Setup required", subtitle="Configure your Thread radio to get started", ) def render_status(values): body = f"""

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):

REST API …

Or manage the Thread network directly in the OTBR dashboard:

OTBR web dashboard Open ↗

Current settings

{_settings_table(values)}

Saving changes restarts the border router automatically to apply them.

""" return _page( body, status_cls="ok", status_text="Running", subtitle="The border router is running", topbtn='Reconfigure', ) def render_waiting(values, reason): device = esc(values.get("DEVICE", "")) if reason == "device": title = "Waiting for the Thread radio" detail = ( f"Settings are saved, but the configured device {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

! {esc(title)}
{detail}

Current settings

{_settings_table(values)}
""" return _page( body, status_cls="warn", status_text="Waiting", subtitle=title, topbtn='Reconfigure', head='', ) class Handler(BaseHTTPRequestHandler): def _send(self, status, body): encoded = body.encode("utf-8") self.send_response(status) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(encoded))) self.end_headers() self.wfile.write(encoded) def do_GET(self): parsed = urllib.parse.urlparse(self.path) query = urllib.parse.parse_qs(parsed.query) if parsed.path == "/healthz": self._send(200, "ok") return if parsed.path == "/ipv6": iface = query.get("iface", [""])[0].strip() if not re.match(r"^[\w.\-]{1,32}$", iface): iface = detect_backbone_if() self._send(200, render_ipv6_checks(iface)) return values = read_settings() if not is_configured() or "reconfigure" in query: self._send(200, render_wizard(values)) elif not device_exists(values.get("DEVICE")): self._send(200, render_waiting(values, "device")) elif config_applied() and otbr_running(): self._send(200, render_status(values)) else: self._send(200, render_waiting(values, "starting")) def _same_origin(self): site = self.headers.get("Sec-Fetch-Site") if site is not None: return site != "cross-site" return True def do_POST(self): if urllib.parse.urlparse(self.path).path != "/save": self._send(404, _page("

Not found

", "warn", "Setup required", "")) return if not self._same_origin(): self._send(403, _page("

Forbidden

" "

Cross-site request blocked.

", "warn", "Setup required", "")) return try: length = int(self.headers.get("Content-Length", "0")) except ValueError: length = 0 if length < 0 or length > 65536: self._send(413, _page("

Request too large

", "warn", "Setup required", "")) return form = urllib.parse.parse_qs(self.rfile.read(length).decode("utf-8", "replace")) def field(name, default=""): return form.get(name, [default])[0].strip() device = field("device") if device == "__manual__": device = field("device_manual") backbone_if = field("backbone_if", DEFAULTS["BACKBONE_IF"]) if backbone_if == "__manual__": backbone_if = field("backbone_if_manual") values = read_settings() candidate = { "DEVICE": device, "BAUDRATE": field("baudrate", DEFAULTS["BAUDRATE"]) or DEFAULTS["BAUDRATE"], "FLOW_CONTROL": field("flow_control", "0"), "BACKBONE_IF": backbone_if or DEFAULTS["BACKBONE_IF"], "FIREWALL": field("firewall", "1"), "NAT64": field("nat64", "1"), "AUTOFLASH_FIRMWARE": field("autoflash", "0"), } error = validate_settings(candidate) if not error and not device_exists(candidate["DEVICE"]): error = (f"Device {candidate['DEVICE']} was not found. Plug the radio " "in and reload, or pick a detected device.") if error: self._send(200, render_wizard(values, error)) return values.update(candidate) write_settings(values) self.send_response(303) self.send_header("Location", "/") self.end_headers() def log_message(self, *args): pass def main(): server = ThreadingHTTPServer(("0.0.0.0", PORT), Handler) print(f"[setup] OTBR setup wizard listening on :{PORT}", flush=True) server.serve_forever() if __name__ == "__main__": main()