AP manageur V1.1 (Bêta)
This commit is contained in:
1 parent
b30639f4ac
commit
ef6961d756
2 files changed
+151
-140
No files matched your search
@@ -113,44 +113,45 @@ def scan_neighboring_wifi_networks(iface=None):
|
|||||||
networks = []
|
networks = []
|
||||||
seen_keys = set()
|
seen_keys = set()
|
||||||
|
|
||||||
# 1. Tentative via nmcli (géré par NetworkManager)
|
# 1. Tentative via nmcli (uniquement si l'interface est activement gérée par NetworkManager)
|
||||||
try:
|
nm_state = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface, timeout=1) or ''
|
||||||
nm_out = command('nmcli', '-t', '-f', 'CHAN,SIGNAL,FREQ,SSID', 'dev', 'wifi', 'list', '--rescan', 'yes')
|
is_nm_managed = bool(nm_state and not nm_state.startswith('10'))
|
||||||
if not nm_out:
|
if is_nm_managed:
|
||||||
nm_out = command('nmcli', '-t', '-f', 'CHAN,SIGNAL,FREQ,SSID', 'dev', 'wifi', 'list')
|
try:
|
||||||
if nm_out:
|
nm_out = command('nmcli', '-t', '-f', 'CHAN,SIGNAL,FREQ,SSID', 'dev', 'wifi', 'list', timeout=2)
|
||||||
for line in nm_out.splitlines():
|
if nm_out:
|
||||||
line = line.strip()
|
for line in nm_out.splitlines():
|
||||||
if not line or ':' not in line:
|
line = line.strip()
|
||||||
continue
|
if not line or ':' not in line:
|
||||||
parts = line.split(':')
|
continue
|
||||||
if len(parts) >= 3:
|
parts = line.split(':')
|
||||||
try:
|
if len(parts) >= 3:
|
||||||
chan_str = parts[0].strip()
|
try:
|
||||||
sig_str = parts[1].strip()
|
chan_str = parts[0].strip()
|
||||||
freq_str = parts[2].strip().replace('MHz', '').strip()
|
sig_str = parts[1].strip()
|
||||||
ssid_str = ':'.join(parts[3:]).strip() if len(parts) > 3 else ''
|
freq_str = parts[2].strip().replace('MHz', '').strip()
|
||||||
if not chan_str.isdigit():
|
ssid_str = ':'.join(parts[3:]).strip() if len(parts) > 3 else ''
|
||||||
continue
|
if not chan_str.isdigit():
|
||||||
chan = int(chan_str)
|
continue
|
||||||
sig_pct = int(sig_str) if sig_str.isdigit() else 50
|
chan = int(chan_str)
|
||||||
sig_dbm = -100.0 + (sig_pct / 2.0)
|
sig_pct = int(sig_str) if sig_str.isdigit() else 50
|
||||||
freq = int(freq_str) if freq_str.isdigit() else (2407 + chan * 5 if chan <= 14 else 5000 + chan * 5)
|
sig_dbm = -100.0 + (sig_pct / 2.0)
|
||||||
key = (chan, freq, round(sig_dbm, 0), ssid_str)
|
freq = int(freq_str) if freq_str.isdigit() else (2407 + chan * 5 if chan <= 14 else 5000 + chan * 5)
|
||||||
if key not in seen_keys:
|
key = (chan, freq, round(sig_dbm, 0), ssid_str)
|
||||||
seen_keys.add(key)
|
if key not in seen_keys:
|
||||||
networks.append({'channel': chan, 'freq': freq, 'signal_dbm': sig_dbm, 'ssid': ssid_str})
|
seen_keys.add(key)
|
||||||
except Exception:
|
networks.append({'channel': chan, 'freq': freq, 'signal_dbm': sig_dbm, 'ssid': ssid_str})
|
||||||
pass
|
except Exception:
|
||||||
except Exception as e:
|
pass
|
||||||
print(f"[ap-wifi] [Auto-Channel] Scan nmcli indisponible : {e}", flush=True)
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
|
||||||
# 2. Si nmcli n'a rien retourné (ex: carte hors NM à cet instant), tenter iw
|
# 2. Si nmcli n'a rien retourné (ex: carte hors NM à cet instant), tenter iw
|
||||||
if not networks and iface:
|
if not networks and iface:
|
||||||
try:
|
try:
|
||||||
iw_out = command('iw', 'dev', iface, 'scan')
|
iw_out = command('iw', 'dev', iface, 'scan', 'dump', timeout=1)
|
||||||
if not iw_out:
|
if not iw_out and is_iface_up(iface) and not is_hostapd_running():
|
||||||
iw_out = command('iw', 'dev', iface, 'scan', 'dump')
|
iw_out = command('iw', 'dev', iface, 'scan', timeout=2)
|
||||||
if iw_out:
|
if iw_out:
|
||||||
curr_net = {}
|
curr_net = {}
|
||||||
for line in iw_out.splitlines():
|
for line in iw_out.splitlines():
|
||||||
@@ -3806,8 +3807,8 @@ def clean_stale_router_leases():
|
|||||||
c.commit(); c.close()
|
c.commit(); c.close()
|
||||||
except Exception: pass
|
except Exception: pass
|
||||||
try:
|
try:
|
||||||
subprocess.run(['ip', 'neigh', 'flush', 'to', '10.42.0.0/16'], capture_output=True)
|
subprocess.run(['ip', 'neigh', 'flush', 'to', '10.42.0.0/16'], capture_output=True, timeout=2)
|
||||||
subprocess.run(['ip', 'neigh', 'flush', 'dev', INTERFACE], capture_output=True)
|
subprocess.run(['ip', 'neigh', 'flush', 'dev', INTERFACE], capture_output=True, timeout=2)
|
||||||
except Exception: pass
|
except Exception: pass
|
||||||
|
|
||||||
def find_bin(name):
|
def find_bin(name):
|
||||||
@@ -3856,16 +3857,19 @@ def teardown_bridge_dns_redirection(bridge_name='br0', iface=None):
|
|||||||
for ipt in [b for b in (find_bin('iptables'),) if b]:
|
for ipt in [b for b in (find_bin('iptables'),) if b]:
|
||||||
for proto in ('udp', 'tcp'):
|
for proto in ('udp', 'tcp'):
|
||||||
if iface:
|
if iface:
|
||||||
while subprocess.run([ipt, '-w', '2', '-t', 'nat', '-D', 'PREROUTING', '-i', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS'], capture_output=True).returncode == 0:
|
for _ in range(5):
|
||||||
pass
|
r = subprocess.run([ipt, '-w', '2', '-t', 'nat', '-D', 'PREROUTING', '-i', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS'], capture_output=True, timeout=2)
|
||||||
while subprocess.run([ipt, '-w', '2', '-t', 'nat', '-D', 'PREROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS'], capture_output=True).returncode == 0:
|
if r.returncode != 0: break
|
||||||
pass
|
for _ in range(5):
|
||||||
while subprocess.run([ipt, '-w', '2', '-t', 'nat', '-D', 'POSTROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS_POST'], capture_output=True).returncode == 0:
|
r = subprocess.run([ipt, '-w', '2', '-t', 'nat', '-D', 'PREROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS'], capture_output=True, timeout=2)
|
||||||
pass
|
if r.returncode != 0: break
|
||||||
subprocess.run([ipt, '-w', '2', '-t', 'nat', '-F', 'AP_BRIDGE_DNS'], capture_output=True)
|
for _ in range(5):
|
||||||
subprocess.run([ipt, '-w', '2', '-t', 'nat', '-X', 'AP_BRIDGE_DNS'], capture_output=True)
|
r = subprocess.run([ipt, '-w', '2', '-t', 'nat', '-D', 'POSTROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS_POST'], capture_output=True, timeout=2)
|
||||||
subprocess.run([ipt, '-w', '2', '-t', 'nat', '-F', 'AP_BRIDGE_DNS_POST'], capture_output=True)
|
if r.returncode != 0: break
|
||||||
subprocess.run([ipt, '-w', '2', '-t', 'nat', '-X', 'AP_BRIDGE_DNS_POST'], capture_output=True)
|
subprocess.run([ipt, '-w', '2', '-t', 'nat', '-F', 'AP_BRIDGE_DNS'], capture_output=True, timeout=2)
|
||||||
|
subprocess.run([ipt, '-w', '2', '-t', 'nat', '-X', 'AP_BRIDGE_DNS'], capture_output=True, timeout=2)
|
||||||
|
subprocess.run([ipt, '-w', '2', '-t', 'nat', '-F', 'AP_BRIDGE_DNS_POST'], capture_output=True, timeout=2)
|
||||||
|
subprocess.run([ipt, '-w', '2', '-t', 'nat', '-X', 'AP_BRIDGE_DNS_POST'], capture_output=True, timeout=2)
|
||||||
# Ne toucher à ebtables que si le module ebtable_broute est déjà chargé en mémoire
|
# Ne toucher à ebtables que si le module ebtable_broute est déjà chargé en mémoire
|
||||||
if os.path.exists('/sys/module/ebtable_broute') and iface:
|
if os.path.exists('/sys/module/ebtable_broute') and iface:
|
||||||
for proto in ('udp', 'tcp'):
|
for proto in ('udp', 'tcp'):
|
||||||
@@ -3975,14 +3979,16 @@ def teardown_ap_nat():
|
|||||||
continue
|
continue
|
||||||
seen.add(rp)
|
seen.add(rp)
|
||||||
try:
|
try:
|
||||||
while subprocess.run([candidate, '-w', '5', '-D', 'FORWARD', '-j', 'AP_NAT_FORWARD'], capture_output=True).returncode == 0:
|
for _ in range(5):
|
||||||
pass
|
r = subprocess.run([candidate, '-w', '2', '-D', 'FORWARD', '-j', 'AP_NAT_FORWARD'], capture_output=True, timeout=2)
|
||||||
subprocess.run([candidate, '-w', '5', '-F', 'AP_NAT_FORWARD'], capture_output=True)
|
if r.returncode != 0: break
|
||||||
subprocess.run([candidate, '-w', '5', '-X', 'AP_NAT_FORWARD'], capture_output=True)
|
subprocess.run([candidate, '-w', '2', '-F', 'AP_NAT_FORWARD'], capture_output=True, timeout=2)
|
||||||
while subprocess.run([candidate, '-w', '5', '-t', 'nat', '-D', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True).returncode == 0:
|
subprocess.run([candidate, '-w', '2', '-X', 'AP_NAT_FORWARD'], capture_output=True, timeout=2)
|
||||||
pass
|
for _ in range(5):
|
||||||
subprocess.run([candidate, '-w', '5', '-t', 'nat', '-F', 'AP_NAT_POST'], capture_output=True)
|
r = subprocess.run([candidate, '-w', '2', '-t', 'nat', '-D', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True, timeout=2)
|
||||||
subprocess.run([candidate, '-w', '5', '-t', 'nat', '-X', 'AP_NAT_POST'], capture_output=True)
|
if r.returncode != 0: break
|
||||||
|
subprocess.run([candidate, '-w', '2', '-t', 'nat', '-F', 'AP_NAT_POST'], capture_output=True, timeout=2)
|
||||||
|
subprocess.run([candidate, '-w', '2', '-t', 'nat', '-X', 'AP_NAT_POST'], capture_output=True, timeout=2)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -4000,7 +4006,7 @@ def is_hostapd_running():
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
try:
|
try:
|
||||||
r = subprocess.run(['pgrep', '-f', HOSTAPD_CONF_FILE], capture_output=True, text=True)
|
r = subprocess.run(['pgrep', '-f', HOSTAPD_CONF_FILE], capture_output=True, text=True, timeout=1)
|
||||||
return r.returncode == 0 and bool(r.stdout.strip())
|
return r.returncode == 0 and bool(r.stdout.strip())
|
||||||
except Exception:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
@@ -4013,10 +4019,10 @@ def stop_hostapd(iface=None):
|
|||||||
try:
|
try:
|
||||||
pid = int(open(HOSTAPD_PID_FILE).read().strip())
|
pid = int(open(HOSTAPD_PID_FILE).read().strip())
|
||||||
os.kill(pid, signal.SIGTERM)
|
os.kill(pid, signal.SIGTERM)
|
||||||
for _ in range(15):
|
for _ in range(10):
|
||||||
try:
|
try:
|
||||||
os.kill(pid, 0)
|
os.kill(pid, 0)
|
||||||
time.sleep(0.1)
|
time.sleep(0.05)
|
||||||
except OSError:
|
except OSError:
|
||||||
break
|
break
|
||||||
try:
|
try:
|
||||||
@@ -4027,11 +4033,20 @@ def stop_hostapd(iface=None):
|
|||||||
pass
|
pass
|
||||||
try: os.remove(HOSTAPD_PID_FILE)
|
try: os.remove(HOSTAPD_PID_FILE)
|
||||||
except OSError: pass
|
except OSError: pass
|
||||||
subprocess.run(['pkill', '-f', HOSTAPD_CONF_FILE], capture_output=True)
|
subprocess.run(['pkill', '-f', HOSTAPD_CONF_FILE], capture_output=True, timeout=2)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
try:
|
||||||
|
if os.path.exists(HOSTAPD_PID_FILE):
|
||||||
|
os.remove(HOSTAPD_PID_FILE)
|
||||||
|
except OSError: pass
|
||||||
if iface:
|
if iface:
|
||||||
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True)
|
try:
|
||||||
|
ctrl_sock = f'/run/hostapd/{iface}'
|
||||||
|
if os.path.exists(ctrl_sock):
|
||||||
|
os.remove(ctrl_sock)
|
||||||
|
except OSError: pass
|
||||||
|
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True, timeout=2)
|
||||||
|
|
||||||
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."""
|
||||||
@@ -4069,42 +4084,41 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No
|
|||||||
if not os.path.exists(f'/sys/class/net/{bridge_name}'):
|
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.")
|
raise RuntimeError(f"Le pont réseau '{bridge_name}' n'existe pas sur le système.")
|
||||||
|
|
||||||
# 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 wlan0
|
||||||
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, timeout=1) or '').startswith('10')
|
||||||
subprocess.run(['nmcli', '--wait', '2', 'device', 'disconnect', iface], capture_output=True, timeout=3)
|
|
||||||
subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'no'], capture_output=True, timeout=3)
|
|
||||||
for _ in range(15):
|
|
||||||
st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface)
|
|
||||||
if not st or st.startswith('10'): # 10 = unmanaged
|
|
||||||
break
|
|
||||||
time.sleep(0.1)
|
|
||||||
# Arrêter wpa_supplicant afin qu'il ne bloque jamais les trames EAPOL de hostapd
|
|
||||||
if was_managed:
|
if was_managed:
|
||||||
time.sleep(0.2)
|
subprocess.run(['nmcli', '--wait', '2', 'device', 'disconnect', iface], capture_output=True, timeout=2)
|
||||||
subprocess.run(['pkill', '-x', 'wpa_supplicant'], capture_output=True)
|
subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'no'], capture_output=True, timeout=2)
|
||||||
for _ in range(10):
|
for _ in range(10):
|
||||||
if subprocess.run(['pgrep', '-x', 'wpa_supplicant'], capture_output=True).returncode != 0:
|
st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface, timeout=1)
|
||||||
|
if not st or st.startswith('10'): # 10 = unmanaged
|
||||||
break
|
break
|
||||||
time.sleep(0.1)
|
time.sleep(0.05)
|
||||||
time.sleep(0.1)
|
# Arrêter wpa_supplicant afin qu'il ne bloque jamais les trames EAPOL de hostapd
|
||||||
|
subprocess.run(['pkill', '-x', 'wpa_supplicant'], capture_output=True, timeout=2)
|
||||||
|
for _ in range(5):
|
||||||
|
if subprocess.run(['pgrep', '-x', 'wpa_supplicant'], capture_output=True, timeout=1).returncode != 0:
|
||||||
|
break
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
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, timeout=2)
|
||||||
subprocess.run(['iw', 'reg', 'set', country], capture_output=True)
|
subprocess.run(['iw', 'reg', 'set', country], capture_output=True, timeout=2)
|
||||||
# Cycle complet DOWN -> managed -> UP -> DOWN pour vider l'ancien BSS/table de clés du firmware
|
# Cycle rapide 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, timeout=2)
|
||||||
subprocess.run(['ip', 'addr', 'flush', 'dev', iface], capture_output=True)
|
subprocess.run(['ip', 'addr', 'flush', 'dev', iface], capture_output=True, timeout=2)
|
||||||
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True)
|
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True, timeout=2)
|
||||||
subprocess.run(['iw', 'dev', iface, 'set', 'type', 'managed'], capture_output=True)
|
subprocess.run(['iw', 'dev', iface, 'set', 'type', 'managed'], capture_output=True, timeout=2)
|
||||||
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True)
|
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True, timeout=2)
|
||||||
time.sleep(0.15)
|
time.sleep(0.1)
|
||||||
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
|
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True, timeout=2)
|
||||||
time.sleep(0.15)
|
time.sleep(0.1)
|
||||||
|
|
||||||
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'
|
||||||
channel = str(get_effective_ap_channel(band)).strip()
|
# Utiliser le canal effectif (sans re-scan lourd au démarrage)
|
||||||
|
channel = str(get_effective_ap_channel(band, force_rescan=False)).strip()
|
||||||
sec_norm = (sec or 'wpa2').lower()
|
sec_norm = (sec or 'wpa2').lower()
|
||||||
|
|
||||||
def _build_conf(enable_ht=True):
|
def _build_conf(enable_ht=True):
|
||||||
@@ -4162,9 +4176,15 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No
|
|||||||
os.chmod(HOSTAPD_CONF_FILE, 0o600)
|
os.chmod(HOSTAPD_CONF_FILE, 0o600)
|
||||||
try: os.remove(HOSTAPD_LOG_FILE)
|
try: os.remove(HOSTAPD_LOG_FILE)
|
||||||
except OSError: pass
|
except OSError: pass
|
||||||
|
try:
|
||||||
|
ctrl_sock = f'/run/hostapd/{iface}'
|
||||||
|
if os.path.exists(ctrl_sock):
|
||||||
|
os.remove(ctrl_sock)
|
||||||
|
except OSError: pass
|
||||||
|
|
||||||
r = subprocess.run(
|
r = subprocess.run(
|
||||||
[hostapd_bin, '-B', '-P', HOSTAPD_PID_FILE, '-f', HOSTAPD_LOG_FILE, HOSTAPD_CONF_FILE],
|
[hostapd_bin, '-B', '-P', HOSTAPD_PID_FILE, '-f', HOSTAPD_LOG_FILE, HOSTAPD_CONF_FILE],
|
||||||
capture_output=True, text=True, timeout=15
|
capture_output=True, text=True, timeout=5
|
||||||
)
|
)
|
||||||
if r.returncode != 0:
|
if r.returncode != 0:
|
||||||
err = (r.stderr or r.stdout or '').strip()
|
err = (r.stderr or r.stdout or '').strip()
|
||||||
@@ -4177,42 +4197,31 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No
|
|||||||
except OSError:
|
except OSError:
|
||||||
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
|
|
||||||
for _ in range(25):
|
for _ in range(20):
|
||||||
time.sleep(0.15)
|
time.sleep(0.1)
|
||||||
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', timeout=1) or ''
|
||||||
has_master = os.path.exists(f'/sys/class/net/{iface}/master')
|
has_master = os.path.exists(f'/sys/class/net/{iface}/master')
|
||||||
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 'AP-ENABLED' in log_txt and 'type AP' in iw_out:
|
if 'AP-DISABLED' in log_txt:
|
||||||
|
return False, 'Interface AP désactivée par hostapd'
|
||||||
|
# Dès que hostapd est actif et que iw confirme le type AP
|
||||||
|
if 'type AP' in iw_out or 'AP-ENABLED' in log_txt:
|
||||||
if not has_master:
|
if not has_master:
|
||||||
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'master', bridge_name], capture_output=True)
|
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'master', bridge_name], capture_output=True, timeout=2)
|
||||||
has_master = os.path.exists(f'/sys/class/net/{iface}/master')
|
|
||||||
if has_master:
|
|
||||||
ap_ready = True
|
|
||||||
break
|
|
||||||
if ap_ready:
|
|
||||||
time.sleep(0.2)
|
|
||||||
iw_out = command('iw', 'dev', iface, 'info') or ''
|
|
||||||
log_txt = ''
|
|
||||||
if os.path.exists(HOSTAPD_LOG_FILE):
|
|
||||||
try: log_txt = open(HOSTAPD_LOG_FILE, encoding='utf-8', errors='replace').read()
|
|
||||||
except OSError: pass
|
|
||||||
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'
|
|
||||||
if is_hostapd_running():
|
if is_hostapd_running():
|
||||||
iw_out = command('iw', 'dev', iface, 'info') or ''
|
iw_out = command('iw', 'dev', iface, 'info', timeout=1) or ''
|
||||||
if 'type AP' in iw_out:
|
if 'type AP' in iw_out:
|
||||||
if not os.path.exists(f'/sys/class/net/{iface}/master'):
|
if not os.path.exists(f'/sys/class/net/{iface}/master'):
|
||||||
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'master', bridge_name], capture_output=True)
|
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'master', bridge_name], capture_output=True, timeout=2)
|
||||||
disable_wifi_powersave(iface)
|
disable_wifi_powersave(iface)
|
||||||
return True, ''
|
return True, ''
|
||||||
return False, 'hostapd démarré mais interface non passée en mode AP'
|
return False, 'hostapd démarré mais interface non passée en mode AP'
|
||||||
@@ -4224,23 +4233,17 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No
|
|||||||
|
|
||||||
ok, err = _try_launch(enable_ht=True)
|
ok, err = _try_launch(enable_ht=True)
|
||||||
if not ok:
|
if not ok:
|
||||||
print(f"[ap-bridge] 1er démarrage hostapd incomplet ({err}), relance propre...", flush=True)
|
print(f"[ap-bridge] hostapd (802.11n) incomplet ({err}), tentative de repli 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, timeout=2)
|
||||||
time.sleep(0.3)
|
time.sleep(0.2)
|
||||||
ok, err2 = _try_launch(enable_ht=True)
|
ok, err2 = _try_launch(enable_ht=False)
|
||||||
if not ok:
|
if not ok:
|
||||||
print(f"[ap-bridge] hostapd (802.11n) a échoué ({err2}), nouvelle tentative sans 802.11n...", flush=True)
|
raise RuntimeError(f"Impossible de démarrer le point d'accès en mode Pont (hostapd) : {err2 or err}")
|
||||||
stop_hostapd(iface)
|
|
||||||
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
|
|
||||||
time.sleep(0.2)
|
|
||||||
ok, err3 = _try_launch(enable_ht=False)
|
|
||||||
if not ok:
|
|
||||||
raise RuntimeError(f"Impossible de démarrer le point d'accès en mode Pont (hostapd) : {err3 or err2 or err}")
|
|
||||||
|
|
||||||
# Appliquer la configuration DNS du mode pont (hôte systemd-resolved + nettoyage broute)
|
# Appliquer la configuration DNS du mode pont (hôte systemd-resolved + nettoyage broute)
|
||||||
setup_bridge_dns_redirection(bridge_name, iface)
|
setup_bridge_dns_redirection(bridge_name, iface)
|
||||||
time.sleep(0.3)
|
time.sleep(0.2)
|
||||||
sync_host_resolved_bridge_dns(bridge_name)
|
sync_host_resolved_bridge_dns(bridge_name)
|
||||||
print(f"[ap-bridge] Point d'accès Pont actif via hostapd sur {iface} -> {bridge_name} (SSID='{ssid}', sécurité={sec_norm})", flush=True)
|
print(f"[ap-bridge] Point d'accès Pont actif via hostapd sur {iface} -> {bridge_name} (SSID='{ssid}', sécurité={sec_norm})", flush=True)
|
||||||
|
|
||||||
@@ -4383,27 +4386,33 @@ def setup_bridge(bridge_name='br0', bridge_eth=None):
|
|||||||
# Si le pont n'existe pas encore au niveau noyau, le créer directement via iproute2 (sans profil NetworkManager)
|
# Si le pont n'existe pas encore au niveau noyau, le créer directement via iproute2 (sans profil NetworkManager)
|
||||||
if not bridge_already_existed:
|
if not bridge_already_existed:
|
||||||
print(f"[ap-bridge] Création sécurisée du pont noyau {bridge_name}...", flush=True)
|
print(f"[ap-bridge] Création sécurisée du pont noyau {bridge_name}...", flush=True)
|
||||||
subprocess.run(['ip', 'link', 'add', 'name', bridge_name, 'type', 'bridge'], capture_output=True)
|
subprocess.run(['ip', 'link', 'add', 'name', bridge_name, 'type', 'bridge', 'forward_delay', '0', 'stp_state', '0'], capture_output=True, timeout=2)
|
||||||
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
|
||||||
|
else:
|
||||||
|
# S'assurer que le pont transmet immédiatement les paquets sans délai STP (forward_delay 0)
|
||||||
|
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'type', 'bridge', 'forward_delay', '0', 'stp_state', '0'], capture_output=True, timeout=2)
|
||||||
|
|
||||||
# Asservir l'Ethernet physique au pont pour relier le Wi-Fi au réseau local et au DHCP de la box
|
# 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}'):
|
if bridge_eth and os.path.exists(f'/sys/class/net/{bridge_eth}'):
|
||||||
subprocess.run(['ip', 'link', 'set', 'dev', bridge_eth, 'up'], capture_output=True)
|
subprocess.run(['ip', 'link', 'set', 'dev', bridge_eth, 'up'], capture_output=True, timeout=2)
|
||||||
if eth_master != bridge_name:
|
if eth_master != bridge_name:
|
||||||
ip_cidr, gw, mac = get_iface_ip_info(bridge_eth)
|
ip_cidr, gw, mac = get_iface_ip_info(bridge_eth)
|
||||||
migrated_gw = gw
|
migrated_gw = gw
|
||||||
if mac and not has_bridge_ip:
|
if mac and not has_bridge_ip:
|
||||||
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'address', mac], capture_output=True)
|
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'address', mac], capture_output=True, timeout=2)
|
||||||
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'up'], capture_output=True)
|
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'up'], capture_output=True, timeout=2)
|
||||||
subprocess.run(['ip', 'link', 'set', 'dev', bridge_eth, 'master', bridge_name], capture_output=True)
|
subprocess.run(['ip', 'link', 'set', 'dev', bridge_eth, 'master', bridge_name], capture_output=True, timeout=2)
|
||||||
if ip_cidr and not has_bridge_ip:
|
if ip_cidr and not has_bridge_ip:
|
||||||
subprocess.run(['ip', 'addr', 'flush', 'dev', bridge_eth], capture_output=True)
|
# Ajouter l'IP au pont AVANT de flusher bridge_eth pour ne jamais couper les connexions TCP
|
||||||
subprocess.run(['ip', 'addr', 'add', ip_cidr, 'dev', bridge_name], capture_output=True)
|
subprocess.run(['ip', 'addr', 'add', ip_cidr, 'dev', bridge_name], capture_output=True, timeout=2)
|
||||||
if gw:
|
if gw:
|
||||||
subprocess.run(['ip', 'route', 'replace', 'default', 'via', gw, 'dev', bridge_name], capture_output=True)
|
subprocess.run(['ip', 'route', 'replace', 'default', 'via', gw, 'dev', bridge_name], capture_output=True, timeout=2)
|
||||||
|
clean_ip = ip_cidr.split('/')[0]
|
||||||
|
subprocess.run(['arping', '-c', '1', '-A', '-I', bridge_name, clean_ip], capture_output=True, timeout=2)
|
||||||
|
subprocess.run(['ip', 'addr', 'flush', 'dev', bridge_eth], capture_output=True, timeout=2)
|
||||||
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)
|
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:
|
else:
|
||||||
print(f"[ap-bridge] Ethernet {bridge_eth} asservi à {bridge_name}.", flush=True)
|
print(f"[ap-bridge] Ethernet {bridge_eth} asservi à {bridge_name}.", flush=True)
|
||||||
@@ -4413,22 +4422,22 @@ def setup_bridge(bridge_name='br0', bridge_eth=None):
|
|||||||
cur_mac = open(f'{bridge_path}/address').read().strip()
|
cur_mac = open(f'{bridge_path}/address').read().strip()
|
||||||
assign_type = open(f'{bridge_path}/addr_assign_type').read().strip()
|
assign_type = open(f'{bridge_path}/addr_assign_type').read().strip()
|
||||||
if cur_mac and assign_type != '3':
|
if cur_mac and assign_type != '3':
|
||||||
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, timeout=2)
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
if not is_iface_up(bridge_name):
|
if not is_iface_up(bridge_name):
|
||||||
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'up'], capture_output=True)
|
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'up'], capture_output=True, timeout=2)
|
||||||
|
|
||||||
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, timeout=2)
|
||||||
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, '-j', 'ACCEPT'], capture_output=True).returncode != 0:
|
if subprocess.run([ipt, '-w', '2', '-C', 'FORWARD', '-i', bridge_name, '-j', 'ACCEPT'], capture_output=True, timeout=2).returncode != 0:
|
||||||
subprocess.run([ipt, '-w', '5', '-I', 'FORWARD', '1', '-i', bridge_name, '-j', 'ACCEPT'], capture_output=True)
|
subprocess.run([ipt, '-w', '2', '-I', 'FORWARD', '1', '-i', bridge_name, '-j', 'ACCEPT'], capture_output=True, timeout=2)
|
||||||
if subprocess.run([ipt, '-w', '5', '-C', 'FORWARD', '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True).returncode != 0:
|
if subprocess.run([ipt, '-w', '2', '-C', 'FORWARD', '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True, timeout=2).returncode != 0:
|
||||||
subprocess.run([ipt, '-w', '5', '-I', 'FORWARD', '1', '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True)
|
subprocess.run([ipt, '-w', '2', '-I', 'FORWARD', '1', '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True, timeout=2)
|
||||||
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)
|
||||||
|
|
||||||
|
|||||||
+5
-3
@@ -9704,13 +9704,15 @@ ${vpnBadgeTopo}
|
|||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (!response.ok) throw Error(data.error || 'Action refusée');
|
if (!response.ok) throw Error(data.error || 'Action refusée');
|
||||||
|
|
||||||
for (let attempt = 0; attempt < 12; attempt++) {
|
for (let attempt = 0; attempt < 25; attempt++) {
|
||||||
await new Promise(resolve => setTimeout(resolve, 800));
|
await new Promise(resolve => setTimeout(resolve, 800));
|
||||||
await load();
|
try {
|
||||||
|
await load();
|
||||||
|
} catch (_) {}
|
||||||
if (action === 'start' && status && status.active) break;
|
if (action === 'start' && status && status.active) break;
|
||||||
if (action === 'stop' && status && !status.active) break;
|
if (action === 'stop' && status && !status.active) break;
|
||||||
if (action === 'restart') {
|
if (action === 'restart') {
|
||||||
if (attempt >= 1 && status && status.active) break;
|
if (attempt >= 2 && status && status.active) break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
Reference in new issue
Block a user