diff --git a/Dockerfile b/Dockerfile index 8dfbcec..69591c3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,7 +7,7 @@ ENV DEBIAN_FRONTEND=noninteractive \ RUN apt-get update \ && apt full-upgrade -y && apt-get install -y --no-install-recommends \ ca-certificates apache2 nano python3 python3-cryptography tzdata \ - network-manager wpasupplicant dbus \ + network-manager wpasupplicant hostapd dbus \ iw iproute2 rfkill wireless-regdb \ dnsmasq-base iptables nftables procps kmod tcpdump \ wireguard-tools openvpn ebtables curl conntrack \ diff --git a/ap.py b/ap.py index c522a2f..e006dbf 100644 --- a/ap.py +++ b/ap.py @@ -1426,6 +1426,7 @@ def save_connection(name): def apply_radio_defaults(): """Applique bande/canal/CCMP à la connexion AP déjà créée (sans avoir à ré-enregistrer les réglages).""" + if is_bridge_mode(): return name = connection_name() if not name: return band = command('nmcli','-t','-g','802-11-wireless.band','connection','show',name) @@ -2937,6 +2938,189 @@ def teardown_ap_nat(): except Exception: pass +HOSTAPD_CONF_FILE = '/run/ap-hostapd.conf' +HOSTAPD_PID_FILE = '/run/ap-hostapd.pid' +HOSTAPD_LOG_FILE = '/run/ap-hostapd.log' + +def is_hostapd_running(): + """Retourne True si l'instance hostapd (mode pont) est en cours d'exécution.""" + try: + if os.path.exists(HOSTAPD_PID_FILE): + pid = int(open(HOSTAPD_PID_FILE).read().strip()) + os.kill(pid, 0) + return True + except Exception: + pass + try: + r = subprocess.run(['pgrep', '-f', HOSTAPD_CONF_FILE], capture_output=True, text=True) + return r.returncode == 0 and bool(r.stdout.strip()) + except Exception: + return False + +def stop_hostapd(iface=None): + """Arrête proprement hostapd et détache l'interface Wi-Fi du pont sans jamais toucher au pont hôte.""" + iface = iface or INTERFACE + try: + if os.path.exists(HOSTAPD_PID_FILE): + try: + pid = int(open(HOSTAPD_PID_FILE).read().strip()) + os.kill(pid, signal.SIGTERM) + for _ in range(15): + try: + os.kill(pid, 0) + time.sleep(0.1) + except OSError: + break + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + except Exception: + pass + try: os.remove(HOSTAPD_PID_FILE) + except OSError: pass + subprocess.run(['pkill', '-f', HOSTAPD_CONF_FILE], capture_output=True) + except Exception: + pass + if iface: + subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True) + +def ensure_nm_manages_wifi(iface=None): + """Rend le contrôle de l'interface Wi-Fi à NetworkManager (pour le mode AP/NAT).""" + iface = iface or INTERFACE + if not iface: + return + stop_hostapd(iface) + subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'yes'], capture_output=True) + for _ in range(25): + st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface) + if st and not st.startswith('10'): # 10 = unmanaged + break + time.sleep(0.2) + +def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=None): + """Démarre le point d'accès Wi-Fi en mode pont directement via hostapd (bridge=br0) sans que NetworkManager ne touche au pont hôte.""" + iface = iface or INTERFACE + bridge_name = bridge_name or 'br0' + hostapd_bin = find_bin('hostapd') + if not hostapd_bin: + raise RuntimeError("Le binaire 'hostapd' est introuvable dans le conteneur. Veuillez reconstruire l'image Docker.") + if not os.path.exists(f'/sys/class/net/{bridge_name}'): + raise RuntimeError(f"Le pont réseau '{bridge_name}' n'existe pas sur le système.") + + # 1. Arrêter toute ancienne instance hostapd et retirer le contrôle NM de la carte Wi-Fi uniquement + stop_hostapd(iface) + subprocess.run(['nmcli', 'device', 'disconnect', iface], capture_output=True) + subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'no'], capture_output=True) + time.sleep(0.4) + subprocess.run(['rfkill', 'unblock', 'wifi'], capture_output=True) + subprocess.run(['ip', 'addr', 'flush', 'dev', iface], capture_output=True) + subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True) + subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True) + + country = os.environ.get('AP_COUNTRY', 'FR').strip().upper() or 'FR' + band = (AP_BAND or 'bg').strip().lower() + hw_mode = 'a' if band == 'a' else 'g' + channel = str(AP_CHANNEL or '6').strip() + sec_norm = (sec or 'wpa2').lower() + + def _build_conf(enable_ht=True): + lines = [ + f"interface={iface}", + f"bridge={bridge_name}", + "driver=nl80211", + f"ssid={ssid}", + "utf8_ssid=1", + f"country_code={country}", + "ieee80211d=1", + f"hw_mode={hw_mode}", + f"channel={channel}", + "auth_algs=1", + "ignore_broadcast_ssid=0", + "wmm_enabled=1", + "ctrl_interface=/run/hostapd", + "ctrl_interface_group=0", + ] + if enable_ht: + lines.append("ieee80211n=1") + if hw_mode == 'a': + lines.append("ieee80211ac=1") + if sec_norm == 'wpa1': + lines += [ + "wpa=1", + "wpa_key_mgmt=WPA-PSK", + "wpa_pairwise=TKIP CCMP", + f"wpa_passphrase={password}", + ] + elif sec_norm == 'wpa3': + lines += [ + "wpa=2", + "wpa_key_mgmt=SAE", + "rsn_pairwise=CCMP", + f"sae_password={password}", + f"wpa_passphrase={password}", + "ieee80211w=2", + ] + else: + lines += [ + "wpa=2", + "wpa_key_mgmt=WPA-PSK", + "rsn_pairwise=CCMP", + f"wpa_passphrase={password}", + ] + return '\n'.join(lines) + '\n' + + os.makedirs('/run/hostapd', exist_ok=True) + + def _try_launch(enable_ht=True): + with open(HOSTAPD_CONF_FILE, 'w', encoding='utf-8') as f: + f.write(_build_conf(enable_ht=enable_ht)) + os.chmod(HOSTAPD_CONF_FILE, 0o600) + try: os.remove(HOSTAPD_LOG_FILE) + except OSError: pass + r = subprocess.run( + [hostapd_bin, '-B', '-P', HOSTAPD_PID_FILE, '-f', HOSTAPD_LOG_FILE, HOSTAPD_CONF_FILE], + capture_output=True, text=True, timeout=15 + ) + if r.returncode != 0: + err = (r.stderr or r.stdout or '').strip() + if os.path.exists(HOSTAPD_LOG_FILE): + try: + log_tail = open(HOSTAPD_LOG_FILE, encoding='utf-8', errors='replace').read().strip() + if log_tail: + last_line = log_tail.splitlines()[-1] + err = last_line if not err else f"{err} | {last_line}" + except OSError: + pass + return False, err or 'hostapd a refusé de démarrer' + for _ in range(25): + time.sleep(0.2) + if is_hostapd_running() and os.path.exists(f'/sys/class/net/{iface}/master'): + return True, '' + if not is_hostapd_running(): + break + if is_hostapd_running(): + if not os.path.exists(f'/sys/class/net/{iface}/master'): + subprocess.run(['ip', 'link', 'set', 'dev', iface, 'master', bridge_name], capture_output=True) + return True, '' + err = '' + if os.path.exists(HOSTAPD_LOG_FILE): + try: err = open(HOSTAPD_LOG_FILE, encoding='utf-8', errors='replace').read().strip() + except OSError: pass + return False, err or 'hostapd s’est arrêté immédiatement' + + ok, err = _try_launch(enable_ht=True) + if not ok: + print(f"[ap-bridge] hostapd (802.11n) a échoué ({err}), nouvelle tentative sans 802.11n...", flush=True) + stop_hostapd(iface) + ok, err2 = _try_launch(enable_ht=False) + if not ok: + raise RuntimeError(f"Impossible de démarrer le point d'accès en mode Pont (hostapd) : {err2 or err}") + + # Appliquer la redirection DNS du mode pont maintenant que l'AP est actif + setup_bridge_dns_redirection(bridge_name, iface) + print(f"[ap-bridge] Point d'accès Pont actif via hostapd sur {iface} -> {bridge_name} (SSID='{ssid}', sécurité={sec_norm})", flush=True) + def setup_bridge(bridge_name='br0', bridge_eth=None): teardown_ap_nat() bridge_name = bridge_name or 'br0' @@ -2985,10 +3169,13 @@ def setup_bridge(bridge_name='br0', bridge_eth=None): subprocess.run(['sysctl', '-w', 'net.ipv4.ip_forward=1'], capture_output=True) except Exception: pass clean_stale_router_leases() - subprocess.run(['iptables', '-I', 'FORWARD', '-i', bridge_name, '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True) + for ipt in _ap_iptables_bins(): + if subprocess.run([ipt, '-w', '5', '-C', 'FORWARD', '-i', bridge_name, '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True).returncode != 0: + subprocess.run([ipt, '-w', '5', '-I', 'FORWARD', '1', '-i', bridge_name, '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True) setup_bridge_dns_redirection(bridge_name, INTERFACE) def teardown_bridge(bridge_name='br0', bridge_eth=None): + stop_hostapd(INTERFACE) teardown_bridge_dns_redirection(bridge_name, INTERFACE) bridge_name = bridge_name or 'br0' bridge_path = f'/sys/class/net/{bridge_name}' @@ -3073,11 +3260,15 @@ def status(force_refresh=False): sec = 'wpa3' if key == 'sae' else 'wpa1' if proto == 'wpa' else 'wpa2' else: sec = db_sec if db_sec in ('wpa1', 'wpa2', 'wpa3') else 'wpa2' + mode = current_mode() state = command('nmcli','-t','-g','GENERAL.STATE','device','show',INTERFACE) # CORRECTION : "30 (disconnected)" contient "connected" ; seul le code 100 signifie connecté. - active = state.startswith('100') + if mode == 'bridge': + active = is_hostapd_running() or (is_iface_up(INTERFACE) and os.path.exists(f'/sys/class/net/{INTERFACE}/master')) + else: + active = state.startswith('100') nm_auto = command('nmcli','-t','-g','connection.autoconnect','connection','show',name).lower() if name else '' - if nm_auto in ('yes', 'no'): + if nm_auto in ('yes', 'no') and mode != 'bridge': auto = (nm_auto == 'yes') elif db_auto is not None: auto = str(db_auto).lower() in ('1', 'true', 'yes', 'oui') @@ -3085,9 +3276,10 @@ def status(force_refresh=False): auto = False if active and uptime_start() is None: mark_ap_started() - slave_type = (command('nmcli','-t','-g','connection.slave-type','connection','show',name) or command('nmcli','-t','-g','connection.port-type','connection','show',name)).lower() if name else '' master = (command('nmcli','-t','-g','connection.master','connection','show',name) or command('nmcli','-t','-g','connection.controller','connection','show',name)) if name else '' - mode = current_mode() + if not master and os.path.exists(f'/sys/class/net/{INTERFACE}/master'): + try: master = os.path.basename(os.readlink(f'/sys/class/net/{INTERFACE}/master')) + except OSError: pass b_name = master or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0')) b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', '')) res = {'ssid':ssid or 'SSID inconnu','password':password,'security':sec,'autoconnect':auto,'mode':mode,'bridge_name':b_name,'bridge_eth':b_eth,'ethernet_interfaces':detect_ethernet_interfaces(),'interface':INTERFACE,'connection':name,'active':active,'configured':bool(name or db_ssid),'uptime_seconds':ap_uptime() if active else 0,'max_clients':get_max_clients(),'dns':get_dns_servers(),'is_starting':not app_startup_done,'boot_time':SERVER_BOOT_TIME} @@ -4525,15 +4717,15 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal print(f"[ap-wifi] Configuration AP: SSID='{ssid}', Sécurité={sec}, Mode={mode}, Autoconnect={'oui' if autoconnect else 'non'}", flush=True) - # Arrêter et supprimer proprement toute ancienne connexion pour éviter les conflits d'options slave/master/ipv4 + # Arrêter et supprimer proprement toute ancienne connexion NM / instance hostapd pour éviter tout conflit + stop_hostapd(INTERFACE) to_delete = {n for n in (old_name, target_name) if n} for c in to_delete: subprocess.run(['nmcli', 'connection', 'down', c], capture_output=True, text=True) subprocess.run(['nmcli', 'connection', 'delete', c], capture_output=True, text=True) if mode == 'bridge': - if start_now: - setup_bridge(bridge_name, bridge_eth) + teardown_ap_nat() # Arrêter le dnsmasq interne pour que les clients reçoivent l'IP de la box et non 10.42.0.x subprocess.run(['pkill', '-f', 'dnsmasq.*shared'], text=True, capture_output=True) for lf in ['/var/lib/misc/dnsmasq.leases', '/var/lib/NetworkManager/dnsmasq.leases']: @@ -4541,37 +4733,15 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal if os.path.exists(lf): open(lf, 'w').close() except OSError: pass - add_args = [ - 'nmcli', 'connection', 'add', - 'type', 'wifi', - 'ifname', INTERFACE, - 'con-name', name, - 'ssid', ssid, - 'slave-type', 'bridge', - 'master', bridge_name - ] - r = subprocess.run(add_args, text=True, capture_output=True) - if r.returncode: - raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé de créer la connexion en mode pont') - - modify_args = [ - 'nmcli', 'connection', 'modify', name, - '802-11-wireless.mode', 'ap', - '802-11-wireless-security.key-mgmt', key, - '802-11-wireless-security.psk', password, - '802-11-wireless-security.pmf', pmf, - '802-11-wireless.band', AP_BAND, - '802-11-wireless.channel', str(AP_CHANNEL), - 'connection.autoconnect', 'yes' if autoconnect else 'no' - ] - if proto: modify_args += ['802-11-wireless-security.proto', proto] - if sec in ('wpa2', 'wpa3'): - modify_args += ['802-11-wireless-security.pairwise', 'ccmp', '802-11-wireless-security.group', 'ccmp'] - r = subprocess.run(modify_args, text=True, capture_output=True) - if r.returncode: - raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé la configuration AP en mode pont') + save_connection(name) + if start_now: + # Prépare le pont noyau sans JAMAIS rendre br0 géré par NetworkManager (préserve l'IP et le DNS de l'hôte) + setup_bridge(bridge_name, bridge_eth) + start_bridge_hostapd(ssid, password, sec=sec, bridge_name=bridge_name, iface=INTERFACE) + mark_ap_started() else: teardown_bridge(bridge_name, bridge_eth) + ensure_nm_manages_wifi(INTERFACE) add_args = [ 'nmcli', 'connection', 'add', 'type', 'wifi', @@ -4604,19 +4774,16 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal if r.returncode: raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé la configuration AP') - ensure_dnsmasq_dns() - save_connection(name) - if start_now: - r = subprocess.run(['nmcli', 'connection', 'up', name], text=True, capture_output=True) - if r.returncode: - raise RuntimeError(r.stderr.strip() or 'Impossible de démarrer le point d’accès') - if mode == 'bridge': - teardown_ap_nat() - else: + ensure_dnsmasq_dns() + save_connection(name) + if start_now: + r = subprocess.run(['nmcli', 'connection', 'up', name], text=True, capture_output=True) + if r.returncode: + raise RuntimeError(r.stderr.strip() or 'Impossible de démarrer le point d’accès') setup_ap_nat(INTERFACE) - mark_ap_started() - else: - teardown_ap_nat() + mark_ap_started() + else: + teardown_ap_nat() invalidate_status_cache() if not silent: log('création' if initial else 'enregistrement_modifie', f"Réseau Wi-Fi {ssid} ({'Mode Pont' if mode == 'bridge' else 'Mode AP'})", ip=caller_ip or 'Non attribuée', mac='AP') @@ -4668,7 +4835,29 @@ def restore_ap_from_db(force_start=False): target_name = get_pref('ap_connection_name', '') or ('AP-' + db_ssid) should_start = bool(force_start or autoconnect) - # Vérifier si le profil NM existe déjà et correspond exactement à la BDD + # Mode Pont : géré nativement via hostapd (br0 reste non géré par NetworkManager) + if db_mode == 'bridge': + save_connection(target_name) + if should_start: + print(f"[ap-api] Démarrage du Wi-Fi Pont '{db_ssid}' depuis la BDD (pont={b_name}, sécurité={db_sec})...", flush=True) + try: + setup_bridge(b_name, b_eth) + start_bridge_hostapd(db_ssid, db_pass, sec=db_sec, bridge_name=b_name, iface=INTERFACE) + mark_ap_started() + invalidate_status_cache() + return True + except Exception as e: + print(f"[ap-api] Erreur démarrage Pont hostapd : {e}", flush=True) + return False + else: + print(f"[ap-api] Profil Wi-Fi Pont '{db_ssid}' restauré depuis la BDD (démarrage automatique désactivé).", flush=True) + stop_hostapd(INTERFACE) + teardown_ap_nat() + invalidate_status_cache() + return True + + # Mode AP (NAT) : géré via NetworkManager + règles NAT/FORWARD + ensure_nm_manages_wifi(INTERFACE) nm_exists = subprocess.run(['nmcli', 'connection', 'show', target_name], capture_output=True, text=True).returncode == 0 needs_rebuild = not nm_exists if nm_exists: @@ -4680,17 +4869,17 @@ def restore_ap_from_db(force_start=False): nm_auto = command('nmcli', '-t', '-g', 'connection.autoconnect', 'connection', 'show', target_name).lower() == 'yes' nm_slave = (command('nmcli', '-t', '-g', 'connection.slave-type', 'connection', 'show', target_name) or command('nmcli', '-t', '-g', 'connection.port-type', 'connection', 'show', target_name)).lower() nm_mode = 'bridge' if nm_slave == 'bridge' else 'ap' - if (nm_ssid != db_ssid or nm_pass != db_pass or nm_sec != db_sec or nm_auto != autoconnect or nm_mode != db_mode): + if (nm_ssid != db_ssid or nm_pass != db_pass or nm_sec != db_sec or nm_auto != autoconnect or nm_mode != 'ap'): needs_rebuild = True if needs_rebuild: - print(f"[ap-api] Reconstruction du profil Wi-Fi '{db_ssid}' depuis la BDD (mode={db_mode}, sécurité={db_sec}, autoconnect={'oui' if autoconnect else 'non'})...", flush=True) + print(f"[ap-api] Reconstruction du profil Wi-Fi '{db_ssid}' depuis la BDD (mode=ap, sécurité={db_sec}, autoconnect={'oui' if autoconnect else 'non'})...", flush=True) try: configure_ap({ 'ssid': db_ssid, 'password': db_pass, 'security': db_sec, - 'mode': db_mode, + 'mode': 'ap', 'autoconnect': autoconnect, 'bridge_name': b_name, 'bridge_eth': b_eth @@ -4703,28 +4892,21 @@ def restore_ap_from_db(force_start=False): # Le profil NM existe déjà et correspond à la BDD save_connection(target_name) if should_start: - if db_mode == 'bridge': - clean_stale_router_leases() - setup_bridge(b_name, b_eth) - else: - teardown_bridge(b_name, b_eth) + teardown_bridge(b_name, b_eth) + ensure_nm_manages_wifi(INTERFACE) state = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', INTERFACE) if not state.startswith('100'): - print(f"[ap-api] Démarrage automatique du Wi-Fi '{db_ssid}' (mode={db_mode})...", flush=True) + print(f"[ap-api] Démarrage automatique du Wi-Fi '{db_ssid}' (mode=ap)...", flush=True) r = subprocess.run(['nmcli', 'connection', 'up', target_name], capture_output=True, text=True) if r.returncode != 0: print(f"[ap-api] Erreur démarrage automatique '{target_name}' : {r.stderr.strip()}", flush=True) return False - if db_mode == 'bridge': - teardown_ap_nat() - else: - setup_ap_nat(INTERFACE) + setup_ap_nat(INTERFACE) mark_ap_started() else: print(f"[ap-api] Profil Wi-Fi '{db_ssid}' restauré depuis la BDD (démarrage automatique désactivé).", flush=True) teardown_ap_nat() - if db_mode != 'bridge': - teardown_bridge(b_name, b_eth) + teardown_bridge(b_name, b_eth) invalidate_status_cache() return True @@ -8176,34 +8358,47 @@ class Handler(BaseHTTPRequestHandler): if self.path == '/api/ap/control': action=str(data.get('action','')); name=connection_name() if not name and not get_pref('ap_ssid', ''): raise ValueError('Aucune connexion AP configurée') - if action in ('start', 'restart'): - nm_exists = bool(name) and (subprocess.run(['nmcli', 'connection', 'show', name], capture_output=True, text=True).returncode == 0) - if not nm_exists and get_pref('ap_ssid', ''): - if not restore_ap_from_db(force_start=True): - raise RuntimeError('Impossible de restaurer et démarrer la connexion Wi-Fi depuis la BDD') - else: - if is_bridge_mode(): - b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0')) - b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', '')) - clean_stale_router_leases() - setup_bridge(b_name, b_eth) + if is_bridge_mode(): + b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0')) + b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', '')) + if action in ('start', 'restart'): + db_ssid = (get_pref('ap_ssid', '') or '').strip() + db_pass = get_pref('ap_password', '') or '' + db_sec = (get_pref('ap_security', 'wpa2') or 'wpa2').lower() + if not db_ssid or not db_pass: + raise RuntimeError('Paramètres Wi-Fi manquants en BDD : veuillez ré-enregistrer les réglages Wi-Fi') if action == 'restart': - subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True) - r = subprocess.run(['nmcli', 'connection', 'up', name], capture_output=True, text=True) - if r.returncode: raise RuntimeError(r.stderr.strip()) - if not is_bridge_mode(): - setup_ap_nat(INTERFACE) + stop_hostapd(INTERFACE) + setup_bridge(b_name, b_eth) + start_bridge_hostapd(db_ssid, db_pass, sec=db_sec, bridge_name=b_name, iface=INTERFACE) + mark_ap_started() + elif action == 'stop': + stop_hostapd(INTERFACE) + teardown_bridge_dns_redirection(b_name, INTERFACE) + try: os.remove(UPTIME_FILE) + except OSError: pass + else: + if action in ('start', 'restart'): + ensure_nm_manages_wifi(INTERFACE) + nm_exists = bool(name) and (subprocess.run(['nmcli', 'connection', 'show', name], capture_output=True, text=True).returncode == 0) + if not nm_exists and get_pref('ap_ssid', ''): + if not restore_ap_from_db(force_start=True): + raise RuntimeError('Impossible de restaurer et démarrer la connexion Wi-Fi depuis la BDD') else: - teardown_ap_nat() - mark_ap_started() - elif action == 'stop': - if name: - r = subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True) - if r.returncode and 'not an active connection' not in r.stderr.lower(): - raise RuntimeError(r.stderr.strip()) - teardown_ap_nat() - try: os.remove(UPTIME_FILE) - except OSError: pass + if action == 'restart': + subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True) + r = subprocess.run(['nmcli', 'connection', 'up', name], capture_output=True, text=True) + if r.returncode: raise RuntimeError(r.stderr.strip()) + setup_ap_nat(INTERFACE) + mark_ap_started() + elif action == 'stop': + if name: + r = subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True) + if r.returncode and 'not an active connection' not in r.stderr.lower(): + raise RuntimeError(r.stderr.strip()) + teardown_ap_nat() + try: os.remove(UPTIME_FILE) + except OSError: pass invalidate_status_cache() log({'start':'démarrage','stop':'arrêt','restart':'redémarrage'}.get(action,'action'), 'Point d’accès Wi-Fi', ip=request_ip(self), mac='AP'); self.send_json({'ok':True}); return if self.path == '/api/setup': self.send_json({'ok':True,'message':'Configuration enregistrée','connection':configure_ap(data,True,caller_ip=request_ip(self))}); return diff --git a/entrypoint.sh b/entrypoint.sh index dc3e653..6f28fc8 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -313,6 +313,13 @@ WEB_PID=$! cleanup() { trap - EXIT TERM INT log "Arrêt des services et nettoyage..." + # Arrêt propre de hostapd (mode pont) et détachement de l'interface Wi-Fi sans toucher au pont hôte + if [[ -f /run/ap-hostapd.pid ]]; then + kill "$(cat /run/ap-hostapd.pid 2>/dev/null || true)" 2>/dev/null || true + rm -f /run/ap-hostapd.pid /run/ap-hostapd.conf 2>/dev/null || true + fi + pkill -f '/run/ap-hostapd.conf' 2>/dev/null || true + [[ -n "${IFACE:-}" ]] && ip link set "$IFACE" nomaster 2>/dev/null || true # Suppression du fichier d'uptime lors de l'arrêt du conteneur rm -f "${AP_UPTIME_FILE:-/data/uptime}" /app/ap-dashboard-uptime 2>/dev/null || true # Restauration uniquement d'un pont créé par APmanageur (/run/ap-created-bridge)