mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-28 19:06:19 -05:00
Hotspot captive portal: welcome page with the WROLPi's address
Devices that join the hotspot probe a fixed plain-HTTP URL to check for Internet access. NetworkManager's shared-mode dnsmasq now resolves those probe hostnames (and `wrolpi`) to the hotspot address via an include the Controller writes when the hotspot starts, the probes land on the Controller (port 80), and are redirected to /portal: "This is your WROLPi, its address is 10.42.0.1, open WROLPi / open the Controller". Only the probe hostnames are hijacked so the hotspot keeps forwarding everything else when the WROLPi has an uplink. The include is corrected and the connection re-activated once if NetworkManager picked a non-default subnet. Writing the include is best-effort; the hotspot starts regardless. `hotspot.captive_portal` (controller.yaml, default true) toggles the probe redirects and the include; like the other hotspot settings it applies on the next hotspot start, so saving while the hotspot is up reports restart_required and both Controller UIs say so. The status endpoint gains the hotspot address and portal URL, shown in both UIs. repair.sh only creates the include directory so a disabled setting survives upgrades. Native only: Docker has no hotspot. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
91f92683ba
commit
6bea09600e
17 changed files with 772 additions and 15 deletions
|
|
@ -14,6 +14,7 @@ from pathlib import Path
|
|||
import yaml
|
||||
|
||||
from controller.lib import config as config_lib
|
||||
from controller.lib import captive_portal as captive_portal_lib
|
||||
from controller.lib.config import is_docker_mode, get_config_value, get_media_directory
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
|
@ -162,10 +163,13 @@ def get_device_hotspot_protocols(device: str) -> list[str]:
|
|||
|
||||
|
||||
def update_hotspot_settings(device: str = None, ssid: str = None, password: str = None,
|
||||
protocol: str = None) -> dict:
|
||||
protocol: str = None, captive_portal: bool = None) -> dict:
|
||||
"""
|
||||
Update hotspot settings in controller.yaml. Only provided values are changed.
|
||||
|
||||
Settings are applied when the hotspot starts, so a change saved while the hotspot is up
|
||||
reports `restart_required`.
|
||||
|
||||
Returns:
|
||||
dict with success status and the current settings
|
||||
"""
|
||||
|
|
@ -195,6 +199,9 @@ def update_hotspot_settings(device: str = None, ssid: str = None, password: str
|
|||
if protocol:
|
||||
config_lib.update_config('hotspot.protocol', protocol)
|
||||
changed = True
|
||||
if captive_portal is not None:
|
||||
config_lib.update_config('hotspot.captive_portal', bool(captive_portal))
|
||||
changed = True
|
||||
|
||||
if changed:
|
||||
try:
|
||||
|
|
@ -202,14 +209,18 @@ def update_hotspot_settings(device: str = None, ssid: str = None, password: str
|
|||
except RuntimeError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
logger.info("Hotspot settings updated (device=%s, ssid=%s, protocol=%s)",
|
||||
get_hotspot_device(), get_hotspot_ssid(), get_hotspot_protocol())
|
||||
logger.info("Hotspot settings updated (device=%s, ssid=%s, protocol=%s, captive_portal=%s)",
|
||||
get_hotspot_device(), get_hotspot_ssid(), get_hotspot_protocol(),
|
||||
captive_portal_lib.is_captive_portal_enabled())
|
||||
return {
|
||||
"success": True,
|
||||
"device": get_hotspot_device(),
|
||||
"ssid": get_hotspot_ssid(),
|
||||
"password": get_hotspot_password(),
|
||||
"protocol": get_hotspot_protocol(),
|
||||
"captive_portal": captive_portal_lib.is_captive_portal_enabled(),
|
||||
# dnsmasq only reads its include when the Hotspot connection activates.
|
||||
"restart_required": changed and get_hotspot_status() == HotspotStatus.connected,
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -372,6 +383,9 @@ def get_hotspot_status_dict() -> dict:
|
|||
reason: Optional[str] - Reason if unavailable
|
||||
ssid: Optional[str] - Hotspot SSID when enabled
|
||||
device: Optional[str] - WiFi device name
|
||||
ip: Optional[str] - Hotspot IPv4 address when enabled
|
||||
captive_portal: bool - Whether the captive portal is enabled
|
||||
portal_url: Optional[str] - Landing page URL when enabled
|
||||
"""
|
||||
device = get_hotspot_device()
|
||||
status = get_hotspot_status()
|
||||
|
|
@ -388,12 +402,17 @@ def get_hotspot_status_dict() -> dict:
|
|||
elif status == HotspotStatus.in_use:
|
||||
reason = "WiFi device is connected to a network"
|
||||
|
||||
ip = captive_portal_lib.get_hotspot_ip(device) if enabled else None
|
||||
portal_enabled = captive_portal_lib.is_captive_portal_enabled()
|
||||
return {
|
||||
"enabled": enabled,
|
||||
"available": available,
|
||||
"reason": reason,
|
||||
"ssid": get_hotspot_ssid() if enabled else None,
|
||||
"device": device,
|
||||
"ip": ip,
|
||||
"captive_portal": portal_enabled,
|
||||
"portal_url": f"http://{ip}{captive_portal_lib.PORTAL_PATH}" if ip and portal_enabled else None,
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -447,6 +466,12 @@ def start_hotspot() -> dict:
|
|||
logger.warning("WiFi device %s did not become ready after turning radio on", device)
|
||||
return {"success": False, "error": f"WiFi device {device} not ready after turning radio on"}
|
||||
|
||||
# dnsmasq reads the captive portal include only when the connection activates, so it
|
||||
# must be in place first. The address is not known until then; NetworkManager almost
|
||||
# always picks the default, and the file is corrected below if it did not.
|
||||
captive_portal_lib.apply_dnsmasq_config(captive_portal_lib.dnsmasq_config_ip()
|
||||
or captive_portal_lib.DEFAULT_HOTSPOT_IP)
|
||||
|
||||
# Create hotspot using NetworkManager
|
||||
logger.info("Starting hotspot on %s with SSID %s", device, ssid)
|
||||
result = subprocess.run(
|
||||
|
|
@ -515,6 +540,8 @@ def start_hotspot() -> dict:
|
|||
# WPA2 is what nmcli created the hotspot with anyway; not fatal.
|
||||
logger.warning("Failed to explicitly set WPA2 on hotspot: %s", error)
|
||||
|
||||
_fix_captive_portal_ip(device)
|
||||
|
||||
logger.info("Hotspot started successfully on %s (%s)", device, protocol)
|
||||
return {"success": True, "ssid": ssid, "device": device}
|
||||
|
||||
|
|
@ -529,6 +556,27 @@ def start_hotspot() -> dict:
|
|||
return {"success": False, "error": str(e)}
|
||||
|
||||
|
||||
def _fix_captive_portal_ip(device: str):
|
||||
"""
|
||||
Re-point the captive portal include at the address NetworkManager actually assigned.
|
||||
|
||||
Rare: NetworkManager uses 10.42.1.1 (and so on) only when another shared connection
|
||||
already holds 10.42.0.1. Re-activating the connection makes dnsmasq re-read the file.
|
||||
"""
|
||||
if not captive_portal_lib.is_captive_portal_enabled():
|
||||
return
|
||||
ip = captive_portal_lib.get_hotspot_ip(device)
|
||||
if not ip or ip == captive_portal_lib.dnsmasq_config_ip():
|
||||
return
|
||||
logger.info("Hotspot address is %s, rewriting captive portal config and re-activating", ip)
|
||||
if not captive_portal_lib.apply_dnsmasq_config(ip):
|
||||
return
|
||||
try:
|
||||
subprocess.run(["nmcli", "connection", "up", "Hotspot"], capture_output=True, text=True, timeout=30)
|
||||
except (subprocess.SubprocessError, FileNotFoundError) as e:
|
||||
logger.warning("Could not re-activate hotspot for captive portal: %s", e)
|
||||
|
||||
|
||||
def stop_hotspot() -> dict:
|
||||
"""
|
||||
Stop the WiFi hotspot by turning the WiFi radio off.
|
||||
|
|
|
|||
135
controller/lib/captive_portal.py
Normal file
135
controller/lib/captive_portal.py
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
"""
|
||||
Hotspot captive portal.
|
||||
|
||||
Phones confirm Internet access after joining WiFi by fetching a fixed plain-HTTP URL and
|
||||
expecting a fixed reply. Any other reply means "there is a sign-in page here", and the phone
|
||||
shows it. The hotspot's DNS (NetworkManager's dnsmasq) answers those probe hostnames with the
|
||||
hotspot's own address, the probes land on the Controller (port 80), and the Controller redirects
|
||||
them to a landing page that shows the WROLPi's address.
|
||||
|
||||
Only the probe hostnames are hijacked. NetworkManager's shared mode forwards other names (and
|
||||
traffic) to whatever uplink the WROLPi has, and a wildcard would break that.
|
||||
|
||||
Native RPi/Debian only: Docker has no hotspot, no host NetworkManager, and no port 80.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from controller.lib.config import get_config_value, is_docker_mode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Hostnames the major operating systems probe. Resolved to the hotspot IP by dnsmasq.
|
||||
PROBE_HOSTS = (
|
||||
'captive.apple.com', # iOS / macOS
|
||||
'connectivitycheck.gstatic.com', # Android
|
||||
'connectivitycheck.android.com', # Android (older)
|
||||
'www.msftconnecttest.com', # Windows 10+
|
||||
'www.msftncsi.com', # Windows 7/8
|
||||
'detectportal.firefox.com', # Firefox
|
||||
'connectivity-check.ubuntu.com', # Ubuntu / NetworkManager (probes `/`, served by the dashboard)
|
||||
'nmcheck.gnome.org', # GNOME
|
||||
)
|
||||
|
||||
# Paths those probes request. The Controller redirects each of these to the portal.
|
||||
# `/` is not listed: the dashboard already answers it with HTML, which a probe treats as a portal.
|
||||
PROBE_PATHS = (
|
||||
'/hotspot-detect.html', # Apple
|
||||
'/generate_204', # Android
|
||||
'/connecttest.txt', # Windows 10+
|
||||
'/ncsi.txt', # Windows 7/8
|
||||
'/success.txt', # Firefox
|
||||
'/canonical.html', # Firefox
|
||||
'/check_network_status.txt', # GNOME
|
||||
)
|
||||
|
||||
# `http://wrolpi/` also reaches the WROLPi from a hotspot client.
|
||||
FRIENDLY_NAME = 'wrolpi'
|
||||
|
||||
# NetworkManager starts its shared-mode dnsmasq with `--conf-dir=` pointing here and reads it
|
||||
# only when the Hotspot connection is activated.
|
||||
DNSMASQ_SHARED_DIR = Path('/etc/NetworkManager/dnsmasq-shared.d')
|
||||
INCLUDE_FILE = DNSMASQ_SHARED_DIR / '50-wrolpi-captive-portal.conf'
|
||||
|
||||
# NetworkManager's default shared-mode subnet. The real address is read once the hotspot is up.
|
||||
DEFAULT_HOTSPOT_IP = '10.42.0.1'
|
||||
|
||||
PORTAL_PATH = '/portal'
|
||||
|
||||
|
||||
def is_captive_portal_enabled() -> bool:
|
||||
"""The maintainer's `hotspot.captive_portal` setting in controller.yaml. Never true in Docker."""
|
||||
if is_docker_mode():
|
||||
return False
|
||||
return bool(get_config_value('hotspot.captive_portal', True))
|
||||
|
||||
|
||||
def get_hotspot_ip(device: str) -> Optional[str]:
|
||||
"""
|
||||
The IPv4 address the hotspot device currently has, or None when it has none (hotspot down),
|
||||
the device is missing, or `ip` is unavailable (Docker, macOS).
|
||||
"""
|
||||
if is_docker_mode() or not device:
|
||||
return None
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['ip', '-4', '-j', 'addr', 'show', 'dev', device],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
for interface in json.loads(result.stdout or '[]'):
|
||||
for addr in interface.get('addr_info') or []:
|
||||
if addr.get('family') == 'inet' and addr.get('local'):
|
||||
return addr['local']
|
||||
except (subprocess.SubprocessError, FileNotFoundError, ValueError) as e:
|
||||
logger.debug('Could not read hotspot IP of %s: %s', device, e)
|
||||
return None
|
||||
|
||||
|
||||
def render_dnsmasq_config(ip: str) -> str:
|
||||
"""The dnsmasq include which points the probe hostnames and the friendly name at the hotspot."""
|
||||
lines = [
|
||||
'# Managed by the WROLPi Controller; changes are overwritten when the hotspot starts.',
|
||||
'# Captive portal: captive-portal probe hostnames resolve to this WROLPi.',
|
||||
'# Only these names are hijacked so the hotspot still forwards everything else.',
|
||||
]
|
||||
lines.extend(f'address=/{host}/{ip}' for host in PROBE_HOSTS)
|
||||
lines.append(f'address=/{FRIENDLY_NAME}/{ip}')
|
||||
return '\n'.join(lines) + '\n'
|
||||
|
||||
|
||||
def apply_dnsmasq_config(ip: str = DEFAULT_HOTSPOT_IP) -> bool:
|
||||
"""
|
||||
Write the dnsmasq include when the captive portal is enabled, remove it when disabled.
|
||||
|
||||
Best-effort: a failure is logged and swallowed, because a working hotspot matters more than
|
||||
the portal. Returns True when the include file now matches the setting.
|
||||
"""
|
||||
try:
|
||||
if is_captive_portal_enabled():
|
||||
INCLUDE_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
INCLUDE_FILE.write_text(render_dnsmasq_config(ip))
|
||||
INCLUDE_FILE.chmod(0o644)
|
||||
logger.info('Captive portal dnsmasq config written for %s', ip)
|
||||
elif INCLUDE_FILE.exists():
|
||||
INCLUDE_FILE.unlink()
|
||||
logger.info('Captive portal disabled; dnsmasq config removed')
|
||||
return True
|
||||
except OSError as e:
|
||||
logger.warning('Could not update captive portal dnsmasq config %s: %s', INCLUDE_FILE, e)
|
||||
return False
|
||||
|
||||
|
||||
def dnsmasq_config_ip() -> Optional[str]:
|
||||
"""The IP the current include file points at, or None when there is no include file."""
|
||||
try:
|
||||
for line in INCLUDE_FILE.read_text().splitlines():
|
||||
if line.startswith('address=/'):
|
||||
return line.rsplit('/', 1)[-1].strip() or None
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
Loading…
Add table
Add a link
Reference in a new issue