From af3f300786a6929ef2a31612f16bd0370efae7b0 Mon Sep 17 00:00:00 2001 From: rhmatzeka <155574253+rhmatzeka@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:23:12 +0700 Subject: [PATCH] desktop: wifi-login opens hotspot login pages, and stays quiet while the internet works another way The watcher (started from hypr-user.lua, Super+Shift+W to check again) finds the captive portal of the WiFi you joined and opens its login page. It used to judge each WiFi on its own, so a campus WiFi that wanted a login kept opening its page and sending notifications even while USB tethering already had internet. Each default route is now checked through its own interface; while one is online, a WiFi that wants a login or does not answer is left alone with no page and no notification, and the login page opens once that connection goes away. --- .github/workflows/ci.yml | 2 + README.md | 2 +- bin/wifi-login | 302 +++++++++++++++++++++++++++++++++ config/caelestia/hypr-user.lua | 8 + linux/debian/desktop.sh | 2 + tests/wifi-login.py | 81 +++++++++ 6 files changed, 396 insertions(+), 1 deletion(-) create mode 100755 bin/wifi-login create mode 100644 tests/wifi-login.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 42f1dbd..5466c9e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,8 @@ jobs: for f in config/nvim/dotfiles.lua config/caelestia/*.lua; do luac5.4 -p "$f" 2>&1 || lua5.4 -e "assert(loadfile('$f'))"; done - name: Menu (scripted answers) run: tests/menu.sh + - name: wifi-login (hotspot login watcher) + run: python3 tests/wifi-login.py - name: Dry run (everything except the desktop, which needs Debian 13) run: ./install.sh --dry-run --yes --only base,shell,tmux,nvim,terminal,browsers - name: Real run of the user-level parts in a throw-away HOME diff --git a/README.md b/README.md index 59b65cf..29b9ed2 100644 --- a/README.md +++ b/README.md @@ -197,7 +197,7 @@ irm https://raw.githubusercontent.com/rhmatzeka/dotfile/main/uninstall.ps1 | iex | `apps` | Microsoft 365 web apps (Word, Excel, PowerPoint, Outlook, OneDrive) in their own windows, plus **Open with Microsoft 365** for local files (converts PDFs to .docx, uploads the file to a private folder of your OneDrive through the Microsoft Graph API, using rclone only for the sign-in, then opens it on the web). Double-clicking Word/Excel/PowerPoint files does this; for PDFs (which stay in your PDF viewer unless you agree to change that during installation) use the Thunar right-click entry **Open with Microsoft 365**. A file that is already open in Word online is not uploaded again (OneDrive locks it); the open copy is shown instead, PDF viewer, VLC, GIMP. Pre-selected only when a graphical session is running | | `web` | Web development: PHP, Composer, MariaDB, Apache, phpMyAdmin. Services are **not** started unless you say yes (Apache listens on port 80); no passwords are set | | `rust` | Rust through the official rustup installer: stable toolchain, clippy, rustfmt, rust-analyzer | -| `desktop` | Hyprland + Caelestia shell with see-through, blurred panels and a few small patches: Bluetooth lists (bar panel and the pair-new-device page) hide devices that only show a MAC address and show the device type instead; the Bluetooth panel says so when no adapter is found instead of showing dead switches; WiFi password fields get an eye button to show what you typed; text on the transparent panels gets a thin halo so it stays readable on bright wallpapers; notifications that contain HTML, such as Instagram's, show clean text; hibernation at critical battery gets enough free memory to succeed (`/sys/power/image_size` = 0) and the laptop powers off if it still fails, instead of staying on with a black screen (AMD GPUs do not come back from a failed hibernation), plus Caelestia's btop, fastfetch, foot, micro, thunar, zed and fish configs (only where you have none). **Debian 13 only, beta.** Builds Qt 6.11 from source (1 to 2 hours) | +| `desktop` | Hyprland + Caelestia shell with see-through, blurred panels and a few small patches: Bluetooth lists (bar panel and the pair-new-device page) hide devices that only show a MAC address and show the device type instead; the Bluetooth panel says so when no adapter is found instead of showing dead switches; WiFi password fields get an eye button to show what you typed; hotspot login pages (campus or cafe WiFi) open by itself when you join, but not while the internet already works through USB tethering, LAN or another WiFi (`wifi-login`, Super+Shift+W checks again); text on the transparent panels gets a thin halo so it stays readable on bright wallpapers; notifications that contain HTML, such as Instagram's, show clean text; hibernation at critical battery gets enough free memory to succeed (`/sys/power/image_size` = 0) and the laptop powers off if it still fails, instead of staying on with a black screen (AMD GPUs do not come back from a failed hibernation), plus Caelestia's btop, fastfetch, foot, micro, thunar, zed and fish configs (only where you have none). **Debian 13 only, beta.** Builds Qt 6.11 from source (1 to 2 hours) | Checked by default: `base`, `shell`, `tmux`, `nvim` and `terminal` (plus `apps` on Linux when a graphical session is running). `web`, `rust`, `browsers` and `desktop` are only installed when you check them. diff --git a/bin/wifi-login b/bin/wifi-login new file mode 100755 index 0000000..386d8a4 --- /dev/null +++ b/bin/wifi-login @@ -0,0 +1,302 @@ +#!/usr/bin/env python3 +"""Find the captive portal (hotspot login page, MikroTik and the like) of the WiFi you joined and open it. + + wifi-login check now and open the login page if there is one (also bound to Super+Shift+W) + wifi-login --watch keep running in the background (started from hypr-user.lua): every time WiFi connects or the + network changes, check and open the login page by itself + +Each check is bound to the WiFi interface (DNS goes to the WiFi's own DHCP DNS server, HTTP through --interface), so it +stays right when another connection (USB tethering, LAN) is the default route or Tailscale has taken over DNS. +While the internet already works through another connection, the watcher leaves a WiFi that wants a login (or does +not answer) alone, without opening pages or showing notifications; it opens the login page once that connection goes. +""" +import html +import random +import re +import select +import socket +import struct +import subprocess +import sys +import time +from urllib.parse import urljoin, urlsplit, urlunsplit + +PROBES = [ + ("http://nmcheck.gnome.org/check_network_status.txt", "NetworkManager is online"), + ("http://detectportal.firefox.com/success.txt", "success"), +] +WATCH_INTERVAL = 60 # seconds between checks in --watch once everything is settled +SO_BINDTODEVICE = 25 + + +def run(*cmd): + return subprocess.run(cmd, capture_output=True, text=True).stdout + + +def notify(title, body, icon="network-wireless", urgency="normal"): + subprocess.Popen(["notify-send", "-a", "WiFi", "-u", urgency, "-i", icon, title, body], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def wifi_devices(): + """[(device, connection name, ip, dns server)] for every WiFi that is connected.""" + out = [] + for line in run("nmcli", "-t", "-f", "DEVICE,TYPE,STATE,CONNECTION", "dev").splitlines(): + parts = re.split(r"(?HHHHHH", tid, 0x0100, 1, 0, 0, 0) + qname + struct.pack(">HH", 1, 1) + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.setsockopt(socket.SOL_SOCKET, SO_BINDTODEVICE, dev.encode()) + s.settimeout(3) + for _ in range(2): + s.sendto(pkt, (server, 53)) + try: + data, _ = s.recvfrom(4096) + except socket.timeout: + continue + if struct.unpack(">H", data[:2])[0] != tid: + continue + ancount = struct.unpack(">H", data[6:8])[0] + i = 12 + len(qname) + 4 + for _ in range(ancount): + if data[i] & 0xC0 == 0xC0: + i += 2 + else: + while data[i]: + i += data[i] + 1 + i += 1 + rtype, _, _, rdlen = struct.unpack(">HHIH", data[i:i + 10]) + i += 10 + if rtype == 1 and rdlen == 4: + return socket.inet_ntoa(data[i:i + 4]) + i += rdlen + return None + except OSError: + return None + finally: + s.close() + return None + + +def system_resolve(name): + try: + return socket.gethostbyname(name) + except OSError: + return None + + +def http_get(url, dev, ip): + """GET without following redirects, through one interface. (status, location, body) or None.""" + host = urlsplit(url).hostname + port = urlsplit(url).port or 80 + cmd = ["curl", "-s", "-m", "8", "--interface", dev, "-A", "Mozilla/5.0 (captive-portal-check)", + "-o", "-", "-w", "\n%{http_code} %{redirect_url}", url] + if ip: + cmd[1:1] = ["--resolve", f"{host}:{port}:{ip}"] + r = subprocess.run(cmd, capture_output=True, text=True, errors="replace") + body, _, tail = r.stdout.rpartition("\n") + code, _, location = tail.partition(" ") + if r.returncode != 0 or code == "000": + return None + return int(code), location.strip(), body + + +def login_url_from(probe_url, status, location, body): + if 300 <= status < 400 and location: + return urljoin(probe_url, location) + patterns = [ + r'http-equiv=["\']?refresh["\']?[^>]*content=["\'][^"\']*url=([^"\'>]+)', + r'(?:window\.)?location(?:\.href)?\s*=\s*["\']([^"\']+)', + r']*action=["\']([^"\']+)', + ] + for pat in patterns: + m = re.search(pat, body, re.I) + if m: + return urljoin(probe_url, html.unescape(m.group(1).strip())) + return probe_url # the portal page is served in place: open any URL and it redirects to the login + + +def check(dev, ip, dns): + """('online'|'portal'|'dead', login_url)""" + if not ip: + return "dead", None + answered = False + for url, expect in PROBES: + host = urlsplit(url).hostname + addr = (dns and resolve_via(host, dns, dev)) or system_resolve(host) + res = http_get(url, dev, addr) + if res is None: + continue + answered = True + status, location, body = res + if status == 200 and expect in body: + return "online", None + return "portal", login_url_from(url, status, location, body) + return ("portal", PROBES[0][0]) if answered else ("dead", None) + + +def default_route_devs(): + """Interfaces that carry a default route, best first (Tailscale, Docker and bridges left out).""" + devs = [] + for m in re.finditer(r"\bdev (\S+)", run("ip", "-4", "route", "show", "default")): + if m.group(1) not in devs and not m.group(1).startswith(("tailscale", "docker", "veth", "br-")): + devs.append(m.group(1)) + return devs + + +def other_uplink(dev): + """Another interface that is the default route (USB tethering, LAN), or None.""" + devs = default_route_devs() + return devs[0] if devs and devs[0] != dev else None + + +def internet_via(): + """The interface (USB tethering, LAN, another WiFi) that already has working internet, or None. + Each default route is checked through its own interface, so a WiFi that still wants a login does not count.""" + for d in default_route_devs(): + ip, dns = dev_addr(d) + if check(d, ip, dns)[0] == "online": + return d + return None + + +def browser_url(url, dev, dns): + """(url, problem). When the system resolver cannot find the portal's host name (DNS through Tailscale or + tethering), an http URL gets the address from the WiFi's DNS instead. An https URL cannot (its certificate is + for the host name), so that is reported as a problem.""" + parts = urlsplit(url) + host = parts.hostname + if not host or re.fullmatch(r"[\d.]+", host) or not dns: + return url, None + wifi_ip = resolve_via(host, dns, dev) + if not wifi_ip or system_resolve(host) == wifi_ip: + return url, None + if parts.scheme == "http": + netloc = wifi_ip + (f":{parts.port}" if parts.port else "") + return urlunsplit(parts._replace(netloc=netloc)), None + return url, f"{host} is only known to this WiFi's DNS ({wifi_ip})" + + +def open_login(conn, url, dev, dns, quiet=False): + """Open the login page. False when that cannot work yet (the internet goes through tethering or LAN).""" + url, problem = browser_url(url, dev, dns) + uplink = other_uplink(dev) + if problem and uplink: + if not quiet: + notify(f"WiFi login: {conn}", + f"The login page cannot open while the internet goes through {uplink} (tethering/LAN).\n" + f"Disconnect {uplink} and the login page opens by itself.", + "network-wireless-acquiring", "critical") + return False + subprocess.Popen(["xdg-open", url], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + notify(f"WiFi login: {conn}", f"Login page opened in the browser.\n{url}", "network-wireless-acquiring") + return True + + +def dead_reason(ip): + if not ip: + return ("Joined the WiFi but got no IP address: the router does not answer DHCP, so no login page can show " + "up yet. Usually the access point is full or out of reach; try moving closer to another one.") + return "Joined and got an IP address, but the router does not answer (weak signal or a full access point)." + + +def once(): + devs = wifi_devices() + if not devs: + notify("WiFi not connected", "Connect to a WiFi network first.", "network-wireless-offline") + return 1 + rc = 1 + for dev, conn, ip, dns in devs: + state, url = check(dev, ip, dns) + if state == "online": + notify(f"{conn}: online", "Already logged in, nothing to do.", "network-wireless") + rc = 0 + elif state == "portal": + open_login(conn, url, dev, dns) + rc = 0 + else: + notify(f"{conn}: no answer", dead_reason(ip), "network-wireless-disconnected", "critical") + return rc + + +def step(prev, state, uplink): + """Watcher decision for one WiFi: (new state, action). action is None, 'open', 'online' or 'dead'. + uplink: interface that already has working internet, or None.""" + if state in ("portal", "dead") and uplink: + return "skip", None # the internet works another way: no login page, no notifications + if state == "portal": + return "portal", (None if prev == "portal" else "open") + if state == "online": + return "online", ("online" if prev in ("portal", "blocked", "dead") else None) + if state == "dead": + if prev == "dead?": + return "dead", "dead" + return ("dead" if prev == "dead" else "dead?"), None # failed once: wait for the next check before telling + return state, None + + +def watch(): + seen = {} # (dev, conn, ip) -> last state + mon = subprocess.Popen(["nmcli", "monitor"], stdout=subprocess.PIPE, text=True, bufsize=1) + next_check = 0.0 + while True: + timeout = max(0.0, next_check - time.monotonic()) + ready, _, _ = select.select([mon.stdout], [], [], timeout) + if ready: + if not mon.stdout.readline(): # nmcli monitor died: start it again + time.sleep(5) + mon = subprocess.Popen(["nmcli", "monitor"], stdout=subprocess.PIPE, text=True, bufsize=1) + # give DHCP and DNS a moment, then check + next_check = min(next_check, time.monotonic() + 3) + continue + current = {} + results = [(dev, conn, ip, dns) + check(dev, ip, dns) for dev, conn, ip, dns in wifi_devices()] + # looked up once per round, and only when some WiFi is not online + uplink = internet_via() if any(r[4] != "online" for r in results) else None + for dev, conn, ip, dns, state, url in results: + key = (dev, conn, ip) + prev = seen.get(key) + state, action = step(prev, state, uplink) + if action == "open" and not open_login(conn, url, dev, dns, quiet=prev == "blocked"): + state = "blocked" # try again on every check, without repeating the notification + elif state == "portal" and prev == "blocked" and not open_login(conn, url, dev, dns, quiet=True): + state = "blocked" + elif action == "online": + notify(f"{conn}: online", "Logged in, the internet works.") + elif action == "dead": + notify(f"{conn}: no answer", dead_reason(ip) + "\nSuper+Shift+W to check again.", + "network-wireless-disconnected") + current[key] = state + seen = current + # until everything is online (or deliberately skipped), check more often to notice a finished login + fast = any(s not in ("online", "skip") for s in current.values()) + next_check = time.monotonic() + (15 if fast else WATCH_INTERVAL) + + +if __name__ == "__main__": + if "--watch" in sys.argv: + watch() + else: + sys.exit(once()) diff --git a/config/caelestia/hypr-user.lua b/config/caelestia/hypr-user.lua index a1f672e..75864cc 100644 --- a/config/caelestia/hypr-user.lua +++ b/config/caelestia/hypr-user.lua @@ -35,6 +35,14 @@ end -- workspace and stops workspace swiping). Bring it back: Super+0, then Super+Alt+1..9 to move it to a workspace. hl.bind("SUPER + A", hl.dsp.window.move({ workspace = "10", follow = false })) +-- Hotspot login pages (campus/cafe WiFi): ~/.local/bin/wifi-login --watch opens the login page by itself when a WiFi +-- wants one, but stays quiet while the internet already works through USB tethering, LAN or another WiFi. +-- Super+Shift+W checks again and opens the login page anyway. +hl.on("hyprland.start", function() + hl.exec_cmd(os.getenv("HOME") .. "/.local/bin/wifi-login --watch") +end) +hl.bind("SUPER + SHIFT + W", hl.dsp.exec_cmd(os.getenv("HOME") .. "/.local/bin/wifi-login")) + -- Transparent Caelestia panels: a softer, slightly darker blur keeps their text readable over bright or busy -- wallpapers (Hyprland default: size 8, passes 2, brightness 1.0, contrast 0.89). Applies to every blurred surface. hl.config({ diff --git a/linux/debian/desktop.sh b/linux/debian/desktop.sh index a6a866a..d0ba083 100755 --- a/linux/debian/desktop.sh +++ b/linux/debian/desktop.sh @@ -255,6 +255,8 @@ install_dots() { # the upstream Hyprland config, cloned here (it is not redistri else mkdir -p "$HOME/.config" && cp -r "$up/$d" "$HOME/.config/$d" && ok "installed ~/.config/$d"; fi done for f in hypr-user.lua hypr-vars.lua shell.json; do backup_and_link "$C/caelestia/$f" "$HOME/.config/caelestia/$f"; done + # hotspot login pages: started by hypr-user.lua, Super+Shift+W checks again + backup_and_link "$DOTFILES_DIR/bin/wifi-login" "$HOME/.local/bin/wifi-login" } install_power() { # the shell hibernates at critical battery: give hibernation room, and power off if it still fails diff --git a/tests/wifi-login.py b/tests/wifi-login.py new file mode 100644 index 0000000..cc56e51 --- /dev/null +++ b/tests/wifi-login.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Unit checks for bin/wifi-login that need no network: the watcher's decisions and the uplink lookup. + + python3 tests/wifi-login.py +""" +import importlib.machinery +import importlib.util +import pathlib +import unittest + +path = pathlib.Path(__file__).resolve().parent.parent / "bin" / "wifi-login" +loader = importlib.machinery.SourceFileLoader("wifi_login", str(path)) +spec = importlib.util.spec_from_loader("wifi_login", loader) +w = importlib.util.module_from_spec(spec) +loader.exec_module(w) + +ROUTES = """default via 10.0.0.1 dev usb0 proto dhcp src 10.0.0.2 metric 100 +default via 192.168.1.1 dev wlan0 proto dhcp src 192.168.1.5 metric 600 +default dev tailscale0 scope link +""" + + +class Step(unittest.TestCase): + def test_portal_opens_once(self): + self.assertEqual(w.step(None, "portal", None), ("portal", "open")) + self.assertEqual(w.step("portal", "portal", None), ("portal", None)) + + def test_quiet_while_internet_works_elsewhere(self): + # the bug: tethering had internet, yet the campus WiFi kept opening its login page and notifying + for prev in (None, "portal", "skip", "dead", "dead?", "blocked"): + self.assertEqual(w.step(prev, "portal", "usb0"), ("skip", None)) + self.assertEqual(w.step(prev, "dead", "usb0"), ("skip", None)) + + def test_login_page_opens_when_tethering_goes(self): + self.assertEqual(w.step("skip", "portal", None), ("portal", "open")) + + def test_dead_needs_two_checks(self): + self.assertEqual(w.step(None, "dead", None), ("dead?", None)) + self.assertEqual(w.step("dead?", "dead", None), ("dead", "dead")) + self.assertEqual(w.step("dead", "dead", None), ("dead", None)) + + def test_online_after_login(self): + self.assertEqual(w.step("portal", "online", None), ("online", "online")) + self.assertEqual(w.step("skip", "online", None), ("online", None)) + + +class Uplink(unittest.TestCase): + def setUp(self): + self.saved = w.run, w.dev_addr, w.check + w.run = lambda *cmd: ROUTES if cmd[:2] == ("ip", "-4") else "" + w.dev_addr = lambda dev: ("10.0.0.2", None) + + def tearDown(self): + w.run, w.dev_addr, w.check = self.saved + + def test_route_devices_skip_tailscale(self): + self.assertEqual(w.default_route_devs(), ["usb0", "wlan0"]) + + def test_tethering_with_internet(self): + w.check = lambda dev, ip, dns: ("online", None) if dev == "usb0" else ("portal", "http://login") + self.assertEqual(w.internet_via(), "usb0") + + def test_only_a_portal(self): + w.check = lambda dev, ip, dns: ("dead", None) if dev == "usb0" else ("portal", "http://login") + self.assertIsNone(w.internet_via()) + + def test_other_uplink(self): + self.assertEqual(w.other_uplink("wlan0"), "usb0") + self.assertIsNone(w.other_uplink("usb0")) + + +class LoginUrl(unittest.TestCase): + def test_redirect_and_meta_refresh(self): + probe = "http://detectportal.firefox.com/success.txt" + self.assertEqual(w.login_url_from(probe, 302, "https://wifi.example/login", ""), "https://wifi.example/login") + body = '' + self.assertEqual(w.login_url_from(probe, 200, "", body), "http://10.5.50.1/login?dst=x") + + +if __name__ == "__main__": + unittest.main(verbosity=2)