AP manageur V1.1 (Bêta)

This commit is contained in:
yoannmultigaming committed 2026-11-23 22:33:51 +01:00
1 parent 13d57a7b65
commit 795d08eedf
4 files changed
+116 -80

No files matched your search

+103 -67
View File
@@ -3750,6 +3750,24 @@ def find_bin(name):
return p return p
return shutil.which(name) or name return shutil.which(name) or name
def ensure_wpa_supplicant_running():
"""Garantit que wpa_supplicant est actif en tâche de fond avec support D-Bus (-u) pour NetworkManager."""
if subprocess.run(['pgrep', '-x', 'wpa_supplicant'], capture_output=True).returncode == 0:
return True
wpa_bin = find_bin('wpa_supplicant') or '/sbin/wpa_supplicant'
if wpa_bin and (os.path.exists(wpa_bin) or shutil.which(wpa_bin)):
os.makedirs('/run/wpa_supplicant', exist_ok=True)
try:
subprocess.run([wpa_bin, '-B', '-u', '-s', '-O', '/run/wpa_supplicant'], capture_output=True, timeout=5)
for _ in range(15):
if subprocess.run(['pgrep', '-x', 'wpa_supplicant'], capture_output=True).returncode == 0:
print("[ap-wifi] wpa_supplicant démarré avec succès pour NetworkManager.", flush=True)
return True
time.sleep(0.1)
except Exception as e:
print(f"[ap-wifi] Erreur démarrage wpa_supplicant : {e}", flush=True)
return False
def run_cmd(*args): def run_cmd(*args):
if not args: return None if not args: return None
cmd = list(args) cmd = list(args)
@@ -3952,21 +3970,22 @@ def ensure_nm_manages_wifi(iface=None):
iface = iface or INTERFACE iface = iface or INTERFACE
if not iface: if not iface:
return return
was_unmanaged = (command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface) or '').startswith('10')
stop_hostapd(iface) stop_hostapd(iface)
if was_unmanaged: # S'assurer que wpa_supplicant est actif (indispensable pour que NM puisse initialiser la radio Wi-Fi)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True) ensure_wpa_supplicant_running()
subprocess.run(['iw', 'dev', iface, 'set', 'type', 'managed'], capture_output=True) subprocess.run(['rfkill', 'unblock', 'wifi'], capture_output=True)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True) subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True)
time.sleep(0.2) subprocess.run(['ip', 'addr', 'flush', 'dev', iface], capture_output=True)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
subprocess.run(['iw', 'dev', iface, 'set', 'type', 'managed'], capture_output=True)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True)
subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'yes'], capture_output=True) subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'yes'], capture_output=True)
for _ in range(35): subprocess.run(['nmcli', 'radio', 'wifi', 'on'], capture_output=True)
for _ in range(25):
st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface) st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface)
if st and not st.startswith('10') and not st.startswith('20'): # 10=unmanaged, 20=unavailable if st and not st.startswith('10') and not st.startswith('20'): # 10=unmanaged, 20=unavailable
break break
time.sleep(0.2) time.sleep(0.15)
if was_unmanaged:
time.sleep(0.3)
def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=None): 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.""" """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."""
@@ -3981,36 +4000,35 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No
# 1. Arrêter toute ancienne instance hostapd et libérer totalement wlan0 de NetworkManager et wpa_supplicant # 1. Arrêter toute ancienne instance hostapd et libérer totalement wlan0 de NetworkManager et wpa_supplicant
stop_hostapd(iface) stop_hostapd(iface)
was_managed = not (command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface) or '').startswith('10') was_managed = not (command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface) or '').startswith('10')
subprocess.run(['nmcli', 'device', 'disconnect', iface], capture_output=True) subprocess.run(['nmcli', '--wait', '2', 'device', 'disconnect', iface], capture_output=True, timeout=3)
subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'no'], capture_output=True) subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'no'], capture_output=True, timeout=3)
for _ in range(25): for _ in range(15):
st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface) st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface)
if not st or st.startswith('10'): # 10 = unmanaged if not st or st.startswith('10'): # 10 = unmanaged
break break
time.sleep(0.2) time.sleep(0.1)
# Arrêter wpa_supplicant (lancé par D-Bus en mode -u sans nom d'interface) afin qu'il ne bloque jamais les trames EAPOL de hostapd. # Arrêter wpa_supplicant afin qu'il ne bloque jamais les trames EAPOL de hostapd
# D-Bus le relancera automatiquement lors d'un retour en mode AP (NAT).
if was_managed: if was_managed:
time.sleep(0.4) time.sleep(0.2)
subprocess.run(['pkill', '-x', 'wpa_supplicant'], capture_output=True) subprocess.run(['pkill', '-x', 'wpa_supplicant'], capture_output=True)
for _ in range(15): for _ in range(10):
if subprocess.run(['pgrep', '-x', 'wpa_supplicant'], capture_output=True).returncode != 0: if subprocess.run(['pgrep', '-x', 'wpa_supplicant'], capture_output=True).returncode != 0:
break break
time.sleep(0.1) time.sleep(0.1)
time.sleep(0.2) time.sleep(0.1)
country = os.environ.get('AP_COUNTRY', 'FR').strip().upper() or 'FR' country = os.environ.get('AP_COUNTRY', 'FR').strip().upper() or 'FR'
subprocess.run(['rfkill', 'unblock', 'wifi'], capture_output=True) subprocess.run(['rfkill', 'unblock', 'wifi'], capture_output=True)
subprocess.run(['iw', 'reg', 'set', country], capture_output=True) subprocess.run(['iw', 'reg', 'set', country], capture_output=True)
# Cycle complet DOWN -> managed -> UP -> DOWN pour vider l'ancien BSS/table de clés du firmware Raspberry Pi (brcmfmac) # Cycle complet DOWN -> managed -> UP -> DOWN pour vider l'ancien BSS/table de clés du firmware
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True) subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
subprocess.run(['ip', 'addr', 'flush', 'dev', iface], 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, 'nomaster'], capture_output=True)
subprocess.run(['iw', 'dev', iface, 'set', 'type', 'managed'], capture_output=True) subprocess.run(['iw', 'dev', iface, 'set', 'type', 'managed'], capture_output=True)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True) subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True)
time.sleep(0.25) time.sleep(0.15)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True) subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
time.sleep(0.25) time.sleep(0.15)
band = (AP_BAND or 'bg').strip().lower() band = (AP_BAND or 'bg').strip().lower()
hw_mode = 'a' if band == 'a' else 'g' hw_mode = 'a' if band == 'a' else 'g'
@@ -4058,6 +4076,7 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No
lines += [ lines += [
"wpa=2", "wpa=2",
"wpa_key_mgmt=WPA-PSK", "wpa_key_mgmt=WPA-PSK",
"wpa_pairwise=CCMP",
"rsn_pairwise=CCMP", "rsn_pairwise=CCMP",
f"wpa_passphrase={password}", f"wpa_passphrase={password}",
] ]
@@ -4087,8 +4106,8 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No
pass pass
return False, err or 'hostapd a refusé de démarrer' return False, err or 'hostapd a refusé de démarrer'
ap_ready = False ap_ready = False
for _ in range(30): for _ in range(25):
time.sleep(0.2) time.sleep(0.15)
if not is_hostapd_running(): if not is_hostapd_running():
break break
iw_out = command('iw', 'dev', iface, 'info') or '' iw_out = command('iw', 'dev', iface, 'info') or ''
@@ -4097,18 +4116,23 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No
if os.path.exists(HOSTAPD_LOG_FILE): if os.path.exists(HOSTAPD_LOG_FILE):
try: log_txt = open(HOSTAPD_LOG_FILE, encoding='utf-8', errors='replace').read() try: log_txt = open(HOSTAPD_LOG_FILE, encoding='utf-8', errors='replace').read()
except OSError: pass except OSError: pass
if 'AP-ENABLED' in log_txt and 'type AP' in iw_out and has_master: if 'AP-ENABLED' in log_txt and 'type AP' in iw_out:
ap_ready = True if not has_master:
break subprocess.run(['ip', 'link', 'set', 'dev', iface, 'master', bridge_name], capture_output=True)
has_master = os.path.exists(f'/sys/class/net/{iface}/master')
if has_master:
ap_ready = True
break
if ap_ready: if ap_ready:
# Vérification de stabilité courte (0,4s) pour s'assurer qu'aucun événement NM résiduel n'a désactivé l'AP time.sleep(0.2)
time.sleep(0.4)
iw_out = command('iw', 'dev', iface, 'info') or '' iw_out = command('iw', 'dev', iface, 'info') or ''
log_txt = '' log_txt = ''
if os.path.exists(HOSTAPD_LOG_FILE): if os.path.exists(HOSTAPD_LOG_FILE):
try: log_txt = open(HOSTAPD_LOG_FILE, encoding='utf-8', errors='replace').read() try: log_txt = open(HOSTAPD_LOG_FILE, encoding='utf-8', errors='replace').read()
except OSError: pass except OSError: pass
if is_hostapd_running() and 'type AP' in iw_out and os.path.exists(f'/sys/class/net/{iface}/master') and 'AP-DISABLED' not in log_txt: if is_hostapd_running() and 'type AP' in iw_out and 'AP-DISABLED' not in log_txt:
if not os.path.exists(f'/sys/class/net/{iface}/master'):
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'master', bridge_name], capture_output=True)
disable_wifi_powersave(iface) disable_wifi_powersave(iface)
return True, '' return True, ''
return False, 'Interface AP instable après initialisation initiale' return False, 'Interface AP instable après initialisation initiale'
@@ -4131,13 +4155,13 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No
print(f"[ap-bridge] 1er démarrage hostapd incomplet ({err}), relance propre...", flush=True) print(f"[ap-bridge] 1er démarrage hostapd incomplet ({err}), relance propre...", flush=True)
stop_hostapd(iface) stop_hostapd(iface)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True) subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
time.sleep(0.5) time.sleep(0.3)
ok, err2 = _try_launch(enable_ht=True) ok, err2 = _try_launch(enable_ht=True)
if not ok: if not ok:
print(f"[ap-bridge] hostapd (802.11n) a échoué ({err2}), nouvelle tentative sans 802.11n...", flush=True) print(f"[ap-bridge] hostapd (802.11n) a échoué ({err2}), nouvelle tentative sans 802.11n...", flush=True)
stop_hostapd(iface) stop_hostapd(iface)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True) subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
time.sleep(0.3) time.sleep(0.2)
ok, err3 = _try_launch(enable_ht=False) ok, err3 = _try_launch(enable_ht=False)
if not ok: if not ok:
raise RuntimeError(f"Impossible de démarrer le point d'accès en mode Pont (hostapd) : {err3 or err2 or err}") raise RuntimeError(f"Impossible de démarrer le point d'accès en mode Pont (hostapd) : {err3 or err2 or err}")
@@ -4291,23 +4315,26 @@ def setup_bridge(bridge_name='br0', bridge_eth=None):
try: open(CREATED_BRIDGE_FILE, 'w').write(f"{bridge_name}:{bridge_eth or ''}") try: open(CREATED_BRIDGE_FILE, 'w').write(f"{bridge_name}:{bridge_eth or ''}")
except OSError: pass except OSError: pass
# Asservir l'Ethernet physique s'il n'est pas déjà dans le pont et que le pont n'existait pas déjà avec IP # Asservir l'Ethernet physique au pont pour relier le Wi-Fi au réseau local et au DHCP de la box
migrated_gw = None migrated_gw = None
has_bridge_ip = bool(get_iface_ip_info(bridge_name)[0]) has_bridge_ip = bool(get_iface_ip_info(bridge_name)[0])
if bridge_eth and os.path.exists(f'/sys/class/net/{bridge_eth}') and eth_master != bridge_name and not has_bridge_ip and not bridge_already_existed: if bridge_eth and os.path.exists(f'/sys/class/net/{bridge_eth}'):
ip_cidr, gw, mac = get_iface_ip_info(bridge_eth) subprocess.run(['ip', 'link', 'set', 'dev', bridge_eth, 'up'], capture_output=True)
migrated_gw = gw if eth_master != bridge_name:
if mac: ip_cidr, gw, mac = get_iface_ip_info(bridge_eth)
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'address', mac], capture_output=True) migrated_gw = gw
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'up'], capture_output=True) if mac and not has_bridge_ip:
subprocess.run(['ip', 'link', 'set', 'dev', bridge_eth, 'master', bridge_name], capture_output=True) subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'address', mac], capture_output=True)
# Transférer l'adresse IP et la passerelle au pont pour ne JAMAIS perdre le ping et l'accès à l'hôte subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'up'], capture_output=True)
if ip_cidr: subprocess.run(['ip', 'link', 'set', 'dev', bridge_eth, 'master', bridge_name], capture_output=True)
subprocess.run(['ip', 'addr', 'flush', 'dev', bridge_eth], capture_output=True) if ip_cidr and not has_bridge_ip:
subprocess.run(['ip', 'addr', 'add', ip_cidr, 'dev', bridge_name], capture_output=True) subprocess.run(['ip', 'addr', 'flush', 'dev', bridge_eth], capture_output=True)
if gw: subprocess.run(['ip', 'addr', 'add', ip_cidr, 'dev', bridge_name], capture_output=True)
subprocess.run(['ip', 'route', 'replace', 'default', 'via', gw, 'dev', bridge_name], capture_output=True) if gw:
print(f"[ap-bridge] Ethernet {bridge_eth} asservi à {bridge_name}. IP {ip_cidr} et passerelle {gw} migrées sur {bridge_name} (Ping préservé).", flush=True) subprocess.run(['ip', 'route', 'replace', 'default', 'via', gw, 'dev', bridge_name], capture_output=True)
print(f"[ap-bridge] Ethernet {bridge_eth} asservi à {bridge_name}. IP {ip_cidr} et passerelle {gw} migrées sur {bridge_name} (Ping préservé).", flush=True)
else:
print(f"[ap-bridge] Ethernet {bridge_eth} asservi à {bridge_name}.", flush=True)
else: else:
# Si le pont hôte existe déjà : verrouiller sa MAC actuelle (sans la modifier) pour éviter que l'ajout de wlan0 ne change la MAC de br0 et ne coupe le DNS hôte # Si le pont hôte existe déjà : verrouiller sa MAC actuelle (sans la modifier) pour éviter que l'ajout de wlan0 ne change la MAC de br0 et ne coupe le DNS hôte
try: try:
@@ -4317,16 +4344,19 @@ def setup_bridge(bridge_name='br0', bridge_eth=None):
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'address', cur_mac], capture_output=True) subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'address', cur_mac], capture_output=True)
except OSError: except OSError:
pass pass
if not is_iface_up(bridge_name):
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'up'], capture_output=True) if not is_iface_up(bridge_name):
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'up'], capture_output=True)
try: try:
subprocess.run(['sysctl', '-w', 'net.ipv4.ip_forward=1'], capture_output=True) subprocess.run(['sysctl', '-w', 'net.ipv4.ip_forward=1'], capture_output=True)
except Exception: pass except Exception: pass
clean_stale_router_leases() clean_stale_router_leases()
for ipt in _ap_iptables_bins(): 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: if subprocess.run([ipt, '-w', '5', '-C', 'FORWARD', '-i', 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) subprocess.run([ipt, '-w', '5', '-I', 'FORWARD', '1', '-i', bridge_name, '-j', 'ACCEPT'], capture_output=True)
if subprocess.run([ipt, '-w', '5', '-C', 'FORWARD', '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True).returncode != 0:
subprocess.run([ipt, '-w', '5', '-I', 'FORWARD', '1', '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True)
setup_bridge_dns_redirection(bridge_name, INTERFACE) setup_bridge_dns_redirection(bridge_name, INTERFACE)
sync_host_resolved_bridge_dns(bridge_name, migrated_gw) sync_host_resolved_bridge_dns(bridge_name, migrated_gw)
@@ -4366,19 +4396,21 @@ def teardown_bridge(bridge_name='br0', bridge_eth=None):
break break
except OSError: pass except OSError: pass
# Ne restaurer et ne détruire le pont QUE si nous l'avons créé nous-mêmes (préserver impérativement la configuration hôte) # Restaurer l'interface Ethernet si elle était asservie au pont
if slaved_eth:
ip_cidr, gw, _ = get_iface_ip_info(bridge_name)
subprocess.run(['ip', 'link', 'set', 'dev', slaved_eth, 'nomaster'], capture_output=True)
if ip_cidr:
subprocess.run(['ip', 'addr', 'flush', 'dev', bridge_name], capture_output=True)
subprocess.run(['ip', 'addr', 'add', ip_cidr, 'dev', slaved_eth], capture_output=True)
if gw:
subprocess.run(['ip', 'route', 'replace', 'default', 'via', gw, 'dev', slaved_eth], capture_output=True)
print(f"[ap-bridge] IP {ip_cidr} et passerelle {gw} restaurées sur {slaved_eth}.", flush=True)
subprocess.run(['ip', 'link', 'set', 'dev', slaved_eth, 'up'], capture_output=True)
# Ne détruire le pont que s'il a été créé par nous-mêmes
if was_created_by_us and os.path.exists(bridge_path): if was_created_by_us and os.path.exists(bridge_path):
revert_host_resolved_bridge_dns(bridge_name) revert_host_resolved_bridge_dns(bridge_name)
if slaved_eth:
ip_cidr, gw, _ = get_iface_ip_info(bridge_name)
subprocess.run(['ip', 'link', 'set', 'dev', slaved_eth, 'nomaster'], capture_output=True)
if ip_cidr:
subprocess.run(['ip', 'addr', 'flush', 'dev', bridge_name], capture_output=True)
subprocess.run(['ip', 'addr', 'add', ip_cidr, 'dev', slaved_eth], capture_output=True)
if gw:
subprocess.run(['ip', 'route', 'replace', 'default', 'via', gw, 'dev', slaved_eth], capture_output=True)
print(f"[ap-bridge] IP {ip_cidr} et passerelle {gw} restaurées sur {slaved_eth}.", flush=True)
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'down'], capture_output=True) subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'down'], capture_output=True)
subprocess.run(['ip', 'link', 'delete', 'name', bridge_name, 'type', 'bridge'], capture_output=True) subprocess.run(['ip', 'link', 'delete', 'name', bridge_name, 'type', 'bridge'], capture_output=True)
print(f"[ap-bridge] Pont créé {bridge_name} nettoyé et supprimé.", flush=True) print(f"[ap-bridge] Pont créé {bridge_name} nettoyé et supprimé.", flush=True)
@@ -6471,11 +6503,14 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal
stop_hostapd(INTERFACE) stop_hostapd(INTERFACE)
to_delete = {n for n in (old_name, target_name) if n} to_delete = {n for n in (old_name, target_name) if n}
for c in to_delete: for c in to_delete:
subprocess.run(['nmcli', 'connection', 'down', c], capture_output=True, text=True) subprocess.run(['nmcli', '--wait', '3', 'connection', 'down', c], capture_output=True, text=True, timeout=5)
subprocess.run(['nmcli', 'connection', 'delete', c], capture_output=True, text=True) subprocess.run(['nmcli', '--wait', '3', 'connection', 'delete', c], capture_output=True, text=True, timeout=5)
if mode == 'bridge': if mode == 'bridge':
teardown_ap_nat() teardown_ap_nat()
# Libérer l'interface Wi-Fi de NetworkManager pour hostapd
subprocess.run(['nmcli', 'device', 'set', INTERFACE, 'managed', 'no'], capture_output=True, timeout=5)
subprocess.run(['ip', 'addr', 'flush', 'dev', INTERFACE], capture_output=True)
# Arrêter le dnsmasq interne pour que les clients reçoivent l'IP de la box et non 10.42.0.x # 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) subprocess.run(['pkill', '-f', 'dnsmasq.*shared'], text=True, capture_output=True)
for lf in ['/var/lib/misc/dnsmasq.leases', '/var/lib/NetworkManager/dnsmasq.leases']: for lf in ['/var/lib/misc/dnsmasq.leases', '/var/lib/NetworkManager/dnsmasq.leases']:
@@ -6499,7 +6534,7 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal
'con-name', name, 'con-name', name,
'ssid', ssid 'ssid', ssid
] ]
r = subprocess.run(add_args, text=True, capture_output=True) r = subprocess.run(add_args, text=True, capture_output=True, timeout=10)
if r.returncode: if r.returncode:
raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé de créer la connexion Wi-Fi') raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé de créer la connexion Wi-Fi')
@@ -6521,14 +6556,14 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal
modify_args += ['802-11-wireless-security.pairwise', 'ccmp', '802-11-wireless-security.group', 'ccmp'] modify_args += ['802-11-wireless-security.pairwise', 'ccmp', '802-11-wireless-security.group', 'ccmp']
# Note : ipv4.dns est interdit par NetworkManager lorsque ipv4.method=shared. # Note : ipv4.dns est interdit par NetworkManager lorsque ipv4.method=shared.
# Les serveurs DNS (AP_DNS) sont distribués aux clients Wi-Fi via dnsmasq (ensure_dnsmasq_dns / dhcp-option=6). # Les serveurs DNS (AP_DNS) sont distribués aux clients Wi-Fi via dnsmasq (ensure_dnsmasq_dns / dhcp-option=6).
r = subprocess.run(modify_args, text=True, capture_output=True) r = subprocess.run(modify_args, text=True, capture_output=True, timeout=10)
if r.returncode: if r.returncode:
raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé la configuration AP') raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé la configuration AP')
ensure_dnsmasq_dns() ensure_dnsmasq_dns()
save_connection(name) save_connection(name)
if start_now: if start_now:
r = subprocess.run(['nmcli', 'connection', 'up', name], text=True, capture_output=True) r = subprocess.run(['nmcli', '--wait', '20', 'connection', 'up', name], text=True, capture_output=True, timeout=25)
if r.returncode: if r.returncode:
raise RuntimeError(r.stderr.strip() or 'Impossible de démarrer le point d’accès') raise RuntimeError(r.stderr.strip() or 'Impossible de démarrer le point d’accès')
disable_wifi_powersave(INTERFACE) disable_wifi_powersave(INTERFACE)
@@ -13387,6 +13422,7 @@ if __name__ == '__main__':
c.commit(); c.close() c.commit(); c.close()
except Exception as e_db: except Exception as e_db:
print(f"[ap-vpn] Erreur réinitialisation statut VPN : {e_db}", flush=True) print(f"[ap-vpn] Erreur réinitialisation statut VPN : {e_db}", flush=True)
ensure_wpa_supplicant_running()
# Restaurer le profil Wi-Fi (SSID, mot de passe, sécurité, mode, démarrage automatique) depuis la BDD SQLite # Restaurer le profil Wi-Fi (SSID, mot de passe, sécurité, mode, démarrage automatique) depuis la BDD SQLite
restore_ap_from_db() restore_ap_from_db()
apply_radio_defaults() apply_radio_defaults()
+9 -9
View File
@@ -2376,7 +2376,7 @@
Administration de l’AP Wi‑Fi</h2> Administration de l’AP Wi‑Fi</h2>
<div class="sub" style="margin-top:4px"><span class="app-short-title">AP Manageur</span> <span <div class="sub" style="margin-top:4px"><span class="app-short-title">AP Manageur</span> <span
class="app-version" class="app-version"
style="font-weight:700;background:var(--panel2);padding:2px 8px;border-radius:6px;border:1px solid var(--line);color:var(--blue);font-size:11px;margin-left:4px">V1.2 (Bêta)</span> style="font-weight:700;background:var(--panel2);padding:2px 8px;border-radius:6px;border:1px solid var(--line);color:var(--blue);font-size:11px;margin-left:4px">V1.1 (Bêta)</span>
</div> </div>
<div id="loaderBadge" <div id="loaderBadge"
style="display:inline-flex;align-items:center;gap:6px;background:rgba(56,189,248,0.12);border:1px solid rgba(56,189,248,0.3);color:var(--blue);padding:3px 12px;border-radius:20px;font-size:12px;font-weight:600;margin-top:8px"> style="display:inline-flex;align-items:center;gap:6px;background:rgba(56,189,248,0.12);border:1px solid rgba(56,189,248,0.3);color:var(--blue);padding:3px 12px;border-radius:20px;font-size:12px;font-weight:600;margin-top:8px">
@@ -2571,7 +2571,7 @@
<div> <div>
<h1><span class="app-title" data-i18n="app_main_heading">Administration de l’AP Wi‑Fi</span></h1> <h1><span class="app-title" data-i18n="app_main_heading">Administration de l’AP Wi‑Fi</span></h1>
<div class="sub"><span class="app-short-title">AP Manageur</span> <span class="app-version" <div class="sub"><span class="app-short-title">AP Manageur</span> <span class="app-version"
style="font-weight:700;background:var(--panel2);padding:2px 8px;border-radius:6px;border:1px solid var(--line);color:var(--blue);font-size:12px;margin-left:4px">V1.2 (Bêta)</span> style="font-weight:700;background:var(--panel2);padding:2px 8px;border-radius:6px;border:1px solid var(--line);color:var(--blue);font-size:12px;margin-left:4px">V1.1 (Bêta)</span>
</div> </div>
</div> </div>
<div class="header-actions"> <div class="header-actions">
@@ -5616,7 +5616,7 @@
<div id="advUpdateCurrentCommit" <div id="advUpdateCurrentCommit"
style="font-family:monospace;font-size:16px;font-weight:700;color:var(--text);margin-top:2px">—</div> style="font-family:monospace;font-size:16px;font-weight:700;color:var(--text);margin-top:2px">—</div>
<div class="muted" style="font-size:11px;margin-top:2px" id="advUpdateVersionTag"><span <div class="muted" style="font-size:11px;margin-top:2px" id="advUpdateVersionTag"><span
class="app-short-title">AP Manageur</span> <span class="app-version">V1.2 (Bêta)</span></div> class="app-short-title">AP Manageur</span> <span class="app-version">V1.1 (Bêta)</span></div>
</div> </div>
<div style="background:var(--panel2);padding:10px 12px;border-radius:8px;border:1px solid var(--line)"> <div style="background:var(--panel2);padding:10px 12px;border-radius:8px;border:1px solid var(--line)">
<div class="label" data-i18n="adv_update_latest_ver" style="font-size:11px">Dernière version (Gitea)</div> <div class="label" data-i18n="adv_update_latest_ver" style="font-size:11px">Dernière version (Gitea)</div>
@@ -7417,7 +7417,7 @@
function $(id) { return document.getElementById(id); } function $(id) { return document.getElementById(id); }
const API_URL = location.protocol === 'file:' ? 'http://127.0.0.1:8080' : ''; const API_URL = location.protocol === 'file:' ? 'http://127.0.0.1:8080' : '';
/* Version de l'application */ /* Version de l'application */
let APP_VERSION = "V1.2 (Bêta)"; let APP_VERSION = "V1.1 (Bêta)";
const ICON_REFRESH_ARROW = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" style="display:inline-block;vertical-align:middle"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.9 1 6.7 2.4L21 8"/><polyline points="21 3 21 8 16 8"/></svg>'; const ICON_REFRESH_ARROW = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" style="display:inline-block;vertical-align:middle"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.9 1 6.7 2.4L21 8"/><polyline points="21 3 21 8 16 8"/></svg>';
const ICON_GEAR = '⚙️'; const ICON_GEAR = '⚙️';
const ICON_TABLET = '<svg width="1.15em" height="1.15em" viewBox="0 0 24 24" fill="none" style="display:inline-block;vertical-align:-0.18em;flex-shrink:0" aria-label="Tablette"><rect x="2.5" y="1.5" width="19" height="21" rx="2.5" fill="#1e293b" stroke="#64748b" stroke-width="1"/><rect x="4" y="3.2" width="16" height="15.6" rx="1.2" fill="#38bdf8"/><circle cx="12" cy="2.3" r="0.5" fill="#94a3b8"/><rect x="10" y="20" width="4" height="1.2" rx="0.6" fill="#94a3b8"/></svg>'; const ICON_TABLET = '<svg width="1.15em" height="1.15em" viewBox="0 0 24 24" fill="none" style="display:inline-block;vertical-align:-0.18em;flex-shrink:0" aria-label="Tablette"><rect x="2.5" y="1.5" width="19" height="21" rx="2.5" fill="#1e293b" stroke="#64748b" stroke-width="1"/><rect x="4" y="3.2" width="16" height="15.6" rx="1.2" fill="#38bdf8"/><circle cx="12" cy="2.3" r="0.5" fill="#94a3b8"/><rect x="10" y="20" width="4" height="1.2" rx="0.6" fill="#94a3b8"/></svg>';
@@ -8025,7 +8025,7 @@
} }
if (devName) options.headers['X-Device-Name'] = encodeURIComponent(devName); if (devName) options.headers['X-Device-Name'] = encodeURIComponent(devName);
let timer; let timer;
const timeoutMs = options.timeout || 15000; const timeoutMs = options.timeout || 45000;
const isEn = typeof currentLanguage !== 'undefined' && currentLanguage.startsWith('en'); const isEn = typeof currentLanguage !== 'undefined' && currentLanguage.startsWith('en');
const timeStr = `${Math.round(timeoutMs / 1000)}s`; const timeStr = `${Math.round(timeoutMs / 1000)}s`;
const timeoutMsg = isEn ? `Request timed out (${timeStr})` : `Délai d'attente dépassé (${timeStr})`; const timeoutMsg = isEn ? `Request timed out (${timeStr})` : `Délai d'attente dépassé (${timeStr})`;
@@ -9621,7 +9621,7 @@ ${vpnBadgeTopo}
async function controlAp(action) { async function controlAp(action) {
return runAction(async () => { return runAction(async () => {
try { try {
const response = await apiFetch('/api/ap/control', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }) }); const response = await apiFetch('/api/ap/control', { method: 'POST', timeout: 45000, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }) });
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Action refusée'); const data = await response.json(); if (!response.ok) throw Error(data.error || 'Action refusée');
await new Promise(resolve => setTimeout(resolve, 1000)); await load(); await new Promise(resolve => setTimeout(resolve, 1000)); await load();
} catch (e) { alert(tErr(e.message)) } } catch (e) { alert(tErr(e.message)) }
@@ -10326,7 +10326,7 @@ ${vpnBadgeTopo}
// Rafraîchir en arrière-plan depuis l'API // Rafraîchir en arrière-plan depuis l'API
try { try {
const res = await apiFetch(`/api/devices/limits?mac=${encodeURIComponent(cleanMac)}`, { timeout: 15000 }); const res = await apiFetch(`/api/devices/limits?mac=${encodeURIComponent(cleanMac)}`, { timeout: 30000 });
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
if (data && data.limits) { if (data && data.limits) {
@@ -13875,7 +13875,7 @@ ${vpnBadgeTopo}
try { try {
const sMode = document.querySelector('input[name="setupMode"]:checked')?.value || 'ap'; const sMode = document.querySelector('input[name="setupMode"]:checked')?.value || 'ap';
const sEth = $('setupBridgeEth')?.value || ''; const sEth = $('setupBridgeEth')?.value || '';
const response = await apiFetch('/api/setup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ssid: $('setupSsid').value, password: password, security: $('setupSecurity').value, mode: sMode, bridge_eth: sEth, max_clients: parseInt($('setupMaxClients') ? $('setupMaxClients').value : 0, 10) || 0 }) }); const response = await apiFetch('/api/setup', { method: 'POST', timeout: 60000, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ssid: $('setupSsid').value, password: password, security: $('setupSecurity').value, mode: sMode, bridge_eth: sEth, max_clients: parseInt($('setupMaxClients') ? $('setupMaxClients').value : 0, 10) || 0 }) });
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Configuration refusée'); const data = await response.json(); if (!response.ok) throw Error(data.error || 'Configuration refusée');
message.textContent = data.message; currentTab = 'dashboard'; sessionStorage.setItem('apDashboardTab', 'dashboard'); message.textContent = data.message; currentTab = 'dashboard'; sessionStorage.setItem('apDashboardTab', 'dashboard');
await new Promise(resolve => setTimeout(resolve, 500)); await load(); await new Promise(resolve => setTimeout(resolve, 500)); await load();
@@ -13906,7 +13906,7 @@ ${vpnBadgeTopo}
try { try {
const setMode = document.querySelector('input[name="settingsMode"]:checked')?.value || 'ap'; const setMode = document.querySelector('input[name="settingsMode"]:checked')?.value || 'ap';
const setEth = $('settingsBridgeEth')?.value || ''; const setEth = $('settingsBridgeEth')?.value || '';
let r = await apiFetch('/api/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ssid: $('settingsSsid').value, password: $('settingsPassword').value, security: $('settingsSecurity').value, mode: setMode, bridge_eth: setEth, max_clients: parseInt($('settingsMaxClients') ? $('settingsMaxClients').value : 0, 10) || 0, autoconnect: $('settingsAutoconnect').checked }) }); let r = await apiFetch('/api/settings', { method: 'POST', timeout: 60000, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ssid: $('settingsSsid').value, password: $('settingsPassword').value, security: $('settingsSecurity').value, mode: setMode, bridge_eth: setEth, max_clients: parseInt($('settingsMaxClients') ? $('settingsMaxClients').value : 0, 10) || 0, autoconnect: $('settingsAutoconnect').checked }) });
let d = await r.json(); if (!r.ok) throw Error(d.error); let d = await r.json(); if (!r.ok) throw Error(d.error);
m.textContent = tMsg(d.message); await new Promise(resolve => setTimeout(resolve, 1000)); await load(); m.textContent = tMsg(d.message); await new Promise(resolve => setTimeout(resolve, 1000)); await load();
} catch (e) { m.textContent = tErr(e.message); } } catch (e) { m.textContent = tErr(e.message); }
+1 -1
View File
@@ -1088,7 +1088,7 @@
</h1> </h1>
<div class="sub"> <div class="sub">
<span class="app-short-title">AP Manageur</span> <span class="app-short-title">AP Manageur</span>
<span class="pill app-version" style="margin-left:6px;font-size:11px">V1.2 (Bêta)</span> <span class="pill app-version" style="margin-left:6px;font-size:11px">V1.1 (Bêta)</span>
<span class="pill" style="margin-left:4px;font-size:11px;color:var(--blue);border-color:var(--blue)" <span class="pill" style="margin-left:4px;font-size:11px;color:var(--blue);border-color:var(--blue)"
data-i18n="app_badge_setup">Configuration initiale</span> data-i18n="app_badge_setup">Configuration initiale</span>
</div> </div>
+3 -3
View File
@@ -1,5 +1,5 @@
{ {
"version": "V1.2 (Bêta)", "version": "V1.1 (Bêta)",
"commit": "a3c2cc93e861319933ba771792d8137d998d32bc", "commit": "13d57a7b6516142e5be23dee5a5825f7ecd44897",
"build_date": "2026-11-23T19:17:26Z" "build_date": "2026-11-23T19:40:56Z"
} }