AP manageur V1.1 (Bêta)
This commit is contained in:
1 parent
25934624ea
commit
cf611c584c
5 files changed
+268
-153
No files matched your search
@@ -504,18 +504,23 @@ def parse_netbios_response(data):
|
||||
return ''
|
||||
|
||||
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.')):
|
||||
return ''
|
||||
try:
|
||||
res = socket.getnameinfo((ip, 0), socket.NI_NAMEREQD)
|
||||
if res and res[0]:
|
||||
cleaned = clean_extracted_hostname(res[0])
|
||||
if cleaned:
|
||||
return cleaned
|
||||
except Exception:
|
||||
pass
|
||||
return ''
|
||||
res_container = []
|
||||
def _worker():
|
||||
try:
|
||||
res = socket.getnameinfo((ip, 0), socket.NI_NAMEREQD)
|
||||
if res and res[0]:
|
||||
cleaned = clean_extracted_hostname(res[0])
|
||||
if cleaned:
|
||||
res_container.append(cleaned)
|
||||
except Exception:
|
||||
pass
|
||||
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):
|
||||
"""Interroge le nom NetBIOS d'un client Windows / NAS / Samba sur UDP 137."""
|
||||
@@ -1325,34 +1330,69 @@ def parse_browser(user_agent):
|
||||
return 'Safari' + (' ' + m.group(1).split('.')[0] if m else '')
|
||||
return 'Navigateur Web'
|
||||
|
||||
_device_name_ip_cache = {}
|
||||
_device_name_ip_cache_lock = threading.Lock()
|
||||
|
||||
def resolve_device_name(ip):
|
||||
if not ip or ip in ('127.0.0.1', '::1', 'localhost', 'Non attribuée', '—'):
|
||||
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:
|
||||
c = db()
|
||||
row = c.execute('SELECT name FROM client_names WHERE last_ip=?', (ip,)).fetchone()
|
||||
c.close()
|
||||
if row and row[0]: return row[0]
|
||||
except Exception: pass
|
||||
for lease_file in ['/var/lib/misc/dnsmasq.leases', '/tmp/dnsmasq.leases']:
|
||||
if row and row[0] and row[0] != 'Nom non communiqué':
|
||||
name = row[0]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not name:
|
||||
for lease_file in ['/var/lib/misc/dnsmasq.leases', '/tmp/dnsmasq.leases']:
|
||||
try:
|
||||
if os.path.exists(lease_file):
|
||||
with open(lease_file, 'r', encoding='utf-8', errors='ignore') as f:
|
||||
for line in f:
|
||||
parts = line.strip().split()
|
||||
if len(parts) >= 4 and parts[2] == ip and parts[3] != '*':
|
||||
name = parts[3]
|
||||
break
|
||||
if name:
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not name:
|
||||
try:
|
||||
if os.path.exists(lease_file):
|
||||
with open(lease_file, 'r', encoding='utf-8', errors='ignore') as f:
|
||||
if os.path.exists('/proc/net/arp'):
|
||||
with open('/proc/net/arp', 'r', encoding='utf-8', errors='ignore') as f:
|
||||
for line in f:
|
||||
parts = line.strip().split()
|
||||
if len(parts) >= 4 and parts[2] == ip and parts[3] != '*':
|
||||
return parts[3]
|
||||
except Exception: pass
|
||||
try:
|
||||
name = socket.gethostbyaddr(ip)[0]
|
||||
if name and name != ip: return name.split('.')[0]
|
||||
except Exception: pass
|
||||
try:
|
||||
host_line = command('ip', 'neigh', 'show', ip)
|
||||
m = re.search(r'\(([^)]+)\)', host_line)
|
||||
if m and m.group(1) != ip: return m.group(1)
|
||||
except Exception: pass
|
||||
return f"Machine ({ip})"
|
||||
if len(parts) >= 4 and parts[0] == ip:
|
||||
arp_mac = parts[3].upper()
|
||||
if is_valid_mac(arp_mac):
|
||||
dname = device_name(ip, arp_mac)
|
||||
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=''):
|
||||
token = secrets.token_urlsafe(32)
|
||||
@@ -1501,7 +1541,15 @@ def list_sessions(current_token='', lang='fr'):
|
||||
browser_name = parse_browser(ua)
|
||||
if not dev_name or dev_name.startswith('Machine ('):
|
||||
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)
|
||||
res.append({
|
||||
'token': token,
|
||||
@@ -3846,30 +3894,38 @@ def run_cmd(*args):
|
||||
except Exception:
|
||||
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):
|
||||
"""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)
|
||||
|
||||
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
|
||||
try:
|
||||
for ipt in [b for b in (find_bin('iptables'),) if b]:
|
||||
for proto in ('udp', 'tcp'):
|
||||
if iface:
|
||||
for _ in range(5):
|
||||
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)
|
||||
if r.returncode != 0: break
|
||||
for _ in range(5):
|
||||
r = subprocess.run([ipt, '-w', '2', '-t', 'nat', '-D', 'PREROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS'], capture_output=True, timeout=2)
|
||||
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)
|
||||
ipt = find_bin('iptables')
|
||||
if ipt:
|
||||
for ch in ('AP_BRIDGE_DNS', 'AP_BRIDGE_DNS_POST'):
|
||||
if _ipt_has_chain(ipt, 'nat', ch):
|
||||
_ipt_del_jump(ipt, 'nat', 'PREROUTING', ch)
|
||||
_ipt_del_jump(ipt, 'nat', 'POSTROUTING', ch)
|
||||
subprocess.run([ipt, '-t', 'nat', '-F', ch], capture_output=True, timeout=1)
|
||||
subprocess.run([ipt, '-t', 'nat', '-X', ch], capture_output=True, timeout=1)
|
||||
# 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:
|
||||
for proto in ('udp', 'tcp'):
|
||||
@@ -3886,7 +3942,7 @@ def _ap_iptables_bins():
|
||||
legacy_bin = find_bin('iptables-legacy')
|
||||
if legacy_bin and os.path.realpath(legacy_bin) != os.path.realpath(default_bin or ''):
|
||||
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):
|
||||
bins.append(legacy_bin)
|
||||
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)."""
|
||||
try:
|
||||
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:
|
||||
m = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+/\d+)', r.stdout)
|
||||
if m:
|
||||
@@ -3913,9 +3969,9 @@ def setup_ap_nat(iface=None):
|
||||
if not iface:
|
||||
return
|
||||
try:
|
||||
subprocess.run(['sysctl', '-w', 'net.ipv4.ip_forward=1'], capture_output=True)
|
||||
subprocess.run(['sysctl', '-w', 'net.ipv4.conf.all.forwarding=1'], capture_output=True)
|
||||
subprocess.run(['sysctl', '-w', f'net.ipv4.conf.{iface}.forwarding=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, timeout=1)
|
||||
subprocess.run(['sysctl', '-w', f'net.ipv4.conf.{iface}.forwarding=1'], capture_output=True, timeout=1)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -3923,31 +3979,28 @@ def setup_ap_nat(iface=None):
|
||||
for ipt in _ap_iptables_bins():
|
||||
try:
|
||||
# 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', '5', '-F', 'AP_NAT_FORWARD'], capture_output=True)
|
||||
subprocess.run([ipt, '-w', '5', '-A', 'AP_NAT_FORWARD', '-i', iface, '-s', subnet, '-j', 'ACCEPT'], capture_output=True)
|
||||
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', '5', '-A', 'AP_NAT_FORWARD', '-i', iface, '-o', iface, '-j', 'ACCEPT'], capture_output=True)
|
||||
subprocess.run([ipt, '-w', '1', '-N', 'AP_NAT_FORWARD'], capture_output=True, timeout=1)
|
||||
subprocess.run([ipt, '-w', '1', '-F', 'AP_NAT_FORWARD'], capture_output=True, timeout=1)
|
||||
subprocess.run([ipt, '-w', '1', '-A', 'AP_NAT_FORWARD', '-i', iface, '-s', subnet, '-j', 'ACCEPT'], capture_output=True, timeout=1)
|
||||
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', '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:
|
||||
pass
|
||||
subprocess.run([ipt, '-w', '5', '-I', 'FORWARD', '1', '-j', 'AP_NAT_FORWARD'], capture_output=True)
|
||||
_ipt_del_jump(ipt, 'filter', 'FORWARD', 'AP_NAT_FORWARD')
|
||||
subprocess.run([ipt, '-w', '1', '-I', 'FORWARD', '1', '-j', 'AP_NAT_FORWARD'], capture_output=True, timeout=1)
|
||||
|
||||
# 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'):
|
||||
if subprocess.run([ipt, '-w', '5', '-C', 'FORWARD', '-j', prio_chain], capture_output=True).returncode == 0:
|
||||
while subprocess.run([ipt, '-w', '5', '-D', 'FORWARD', '-j', prio_chain], capture_output=True).returncode == 0:
|
||||
pass
|
||||
subprocess.run([ipt, '-w', '5', '-I', 'FORWARD', '1', '-j', prio_chain], capture_output=True)
|
||||
if subprocess.run([ipt, '-w', '1', '-C', 'FORWARD', '-j', prio_chain], capture_output=True, timeout=1).returncode == 0:
|
||||
_ipt_del_jump(ipt, 'filter', 'FORWARD', prio_chain)
|
||||
subprocess.run([ipt, '-w', '1', '-I', 'FORWARD', '1', '-j', prio_chain], capture_output=True, timeout=1)
|
||||
|
||||
# 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', '5', '-t', 'nat', '-F', 'AP_NAT_POST'], capture_output=True)
|
||||
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', '-N', 'AP_NAT_POST'], capture_output=True, timeout=1)
|
||||
subprocess.run([ipt, '-w', '1', '-t', 'nat', '-F', 'AP_NAT_POST'], capture_output=True, timeout=1)
|
||||
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:
|
||||
pass
|
||||
subprocess.run([ipt, '-w', '5', '-t', 'nat', '-A', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True)
|
||||
_ipt_del_jump(ipt, 'nat', 'POSTROUTING', 'AP_NAT_POST')
|
||||
subprocess.run([ipt, '-w', '1', '-t', 'nat', '-A', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True, timeout=1)
|
||||
except Exception as e:
|
||||
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)
|
||||
@@ -3961,15 +4014,15 @@ def ensure_ap_nat_active(iface=None):
|
||||
ipt = find_bin('iptables')
|
||||
if not ipt:
|
||||
return
|
||||
r_fwd = subprocess.run([ipt, '-w', '1', '-C', 'FORWARD', '-j', 'AP_NAT_FORWARD'], capture_output=True, timeout=3)
|
||||
r_nat = subprocess.run([ipt, '-w', '1', '-t', 'nat', '-C', 'POSTROUTING', '-j', 'AP_NAT_POST'], 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=1)
|
||||
if r_fwd.returncode != 0 or r_nat.returncode != 0:
|
||||
setup_ap_nat(iface)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
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()
|
||||
for candidate in (find_bin('iptables'), find_bin('iptables-legacy')):
|
||||
if not candidate:
|
||||
@@ -3979,16 +4032,14 @@ def teardown_ap_nat():
|
||||
continue
|
||||
seen.add(rp)
|
||||
try:
|
||||
for _ in range(5):
|
||||
r = subprocess.run([candidate, '-w', '2', '-D', 'FORWARD', '-j', 'AP_NAT_FORWARD'], capture_output=True, timeout=2)
|
||||
if r.returncode != 0: break
|
||||
subprocess.run([candidate, '-w', '2', '-F', 'AP_NAT_FORWARD'], capture_output=True, timeout=2)
|
||||
subprocess.run([candidate, '-w', '2', '-X', 'AP_NAT_FORWARD'], capture_output=True, timeout=2)
|
||||
for _ in range(5):
|
||||
r = subprocess.run([candidate, '-w', '2', '-t', 'nat', '-D', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True, timeout=2)
|
||||
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)
|
||||
if _ipt_has_chain(candidate, 'filter', 'AP_NAT_FORWARD'):
|
||||
_ipt_del_jump(candidate, 'filter', 'FORWARD', 'AP_NAT_FORWARD')
|
||||
subprocess.run([candidate, '-w', '1', '-F', 'AP_NAT_FORWARD'], capture_output=True, timeout=1)
|
||||
subprocess.run([candidate, '-w', '1', '-X', 'AP_NAT_FORWARD'], capture_output=True, timeout=1)
|
||||
if _ipt_has_chain(candidate, 'nat', 'AP_NAT_POST'):
|
||||
_ipt_del_jump(candidate, 'nat', 'POSTROUTING', 'AP_NAT_POST')
|
||||
subprocess.run([candidate, '-w', '1', '-t', 'nat', '-F', 'AP_NAT_POST'], capture_output=True, timeout=1)
|
||||
subprocess.run([candidate, '-w', '1', '-t', 'nat', '-X', 'AP_NAT_POST'], capture_output=True, timeout=1)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -4198,30 +4249,35 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No
|
||||
pass
|
||||
return False, err or 'hostapd a refusé de démarrer'
|
||||
|
||||
for _ in range(20):
|
||||
for i_attempt in range(20):
|
||||
time.sleep(0.1)
|
||||
if not is_hostapd_running():
|
||||
break
|
||||
iw_out = command('iw', 'dev', iface, 'info', timeout=1) or ''
|
||||
has_master = os.path.exists(f'/sys/class/net/{iface}/master')
|
||||
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 '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:
|
||||
has_master = os.path.exists(f'/sys/class/net/{iface}/master')
|
||||
if 'AP-ENABLED' in log_txt:
|
||||
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)
|
||||
return True, ''
|
||||
|
||||
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 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)
|
||||
return True, ''
|
||||
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:
|
||||
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)
|
||||
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:
|
||||
obj = bus.get_object('org.freedesktop.resolve1', '/org/freedesktop/resolve1')
|
||||
mgr = dbus.Interface(obj, 'org.freedesktop.resolve1.Manager')
|
||||
mgr.SetLinkDNS(dbus.Int32(ifindex), dbus.Array(addrs, signature='(iay)'))
|
||||
mgr.SetLinkDefaultRoute(dbus.Int32(ifindex), dbus.Boolean(True))
|
||||
mgr.SetLinkDNS(dbus.Int32(ifindex), dbus.Array(addrs, signature='(iay)'), timeout=1.5)
|
||||
mgr.SetLinkDefaultRoute(dbus.Int32(ifindex), dbus.Boolean(True), timeout=1.5)
|
||||
try:
|
||||
mgr.FlushCaches()
|
||||
mgr.FlushCaches(timeout=1.5)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
@@ -4329,11 +4382,11 @@ def ensure_host_resolved_bridge_dns(bridge_name=None):
|
||||
try:
|
||||
obj = bus.get_object('org.freedesktop.resolve1', '/org/freedesktop/resolve1')
|
||||
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)
|
||||
props = dbus.Interface(link_obj, 'org.freedesktop.DBus.Properties')
|
||||
cur_dns = props.Get('org.freedesktop.resolve1.Link', 'DNS')
|
||||
cur_def = bool(props.Get('org.freedesktop.resolve1.Link', 'DefaultRoute'))
|
||||
cur_dns = props.Get('org.freedesktop.resolve1.Link', 'DNS', timeout=1.5)
|
||||
cur_def = bool(props.Get('org.freedesktop.resolve1.Link', 'DefaultRoute', timeout=1.5))
|
||||
if not cur_dns or not cur_def:
|
||||
needs_sync = True
|
||||
finally:
|
||||
@@ -4357,7 +4410,7 @@ def revert_host_resolved_bridge_dns(bridge_name='br0'):
|
||||
try:
|
||||
obj = bus.get_object('org.freedesktop.resolve1', '/org/freedesktop/resolve1')
|
||||
mgr = dbus.Interface(obj, 'org.freedesktop.resolve1.Manager')
|
||||
mgr.RevertLink(dbus.Int32(ifindex))
|
||||
mgr.RevertLink(dbus.Int32(ifindex), timeout=1.5)
|
||||
finally:
|
||||
try: bus.close()
|
||||
except Exception: pass
|
||||
@@ -4454,14 +4507,14 @@ def setup_bridge(bridge_name='br0', bridge_eth=None):
|
||||
try:
|
||||
for ipt in _ap_iptables_bins():
|
||||
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:
|
||||
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
|
||||
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:
|
||||
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
|
||||
|
||||
@@ -10613,6 +10666,15 @@ def _delete_s3(cfg, remote_filename):
|
||||
req.add_header('x-amz-content-sha256', payload_hash)
|
||||
req.add_header('Authorization', auth_hdr)
|
||||
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:
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=30) as resp:
|
||||
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)
|
||||
if 'message' in data and isinstance(data['message'], str):
|
||||
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_GET(self):
|
||||
if self.path == '/api/version':
|
||||
@@ -13548,6 +13625,13 @@ class UnixServer(ThreadingHTTPServer):
|
||||
socketserver.TCPServer.server_bind(self)
|
||||
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()
|
||||
|
||||
def update_checker_loop():
|
||||
|
||||
+67
-45
@@ -9700,7 +9700,7 @@ ${vpnBadgeTopo}
|
||||
apActionInProgress = action;
|
||||
updateApButtons();
|
||||
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();
|
||||
if (!response.ok) throw Error(data.error || 'Action refusée');
|
||||
|
||||
@@ -14013,7 +14013,7 @@ ${vpnBadgeTopo}
|
||||
try {
|
||||
const sMode = document.querySelector('input[name="setupMode"]:checked')?.value || 'ap';
|
||||
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');
|
||||
message.textContent = data.message; currentTab = 'dashboard'; sessionStorage.setItem('apDashboardTab', 'dashboard');
|
||||
await new Promise(resolve => setTimeout(resolve, 500)); await load();
|
||||
@@ -14071,50 +14071,72 @@ ${vpnBadgeTopo}
|
||||
if (panel) panel.style.cursor = disabled ? 'wait' : '';
|
||||
}
|
||||
|
||||
$('saveSettings').onclick = () => runAction(async () => {
|
||||
let m = $('message');
|
||||
if (settingsMessageTimer) {
|
||||
clearTimeout(settingsMessageTimer);
|
||||
settingsMessageTimer = null;
|
||||
}
|
||||
setSettingsWifiInputsDisabled(true);
|
||||
m.style.color = 'var(--muted)';
|
||||
m.textContent = t('loading', 'Enregistrement…');
|
||||
try {
|
||||
const setMode = document.querySelector('input[name="settingsMode"]:checked')?.value || 'ap';
|
||||
const setEth = $('settingsBridgeEth')?.value || '';
|
||||
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);
|
||||
m.style.color = 'var(--green)';
|
||||
m.textContent = tMsg(d.message);
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
await load();
|
||||
} catch (e) {
|
||||
m.style.color = 'var(--red)';
|
||||
m.textContent = tErr(e.message);
|
||||
} finally {
|
||||
setSettingsWifiInputsDisabled(false);
|
||||
if (settingsMessageTimer) clearTimeout(settingsMessageTimer);
|
||||
settingsMessageTimer = setTimeout(() => {
|
||||
if (m) m.textContent = '';
|
||||
$('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');
|
||||
if (settingsMessageTimer) {
|
||||
clearTimeout(settingsMessageTimer);
|
||||
settingsMessageTimer = null;
|
||||
}, 4000);
|
||||
}
|
||||
});
|
||||
}
|
||||
apActionInProgress = 'restart';
|
||||
updateApButtons();
|
||||
setSettingsWifiInputsDisabled(true);
|
||||
if (m) {
|
||||
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 {
|
||||
const setMode = document.querySelector('input[name="settingsMode"]:checked')?.value || 'ap';
|
||||
const setEth = $('settingsBridgeEth')?.value || '';
|
||||
let r = await apiFetch('/api/settings', {
|
||||
method: 'POST',
|
||||
timeout: 90000,
|
||||
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 || 'Erreur lors de l’enregistrement');
|
||||
|
||||
for (let attempt = 0; attempt < 25; attempt++) {
|
||||
await new Promise(resolve => setTimeout(resolve, 800));
|
||||
try {
|
||||
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) {
|
||||
if (m) {
|
||||
m.style.color = 'var(--red)';
|
||||
m.textContent = '❌ ' + tErr(e.message);
|
||||
}
|
||||
} finally {
|
||||
apActionInProgress = null;
|
||||
updateApButtons();
|
||||
setSettingsWifiInputsDisabled(false);
|
||||
if (settingsMessageTimer) clearTimeout(settingsMessageTimer);
|
||||
settingsMessageTimer = setTimeout(() => {
|
||||
if (m) m.textContent = '';
|
||||
settingsMessageTimer = null;
|
||||
}, 5000);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
$('logout').onclick = logout;
|
||||
|
||||
|
||||
+4
-1
@@ -1459,5 +1459,8 @@ window.I18N['en-gb'] = {
|
||||
"btn_stopping": "Stopping…",
|
||||
"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_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
@@ -1459,5 +1459,8 @@ window.I18N['en-us'] = {
|
||||
"btn_stopping": "Stopping…",
|
||||
"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_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
@@ -1459,5 +1459,8 @@ window.I18N['fr'] = {
|
||||
"btn_stopping": "Arrêt…",
|
||||
"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_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 !"
|
||||
};
|
||||
Reference in new issue
Block a user