AP manageur V1.1 (Bêta)

This commit is contained in:
yoannmultigaming committed 2026-11-25 02:10:59 +01:00
1 parent a9630cc035
commit 7fe1dbf389
2 files changed
+90 -67

No files matched your search

+83 -65
View File
@@ -15,7 +15,34 @@ for p in ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin',
if p not in os.environ.get('PATH', '').split(':'): if p not in os.environ.get('PATH', '').split(':'):
os.environ['PATH'] = p + ':' + os.environ.get('PATH', '') os.environ['PATH'] = p + ':' + os.environ.get('PATH', '')
INTERFACE = os.environ.get('AP_INTERFACE', 'wls16b1') def detect_wifi_interface():
env_iface = (os.environ.get('AP_INTERFACE') or '').strip()
if env_iface and os.path.exists(f'/sys/class/net/{env_iface}'):
return env_iface
try:
if os.path.exists('/sys/class/net'):
for d in os.listdir('/sys/class/net'):
p = os.path.join('/sys/class/net', d)
if os.path.isdir(os.path.join(p, 'wireless')) or os.path.isdir(os.path.join(p, 'phy80211')):
return d
except Exception: pass
try:
out = subprocess.check_output(['iw', 'dev'], text=True, stderr=subprocess.DEVNULL)
for line in out.splitlines():
parts = line.strip().split()
if len(parts) >= 2 and parts[0] == 'Interface':
return parts[1]
except Exception: pass
try:
out = subprocess.check_output(['nmcli', '-t', '-g', 'DEVICE,TYPE', 'device'], text=True, stderr=subprocess.DEVNULL)
for line in out.splitlines():
if ':wifi' in line or ':802-11-wireless' in line:
d = line.split(':')[0].strip()
if d: return d
except Exception: pass
return env_iface or 'wlan0'
INTERFACE = detect_wifi_interface()
SOCKET_PATH = os.environ.get('AP_SOCKET', '/run/ap-api.sock') SOCKET_PATH = os.environ.get('AP_SOCKET', '/run/ap-api.sock')
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DB_FILE = os.environ.get('AP_DB_FILE', os.path.join(BASE_DIR, 'ap-dashboard.sqlite3')) DB_FILE = os.environ.get('AP_DB_FILE', os.path.join(BASE_DIR, 'ap-dashboard.sqlite3'))
@@ -4008,34 +4035,29 @@ def stop_hostapd(iface=None):
def ensure_nm_manages_wifi(iface=None, force=False): def ensure_nm_manages_wifi(iface=None, force=False):
"""Rend le contrôle de l'interface Wi-Fi à NetworkManager (pour le mode AP/NAT) et attend qu'elle soit prête.""" """Rend le contrôle de l'interface Wi-Fi à NetworkManager (pour le mode AP/NAT) et attend qu'elle soit prête."""
iface = iface or INTERFACE iface = iface or get_wifi_interface()
if not iface: if not iface:
return return
# Si le périphérique est déjà sous le contrôle de NetworkManager (pas de hostapd actif, non asservi à un pont et état >= 30)
# il est contre-productif de faire un reset physique (down/up) qui déconnecterait l'interface.
is_master = os.path.exists(f'/sys/class/net/{iface}/master') is_master = os.path.exists(f'/sys/class/net/{iface}/master')
hostapd_act = is_hostapd_running() hostapd_act = is_hostapd_running()
current_st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface, timeout=2) current_st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface, timeout=2)
# Si le périphérique est déjà sous le contrôle de NetworkManager (pas de hostapd actif, non asservi à un pont et état != 10 unmanaged)
# il ne faut JAMAIS faire de reset physique (down/up) qui déconnecterait l'interface.
if not force and not is_master and not hostapd_act: if not force and not is_master and not hostapd_act:
if current_st and not current_st.startswith('10') and not current_st.startswith('20'): if current_st and not current_st.startswith('10'):
return return
stop_hostapd(iface) stop_hostapd(iface)
# S'assurer que wpa_supplicant est actif (indispensable pour que NM puisse initialiser la radio Wi-Fi)
ensure_wpa_supplicant_running() ensure_wpa_supplicant_running()
subprocess.run(['rfkill', 'unblock', 'wifi'], capture_output=True, timeout=3) subprocess.run(['rfkill', 'unblock', 'wifi'], capture_output=True, timeout=2)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True, timeout=3) subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True, timeout=2)
subprocess.run(['ip', 'addr', 'flush', 'dev', iface], capture_output=True, timeout=3) subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'yes'], capture_output=True, timeout=2)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True, timeout=3) subprocess.run(['nmcli', 'radio', 'wifi', 'on'], capture_output=True, timeout=2)
subprocess.run(['iw', 'dev', iface, 'set', 'type', 'managed'], capture_output=True, timeout=3) for _ in range(5):
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True, timeout=3) st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface, timeout=1)
subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'yes'], capture_output=True, timeout=5) if st and not st.startswith('10'):
subprocess.run(['nmcli', 'radio', 'wifi', 'on'], capture_output=True, timeout=5)
for _ in range(35):
st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface, timeout=2)
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.1)
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."""
@@ -6609,7 +6631,7 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal
'ipv4.method', 'shared', 'ipv4.method', 'shared',
'ipv6.method', 'ignore', 'ipv6.method', 'ignore',
'802-11-wireless.band', AP_BAND, '802-11-wireless.band', AP_BAND,
'802-11-wireless.channel', str(get_effective_ap_channel(AP_BAND, force_rescan=is_auto_channel())), '802-11-wireless.channel', str(get_effective_ap_channel(AP_BAND, force_rescan=False)),
'connection.autoconnect', 'yes' if autoconnect else 'no' 'connection.autoconnect', 'yes' if autoconnect else 'no'
] ]
if proto: modify_args += ['802-11-wireless-security.proto', proto] if proto: modify_args += ['802-11-wireless-security.proto', proto]
@@ -6624,8 +6646,10 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal
ensure_dnsmasq_dns() ensure_dnsmasq_dns()
save_connection(name) save_connection(name)
if start_now: if start_now:
r = subprocess.run(['nmcli', '--wait', '20', 'connection', 'up', name], text=True, capture_output=True, timeout=25) r = subprocess.run(['nmcli', 'connection', 'up', name, 'ifname', INTERFACE], text=True, capture_output=True, timeout=12)
if r.returncode: if r.returncode != 0:
r = subprocess.run(['nmcli', 'connection', 'up', name], text=True, capture_output=True, timeout=10)
if r.returncode != 0:
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)
setup_ap_nat(INTERFACE) setup_ap_nat(INTERFACE)
@@ -6741,16 +6765,19 @@ def restore_ap_from_db(force_start=False):
save_connection(target_name) save_connection(target_name)
if should_start: if should_start:
teardown_bridge(b_name, b_eth) teardown_bridge(b_name, b_eth)
ensure_nm_manages_wifi(INTERFACE) wifi_if = get_wifi_interface()
state = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', INTERFACE) ensure_nm_manages_wifi(wifi_if)
state = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', wifi_if, timeout=2)
if not state.startswith('100'): if not state.startswith('100'):
print(f"[ap-api] Démarrage automatique du Wi-Fi '{db_ssid}' (mode=ap)...", flush=True) print(f"[ap-api] Démarrage automatique du Wi-Fi '{db_ssid}' (mode=ap)...", flush=True)
r = subprocess.run(['nmcli', '--wait', '15', 'connection', 'up', target_name], capture_output=True, text=True, timeout=20) r = subprocess.run(['nmcli', 'connection', 'up', target_name, 'ifname', wifi_if], capture_output=True, text=True, timeout=12)
if r.returncode != 0:
r = subprocess.run(['nmcli', 'connection', 'up', target_name], capture_output=True, text=True, timeout=10)
if r.returncode != 0: if r.returncode != 0:
print(f"[ap-api] Erreur démarrage automatique '{target_name}' : {r.stderr.strip()}", flush=True) print(f"[ap-api] Erreur démarrage automatique '{target_name}' : {r.stderr.strip()}", flush=True)
return False return False
disable_wifi_powersave(INTERFACE) disable_wifi_powersave(wifi_if)
setup_ap_nat(INTERFACE) setup_ap_nat(wifi_if)
mark_ap_started() mark_ap_started()
else: else:
print(f"[ap-api] Profil Wi-Fi '{db_ssid}' restauré depuis la BDD (démarrage automatique désactivé).", flush=True) print(f"[ap-api] Profil Wi-Fi '{db_ssid}' restauré depuis la BDD (démarrage automatique désactivé).", flush=True)
@@ -7292,28 +7319,8 @@ def parse_packet(raw, ts):
def get_wifi_interface(): def get_wifi_interface():
global INTERFACE global INTERFACE
env_iface = os.environ.get('AP_INTERFACE', '').strip() INTERFACE = detect_wifi_interface()
if env_iface and os.path.exists(f'/sys/class/net/{env_iface}'):
INTERFACE = env_iface
return env_iface
if INTERFACE and os.path.exists(f'/sys/class/net/{INTERFACE}'):
return INTERFACE return INTERFACE
try:
for d in os.listdir('/sys/class/net'):
p = os.path.join('/sys/class/net', d)
if os.path.isdir(os.path.join(p, 'wireless')) or os.path.isdir(os.path.join(p, 'phy80211')):
INTERFACE = d
return d
except Exception: pass
try:
out = subprocess.check_output(['iw', 'dev'], text=True, stderr=subprocess.DEVNULL)
for line in out.splitlines():
parts = line.strip().split()
if len(parts) >= 2 and parts[0] == 'Interface':
INTERFACE = parts[1]
return parts[1]
except Exception: pass
return INTERFACE or 'wls16b1'
def start_capture(target_iface=None): def start_capture(target_iface=None):
global capture_running, capture_thread, capture_pcap_bytes, capture_iface_used, capture_started_at global capture_running, capture_thread, capture_pcap_bytes, capture_iface_used, capture_started_at
@@ -13023,6 +13030,7 @@ class Handler(BaseHTTPRequestHandler):
if is_bridge_mode(): if is_bridge_mode():
b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0')) 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', '')) b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
wifi_if = get_wifi_interface()
if action in ('start', 'restart'): if action in ('start', 'restart'):
db_ssid = (get_pref('ap_ssid', '') or '').strip() db_ssid = (get_pref('ap_ssid', '') or '').strip()
db_pass = get_pref('ap_password', '') or '' db_pass = get_pref('ap_password', '') or ''
@@ -13030,38 +13038,48 @@ class Handler(BaseHTTPRequestHandler):
if not db_ssid or not db_pass: 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') raise RuntimeError('Paramètres Wi-Fi manquants en BDD : veuillez ré-enregistrer les réglages Wi-Fi')
if action == 'restart': if action == 'restart':
stop_hostapd(INTERFACE) stop_hostapd(wifi_if)
time.sleep(0.3) time.sleep(0.3)
setup_bridge(b_name, b_eth) setup_bridge(b_name, b_eth)
start_bridge_hostapd(db_ssid, db_pass, sec=db_sec, bridge_name=b_name, iface=INTERFACE) start_bridge_hostapd(db_ssid, db_pass, sec=db_sec, bridge_name=b_name, iface=wifi_if)
mark_ap_started() mark_ap_started()
elif action == 'stop': elif action == 'stop':
stop_hostapd(INTERFACE) stop_hostapd(wifi_if)
teardown_bridge_dns_redirection(b_name, INTERFACE) teardown_bridge_dns_redirection(b_name, wifi_if)
try: os.remove(UPTIME_FILE) try: os.remove(UPTIME_FILE)
except OSError: pass except OSError: pass
else: else:
wifi_if = get_wifi_interface()
if action in ('start', 'restart'): if action in ('start', 'restart'):
ensure_nm_manages_wifi(INTERFACE) if not name:
nm_exists = bool(name) and (subprocess.run(['nmcli', 'connection', 'show', name], capture_output=True, text=True, timeout=5).returncode == 0) name = connection_name()
if not nm_exists and get_pref('ap_ssid', ''): if not name and get_pref('ap_ssid', ''):
if not restore_ap_from_db(force_start=True): name = 'AP-' + get_pref('ap_ssid', '').strip()
raise RuntimeError('Impossible de restaurer et démarrer la connexion Wi-Fi depuis la BDD') if not name:
else: raise ValueError('Aucune connexion AP configurée')
ensure_nm_manages_wifi(wifi_if)
if action == 'restart': if action == 'restart':
subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True, timeout=10) subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True, timeout=5)
time.sleep(0.5) time.sleep(0.3)
r = subprocess.run(['nmcli', '--wait', '15', 'connection', 'up', name], capture_output=True, text=True, timeout=20)
if r.returncode: # Tentative d'activation directe rapide
print(f"[ap-control] Échec activation '{name}' ({r.stderr.strip()}), tentative de restauration BDD...", flush=True) r = subprocess.run(['nmcli', 'connection', 'up', name, 'ifname', wifi_if], capture_output=True, text=True, timeout=12)
if r.returncode != 0:
# Deuxième tentative sans ifname explicite
r = subprocess.run(['nmcli', 'connection', 'up', name], capture_output=True, text=True, timeout=10)
if r.returncode != 0:
print(f"[ap-control] Échec activation directe '{name}' ({r.stderr.strip()}), restauration via BDD...", flush=True)
if not restore_ap_from_db(force_start=True): if not restore_ap_from_db(force_start=True):
raise RuntimeError(r.stderr.strip() or "Échec de l'activation du point d'accès Wi-Fi") raise RuntimeError(r.stderr.strip() or "Échec de l'activation du point d'accès Wi-Fi")
disable_wifi_powersave(INTERFACE)
setup_ap_nat(INTERFACE) disable_wifi_powersave(wifi_if)
setup_ap_nat(wifi_if)
mark_ap_started() mark_ap_started()
elif action == 'stop': elif action == 'stop':
if name: if name:
r = subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True, timeout=10) r = subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True, timeout=5)
if r.returncode and 'not an active connection' not in r.stderr.lower(): if r.returncode and 'not an active connection' not in r.stderr.lower():
raise RuntimeError(r.stderr.strip()) raise RuntimeError(r.stderr.strip())
teardown_ap_nat() teardown_ap_nat()
+7 -2
View File
@@ -9688,10 +9688,15 @@ ${vpnBadgeTopo}
rstBtn.innerHTML = `<span style="display:inline-flex;animation:spin 1s linear infinite">⚙️</span> <span>${escapeHtml(t('btn_restarting', 'Redémarrage…'))}</span>`; rstBtn.innerHTML = `<span style="display:inline-flex;animation:spin 1s linear infinite">⚙️</span> <span>${escapeHtml(t('btn_restarting', 'Redémarrage…'))}</span>`;
} }
try { try {
const response = await apiFetch('/api/ap/control', { method: 'POST', timeout: 35000, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }) }); const response = await apiFetch('/api/ap/control', { method: 'POST', timeout: 60000, 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, 800)); for (let attempt = 0; attempt < 6; attempt++) {
await new Promise(resolve => setTimeout(resolve, 600));
await load(); await load();
if (action === 'start' && status && status.active) break;
if (action === 'stop' && status && !status.active) break;
if (action === 'restart' && status && status.active) break;
}
} catch (e) { } catch (e) {
alert(tErr(e.message)); alert(tErr(e.message));
} finally { } finally {