1
0

manager.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. """
  2. WiFi management via NetworkManager (nmcli).
  3. Handles scanning, connecting, and managing WiFi connections.
  4. In Docker, nmcli communicates with the host's NetworkManager over the
  5. mounted D-Bus system socket — same mechanism systemctl uses for shutdown.
  6. """
  7. import subprocess
  8. import os
  9. import logging
  10. import asyncio
  11. logger = logging.getLogger(__name__)
  12. HOST_HOSTNAME_FILE = "/etc/host-hostname"
  13. HOTSPOT_CON_NAME = "DuneWeaver-Hotspot"
  14. def is_docker() -> bool:
  15. """Check if running inside a Docker container."""
  16. return os.path.exists("/.dockerenv") or os.getenv("DOCKER_CONTAINER") == "1"
  17. def run_nmcli(*args: str, timeout: int = 30) -> str:
  18. """Run nmcli and return stdout.
  19. In both Docker and venv modes, nmcli runs directly. In Docker, it
  20. communicates with the host's NetworkManager via the mounted D-Bus
  21. system bus socket (/var/run/dbus/system_bus_socket).
  22. """
  23. cmd = ["nmcli"] + list(args)
  24. logger.debug(f"Running nmcli: {' '.join(cmd)}")
  25. result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
  26. if result.returncode != 0:
  27. logger.warning(f"nmcli failed (rc={result.returncode}): {' '.join(cmd)}")
  28. if result.stderr:
  29. logger.warning(f" stderr: {result.stderr.strip()}")
  30. return result.stdout
  31. def run_nmcli_check(*args: str, timeout: int = 30) -> subprocess.CompletedProcess:
  32. """Run nmcli and return the full CompletedProcess (for checking returncode)."""
  33. cmd = ["nmcli"] + list(args)
  34. logger.debug(f"Running nmcli: {' '.join(cmd)}")
  35. result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
  36. if result.returncode != 0:
  37. logger.warning(f"nmcli failed (rc={result.returncode}): {' '.join(cmd)}")
  38. if result.stderr:
  39. logger.warning(f" stderr: {result.stderr.strip()}")
  40. return result
  41. def get_wifi_mode() -> str:
  42. """Detect WiFi mode by querying NetworkManager active connections.
  43. Uses 'nmcli con show --active' instead of 'nmcli dev show wlan0'
  44. because the latter can behave differently in AP (hotspot) mode
  45. across NM versions.
  46. """
  47. try:
  48. output = run_nmcli("-t", "-f", "NAME,TYPE,DEVICE", "con", "show", "--active")
  49. logger.info(f"Active connections: {output.strip()}")
  50. for line in output.strip().splitlines():
  51. parts = line.split(":")
  52. if len(parts) >= 3 and parts[2] == "wlan0":
  53. con_name = parts[0]
  54. if con_name == HOTSPOT_CON_NAME:
  55. return "hotspot"
  56. return "client"
  57. except (subprocess.TimeoutExpired, Exception) as e:
  58. logger.warning(f"Error detecting WiFi mode: {e}")
  59. return "unknown"
  60. def get_current_ssid() -> str:
  61. """Get the SSID of the currently connected WiFi network."""
  62. try:
  63. # Use active connections to find the wifi connection on wlan0
  64. output = run_nmcli("-t", "-f", "NAME,TYPE,DEVICE", "con", "show", "--active")
  65. for line in output.strip().splitlines():
  66. parts = line.split(":")
  67. if len(parts) >= 3 and parts[2] == "wlan0":
  68. con_name = parts[0]
  69. if con_name and con_name != HOTSPOT_CON_NAME:
  70. return con_name
  71. except (subprocess.TimeoutExpired, Exception) as e:
  72. logger.debug(f"Error getting SSID: {e}")
  73. return ""
  74. def get_current_ip() -> str:
  75. """Get the current IP address of the wlan0 interface."""
  76. try:
  77. output = run_nmcli("-t", "-f", "IP4.ADDRESS", "dev", "show", "wlan0")
  78. logger.debug(f"IP output: {output.strip()}")
  79. for line in output.strip().splitlines():
  80. if "IP4.ADDRESS" in line:
  81. addr = line.split(":", 1)[1] if ":" in line else ""
  82. if addr:
  83. return addr.split("/")[0]
  84. except (subprocess.TimeoutExpired, Exception) as e:
  85. logger.debug(f"Error getting IP: {e}")
  86. return ""
  87. def get_hostname() -> str:
  88. """Get the host system hostname.
  89. In Docker, reads from the mounted /etc/host-hostname file to get the
  90. real host identity instead of the container ID.
  91. """
  92. try:
  93. if is_docker() and os.path.exists(HOST_HOSTNAME_FILE):
  94. with open(HOST_HOSTNAME_FILE, "r") as f:
  95. name = f.read().strip()
  96. if name:
  97. return name
  98. # Fallback: use nmcli to query NM's hostname
  99. output = run_nmcli("general", "hostname")
  100. name = output.strip()
  101. if name:
  102. return name
  103. except Exception:
  104. pass
  105. return "duneweaver"
  106. def get_wifi_status() -> dict:
  107. """Get comprehensive WiFi status."""
  108. mode = get_wifi_mode()
  109. ssid = get_current_ssid()
  110. ip = get_current_ip()
  111. hostname = get_hostname()
  112. return {
  113. "mode": mode,
  114. "ssid": ssid,
  115. "ip": ip,
  116. "hostname": hostname,
  117. }
  118. def scan_networks() -> list[dict]:
  119. """Scan for available WiFi networks."""
  120. try:
  121. # Trigger rescan
  122. run_nmcli("dev", "wifi", "rescan", "ifname", "wlan0")
  123. except Exception:
  124. pass
  125. # Brief wait for scan results
  126. import time
  127. time.sleep(2)
  128. try:
  129. output = run_nmcli("-t", "-f", "SSID,SIGNAL,SECURITY,ACTIVE", "dev", "wifi", "list", "ifname", "wlan0")
  130. except subprocess.TimeoutExpired:
  131. logger.error("WiFi scan timed out")
  132. return []
  133. # Get saved connections for cross-reference
  134. saved = get_saved_connections()
  135. saved_ssids = {c["ssid"] for c in saved}
  136. networks = []
  137. seen_ssids = set()
  138. for line in output.strip().splitlines():
  139. if not line.strip():
  140. continue
  141. # nmcli -t uses : as delimiter, but SSID can contain colons
  142. # Format: SSID:SIGNAL:SECURITY:ACTIVE
  143. # Parse from the right since SSID is the only field that can contain ':'
  144. parts = line.rsplit(":", 3)
  145. if len(parts) < 4:
  146. continue
  147. ssid = parts[0].strip()
  148. if not ssid or ssid in seen_ssids:
  149. continue
  150. seen_ssids.add(ssid)
  151. try:
  152. signal = int(parts[1])
  153. except (ValueError, IndexError):
  154. signal = 0
  155. security = parts[2] if len(parts) > 2 else ""
  156. active = parts[3].strip().lower() == "yes" if len(parts) > 3 else False
  157. networks.append({
  158. "ssid": ssid,
  159. "signal": signal,
  160. "security": security if security and security != "--" else "Open",
  161. "saved": ssid in saved_ssids,
  162. "active": active,
  163. })
  164. # Sort by signal strength (strongest first)
  165. networks.sort(key=lambda n: n["signal"], reverse=True)
  166. return networks
  167. def get_saved_connections() -> list[dict]:
  168. """Get list of saved WiFi connections."""
  169. try:
  170. output = run_nmcli("-t", "-f", "NAME,TYPE", "con", "show")
  171. except subprocess.TimeoutExpired:
  172. return []
  173. connections = []
  174. for line in output.strip().splitlines():
  175. if "wireless" not in line:
  176. continue
  177. name = line.split(":")[0]
  178. if name == HOTSPOT_CON_NAME:
  179. continue
  180. # Get the SSID for this connection
  181. try:
  182. detail = run_nmcli("-t", "-f", "802-11-wireless.ssid", "con", "show", name)
  183. ssid = ""
  184. for detail_line in detail.strip().splitlines():
  185. if "802-11-wireless.ssid" in detail_line:
  186. ssid = detail_line.split(":", 1)[1] if ":" in detail_line else name
  187. break
  188. if not ssid:
  189. ssid = name
  190. except Exception:
  191. ssid = name
  192. connections.append({
  193. "name": name,
  194. "ssid": ssid,
  195. })
  196. return connections
  197. async def connect_to_network(ssid: str, password: str) -> dict:
  198. """Connect to a WiFi network and schedule reboot.
  199. Uses explicit connection profile creation (nmcli con add) instead of
  200. 'nmcli dev wifi connect' because the latter fails on Pi Trixie with
  201. 'key-mgmt: property is missing' for WPA networks.
  202. """
  203. try:
  204. # Delete any stale connection profile for this SSID (ignore if not found)
  205. subprocess.run(
  206. ["nmcli", "con", "delete", ssid],
  207. capture_output=True, text=True, timeout=10,
  208. )
  209. # Create connection profile with explicit security settings
  210. if password:
  211. result = run_nmcli_check(
  212. "con", "add",
  213. "type", "wifi",
  214. "ifname", "wlan0",
  215. "con-name", ssid,
  216. "ssid", ssid,
  217. "wifi-sec.key-mgmt", "wpa-psk",
  218. "wifi-sec.psk", password,
  219. timeout=15,
  220. )
  221. else:
  222. result = run_nmcli_check(
  223. "con", "add",
  224. "type", "wifi",
  225. "ifname", "wlan0",
  226. "con-name", ssid,
  227. "ssid", ssid,
  228. timeout=15,
  229. )
  230. if result.returncode != 0:
  231. error_msg = result.stderr.strip() or "Failed to create connection"
  232. logger.error(f"WiFi connection add failed: {error_msg}")
  233. return {"success": False, "message": error_msg}
  234. # Activate the connection
  235. result = run_nmcli_check("con", "up", ssid, timeout=30)
  236. if result.returncode != 0:
  237. error_msg = result.stderr.strip() or "Failed to connect"
  238. logger.error(f"WiFi connect failed: {error_msg}")
  239. # Clean up the failed connection profile
  240. run_nmcli_check("con", "delete", ssid, timeout=10)
  241. return {"success": False, "message": error_msg}
  242. logger.info(f"WiFi connection to '{ssid}' successful, scheduling reboot...")
  243. # Schedule reboot so the response can be sent first
  244. asyncio.get_event_loop().call_later(3, _schedule_reboot)
  245. return {
  246. "success": True,
  247. "message": f"Connected to '{ssid}'. Rebooting in 3 seconds...",
  248. }
  249. except subprocess.TimeoutExpired:
  250. return {"success": False, "message": "Connection timed out"}
  251. except Exception as e:
  252. logger.error(f"WiFi connect error: {e}")
  253. return {"success": False, "message": str(e)}
  254. def _schedule_reboot():
  255. """Trigger a system reboot via systemctl (communicates over D-Bus)."""
  256. try:
  257. logger.info("Rebooting system for WiFi mode change...")
  258. subprocess.run(["systemctl", "reboot"], check=True)
  259. except FileNotFoundError:
  260. logger.error("systemctl not found — ensure systemd is installed in container")
  261. except Exception as e:
  262. logger.error(f"Reboot failed: {e}")
  263. def forget_network(ssid: str) -> dict:
  264. """Delete a saved WiFi connection by SSID.
  265. If the forgotten network was the active connection, triggers the
  266. autohotspot script to re-evaluate and fall back to hotspot mode.
  267. """
  268. # Check if this is the currently active connection
  269. current_ssid = get_current_ssid()
  270. was_active = current_ssid == ssid or current_ssid == ssid.replace(" ", "")
  271. saved = get_saved_connections()
  272. con_name = None
  273. for con in saved:
  274. if con["ssid"] == ssid:
  275. con_name = con["name"]
  276. break
  277. if not con_name:
  278. return {"success": False, "message": f"No saved connection found for '{ssid}'"}
  279. try:
  280. result = run_nmcli_check("con", "delete", con_name, timeout=15)
  281. if result.returncode == 0:
  282. logger.info(f"Forgot WiFi network '{ssid}' (connection: {con_name})")
  283. # If we just forgot the active connection, re-run autohotspot
  284. # so it can fall back to hotspot mode
  285. if was_active:
  286. _trigger_autohotspot()
  287. return {"success": True, "message": f"Forgot '{ssid}'"}
  288. else:
  289. error_msg = result.stderr.strip() or "Failed to delete connection"
  290. return {"success": False, "message": error_msg}
  291. except Exception as e:
  292. return {"success": False, "message": str(e)}
  293. def _trigger_autohotspot():
  294. """Trigger an immediate autohotspot check.
  295. Called when the active network is forgotten so the user doesn't have
  296. to wait for the next 60s timer tick. Falls back to direct nmcli
  297. commands in Docker where the host script isn't available.
  298. """
  299. autohotspot_path = "/usr/local/bin/autohotspot"
  300. try:
  301. if os.path.exists(autohotspot_path):
  302. logger.info("Triggering autohotspot --check after forgetting active network...")
  303. subprocess.Popen(
  304. [autohotspot_path, "--check"],
  305. stdout=subprocess.DEVNULL,
  306. stderr=subprocess.DEVNULL,
  307. )
  308. else:
  309. # Docker fallback: directly activate hotspot via D-Bus
  310. logger.info("Autohotspot script not found, activating hotspot directly...")
  311. run_nmcli("dev", "disconnect", "wlan0")
  312. run_nmcli("con", "up", HOTSPOT_CON_NAME)
  313. except Exception as e:
  314. logger.error(f"Failed to trigger autohotspot: {e}")