AP manageur V1.1 (Bêta)

This commit is contained in:
yoannmultigaming committed 2026-11-25 16:33:04 +01:00
1 parent 25934624ea
commit cf611c584c
5 files changed
+223 -108

No files matched your search

+177 -93
View File
@@ -504,18 +504,23 @@ def parse_netbios_response(data):
return '' return ''
def quick_reverse_dns(ip): def quick_reverse_dns(ip):
"""Résolution DNS inverse rapide (les box internet Freebox/Livebox/etc. enregistrent les noms d'hôtes).""" """Résolution DNS inverse rapide et sécurisée en tâche de fond (timeout strict 0.3s) pour ne jamais bloquer l'API."""
if not ip or ip in ('Non attribuée', '—', '127.0.0.1') or ip.startswith(('0.', '169.254.', '255.')): if not ip or ip in ('Non attribuée', '—', '127.0.0.1') or ip.startswith(('0.', '169.254.', '255.')):
return '' return ''
res_container = []
def _worker():
try: try:
res = socket.getnameinfo((ip, 0), socket.NI_NAMEREQD) res = socket.getnameinfo((ip, 0), socket.NI_NAMEREQD)
if res and res[0]: if res and res[0]:
cleaned = clean_extracted_hostname(res[0]) cleaned = clean_extracted_hostname(res[0])
if cleaned: if cleaned:
return cleaned res_container.append(cleaned)
except Exception: except Exception:
pass pass
return '' t = threading.Thread(target=_worker, daemon=True)
t.start()
t.join(timeout=0.3)
return res_container[0] if res_container else ''
def query_netbios_name(ip): def query_netbios_name(ip):
"""Interroge le nom NetBIOS d'un client Windows / NAS / Samba sur UDP 137.""" """Interroge le nom NetBIOS d'un client Windows / NAS / Samba sur UDP 137."""
@@ -1325,15 +1330,30 @@ def parse_browser(user_agent):
return 'Safari' + (' ' + m.group(1).split('.')[0] if m else '') return 'Safari' + (' ' + m.group(1).split('.')[0] if m else '')
return 'Navigateur Web' return 'Navigateur Web'
_device_name_ip_cache = {}
_device_name_ip_cache_lock = threading.Lock()
def resolve_device_name(ip): def resolve_device_name(ip):
if not ip or ip in ('127.0.0.1', '::1', 'localhost', 'Non attribuée', '—'): if not ip or ip in ('127.0.0.1', '::1', 'localhost', 'Non attribuée', '—'):
return 'Serveur local' return 'Serveur local'
now = time.time()
with _device_name_ip_cache_lock:
if ip in _device_name_ip_cache:
name, exp = _device_name_ip_cache[ip]
if now < exp:
return name
name = None
try: try:
c = db() c = db()
row = c.execute('SELECT name FROM client_names WHERE last_ip=?', (ip,)).fetchone() row = c.execute('SELECT name FROM client_names WHERE last_ip=?', (ip,)).fetchone()
c.close() c.close()
if row and row[0]: return row[0] if row and row[0] and row[0] != 'Nom non communiqué':
except Exception: pass name = row[0]
except Exception:
pass
if not name:
for lease_file in ['/var/lib/misc/dnsmasq.leases', '/tmp/dnsmasq.leases']: for lease_file in ['/var/lib/misc/dnsmasq.leases', '/tmp/dnsmasq.leases']:
try: try:
if os.path.exists(lease_file): if os.path.exists(lease_file):
@@ -1341,18 +1361,38 @@ def resolve_device_name(ip):
for line in f: for line in f:
parts = line.strip().split() parts = line.strip().split()
if len(parts) >= 4 and parts[2] == ip and parts[3] != '*': if len(parts) >= 4 and parts[2] == ip and parts[3] != '*':
return parts[3] name = parts[3]
except Exception: pass break
if name:
break
except Exception:
pass
if not name:
try: try:
name = socket.gethostbyaddr(ip)[0] if os.path.exists('/proc/net/arp'):
if name and name != ip: return name.split('.')[0] with open('/proc/net/arp', 'r', encoding='utf-8', errors='ignore') as f:
except Exception: pass for line in f:
try: parts = line.strip().split()
host_line = command('ip', 'neigh', 'show', ip) if len(parts) >= 4 and parts[0] == ip:
m = re.search(r'\(([^)]+)\)', host_line) arp_mac = parts[3].upper()
if m and m.group(1) != ip: return m.group(1) if is_valid_mac(arp_mac):
except Exception: pass dname = device_name(ip, arp_mac)
return f"Machine ({ip})" if dname and not dname.startswith(('Client ', 'Appareil ', 'Équipement ')):
name = dname
break
except Exception:
pass
if not name:
rdns = quick_reverse_dns(ip)
if rdns:
name = rdns
final_name = name or f"Machine ({ip})"
with _device_name_ip_cache_lock:
_device_name_ip_cache[ip] = (final_name, now + 300)
return final_name
def new_session(username, ip='', ua='', custom_name=''): def new_session(username, ip='', ua='', custom_name=''):
token = secrets.token_urlsafe(32) token = secrets.token_urlsafe(32)
@@ -1501,7 +1541,15 @@ def list_sessions(current_token='', lang='fr'):
browser_name = parse_browser(ua) browser_name = parse_browser(ua)
if not dev_name or dev_name.startswith('Machine ('): if not dev_name or dev_name.startswith('Machine ('):
resolved = resolve_device_name(ip) resolved = resolve_device_name(ip)
if resolved: dev_name = resolved if resolved:
dev_name = resolved
if not dev_name.startswith('Machine ('):
try:
c_u = db()
c_u.execute('UPDATE auth_sessions SET device_name=? WHERE token=?', (dev_name, token))
c_u.commit(); c_u.close()
except Exception:
pass
is_current = bool(current_token and token == current_token) is_current = bool(current_token and token == current_token)
res.append({ res.append({
'token': token, 'token': token,
@@ -3846,30 +3894,38 @@ def run_cmd(*args):
except Exception: except Exception:
return None return None
def _ipt_has_chain(ipt, table, chain):
try:
r = subprocess.run([ipt, '-t', table, '-n', '-L', chain], capture_output=True, timeout=1)
return r.returncode == 0
except Exception:
return False
def _ipt_del_jump(ipt, table, parent_chain, target_chain):
try:
for _ in range(10):
r = subprocess.run([ipt, '-t', table, '-D', parent_chain, '-j', target_chain], capture_output=True, timeout=1)
if r.returncode != 0:
break
except Exception:
pass
def setup_bridge_dns_redirection(bridge_name='br0', iface=None): def setup_bridge_dns_redirection(bridge_name='br0', iface=None):
"""En mode pont L2, laisse le trafic DNS passer nativement sur le pont vers la box sans broute/ebtables (préserve le DNS de l'hôte et des clients).""" """En mode pont L2, laisse le trafic DNS passer nativement sur le pont vers la box sans broute/ebtables (préserve le DNS de l'hôte et des clients)."""
teardown_bridge_dns_redirection(bridge_name, iface) teardown_bridge_dns_redirection(bridge_name, iface)
def teardown_bridge_dns_redirection(bridge_name='br0', iface=None): def teardown_bridge_dns_redirection(bridge_name='br0', iface=None):
"""Nettoie d'éventuelles règles résiduelles AP_BRIDGE_DNS sans jamais utiliser -m physdev (qui chargerait br_netfilter).""" """Nettoie d'éventuelles règles résiduelles AP_BRIDGE_DNS instantanément sans jamais bloquer l'API."""
iface = iface or INTERFACE iface = iface or INTERFACE
try: try:
for ipt in [b for b in (find_bin('iptables'),) if b]: ipt = find_bin('iptables')
for proto in ('udp', 'tcp'): if ipt:
if iface: for ch in ('AP_BRIDGE_DNS', 'AP_BRIDGE_DNS_POST'):
for _ in range(5): if _ipt_has_chain(ipt, 'nat', ch):
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) _ipt_del_jump(ipt, 'nat', 'PREROUTING', ch)
if r.returncode != 0: break _ipt_del_jump(ipt, 'nat', 'POSTROUTING', ch)
for _ in range(5): subprocess.run([ipt, '-t', 'nat', '-F', ch], capture_output=True, timeout=1)
r = subprocess.run([ipt, '-w', '2', '-t', 'nat', '-D', 'PREROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS'], capture_output=True, timeout=2) subprocess.run([ipt, '-t', 'nat', '-X', ch], capture_output=True, timeout=1)
if r.returncode != 0: break
for _ in range(5):
r = subprocess.run([ipt, '-w', '2', '-t', 'nat', '-D', 'POSTROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS_POST'], capture_output=True, timeout=2)
if r.returncode != 0: break
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'):
@@ -3886,7 +3942,7 @@ def _ap_iptables_bins():
legacy_bin = find_bin('iptables-legacy') legacy_bin = find_bin('iptables-legacy')
if legacy_bin and os.path.realpath(legacy_bin) != os.path.realpath(default_bin or ''): if legacy_bin and os.path.realpath(legacy_bin) != os.path.realpath(default_bin or ''):
try: try:
r = subprocess.run([legacy_bin, '-S', 'FORWARD'], capture_output=True, text=True, timeout=2) r = subprocess.run([legacy_bin, '-S', 'FORWARD'], capture_output=True, text=True, timeout=1)
if r.returncode == 0 and ('-P FORWARD DROP' in r.stdout or 'DOCKER' in r.stdout): if r.returncode == 0 and ('-P FORWARD DROP' in r.stdout or 'DOCKER' in r.stdout):
bins.append(legacy_bin) bins.append(legacy_bin)
except Exception: except Exception:
@@ -3897,7 +3953,7 @@ def _get_ap_subnet(iface):
"""Détecte le sous-réseau IPv4 actif de l'interface AP (ex. 10.42.0.0/24).""" """Détecte le sous-réseau IPv4 actif de l'interface AP (ex. 10.42.0.0/24)."""
try: try:
import ipaddress import ipaddress
r = subprocess.run(['ip', '-4', '-o', 'addr', 'show', 'dev', iface], capture_output=True, text=True, timeout=2) r = subprocess.run(['ip', '-4', '-o', 'addr', 'show', 'dev', iface], capture_output=True, text=True, timeout=1)
if r.returncode == 0: if r.returncode == 0:
m = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+/\d+)', r.stdout) m = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+/\d+)', r.stdout)
if m: if m:
@@ -3913,9 +3969,9 @@ def setup_ap_nat(iface=None):
if not iface: if not iface:
return return
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=1)
subprocess.run(['sysctl', '-w', 'net.ipv4.conf.all.forwarding=1'], capture_output=True) subprocess.run(['sysctl', '-w', 'net.ipv4.conf.all.forwarding=1'], capture_output=True, timeout=1)
subprocess.run(['sysctl', '-w', f'net.ipv4.conf.{iface}.forwarding=1'], capture_output=True) subprocess.run(['sysctl', '-w', f'net.ipv4.conf.{iface}.forwarding=1'], capture_output=True, timeout=1)
except Exception: except Exception:
pass pass
@@ -3923,31 +3979,28 @@ def setup_ap_nat(iface=None):
for ipt in _ap_iptables_bins(): for ipt in _ap_iptables_bins():
try: try:
# 1. Chaîne filter FORWARD dédiée au mode AP (autorise le trafic des clients Wi-Fi vers Internet et le retour) # 1. Chaîne filter FORWARD dédiée au mode AP (autorise le trafic des clients Wi-Fi vers Internet et le retour)
subprocess.run([ipt, '-w', '5', '-N', 'AP_NAT_FORWARD'], capture_output=True) subprocess.run([ipt, '-w', '1', '-N', 'AP_NAT_FORWARD'], capture_output=True, timeout=1)
subprocess.run([ipt, '-w', '5', '-F', 'AP_NAT_FORWARD'], capture_output=True) subprocess.run([ipt, '-w', '1', '-F', 'AP_NAT_FORWARD'], capture_output=True, timeout=1)
subprocess.run([ipt, '-w', '5', '-A', 'AP_NAT_FORWARD', '-i', iface, '-s', subnet, '-j', 'ACCEPT'], capture_output=True) subprocess.run([ipt, '-w', '1', '-A', 'AP_NAT_FORWARD', '-i', iface, '-s', subnet, '-j', 'ACCEPT'], capture_output=True, timeout=1)
subprocess.run([ipt, '-w', '5', '-A', 'AP_NAT_FORWARD', '-o', iface, '-d', subnet, '-m', 'conntrack', '--ctstate', 'ESTABLISHED,RELATED', '-j', 'ACCEPT'], capture_output=True) subprocess.run([ipt, '-w', '1', '-A', 'AP_NAT_FORWARD', '-o', iface, '-d', subnet, '-m', 'conntrack', '--ctstate', 'ESTABLISHED,RELATED', '-j', 'ACCEPT'], capture_output=True, timeout=1)
subprocess.run([ipt, '-w', '5', '-A', 'AP_NAT_FORWARD', '-i', iface, '-o', iface, '-j', 'ACCEPT'], capture_output=True) subprocess.run([ipt, '-w', '1', '-A', 'AP_NAT_FORWARD', '-i', iface, '-o', iface, '-j', 'ACCEPT'], capture_output=True, timeout=1)
while subprocess.run([ipt, '-w', '5', '-D', 'FORWARD', '-j', 'AP_NAT_FORWARD'], capture_output=True).returncode == 0: _ipt_del_jump(ipt, 'filter', 'FORWARD', 'AP_NAT_FORWARD')
pass subprocess.run([ipt, '-w', '1', '-I', 'FORWARD', '1', '-j', 'AP_NAT_FORWARD'], capture_output=True, timeout=1)
subprocess.run([ipt, '-w', '5', '-I', 'FORWARD', '1', '-j', 'AP_NAT_FORWARD'], capture_output=True)
# Conserver les chaînes prioritaires (blocage quota et isolation VPN) toujours AU-DESSUS de AP_NAT_FORWARD # Conserver les chaînes prioritaires (blocage quota et isolation VPN) toujours AU-DESSUS de AP_NAT_FORWARD
for prio_chain in ('AP_VPN_ISOLATION', 'AP_QUOTA_BLOCK'): for prio_chain in ('AP_VPN_ISOLATION', 'AP_QUOTA_BLOCK'):
if subprocess.run([ipt, '-w', '5', '-C', 'FORWARD', '-j', prio_chain], capture_output=True).returncode == 0: if subprocess.run([ipt, '-w', '1', '-C', 'FORWARD', '-j', prio_chain], capture_output=True, timeout=1).returncode == 0:
while subprocess.run([ipt, '-w', '5', '-D', 'FORWARD', '-j', prio_chain], capture_output=True).returncode == 0: _ipt_del_jump(ipt, 'filter', 'FORWARD', prio_chain)
pass subprocess.run([ipt, '-w', '1', '-I', 'FORWARD', '1', '-j', prio_chain], capture_output=True, timeout=1)
subprocess.run([ipt, '-w', '5', '-I', 'FORWARD', '1', '-j', prio_chain], capture_output=True)
# 2. Chaîne nat POSTROUTING dédiée au mode AP (MASQUERADE vers la passerelle Internet) # 2. Chaîne nat POSTROUTING dédiée au mode AP (MASQUERADE vers la passerelle Internet)
subprocess.run([ipt, '-w', '5', '-t', 'nat', '-N', 'AP_NAT_POST'], capture_output=True) subprocess.run([ipt, '-w', '1', '-t', 'nat', '-N', 'AP_NAT_POST'], capture_output=True, timeout=1)
subprocess.run([ipt, '-w', '5', '-t', 'nat', '-F', 'AP_NAT_POST'], capture_output=True) subprocess.run([ipt, '-w', '1', '-t', 'nat', '-F', 'AP_NAT_POST'], capture_output=True, timeout=1)
subprocess.run([ipt, '-w', '5', '-t', 'nat', '-A', 'AP_NAT_POST', '-s', subnet, '!', '-o', iface, '-j', 'MASQUERADE'], capture_output=True) subprocess.run([ipt, '-w', '1', '-t', 'nat', '-A', 'AP_NAT_POST', '-s', subnet, '!', '-o', iface, '-j', 'MASQUERADE'], capture_output=True, timeout=1)
while subprocess.run([ipt, '-w', '5', '-t', 'nat', '-D', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True).returncode == 0: _ipt_del_jump(ipt, 'nat', 'POSTROUTING', 'AP_NAT_POST')
pass subprocess.run([ipt, '-w', '1', '-t', 'nat', '-A', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True, timeout=1)
subprocess.run([ipt, '-w', '5', '-t', 'nat', '-A', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True)
except Exception as e: except Exception as e:
print(f"[ap-nat] Erreur configuration NAT ({ipt}) : {e}", flush=True) print(f"[ap-nat] Erreur configuration NAT ({ipt}) : {e}", flush=True)
print(f"[ap-nat] NAT/FORWARD actif pour le mode AP ({iface}, {subnet})", flush=True) print(f"[ap-nat] NAT/FORWARD actif pour le mode AP ({iface}, {subnet})", flush=True)
@@ -3961,15 +4014,15 @@ def ensure_ap_nat_active(iface=None):
ipt = find_bin('iptables') ipt = find_bin('iptables')
if not ipt: if not ipt:
return return
r_fwd = subprocess.run([ipt, '-w', '1', '-C', 'FORWARD', '-j', 'AP_NAT_FORWARD'], capture_output=True, timeout=3) r_fwd = subprocess.run([ipt, '-w', '1', '-C', 'FORWARD', '-j', 'AP_NAT_FORWARD'], capture_output=True, timeout=1)
r_nat = subprocess.run([ipt, '-w', '1', '-t', 'nat', '-C', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True, timeout=3) r_nat = subprocess.run([ipt, '-w', '1', '-t', 'nat', '-C', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True, timeout=1)
if r_fwd.returncode != 0 or r_nat.returncode != 0: if r_fwd.returncode != 0 or r_nat.returncode != 0:
setup_ap_nat(iface) setup_ap_nat(iface)
except Exception: except Exception:
pass pass
def teardown_ap_nat(): def teardown_ap_nat():
"""Supprime proprement les règles NAT/FORWARD dédiées au mode AP.""" """Supprime proprement les règles NAT/FORWARD dédiées au mode AP sans jamais bloquer l'API."""
seen = set() seen = set()
for candidate in (find_bin('iptables'), find_bin('iptables-legacy')): for candidate in (find_bin('iptables'), find_bin('iptables-legacy')):
if not candidate: if not candidate:
@@ -3979,16 +4032,14 @@ def teardown_ap_nat():
continue continue
seen.add(rp) seen.add(rp)
try: try:
for _ in range(5): if _ipt_has_chain(candidate, 'filter', 'AP_NAT_FORWARD'):
r = subprocess.run([candidate, '-w', '2', '-D', 'FORWARD', '-j', 'AP_NAT_FORWARD'], capture_output=True, timeout=2) _ipt_del_jump(candidate, 'filter', 'FORWARD', 'AP_NAT_FORWARD')
if r.returncode != 0: break subprocess.run([candidate, '-w', '1', '-F', 'AP_NAT_FORWARD'], capture_output=True, timeout=1)
subprocess.run([candidate, '-w', '2', '-F', 'AP_NAT_FORWARD'], capture_output=True, timeout=2) subprocess.run([candidate, '-w', '1', '-X', 'AP_NAT_FORWARD'], capture_output=True, timeout=1)
subprocess.run([candidate, '-w', '2', '-X', 'AP_NAT_FORWARD'], capture_output=True, timeout=2) if _ipt_has_chain(candidate, 'nat', 'AP_NAT_POST'):
for _ in range(5): _ipt_del_jump(candidate, 'nat', 'POSTROUTING', 'AP_NAT_POST')
r = subprocess.run([candidate, '-w', '2', '-t', 'nat', '-D', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True, timeout=2) subprocess.run([candidate, '-w', '1', '-t', 'nat', '-F', 'AP_NAT_POST'], capture_output=True, timeout=1)
if r.returncode != 0: break subprocess.run([candidate, '-w', '1', '-t', 'nat', '-X', 'AP_NAT_POST'], capture_output=True, timeout=1)
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
@@ -4198,30 +4249,35 @@ 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'
for _ in range(20): for i_attempt in range(20):
time.sleep(0.1) time.sleep(0.1)
if not is_hostapd_running(): if not is_hostapd_running():
break break
iw_out = command('iw', 'dev', iface, 'info', timeout=1) or ''
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-DISABLED' in log_txt: if 'AP-DISABLED' in log_txt:
return False, 'Interface AP désactivée par hostapd' return False, 'Interface AP désactivée par hostapd'
# Dès que hostapd est actif et que iw confirme le type AP has_master = os.path.exists(f'/sys/class/net/{iface}/master')
if 'type AP' in iw_out or 'AP-ENABLED' in log_txt: if '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, timeout=2) subprocess.run(['ip', 'link', 'set', 'dev', iface, 'master', bridge_name], capture_output=True, timeout=1)
disable_wifi_powersave(iface)
return True, ''
if i_attempt % 3 == 0:
iw_out = command('iw', 'dev', iface, 'info', timeout=0.8) or ''
if 'type AP' in iw_out:
if not has_master:
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'master', bridge_name], capture_output=True, timeout=1)
disable_wifi_powersave(iface) disable_wifi_powersave(iface)
return True, '' return True, ''
if is_hostapd_running(): if is_hostapd_running():
iw_out = command('iw', 'dev', iface, 'info', timeout=1) or '' iw_out = command('iw', 'dev', iface, 'info', timeout=0.8) 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, timeout=2) subprocess.run(['ip', 'link', 'set', 'dev', iface, 'master', bridge_name], capture_output=True, timeout=1)
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'
@@ -4241,9 +4297,6 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No
if not ok: if not ok:
raise RuntimeError(f"Impossible de démarrer le point d'accès en mode Pont (hostapd) : {err2 or err}") raise RuntimeError(f"Impossible de démarrer le point d'accès en mode Pont (hostapd) : {err2 or err}")
# Appliquer la configuration DNS du mode pont (hôte systemd-resolved + nettoyage broute)
setup_bridge_dns_redirection(bridge_name, iface)
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)
@@ -4295,10 +4348,10 @@ def sync_host_resolved_bridge_dns(bridge_name='br0', gateway_ip=None):
try: try:
obj = bus.get_object('org.freedesktop.resolve1', '/org/freedesktop/resolve1') obj = bus.get_object('org.freedesktop.resolve1', '/org/freedesktop/resolve1')
mgr = dbus.Interface(obj, 'org.freedesktop.resolve1.Manager') mgr = dbus.Interface(obj, 'org.freedesktop.resolve1.Manager')
mgr.SetLinkDNS(dbus.Int32(ifindex), dbus.Array(addrs, signature='(iay)')) mgr.SetLinkDNS(dbus.Int32(ifindex), dbus.Array(addrs, signature='(iay)'), timeout=1.5)
mgr.SetLinkDefaultRoute(dbus.Int32(ifindex), dbus.Boolean(True)) mgr.SetLinkDefaultRoute(dbus.Int32(ifindex), dbus.Boolean(True), timeout=1.5)
try: try:
mgr.FlushCaches() mgr.FlushCaches(timeout=1.5)
except Exception: except Exception:
pass pass
finally: finally:
@@ -4329,11 +4382,11 @@ def ensure_host_resolved_bridge_dns(bridge_name=None):
try: try:
obj = bus.get_object('org.freedesktop.resolve1', '/org/freedesktop/resolve1') obj = bus.get_object('org.freedesktop.resolve1', '/org/freedesktop/resolve1')
mgr = dbus.Interface(obj, 'org.freedesktop.resolve1.Manager') mgr = dbus.Interface(obj, 'org.freedesktop.resolve1.Manager')
link_path = mgr.GetLink(dbus.Int32(ifindex)) link_path = mgr.GetLink(dbus.Int32(ifindex), timeout=1.5)
link_obj = bus.get_object('org.freedesktop.resolve1', link_path) link_obj = bus.get_object('org.freedesktop.resolve1', link_path)
props = dbus.Interface(link_obj, 'org.freedesktop.DBus.Properties') props = dbus.Interface(link_obj, 'org.freedesktop.DBus.Properties')
cur_dns = props.Get('org.freedesktop.resolve1.Link', 'DNS') cur_dns = props.Get('org.freedesktop.resolve1.Link', 'DNS', timeout=1.5)
cur_def = bool(props.Get('org.freedesktop.resolve1.Link', 'DefaultRoute')) cur_def = bool(props.Get('org.freedesktop.resolve1.Link', 'DefaultRoute', timeout=1.5))
if not cur_dns or not cur_def: if not cur_dns or not cur_def:
needs_sync = True needs_sync = True
finally: finally:
@@ -4357,7 +4410,7 @@ def revert_host_resolved_bridge_dns(bridge_name='br0'):
try: try:
obj = bus.get_object('org.freedesktop.resolve1', '/org/freedesktop/resolve1') obj = bus.get_object('org.freedesktop.resolve1', '/org/freedesktop/resolve1')
mgr = dbus.Interface(obj, 'org.freedesktop.resolve1.Manager') mgr = dbus.Interface(obj, 'org.freedesktop.resolve1.Manager')
mgr.RevertLink(dbus.Int32(ifindex)) mgr.RevertLink(dbus.Int32(ifindex), timeout=1.5)
finally: finally:
try: bus.close() try: bus.close()
except Exception: pass except Exception: pass
@@ -4454,14 +4507,14 @@ def setup_bridge(bridge_name='br0', bridge_eth=None):
try: try:
for ipt in _ap_iptables_bins(): for ipt in _ap_iptables_bins():
try: try:
r1 = subprocess.run([ipt, '-w', '1', '-C', 'FORWARD', '-i', bridge_name, '-j', 'ACCEPT'], capture_output=True, timeout=3) r1 = subprocess.run([ipt, '-w', '1', '-C', 'FORWARD', '-i', bridge_name, '-j', 'ACCEPT'], capture_output=True, timeout=1)
if r1.returncode != 0: if r1.returncode != 0:
subprocess.run([ipt, '-w', '1', '-I', 'FORWARD', '1', '-i', bridge_name, '-j', 'ACCEPT'], capture_output=True, timeout=3) subprocess.run([ipt, '-w', '1', '-I', 'FORWARD', '1', '-i', bridge_name, '-j', 'ACCEPT'], capture_output=True, timeout=1)
except Exception: pass except Exception: pass
try: try:
r2 = subprocess.run([ipt, '-w', '1', '-C', 'FORWARD', '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True, timeout=3) r2 = subprocess.run([ipt, '-w', '1', '-C', 'FORWARD', '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True, timeout=1)
if r2.returncode != 0: if r2.returncode != 0:
subprocess.run([ipt, '-w', '1', '-I', 'FORWARD', '1', '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True, timeout=3) subprocess.run([ipt, '-w', '1', '-I', 'FORWARD', '1', '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True, timeout=1)
except Exception: pass except Exception: pass
except Exception: pass except Exception: pass
@@ -10613,6 +10666,15 @@ def _delete_s3(cfg, remote_filename):
req.add_header('x-amz-content-sha256', payload_hash) req.add_header('x-amz-content-sha256', payload_hash)
req.add_header('Authorization', auth_hdr) req.add_header('Authorization', auth_hdr)
ctx = ssl.create_default_context() ctx = ssl.create_default_context()
try:
with urllib.request.urlopen(req, context=ctx, timeout=30) as resp:
return True, f"Fichier {remote_filename} supprimé sur S3"
except Exception as e:
req.add_header('Host', host)
req.add_header('x-amz-date', amz_date)
req.add_header('x-amz-content-sha256', payload_hash)
req.add_header('Authorization', auth_hdr)
ctx = ssl.create_default_context()
try: try:
with urllib.request.urlopen(req, context=ctx, timeout=30) as resp: with urllib.request.urlopen(req, context=ctx, timeout=30) as resp:
return True, f"Fichier {remote_filename} supprimé sur S3" return True, f"Fichier {remote_filename} supprimé sur S3"
@@ -11746,7 +11808,22 @@ class Handler(BaseHTTPRequestHandler):
data['error'] = translate_api_text(data['error'], req_lang) data['error'] = translate_api_text(data['error'], req_lang)
if 'message' in data and isinstance(data['message'], str): if 'message' in data and isinstance(data['message'], str):
data['message'] = translate_api_text(data['message'], req_lang) data['message'] = translate_api_text(data['message'], req_lang)
body=json.dumps(data,ensure_ascii=False).encode(); self.send_response(status); self.send_header('Content-Type','application/json; charset=utf-8'); self.send_header('Connection','close'); self.send_header('X-Content-Type-Options','nosniff'); self.send_header('X-Frame-Options','SAMEORIGIN'); self.send_header('Referrer-Policy','strict-origin-when-cross-origin'); self.send_header('Access-Control-Allow-Origin','*'); self.send_header('Access-Control-Allow-Headers','Content-Type, X-Session-Token, X-Language, Accept-Language'); self.send_header('Access-Control-Allow-Methods','GET, POST, OPTIONS'); self.send_header('Content-Length',str(len(body))); self.end_headers(); self.wfile.write(body) try:
body = json.dumps(data, ensure_ascii=False).encode()
self.send_response(status)
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Connection', 'close')
self.send_header('X-Content-Type-Options', 'nosniff')
self.send_header('X-Frame-Options', 'SAMEORIGIN')
self.send_header('Referrer-Policy', 'strict-origin-when-cross-origin')
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Headers', 'Content-Type, X-Session-Token, X-Language, Accept-Language')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError):
pass
def do_OPTIONS(self): self.send_response(204); self.send_header('Access-Control-Allow-Origin','*'); self.send_header('Access-Control-Allow-Headers','Content-Type, X-Session-Token'); self.send_header('Access-Control-Allow-Methods','GET, POST, OPTIONS'); self.end_headers() def do_OPTIONS(self): self.send_response(204); self.send_header('Access-Control-Allow-Origin','*'); self.send_header('Access-Control-Allow-Headers','Content-Type, X-Session-Token'); self.send_header('Access-Control-Allow-Methods','GET, POST, OPTIONS'); self.end_headers()
def do_GET(self): def do_GET(self):
if self.path == '/api/version': if self.path == '/api/version':
@@ -13548,6 +13625,13 @@ class UnixServer(ThreadingHTTPServer):
socketserver.TCPServer.server_bind(self) socketserver.TCPServer.server_bind(self)
self.server_name, self.server_port = 'localhost', 0 self.server_name, self.server_port = 'localhost', 0
def handle_error(self, request, client_address):
import sys
exctype, value, tb = sys.exc_info()
if exctype in (BrokenPipeError, ConnectionResetError):
return
super().handle_error(request, client_address)
_update_loop_event = threading.Event() _update_loop_event = threading.Event()
def update_checker_loop(): def update_checker_loop():
+34 -12
View File
@@ -9700,7 +9700,7 @@ ${vpnBadgeTopo}
apActionInProgress = action; apActionInProgress = action;
updateApButtons(); updateApButtons();
try { try {
const response = await apiFetch('/api/ap/control', { method: 'POST', timeout: 60000, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }) }); const response = await apiFetch('/api/ap/control', { method: 'POST', timeout: 90000, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }) });
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');
@@ -14013,7 +14013,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', 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 response = await apiFetch('/api/setup', { method: 'POST', timeout: 90000, 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();
@@ -14071,21 +14071,29 @@ ${vpnBadgeTopo}
if (panel) panel.style.cursor = disabled ? 'wait' : ''; if (panel) panel.style.cursor = disabled ? 'wait' : '';
} }
$('saveSettings').onclick = () => runAction(async () => { $('saveSettings').onclick = () => {
const confirmMsg = t('confirm_save_settings_restart', "La modification des réglages Wi-Fi va redémarrer le point d’accès.\n\nTous les appareils connectés seront temporairement déconnectés.\nCette opération peut durer plusieurs minutes.\n\nSouhaitez-vous continuer ?");
if (!confirm(confirmMsg)) return;
return runAction(async () => {
let m = $('message'); let m = $('message');
if (settingsMessageTimer) { if (settingsMessageTimer) {
clearTimeout(settingsMessageTimer); clearTimeout(settingsMessageTimer);
settingsMessageTimer = null; settingsMessageTimer = null;
} }
apActionInProgress = 'restart';
updateApButtons();
setSettingsWifiInputsDisabled(true); setSettingsWifiInputsDisabled(true);
m.style.color = 'var(--muted)'; if (m) {
m.textContent = t('loading', 'Enregistrement…'); m.style.color = 'var(--blue)';
m.innerHTML = `<span style="display:inline-flex;animation:spin 1s linear infinite;margin-right:6px">⚙️</span> <span>${escapeHtml(t('settings_restarting_warning', "Redémarrage : cette opération peut durer plusieurs minutes…"))}</span>`;
}
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', { let r = await apiFetch('/api/settings', {
method: 'POST', method: 'POST',
timeout: 60000, timeout: 90000,
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
ssid: $('settingsSsid').value, ssid: $('settingsSsid').value,
@@ -14098,23 +14106,37 @@ ${vpnBadgeTopo}
}) })
}); });
let d = await r.json(); let d = await r.json();
if (!r.ok) throw Error(d.error); if (!r.ok) throw Error(d.error || 'Erreur lors de l’enregistrement');
m.style.color = 'var(--green)';
m.textContent = tMsg(d.message); for (let attempt = 0; attempt < 25; attempt++) {
await new Promise(resolve => setTimeout(resolve, 1000)); await new Promise(resolve => setTimeout(resolve, 800));
try {
await load(); await load();
} catch (_) {}
if (attempt >= 2 && status && status.active) break;
}
if (m) {
m.style.color = 'var(--green)';
m.textContent = '✅ ' + tMsg(d.message || t('settings_saved_restarted', 'Réglages enregistrés et point d’accès redémarré avec succès !'));
}
} catch (e) { } catch (e) {
if (m) {
m.style.color = 'var(--red)'; m.style.color = 'var(--red)';
m.textContent = tErr(e.message); m.textContent = '❌ ' + tErr(e.message);
}
} finally { } finally {
apActionInProgress = null;
updateApButtons();
setSettingsWifiInputsDisabled(false); setSettingsWifiInputsDisabled(false);
if (settingsMessageTimer) clearTimeout(settingsMessageTimer); if (settingsMessageTimer) clearTimeout(settingsMessageTimer);
settingsMessageTimer = setTimeout(() => { settingsMessageTimer = setTimeout(() => {
if (m) m.textContent = ''; if (m) m.textContent = '';
settingsMessageTimer = null; settingsMessageTimer = null;
}, 4000); }, 5000);
} }
}); });
};
$('logout').onclick = logout; $('logout').onclick = logout;
+4 -1
View File
@@ -1459,5 +1459,8 @@ window.I18N['en-gb'] = {
"btn_stopping": "Stopping…", "btn_stopping": "Stopping…",
"btn_restarting": "Restarting…", "btn_restarting": "Restarting…",
"confirm_stop_ap": "Are you sure you want to stop the Wi-Fi access point?\n\nAll connected devices will be disconnected.\nThis operation may take several minutes.", "confirm_stop_ap": "Are you sure you want to stop the Wi-Fi access point?\n\nAll connected devices will be disconnected.\nThis operation may take several minutes.",
"confirm_restart_ap": "Are you sure you want to restart the Wi-Fi access point?\n\nAll connected devices will be temporarily disconnected.\nThis operation may take several minutes." "confirm_restart_ap": "Are you sure you want to restart the Wi-Fi access point?\n\nAll connected devices will be temporarily disconnected.\nThis operation may take several minutes.",
"confirm_save_settings_restart": "Modifying Wi-Fi settings will restart the access point.\n\nAll connected devices will be temporarily disconnected.\nThis operation may take several minutes.\n\nDo you want to continue?",
"settings_restarting_warning": "Restarting: this operation may take several minutes…",
"settings_saved_restarted": "Settings saved and access point restarted successfully!"
}; };
+4 -1
View File
@@ -1459,5 +1459,8 @@ window.I18N['en-us'] = {
"btn_stopping": "Stopping…", "btn_stopping": "Stopping…",
"btn_restarting": "Restarting…", "btn_restarting": "Restarting…",
"confirm_stop_ap": "Are you sure you want to stop the Wi-Fi access point?\n\nAll connected devices will be disconnected.\nThis operation may take several minutes.", "confirm_stop_ap": "Are you sure you want to stop the Wi-Fi access point?\n\nAll connected devices will be disconnected.\nThis operation may take several minutes.",
"confirm_restart_ap": "Are you sure you want to restart the Wi-Fi access point?\n\nAll connected devices will be temporarily disconnected.\nThis operation may take several minutes." "confirm_restart_ap": "Are you sure you want to restart the Wi-Fi access point?\n\nAll connected devices will be temporarily disconnected.\nThis operation may take several minutes.",
"confirm_save_settings_restart": "Modifying Wi-Fi settings will restart the access point.\n\nAll connected devices will be temporarily disconnected.\nThis operation may take several minutes.\n\nDo you want to continue?",
"settings_restarting_warning": "Restarting: this operation may take several minutes…",
"settings_saved_restarted": "Settings saved and access point restarted successfully!"
}; };
+4 -1
View File
@@ -1459,5 +1459,8 @@ window.I18N['fr'] = {
"btn_stopping": "Arrêt…", "btn_stopping": "Arrêt…",
"btn_restarting": "Redémarrage…", "btn_restarting": "Redémarrage…",
"confirm_stop_ap": "Êtes-vous sûr de vouloir arrêter le point d’accès Wi-Fi ?\n\nTous les appareils connectés seront déconnectés.\nCette opération peut prendre plusieurs minutes.", "confirm_stop_ap": "Êtes-vous sûr de vouloir arrêter le point d’accès Wi-Fi ?\n\nTous les appareils connectés seront déconnectés.\nCette opération peut prendre plusieurs minutes.",
"confirm_restart_ap": "Êtes-vous sûr de vouloir redémarrer le point d’accès Wi-Fi ?\n\nTous les appareils connectés seront temporairement déconnectés.\nCette opération peut prendre plusieurs minutes." "confirm_restart_ap": "Êtes-vous sûr de vouloir redémarrer le point d’accès Wi-Fi ?\n\nTous les appareils connectés seront temporairement déconnectés.\nCette opération peut prendre plusieurs minutes.",
"confirm_save_settings_restart": "La modification des réglages Wi-Fi va redémarrer le point d’accès.\n\nTous les appareils connectés seront temporairement déconnectés.\nCette opération peut durer plusieurs minutes.\n\nSouhaitez-vous continuer ?",
"settings_restarting_warning": "Redémarrage : cette opération peut durer plusieurs minutes…",
"settings_saved_restarted": "Réglages enregistrés et point d’accès redémarré avec succès !"
}; };