diff --git a/ap.py b/ap.py index ca24a2a..f1f027a 100644 --- a/ap.py +++ b/ap.py @@ -2766,62 +2766,30 @@ def run_cmd(*args): return None def setup_bridge_dns_redirection(bridge_name='br0', iface=None): - """Intercepte les requêtes DNS (port 53 UDP/TCP) des clients Wi-Fi en mode pont pour les rediriger vers AP_DNS.""" - iface = iface or INTERFACE - dns_servers = get_dns_servers() - if not dns_servers or not iface: - return - - # Si l'interface Wi-Fi n'est pas active ou pas encore en mode AP, ne rien faire pour préserver l'hôte - if not is_iface_up(iface): - return - st = command('iw', 'dev', iface, 'info') or '' - if 'type AP' not in st: - return - - try: - # Redirection DNS propre ciblée UNIQUEMENT sur l'interface Wi-Fi via ebtables broute - # Cela détourne uniquement le port 53 des clients Wi-Fi vers la couche IP locale - for proto in ('udp', 'tcp'): - run_cmd('ebtables', '-t', 'broute', '-D', 'BROUTING', '-i', iface, '-p', 'IPv4', '--ip-proto', proto, '--ip-dport', '53', '-j', 'redirect', '--redirect-target', 'DROP') - run_cmd('ebtables', '-t', 'broute', '-A', 'BROUTING', '-i', iface, '-p', 'IPv4', '--ip-proto', proto, '--ip-dport', '53', '-j', 'redirect', '--redirect-target', 'DROP') - - # Chaîne personnalisée de redirection PREROUTING (DNAT) pour l'interface Wi-Fi uniquement - run_cmd('iptables', '-t', 'nat', '-N', 'AP_BRIDGE_DNS') - run_cmd('iptables', '-t', 'nat', '-F', 'AP_BRIDGE_DNS') - - for proto in ('udp', 'tcp'): - run_cmd('iptables', '-t', 'nat', '-D', 'PREROUTING', '-i', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS') - run_cmd('iptables', '-t', 'nat', '-I', 'PREROUTING', '1', '-i', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS') - - # Rediriger vers AP_DNS (avec répartition équitable si plusieurs serveurs) - n = len(dns_servers) - for idx, s in enumerate(dns_servers): - prob = round(1.0 / (n - idx), 4) if idx < n - 1 else None - for proto in ('udp', 'tcp'): - cmd = ['iptables', '-t', 'nat', '-A', 'AP_BRIDGE_DNS', '-p', proto, '--dport', '53'] - if prob is not None: - cmd += ['-m', 'statistic', '--mode', 'random', '--probability', str(prob)] - cmd += ['-j', 'DNAT', '--to-destination', f"{s}:53"] - run_cmd(*cmd) - - print(f"[ap-bridge] Redirection DNS active en mode Pont pour les clients Wi-Fi ({iface}) vers {', '.join(dns_servers)}", flush=True) - except Exception as e: - print(f"[ap-bridge] Erreur configuration redirection DNS : {e}", flush=True) + """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 les règles de redirection DNS du mode pont.""" + """Nettoie d'éventuelles règles résiduelles AP_BRIDGE_DNS sans jamais utiliser -m physdev (qui chargerait br_netfilter).""" iface = iface or INTERFACE try: - run_cmd('iptables', '-t', 'nat', '-F', 'AP_BRIDGE_DNS') - run_cmd('iptables', '-t', 'nat', '-F', 'AP_BRIDGE_DNS_POST') - for proto in ('udp', 'tcp'): - if iface: - run_cmd('iptables', '-t', 'nat', '-D', 'PREROUTING', '-i', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS') - run_cmd('iptables', '-t', 'nat', '-D', 'PREROUTING', '-m', 'physdev', '--physdev-in', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS') - run_cmd('iptables', '-t', 'nat', '-D', 'POSTROUTING', '-m', 'physdev', '--physdev-in', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS_POST') + for ipt in [b for b in (find_bin('iptables'),) if b]: + for proto in ('udp', 'tcp'): + 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: + pass + while subprocess.run([ipt, '-w', '2', '-t', 'nat', '-D', 'PREROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS'], capture_output=True).returncode == 0: + pass + while subprocess.run([ipt, '-w', '2', '-t', 'nat', '-D', 'POSTROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS_POST'], capture_output=True).returncode == 0: + pass + subprocess.run([ipt, '-w', '2', '-t', 'nat', '-F', 'AP_BRIDGE_DNS'], capture_output=True) + subprocess.run([ipt, '-w', '2', '-t', 'nat', '-X', 'AP_BRIDGE_DNS'], capture_output=True) + subprocess.run([ipt, '-w', '2', '-t', 'nat', '-F', 'AP_BRIDGE_DNS_POST'], capture_output=True) + subprocess.run([ipt, '-w', '2', '-t', 'nat', '-X', 'AP_BRIDGE_DNS_POST'], capture_output=True) + # 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'): run_cmd('ebtables', '-t', 'broute', '-D', 'BROUTING', '-i', iface, '-p', 'IPv4', '--ip-proto', proto, '--ip-dport', '53', '-j', 'redirect', '--redirect-target', 'DROP') - run_cmd('iptables', '-t', 'nat', '-D', 'POSTROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS_POST') except Exception: pass @@ -3016,7 +2984,7 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No 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.") - # 1. Arrêter toute ancienne instance hostapd et attendre que NetworkManager + wpa_supplicant libèrent complètement la carte Wi-Fi + # 1. Arrêter toute ancienne instance hostapd et libérer totalement wlan0 de NetworkManager et wpa_supplicant stop_hostapd(iface) was_managed = not (command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface) or '').startswith('10') subprocess.run(['nmcli', 'device', 'disconnect', iface], capture_output=True) @@ -3026,21 +2994,29 @@ def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=No if not st or st.startswith('10'): # 10 = unmanaged break time.sleep(0.2) - # Si la carte venait d'être gérée par NM, laisser wpa_supplicant finir le retrait D-Bus/nl80211 pour éviter tout conflit EAPOL au 1er démarrage + # Arrêter wpa_supplicant (lancé par D-Bus en mode -u sans nom d'interface) afin qu'il ne bloque jamais les trames EAPOL de hostapd. + # D-Bus le relancera automatiquement lors d'un retour en mode AP (NAT). if was_managed: - time.sleep(1.0) - # S'assurer qu'aucune instance wpa_supplicant résiduelle ne garde l'interface Wi-Fi verrouillée - subprocess.run(['pkill', '-f', f'wpa_supplicant.*{iface}'], capture_output=True) - time.sleep(0.3) + time.sleep(0.4) + subprocess.run(['pkill', '-x', 'wpa_supplicant'], capture_output=True) + for _ in range(15): + if subprocess.run(['pgrep', '-x', 'wpa_supplicant'], capture_output=True).returncode != 0: + break + time.sleep(0.1) + time.sleep(0.2) country = os.environ.get('AP_COUNTRY', 'FR').strip().upper() or 'FR' subprocess.run(['rfkill', 'unblock', 'wifi'], capture_output=True) subprocess.run(['iw', 'reg', 'set', country], capture_output=True) - # Remise à zéro propre de l'interface (DOWN -> flush -> nomaster) afin que hostapd l'initialise lui-même en mode AP + bridge + # Cycle complet DOWN -> managed -> UP -> DOWN pour vider l'ancien BSS/table de clés du firmware Raspberry Pi (brcmfmac) subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True) subprocess.run(['ip', 'addr', 'flush', 'dev', iface], capture_output=True) subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True) - time.sleep(0.2) + subprocess.run(['iw', 'dev', iface, 'set', 'type', 'managed'], capture_output=True) + subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True) + time.sleep(0.25) + subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True) + time.sleep(0.25) band = (AP_BAND or 'bg').strip().lower() hw_mode = 'a' if band == 'a' else 'g' @@ -3448,33 +3424,70 @@ def clients(): except ValueError: pass - def _extract_signal_dbm(blk, sta_mac): - # 1. « signal: -XX dBm » puis « signal avg: -XX dBm » (utilisé par brcmfmac sur Raspberry Pi) + def _extract_signal_info(blk, sta_mac): + """Retourne (signal_dbm, signal_estimated, link_rate_mbps) avec repli intelligent pour Raspberry Pi (brcmfmac).""" + def _parse_rates(text): + rates = [] + for rm in re.finditer(r'^\s*(?:tx|rx)\s+bitrate:\s*([\d.]+)\s*MBit/s', text or '', re.I | re.M): + try: + rv = float(rm.group(1)) + if rv > 0: + rates.append(rv) + except ValueError: + pass + return max(rates) if rates else None + + link_rate = _parse_rates(blk) + + # 1. « signal: -XX dBm » puis « signal avg: -XX dBm » for pat in (r'^\s*signal:\s*(-?\d+)', r'^\s*signal\s+avg:\s*(-?\d+)'): mm = re.search(pat, blk, re.I | re.M) if mm: try: val = int(mm.group(1)) if -120 <= val < 0: - return val + return val, False, link_rate except ValueError: pass # 2. Repli hostapd_cli all_sta (mode Pont) if sta_mac in hostapd_signals: - return hostapd_signals[sta_mac] - # 3. Repli « iw dev station get » (force une lecture fraîche du firmware brcmfmac) + return hostapd_signals[sta_mac], False, link_rate + # 3. Repli « iw dev station get » (force une lecture fraîche du firmware) g_out = command('iw', 'dev', INTERFACE, 'station', 'get', sta_mac.lower()) if g_out: + if link_rate is None: + link_rate = _parse_rates(g_out) for pat in (r'^\s*signal:\s*(-?\d+)', r'^\s*signal\s+avg:\s*(-?\d+)'): mm = re.search(pat, g_out, re.I | re.M) if mm: try: val = int(mm.group(1)) if -120 <= val < 0: - return val + return val, False, link_rate except ValueError: pass - return None + # 4. Repli Raspberry Pi (brcmfmac en mode AP ne remonte pas le RSSI brut) : estimation fiable via le débit PHY négocié (tx/rx bitrate) + if link_rate is not None and link_rate > 0: + if link_rate >= 58.0: est = -48 + elif link_rate >= 36.0: est = -57 + elif link_rate >= 18.0: est = -67 + else: est = -76 + return est, True, round(link_rate, 1) + # 5. Repli ultime si le firmware brcmfmac omet aussi les débits PHY : qualité déduite du taux de perte TX + tx_pkts_m = re.search(r'^\s*tx packets:\s*(\d+)', blk, re.I | re.M) + tx_fail_m = re.search(r'^\s*tx failed:\s*(\d+)', blk, re.I | re.M) + rx_pkts_m = re.search(r'^\s*rx packets:\s*(\d+)', blk, re.I | re.M) + tx_pkts = int(tx_pkts_m.group(1)) if tx_pkts_m else 0 + tx_fail = int(tx_fail_m.group(1)) if tx_fail_m else 0 + rx_pkts = int(rx_pkts_m.group(1)) if rx_pkts_m else 0 + if tx_pkts > 0 or rx_pkts > 0: + loss = tx_fail / max(1, tx_pkts + tx_fail) + if loss < 0.01: est = -49 + elif loss < 0.05: est = -58 + elif loss < 0.15: est = -67 + else: est = -76 + return est, True, None + return None, False, None for m in re.finditer(r'^Station ([0-9a-f:]{17})(.*?)(?=^Station |\Z)', dump, re.I|re.M|re.S): mac = m.group(1).upper(); detail = m.group(2) @@ -3482,7 +3495,7 @@ def clients(): # (authorized: no, 0 octet échangé). Ce ne sont pas des clients connectés. am = re.search(r'^\s*authorized:\s*(\w+)', detail, re.I|re.M) if am and am.group(1).lower() != 'yes' and mac not in blocked_macs: continue - sig_dbm = _extract_signal_dbm(detail, mac) + sig_dbm, sig_estimated, link_rate_mbps = _extract_signal_info(detail, mac) rx_m = re.search(r'^\s*rx bytes:\s*(\d+)', detail, re.I|re.M) tx_m = re.search(r'^\s*tx bytes:\s*(\d+)', detail, re.I|re.M) raw_rx = int(rx_m.group(1)) if rx_m else 0 @@ -3592,6 +3605,8 @@ def clients(): 'mac': mac, 'device_type': custom_types.get(mac) or guess_device_type(name, mac), 'signal_dbm': sig_dbm, + 'signal_estimated': sig_estimated, + 'link_rate_mbps': link_rate_mbps, 'blocked': blocked, 'connected': not blocked, 'download_speed': round(tx_rate), @@ -3902,9 +3917,9 @@ def sync_client_bandwidth_and_quotas(force=False): except Exception as e: print(f"[ap-limits] Erreur nftables bridge : {e}", flush=True) - # 3. Couche 2 Pont Ethernet (L2 Bridge) : ebtables (avec --concurrent) + # 3. Couche 2 Pont Ethernet (L2 Bridge) : ebtables (uniquement si blocage actif ou module déjà chargé) ebtables_bin = find_bin('ebtables') - if ebtables_bin: + if ebtables_bin and (all_blocked_macs or os.path.exists('/sys/module/ebtable_filter')): try: subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-N', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5) subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-F', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5) @@ -6647,7 +6662,8 @@ def sync_vpn_client_rules(): subprocess.run(['iptables', '-t', 'nat', '-F', 'AP_VPN_DNS'], capture_output=True) while subprocess.run(['iptables', '-t', 'mangle', '-D', 'PREROUTING', '-j', 'AP_VPN_MANGLE'], capture_output=True).returncode == 0: pass subprocess.run(['iptables', '-t', 'mangle', '-F', 'AP_VPN_MANGLE'], capture_output=True) - subprocess.run(['ebtables', '-t', 'broute', '-F', 'BROUTING'], capture_output=True) + if os.path.exists('/sys/module/ebtable_broute'): + subprocess.run(['ebtables', '-t', 'broute', '-F', 'BROUTING'], capture_output=True) nft_b = find_bin('nft') if nft_b: subprocess.run([nft_b, 'delete', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True) return diff --git a/index.html b/index.html index b8b93dc..1e98b69 100644 --- a/index.html +++ b/index.html @@ -9996,14 +9996,21 @@ ${vpnBadgeTopo} return (d ? d + 'j ' : '') + (h ? String(h).padStart(2, '0') + 'h ' : '') + String(m).padStart(2, '0') + 'm ' + String(sec).padStart(2, '0') + 's'; } function esc(s) { return String(s).replace(/([\\;,:])/g, '\\$1') } - function signalQuality(dbm) { + function signalQuality(dbm, client) { if (dbm === null || dbm === undefined || Number.isNaN(Number(dbm))) return '—'; const val = Math.round(Number(dbm)); - const dbmTag = ` (${val} dBm)`; - if (val >= -50) return `${t('signal_excellent', 'Excellent')}${dbmTag}`; - if (val >= -60) return `${t('signal_good', 'Bon')}${dbmTag}`; - if (val >= -70) return `${t('signal_fair', 'Moyen')}${dbmTag}`; - return `${t('signal_weak', 'Faible')}${dbmTag}`; + const isEst = !!(client && client.signal_estimated); + const rate = client && client.link_rate_mbps ? Number(client.link_rate_mbps) : null; + const suffix = isEst + ? (rate ? ` (${Math.round(rate)} Mbps)` : ` (~)`) + : ` (${val} dBm)`; + const tip = isEst + ? (rate ? `Estimé via lien Wi-Fi ${rate} MBit/s (pilote Raspberry Pi brcmfmac)` : `Qualité estimée via les statistiques de paquets (pilote Raspberry Pi brcmfmac)`) + : `${val} dBm`; + if (val >= -50) return `${t('signal_excellent', 'Excellent')}${suffix}`; + if (val >= -60) return `${t('signal_good', 'Bon')}${suffix}`; + if (val >= -70) return `${t('signal_fair', 'Moyen')}${suffix}`; + return `${t('signal_weak', 'Faible')}${suffix}`; } function cleanQrBox(box) { @@ -10241,13 +10248,9 @@ ${vpnBadgeTopo} : (c.vpn_profile_name ? (c.kill_switch ? `🛡️ ${t('vpn_killswitch_chk', 'Kill-Switch')}` - : `⚠️ Direct`) - : `🌐 ${t('topo_direct_wan', 'Direct WAN (Box)')}`); - const ipLabel = c.ip || t('not_assigned', 'Non attribuée'); - const nameLabel = String(c.name || t('name_unknown', 'Nom non communiqué')).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';'); const blockBtnLabel = c.blocked ? t('btn_unblock', 'Débloquer') : t('btn_block', 'Bloquer'); const quotaBtnLabel = '⚖️ ' + t('th_quota', 'Quota'); - return `
${String(c.name || '?')[0].toUpperCase()}
${nameLabel}
${ipLabel}${c.mac || '—'}${vpnHtml}${signalQuality(c.signal_dbm)}${speedHtml}
`; + return `
${String(c.name || '?')[0].toUpperCase()}
${nameLabel}
${ipLabel}${c.mac || '—'}${vpnHtml}${signalQuality(c.signal_dbm, c)}${speedHtml}
`; }).join('') : `${t('no_clients', 'Aucun client connecté')}`; renderPagination('clientsPagination', clientsPage, clients.length, 'changeClientsPage', 10);