#!/usr/bin/env python3
# ==============================================================================
# VERSION DU LOGICIEL AP MANAGEUR
# Modifiez cette variable pour changer la version dans toute l'application :
# ==============================================================================
APP_VERSION = 'V1.2 (Bêta)'
# ==============================================================================
import base64, copy, hashlib, hmac, json, os, re, secrets, socket, sqlite3, subprocess, threading, time, urllib.parse, urllib.request, urllib.error, socketserver, shutil, datetime, atexit, signal, struct, smtplib, ssl, ipaddress, queue, http.client, io, zipfile, tempfile
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
for p in ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin']:
if p not in os.environ.get('PATH', '').split(':'):
os.environ['PATH'] = p + ':' + os.environ.get('PATH', '')
INTERFACE = os.environ.get('AP_INTERFACE', 'wls16b1')
SOCKET_PATH = os.environ.get('AP_SOCKET', '/run/ap-api.sock')
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DB_FILE = os.environ.get('AP_DB_FILE', os.path.join(BASE_DIR, 'ap-dashboard.sqlite3'))
CONNECTION_FILE = os.environ.get('AP_CONNECTION_FILE', os.path.join(BASE_DIR, 'ap-dashboard-connection'))
UPTIME_FILE = os.environ.get('AP_UPTIME_FILE', os.path.join(BASE_DIR, 'ap-dashboard-uptime'))
def remove_uptime_file():
try:
if os.path.exists(UPTIME_FILE):
os.remove(UPTIME_FILE)
except OSError: pass
atexit.register(remove_uptime_file)
def _sig_handler(signum, frame):
remove_uptime_file()
os._exit(0)
try:
signal.signal(signal.SIGTERM, _sig_handler)
signal.signal(signal.SIGINT, _sig_handler)
except Exception: pass
# Auto-migration de l'ancienne DB si présente
OLD_DB_FILE = '/var/lib/ap-dashboard.sqlite3'
if not os.path.exists(DB_FILE) and os.path.exists(OLD_DB_FILE):
try:
import shutil
shutil.copy2(OLD_DB_FILE, DB_FILE)
except Exception: pass
# Exécution de commandes système
def command(*args, timeout=5):
try: return subprocess.check_output(args, text=True, stderr=subprocess.DEVNULL, timeout=timeout).strip()
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError): return ''
# Radio : 2,4 GHz ou 5 GHz.
AP_BAND = os.environ.get('AP_BAND', 'bg') if os.environ.get('AP_BAND', 'bg') in ('bg', 'a') else 'bg'
AP_CHANNEL_CONFIGURED = os.environ.get('AP_CHANNEL', '').strip()
_auto_channel_cache = {
'channel': None,
'band': None,
'time': 0,
'details': {}
}
_auto_channel_lock = threading.Lock()
def is_auto_channel():
"""Vérifie si AP_CHANNEL n'est pas renseigné ou est configuré sur 'auto' / '0'."""
raw = os.environ.get('AP_CHANNEL')
if raw is None:
return True
s = str(raw).strip().lower()
return s in ('', 'auto', '0', 'none', 'null')
def scan_neighboring_wifi_networks(iface=None):
"""
Scanne les réseaux Wi-Fi voisins pour mesurer l'encombrement par canal.
Utilise nmcli dev wifi list (avec rescan), iw dev scan, ou iw dev scan dump.
Retourne une liste de dicts : [{'channel': int, 'freq': int, 'signal_dbm': float, 'ssid': str}]
"""
iface = iface or INTERFACE
networks = []
seen_keys = set()
# 1. Tentative via nmcli (géré par NetworkManager)
try:
nm_out = command('nmcli', '-t', '-f', 'CHAN,SIGNAL,FREQ,SSID', 'dev', 'wifi', 'list', '--rescan', 'yes')
if not nm_out:
nm_out = command('nmcli', '-t', '-f', 'CHAN,SIGNAL,FREQ,SSID', 'dev', 'wifi', 'list')
if nm_out:
for line in nm_out.splitlines():
line = line.strip()
if not line or ':' not in line:
continue
parts = line.split(':')
if len(parts) >= 3:
try:
chan_str = parts[0].strip()
sig_str = parts[1].strip()
freq_str = parts[2].strip().replace('MHz', '').strip()
ssid_str = ':'.join(parts[3:]).strip() if len(parts) > 3 else ''
if not chan_str.isdigit():
continue
chan = int(chan_str)
sig_pct = int(sig_str) if sig_str.isdigit() else 50
sig_dbm = -100.0 + (sig_pct / 2.0)
freq = int(freq_str) if freq_str.isdigit() else (2407 + chan * 5 if chan <= 14 else 5000 + chan * 5)
key = (chan, freq, round(sig_dbm, 0), ssid_str)
if key not in seen_keys:
seen_keys.add(key)
networks.append({'channel': chan, 'freq': freq, 'signal_dbm': sig_dbm, 'ssid': ssid_str})
except Exception:
pass
except Exception as e:
print(f"[ap-wifi] [Auto-Channel] Scan nmcli indisponible : {e}", flush=True)
# 2. Si nmcli n'a rien retourné (ex: carte hors NM à cet instant), tenter iw
if not networks and iface:
try:
iw_out = command('iw', 'dev', iface, 'scan')
if not iw_out:
iw_out = command('iw', 'dev', iface, 'scan', 'dump')
if iw_out:
curr_net = {}
for line in iw_out.splitlines():
line = line.strip()
if line.startswith('BSS '):
if curr_net.get('channel') is not None:
key = (curr_net.get('channel'), curr_net.get('freq', 0), round(curr_net.get('signal_dbm', -70), 0), curr_net.get('ssid', ''))
if key not in seen_keys:
seen_keys.add(key)
networks.append(dict(curr_net))
curr_net = {'channel': None, 'freq': 0, 'signal_dbm': -70.0, 'ssid': ''}
elif line.startswith('freq:'):
parts = line.split()
if len(parts) >= 2 and parts[1].isdigit():
f = int(parts[1])
curr_net['freq'] = f
if curr_net.get('channel') is None:
if 2412 <= f <= 2484:
curr_net['channel'] = 14 if f == 2484 else (f - 2407) // 5
elif 5000 <= f <= 5900:
curr_net['channel'] = (f - 5000) // 5
elif line.startswith('signal:'):
m_sig = re.search(r'([-0-9\.]+)\s*dBm', line)
if m_sig:
curr_net['signal_dbm'] = float(m_sig.group(1))
elif 'primary channel:' in line or 'DS Parameter set: channel' in line:
m_ch = re.search(r'channel\s*(\d+)', line)
if m_ch:
curr_net['channel'] = int(m_ch.group(1))
elif line.startswith('SSID:'):
curr_net['ssid'] = line.replace('SSID:', '').strip()
if curr_net.get('channel') is not None:
key = (curr_net.get('channel'), curr_net.get('freq', 0), round(curr_net.get('signal_dbm', -70), 0), curr_net.get('ssid', ''))
if key not in seen_keys:
seen_keys.add(key)
networks.append(dict(curr_net))
except Exception as e:
print(f"[ap-wifi] [Auto-Channel] Scan iw indisponible : {e}", flush=True)
return networks
def calculate_best_channel(networks, band='bg'):
"""
Analyse les réseaux scannés et calcule le canal optimal (le moins encombré et le plus rapide).
Pour 2.4 GHz ('bg') :
- Évalue les canaux non recouvrants standard : 1, 6, 11 (et 13 pour l'Europe/France).
- Calcule l'encombrement en tenant compte du débordement spectral adjacent (|c - c_voisin| <= 4).
- Privilégie le canal ayant le score de collision le plus bas pour garantir le meilleur débit Wi-Fi.
Pour 5 GHz ('a') :
- Évalue les canaux U-NII-1 (36, 40, 44, 48) sans radar DFS, permettant des largeurs 40/80 MHz immédiates.
"""
band = (band or 'bg').lower().strip()
is_5g = (band == 'a')
if is_5g:
candidates = [36, 40, 44, 48]
relevant_nets = [n for n in networks if n.get('freq', 0) > 4000 or n.get('channel', 0) >= 36]
else:
candidates = [1, 6, 11, 13]
relevant_nets = [n for n in networks if n.get('freq', 0) < 4000 and n.get('channel', 0) <= 14]
scores = {}
net_counts = {}
for cand in candidates:
score = 0.0
count = 0
for net in relevant_nets:
c_net = net.get('channel')
if c_net is None:
continue
sig_dbm = net.get('signal_dbm', -75.0)
if sig_dbm >= -55:
weight = 100.0
elif sig_dbm >= -67:
weight = 50.0
elif sig_dbm >= -75:
weight = 25.0
elif sig_dbm >= -85:
weight = 10.0
else:
weight = 3.0
if is_5g:
if c_net == cand:
score += weight * 1.5
count += 1
elif abs(c_net - cand) <= 12:
score += weight * 0.3
count += 1
else:
diff = abs(c_net - cand)
if diff == 0:
score += weight * 1.5
count += 1
elif diff == 1:
score += weight * 0.85
count += 1
elif diff == 2:
score += weight * 0.60
count += 1
elif diff == 3:
score += weight * 0.35
count += 1
elif diff == 4:
score += weight * 0.15
count += 1
scores[cand] = score
net_counts[cand] = count
tie_breaker_order = [36, 44, 40, 48] if is_5g else [6, 1, 11, 13]
def sort_key(ch):
pref_idx = tie_breaker_order.index(ch) if ch in tie_breaker_order else 99
return (scores.get(ch, 0.0), pref_idx)
best_channel = min(candidates, key=sort_key)
return best_channel, scores, net_counts
def detect_best_wifi_channel(band=None, iface=None, force_rescan=False):
"""
Détecte automatiquement le meilleur canal Wi-Fi (le moins encombré et le plus rapide).
Met en cache le résultat pendant 30 minutes sauf si force_rescan=True.
"""
band = (band or AP_BAND or 'bg').lower().strip()
iface = iface or INTERFACE
now = time.time()
with _auto_channel_lock:
if not force_rescan and _auto_channel_cache['channel'] is not None and (now - _auto_channel_cache['time'] < 1800) and (_auto_channel_cache['band'] == band):
return _auto_channel_cache['channel']
print(f"[ap-wifi] [Auto-Channel] Analyse de l'environnement radio Wi-Fi sur {iface} (bande {band})...", flush=True)
networks = scan_neighboring_wifi_networks(iface=iface)
best_chan, scores, counts = calculate_best_channel(networks, band=band)
scores_repr = ', '.join([f"Ch.{ch}: score={scores.get(ch, 0):.0f} ({counts.get(ch, 0)} AP)" for ch in sorted(scores.keys())])
print(f"[ap-wifi] [Auto-Channel] {len(networks)} réseau(x) détecté(s). Encombrement : [{scores_repr}] -> Canal {best_chan} sélectionné (le plus rapide & disponible)", flush=True)
with _auto_channel_lock:
_auto_channel_cache['channel'] = best_chan
_auto_channel_cache['band'] = band
_auto_channel_cache['time'] = now
_auto_channel_cache['details'] = {
'best_channel': best_chan,
'band': band,
'scores': scores,
'counts': counts,
'total_networks': len(networks),
'scanned_at': time.strftime('%Y-%m-%d %H:%M:%S')
}
return best_chan
def get_effective_ap_channel(band=None, force_rescan=False):
"""
Retourne le canal effectif à utiliser pour le point d'accès :
- Canal fixe si AP_CHANNEL est renseigné dans docker-compose (ex. '6', '11', '36')
- Canal automatique scanné (le moins utilisé et plus rapide) si AP_CHANNEL n'est pas renseigné ou est 'auto'
"""
if is_auto_channel():
return detect_best_wifi_channel(band=band or AP_BAND, force_rescan=force_rescan)
try:
val = int(os.environ.get('AP_CHANNEL', '6').strip())
return val if val > 0 else 6
except (TypeError, ValueError):
return 6
# Initialisation du canal par défaut
if not is_auto_channel():
try: AP_CHANNEL = int(AP_CHANNEL_CONFIGURED)
except ValueError: AP_CHANNEL = 6
else:
AP_CHANNEL = get_effective_ap_channel(AP_BAND)
SERVER_BOOT_TIME = time.time()
app_startup_done = False
SESSION_TTL = 30 * 86400 # 30 jours (1 mois)
sessions = {}
last_macs = set()
def uptime_start():
try: return float(open(UPTIME_FILE, encoding='utf8').read().strip())
except (OSError, ValueError): return None
def mark_ap_started():
try:
folder = os.path.dirname(UPTIME_FILE)
if folder: os.makedirs(folder, exist_ok=True)
open(UPTIME_FILE, 'w', encoding='utf8').write(str(time.time()))
except OSError: pass
def ap_uptime():
started = uptime_start()
return max(0, int(time.time() - started)) if started else 0
def lease_entries():
"""Baux dnsmasq (mac, ip, hostname) de TOUS les fichiers existants.
En mode pont, dnsmasq est inactif : les baux résiduels 10.42.x.x sont ignorés."""
try:
if is_bridge_mode(): return []
except Exception: pass
import glob
files = ['/var/lib/misc/dnsmasq.leases', '/var/lib/NetworkManager/dnsmasq.leases', '/data/nm-state/dnsmasq.leases']
files += sorted(glob.glob('/var/lib/NetworkManager/dnsmasq-*.leases') + glob.glob('/data/nm-state/dnsmasq-*.leases'))
entries = []
for path in files:
try:
with open(path, encoding='utf8') as f:
for line in f:
fields = line.split()
if len(fields) >= 4: entries.append((fields[1].upper(), fields[2], fields[3]))
except (OSError, UnicodeError): continue
return entries
def is_valid_mac(mac):
"""Vérifie si une chaîne correspond strictement au format d'une adresse MAC valide."""
if not mac or not isinstance(mac, str):
return False
clean = mac.strip().upper().replace('-', ':')
return bool(re.fullmatch(r'[0-9A-F]{2}(:[0-9A-F]{2}){5}', clean))
_device_name_cache = {} # mac -> (name, expiry_timestamp)
_journal_dhcp_cache = {'time': 0, 'entries': {}}
station_live_names = {} # mac -> hostname réel capturé en direct (DHCP, mDNS, NetBIOS, DNS)
def clean_extracted_hostname(name):
"""Nettoie et valide un nom d'hôte extrait du réseau (DHCP, mDNS, NetBIOS, DNS)."""
if not name or not isinstance(name, str):
return ''
name = name.strip('\x00 \t\r\n')
for suffix in ('.local', '.lan', '.home', '.domain', '.localdomain', '.fritz.box', '.livebox', '.bbox', '.sfr'):
if name.lower().endswith(suffix):
name = name[:-len(suffix)]
name = re.sub(r'[^a-zA-Z0-9_\-\.\s]', '', name).strip()
if len(name) < 2 or len(name) > 64:
return ''
if re.fullmatch(r'\d{1,3}(\.\d{1,3}){3}', name):
return ''
if re.fullmatch(r'([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}', name):
return ''
if name.lower() in ('localhost', 'unknown', 'none', 'null', 'client', 'gateway', 'router', 'wpad', 'in-addr', 'ip6'):
return ''
return name
def extract_dhcp_hostname_from_udp(payload):
"""Extrait le nom d'hôte de l'option DHCP 12 (Host Name) ou option 81 (Client FQDN) d'un paquet DHCP."""
try:
cookie_idx = payload.find(b'\x63\x82\x53\x63')
if cookie_idx < 0:
return ''
idx = cookie_idx + 4
length = len(payload)
hostname = ''
fqdn = ''
while idx < length:
opt = payload[idx]
if opt == 255:
break
if opt == 0:
idx += 1
continue
if idx + 1 >= length:
break
opt_len = payload[idx + 1]
opt_data = payload[idx + 2 : idx + 2 + opt_len]
if opt == 12:
try:
hostname = opt_data.decode('utf-8', errors='ignore')
except Exception:
pass
elif opt == 81 and opt_len >= 3:
try:
raw_fqdn = opt_data[3:]
if raw_fqdn and raw_fqdn[0] < 32:
parts = []
p_idx = 0
while p_idx < len(raw_fqdn):
plen = raw_fqdn[p_idx]
if plen == 0:
break
p_idx += 1
parts.append(raw_fqdn[p_idx:p_idx+plen].decode('utf-8', errors='ignore'))
p_idx += plen
fqdn = '.'.join(parts)
else:
fqdn = raw_fqdn.decode('utf-8', errors='ignore')
except Exception:
pass
idx += 2 + opt_len
return clean_extracted_hostname(hostname) or clean_extracted_hostname(fqdn)
except Exception:
return ''
def extract_dns_name_from_packet(payload):
"""Extrait le premier nom d'hôte complet d'un paquet DNS, mDNS (5353) ou LLMNR (5355)."""
try:
if len(payload) < 12:
return ''
idx = 12
length = len(payload)
labels = []
while idx < length:
lbl_len = payload[idx]
if lbl_len == 0:
break
if lbl_len > 63 or idx + 1 + lbl_len > length:
return ''
idx += 1
labels.append(payload[idx:idx+lbl_len].decode('utf-8', errors='ignore'))
idx += lbl_len
if not labels:
return ''
full_domain = '.'.join(labels)
if len(labels) == 2 and labels[1].lower() == 'local':
return clean_extracted_hostname(labels[0])
elif len(labels) == 1:
return clean_extracted_hostname(labels[0])
elif full_domain.lower().endswith('.local'):
return clean_extracted_hostname(labels[0])
return clean_extracted_hostname(full_domain)
except Exception:
return ''
def build_netbios_status_query():
"""Génère un paquet NetBIOS Node Status Query (UDP 137)."""
return b'\x13\x37\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x20CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\x00\x00\x21\x00\x01'
def parse_netbios_response(data):
"""Extrait le nom de machine NetBIOS d'une réponse Node Status."""
try:
if len(data) < 57:
return ''
num_names = data[56]
offset = 57
for _ in range(num_names):
if offset + 18 > len(data):
break
raw_name = data[offset : offset + 15].decode('ascii', errors='ignore').strip()
name_type = data[offset + 15]
if name_type == 0x00 and raw_name and not raw_name.startswith('__MSBROWSE__'):
cleaned = clean_extracted_hostname(raw_name)
if cleaned:
return cleaned
offset += 18
return ''
except Exception:
return ''
def quick_reverse_dns(ip):
"""Résolution DNS inverse rapide (les box internet Freebox/Livebox/etc. enregistrent les noms d'hôtes)."""
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 ''
def query_netbios_name(ip):
"""Interroge le nom NetBIOS d'un client Windows / NAS / Samba sur UDP 137."""
if not ip or ip in ('Non attribuée', '—', '127.0.0.1') or ip.startswith(('0.', '169.254.', '255.')):
return ''
sock = None
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(0.35)
pkt = build_netbios_status_query()
sock.sendto(pkt, (ip, 137))
resp, _ = sock.recvfrom(1024)
return parse_netbios_response(resp)
except Exception:
pass
finally:
if sock:
try: sock.close()
except Exception: pass
return ''
def record_live_device_name(mac, name, ip=None):
"""Enregistre en mémoire le vrai nom d'un appareil détecté lors de la connexion."""
if not mac or not name:
return
mac = mac.upper()
name = clean_extracted_hostname(name)
if not name or name.startswith('Client ') or name == 'Nom non communiqué':
return
try:
c = db()
ts = time.strftime('%Y-%m-%d %H:%M:%S')
cn_cols = {col[1] for col in c.execute('PRAGMA table_info(client_names)').fetchall()}
has_cust = 'is_custom' in cn_cols
q = "SELECT name, COALESCE(is_custom, 0) FROM client_names WHERE UPPER(mac)=?" if has_cust else "SELECT name, 0 FROM client_names WHERE UPPER(mac)=?"
row = c.execute(q, (mac,)).fetchone()
if row:
if row[1]: # is_custom == 1 : nom personnalisé par l'utilisateur !
# Conserver impérativement le nom personnalisé de l'utilisateur
station_live_names[mac] = row[0]
_device_name_cache[mac] = (row[0], time.time() + 86400)
if ip and ip not in ('Non attribuée', '', '—'):
c.execute("UPDATE client_names SET last_ip=?, last_seen=? WHERE UPPER(mac)=?", (ip, ts, mac))
c.commit()
c.close()
return
station_live_names[mac] = name
_device_name_cache[mac] = (name, time.time() + 300)
if row[0] in ('Nom non communiqué', '', None) or row[0].startswith('Client '):
if ip and ip not in ('Non attribuée', '', '—'):
c.execute("UPDATE client_names SET name=?, last_ip=?, last_seen=? WHERE UPPER(mac)=?",
(name, ip, ts, mac))
else:
c.execute("UPDATE client_names SET name=?, last_seen=? WHERE UPPER(mac)=?",
(name, ts, mac))
elif ip and ip not in ('Non attribuée', '', '—'):
c.execute("UPDATE client_names SET last_ip=?, last_seen=? WHERE UPPER(mac)=?", (ip, ts, mac))
# Mettre à jour rétroactivement les logs très récents qui avaient un nom générique
c.execute('''
UPDATE connection_logs
SET name = ?
WHERE UPPER(mac) = ?
AND (name LIKE 'Client %' OR name = 'Nom non communiqué' OR name = '' OR name IS NULL)
AND id >= (SELECT COALESCE(MAX(id)-20, 0) FROM connection_logs)
''', (name, mac))
c.commit()
c.close()
except Exception:
pass
def resolve_client_hostname_now(ip, mac):
"""Résout de manière active et multicanale le vrai nom d'hôte d'un client Wi-Fi."""
mac = (mac or '').upper()
if mac in station_live_names:
return station_live_names[mac]
try:
c = db()
row = c.execute("SELECT name FROM client_names WHERE UPPER(mac)=?", (mac,)).fetchone()
c.close()
if row and row[0] and not row[0].startswith('Client ') and row[0] != 'Nom non communiqué':
station_live_names[mac] = row[0]
return row[0]
except Exception:
pass
try: is_bridge = is_bridge_mode()
except Exception: is_bridge = False
if not is_bridge:
for l_mac, l_ip, l_host in reversed(lease_entries()):
if l_mac == mac or (ip and l_ip == ip):
if l_host and l_host != '*':
cl = clean_extracted_hostname(l_host)
if cl:
record_live_device_name(mac, cl, ip)
return cl
dhcp_entries = get_journal_dhcp_entries()
if mac in dhcp_entries:
cl = clean_extracted_hostname(dhcp_entries[mac])
if cl:
record_live_device_name(mac, cl, ip)
return cl
if ip and ip not in ('Non attribuée', '—'):
rdns = quick_reverse_dns(ip)
if rdns:
record_live_device_name(mac, rdns, ip)
return rdns
if ip and ip not in ('Non attribuée', '—'):
nb_name = query_netbios_name(ip)
if nb_name:
record_live_device_name(mac, nb_name, ip)
return nb_name
return ''
def get_journal_dhcp_entries():
now = time.time()
if now - _journal_dhcp_cache['time'] < 15:
return _journal_dhcp_cache['entries']
entries = {}
try:
journal = command('journalctl', '-u', 'NetworkManager', '--no-pager', '-n', '200', timeout=1)
pattern = r'DHCPACK\([^)]*\)\s+(\S+)\s+([0-9a-f:]{17})\s+(\S+)'
for line in reversed(journal.splitlines()):
m = re.search(pattern, line, re.I)
if m:
j_mac = m.group(2).upper()
j_host = m.group(3).strip()
if j_host and j_host != '*' and j_mac not in entries:
entries[j_mac] = j_host
except Exception:
pass
_journal_dhcp_cache['time'] = now
_journal_dhcp_cache['entries'] = entries
return entries
def device_name(ip, mac):
mac = (mac or '').upper()
now = time.time()
if mac and mac in _device_name_cache:
c_name, c_exp = _device_name_cache[mac]
if not c_name.startswith('Client ') and c_name != 'Nom non communiqué':
if now < c_exp:
return c_name
elif now < c_exp:
return c_name
# 1. Base de données client_names (nom personnalisé ou précédemment appris)
if mac:
try:
c = db()
cn_cols = {col[1] for col in c.execute('PRAGMA table_info(client_names)').fetchall()}
has_cust = 'is_custom' in cn_cols
q = 'SELECT name, COALESCE(is_custom, 0) FROM client_names WHERE UPPER(mac)=?' if has_cust else 'SELECT name, 0 FROM client_names WHERE UPPER(mac)=?'
row = c.execute(q, (mac,)).fetchone()
c.close()
if row and row[0]:
is_cust = bool(row[1])
if is_cust:
_device_name_cache[mac] = (row[0], now + 86400)
station_live_names[mac] = row[0]
return row[0]
elif not row[0].startswith('Client ') and row[0] != 'Nom non communiqué':
_device_name_cache[mac] = (row[0], now + 300)
return row[0]
except sqlite3.Error: pass
# 2. Nom capturé en direct (DHCP sniffer, mDNS, LLMNR, NetBIOS)
if mac and mac in station_live_names:
_device_name_cache[mac] = (station_live_names[mac], now + 300)
return station_live_names[mac]
# 3. Résolution active immédiate (Reverse DNS, NetBIOS, Baux)
if ip and ip not in ('Non attribuée', '—'):
res_name = resolve_client_hostname_now(ip, mac)
if res_name:
_device_name_cache[mac] = (res_name, now + 300)
return res_name
# 4. Baux DHCP dnsmasq (NAT)
try: is_bridge = is_bridge_mode()
except Exception: is_bridge = False
if not is_bridge:
for l_mac, l_ip, l_host in reversed(lease_entries()):
if l_mac == mac or (ip and l_ip == ip):
if l_host and l_host != '*':
name = clean_extracted_hostname(l_host)
if name:
record_live_device_name(mac, name, ip)
_device_name_cache[mac] = (name, now + 300)
return name
dhcp_entries = get_journal_dhcp_entries()
if mac in dhcp_entries:
name = clean_extracted_hostname(dhcp_entries[mac])
if name:
record_live_device_name(mac, name, ip)
_device_name_cache[mac] = (name, now + 300)
return name
# 5. Table des voisins ARP (ip neigh)
if ip and ip not in ('Non attribuée', '—') and not (is_bridge and ip.startswith('10.42.')):
host_line = command('ip', 'neigh', 'show', ip, timeout=1)
match = re.search(r'\(([^)]+)\)', host_line)
if match and match.group(1) != ip:
name = clean_extracted_hostname(match.group(1))
if name:
record_live_device_name(mac, name, ip)
_device_name_cache[mac] = (name, now + 300)
return name
# 6. Nom en base même si générique
if mac:
try:
c = db(); row = c.execute('SELECT name FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close()
if row and row[0]:
_device_name_cache[mac] = (row[0], now + 1.5)
return row[0]
except sqlite3.Error: pass
fallback = 'Client ' + mac.replace(':', '')[-4:] if mac else 'Nom non communiqué'
if mac:
_device_name_cache[mac] = (fallback, now + 1.5)
return fallback
# __AUTHENTICATION_IMPLEMENTATION__
_db_initialized = False
_db_init_lock = threading.Lock()
def init_db():
global _db_initialized
with _db_init_lock:
if _db_initialized:
return
folder = os.path.dirname(DB_FILE)
if folder: os.makedirs(folder, exist_ok=True)
c = sqlite3.connect(DB_FILE, timeout=30.0)
try:
c.execute('PRAGMA journal_mode = WAL')
c.execute('PRAGMA synchronous = NORMAL')
c.execute('PRAGMA busy_timeout = 30000')
c.execute('CREATE TABLE IF NOT EXISTS auth_users (username TEXT PRIMARY KEY, password_hash TEXT NOT NULL)')
columns = {row[1] for row in c.execute('PRAGMA table_info(auth_users)').fetchall()}
if 'totp_secret' not in columns:
c.execute('ALTER TABLE auth_users ADD COLUMN totp_secret TEXT DEFAULT NULL')
c.commit()
recovery_table(c)
c.execute('CREATE TABLE IF NOT EXISTS connection_logs(id INTEGER PRIMARY KEY,event_time TEXT,event TEXT,name TEXT,ip TEXT,mac TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS blocked_clients(mac TEXT PRIMARY KEY,blocked_at TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS client_names(mac TEXT PRIMARY KEY,name TEXT NOT NULL,last_ip TEXT,last_seen TEXT,device_type TEXT DEFAULT "",is_custom INTEGER DEFAULT 0)')
cn_cols = {row[1] for row in c.execute('PRAGMA table_info(client_names)').fetchall()}
if 'device_type' not in cn_cols:
try:
c.execute('ALTER TABLE client_names ADD COLUMN device_type TEXT DEFAULT ""')
c.commit()
except Exception: pass
if 'is_custom' not in cn_cols:
try:
c.execute('ALTER TABLE client_names ADD COLUMN is_custom INTEGER DEFAULT 0')
c.commit()
except Exception: pass
c.execute('CREATE TABLE IF NOT EXISTS client_traffic(mac TEXT PRIMARY KEY, rx_bytes INTEGER DEFAULT 0, tx_bytes INTEGER DEFAULT 0, last_updated TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS client_traffic_daily(mac TEXT, traffic_date TEXT, rx_bytes INTEGER DEFAULT 0, tx_bytes INTEGER DEFAULT 0, PRIMARY KEY(mac, traffic_date))')
c.execute('CREATE INDEX IF NOT EXISTS idx_client_traffic_daily_date ON client_traffic_daily(traffic_date)')
try:
cnt_daily = c.execute("SELECT COUNT(*) FROM client_traffic_daily").fetchone()[0]
if cnt_daily == 0:
today_str = time.strftime('%Y-%m-%d')
c.execute('''
INSERT OR IGNORE INTO client_traffic_daily(mac, traffic_date, rx_bytes, tx_bytes)
SELECT mac, COALESCE(SUBSTR(last_updated, 1, 10), ?), rx_bytes, tx_bytes
FROM client_traffic
WHERE rx_bytes > 0 OR tx_bytes > 0
''', (today_str,))
c.commit()
except Exception: pass
c.execute('CREATE TABLE IF NOT EXISTS preferences(key TEXT PRIMARY KEY, value TEXT NOT NULL)')
c.execute('CREATE TABLE IF NOT EXISTS geoip_cache (ip TEXT PRIMARY KEY, code TEXT, country TEXT, flag TEXT, created_at REAL)')
c.execute('CREATE TABLE IF NOT EXISTS vpn_profiles (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, type TEXT NOT NULL, config_content TEXT NOT NULL, auth_user TEXT DEFAULT "", auth_pass TEXT DEFAULT "", table_id INTEGER DEFAULT 101, iface TEXT DEFAULT "", auto_connect INTEGER DEFAULT 0, status TEXT DEFAULT "disconnected", last_error TEXT DEFAULT "", created_at TEXT DEFAULT "", updated_at TEXT DEFAULT "")')
c.execute('CREATE TABLE IF NOT EXISTS client_vpn_routes (mac TEXT PRIMARY KEY, profile_id INTEGER DEFAULT 0, kill_switch INTEGER DEFAULT 0, updated_at TEXT DEFAULT "")')
c.execute('CREATE TABLE IF NOT EXISTS auth_sessions(token TEXT PRIMARY KEY, username TEXT, expires REAL, ip TEXT DEFAULT "", ua TEXT DEFAULT "", device_name TEXT DEFAULT "", os_name TEXT DEFAULT "", created_at TEXT DEFAULT "", last_seen TEXT DEFAULT "")')
session_cols = {row[1] for row in c.execute('PRAGMA table_info(auth_sessions)').fetchall()}
for col in ('ip', 'ua', 'device_name', 'os_name', 'browser_name', 'created_at', 'last_seen'):
if col not in session_cols:
try: c.execute(f'ALTER TABLE auth_sessions ADD COLUMN {col} TEXT DEFAULT ""')
except Exception: pass
c.execute('CREATE TABLE IF NOT EXISTS auth_passkeys(id TEXT PRIMARY KEY, username TEXT NOT NULL, public_key TEXT NOT NULL, name TEXT NOT NULL, device_type TEXT DEFAULT "security_key", sign_count INTEGER DEFAULT 0, created_at TEXT DEFAULT "", last_used_at TEXT DEFAULT "")')
c.execute('''
CREATE TABLE IF NOT EXISTS client_limits (
mac TEXT PRIMARY KEY,
quota_enabled INTEGER DEFAULT 0,
quota_bytes INTEGER DEFAULT 0,
quota_period TEXT DEFAULT 'total',
bandwidth_enabled INTEGER DEFAULT 0,
rate_down_kbps INTEGER DEFAULT 0,
rate_up_kbps INTEGER DEFAULT 0,
quota_action TEXT DEFAULT 'block',
updated_at TEXT DEFAULT ''
)
''')
c.execute('''
CREATE TABLE IF NOT EXISTS api_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
key_hash TEXT UNIQUE NOT NULL,
prefix TEXT NOT NULL,
permissions TEXT NOT NULL,
created_at TEXT NOT NULL,
expires_at TEXT DEFAULT NULL,
last_used_at TEXT DEFAULT NULL,
last_ip TEXT DEFAULT NULL,
is_active INTEGER DEFAULT 1
)
''')
init_device_types_table(c)
# Assainissement et nettoyage des anciennes données non-MAC (sauvegardes, audits, etc.)
try:
# Mettre à jour les logs système/sauvegarde où l'adresse MAC contient du texte non valide
c.execute("""
UPDATE connection_logs
SET mac = 'BACKUP'
WHERE (
event LIKE '%sauvegarde%'
OR event LIKE '%distant%'
OR event LIKE '%export%'
OR event LIKE '%import%'
OR event LIKE '%planification%'
) AND mac != 'BACKUP' AND mac != 'SYSTEM'
""")
c.execute("""
UPDATE connection_logs
SET mac = 'BACKUP'
WHERE mac LIKE '%:%' AND LENGTH(mac) != 17
""")
# Supprimer les entrées corrompues avec de fausses adresses MAC dans les tables d'équipements
c.execute("DELETE FROM client_names WHERE mac NOT LIKE '__:__:__:__:__:__' AND mac NOT LIKE '__-__-__-__-__-__'")
c.execute("DELETE FROM client_traffic WHERE mac NOT LIKE '__:__:__:__:__:__' AND mac NOT LIKE '__-__-__-__-__-__'")
c.execute("DELETE FROM client_traffic_daily WHERE mac NOT LIKE '__:__:__:__:__:__' AND mac NOT LIKE '__-__-__-__-__-__'")
c.execute("DELETE FROM client_limits WHERE mac NOT LIKE '__:__:__:__:__:__' AND mac NOT LIKE '__-__-__-__-__-__'")
c.execute("DELETE FROM client_vpn_routes WHERE mac NOT LIKE '__:__:__:__:__:__' AND mac NOT LIKE '__-__-__-__-__-__'")
c.execute("DELETE FROM blocked_clients WHERE mac NOT LIKE '__:__:__:__:__:__' AND mac NOT LIKE '__-__-__-__-__-__'")
# Harmonisation des journaux : 127.0.0.1 -> SYSTEM
c.execute("UPDATE connection_logs SET ip='SYSTEM' WHERE ip IN ('127.0.0.1', '::1', 'localhost')")
# Rétro-alimentation de client_names à partir des connexions antérieures ayant un nom et une IP
c.execute('''
INSERT INTO client_names (mac, name, last_ip, last_seen)
SELECT UPPER(mac), name, ip, event_time
FROM connection_logs
WHERE event LIKE '%connexion%'
AND mac LIKE '__:__:__:__:__:__'
AND name NOT IN ('Nom non communiqué', '')
AND ip NOT IN ('Non attribuée', '', '—')
ORDER BY id ASC
ON CONFLICT(mac) DO UPDATE SET
name = CASE
WHEN excluded.name NOT LIKE 'Client %' AND excluded.name != 'Nom non communiqué' THEN excluded.name
WHEN client_names.name IS NULL OR client_names.name = '' OR client_names.name = 'Nom non communiqué' THEN excluded.name
ELSE client_names.name
END,
last_ip = CASE WHEN excluded.last_ip NOT IN ('Non attribuée', '', '—') THEN excluded.last_ip ELSE client_names.last_ip END,
last_seen = excluded.last_seen
''')
# Purger les équipements fantômes du LAN qui ne se sont jamais connectés en Wi-Fi
c.execute('''
DELETE FROM client_names
WHERE UPPER(mac) NOT IN (SELECT UPPER(mac) FROM connection_logs WHERE event IN ('connexion', 'déconnexion'))
AND UPPER(mac) NOT IN (SELECT UPPER(mac) FROM blocked_clients)
AND UPPER(mac) NOT IN (SELECT UPPER(mac) FROM client_limits)
AND UPPER(mac) NOT IN (SELECT UPPER(mac) FROM client_traffic WHERE rx_bytes > 0 OR tx_bytes > 0)
''')
# Mise à jour rétroactive des logs ayant un nom manquant
c.execute('''
UPDATE connection_logs
SET name = (
SELECT name FROM client_names
WHERE UPPER(client_names.mac) = UPPER(connection_logs.mac)
AND client_names.name NOT IN ('Nom non communiqué', '')
LIMIT 1
)
WHERE (name = 'Nom non communiqué' OR name IS NULL OR name = '')
AND mac LIKE '__:__:__:__:__:__'
AND EXISTS (
SELECT 1 FROM client_names
WHERE UPPER(client_names.mac) = UPPER(connection_logs.mac)
AND client_names.name NOT IN ('Nom non communiqué', '')
)
''')
# Mise à jour rétroactive des logs ayant un nom manquant à partir des autres logs du même appareil
c.execute('''
UPDATE connection_logs
SET name = (
SELECT name FROM connection_logs l2
WHERE UPPER(l2.mac) = UPPER(connection_logs.mac)
AND l2.name NOT IN ('Nom non communiqué', '', 'Inconnu')
AND l2.name IS NOT NULL
ORDER BY l2.id DESC LIMIT 1
)
WHERE (name = 'Nom non communiqué' OR name IS NULL OR name = '' OR name = 'Inconnu')
AND mac LIKE '__:__:__:__:__:__'
AND EXISTS (
SELECT 1 FROM connection_logs l2
WHERE UPPER(l2.mac) = UPPER(connection_logs.mac)
AND l2.name NOT IN ('Nom non communiqué', '', 'Inconnu')
AND l2.name IS NOT NULL
)
''')
# Mise à jour rétroactive des logs ayant une IP manquante
c.execute('''
UPDATE connection_logs
SET ip = (
SELECT last_ip FROM client_names
WHERE UPPER(client_names.mac) = UPPER(connection_logs.mac)
AND client_names.last_ip NOT IN ('Non attribuée', '', '—')
LIMIT 1
)
WHERE (ip = 'Non attribuée' OR ip IS NULL OR ip = '' OR ip = '—')
AND mac LIKE '__:__:__:__:__:__'
AND EXISTS (
SELECT 1 FROM client_names
WHERE UPPER(client_names.mac) = UPPER(connection_logs.mac)
AND client_names.last_ip NOT IN ('Non attribuée', '', '—')
)
''')
# Mise à jour rétroactive des logs ayant une IP manquante à partir des autres logs du même appareil
c.execute('''
UPDATE connection_logs
SET ip = (
SELECT ip FROM connection_logs l2
WHERE UPPER(l2.mac) = UPPER(connection_logs.mac)
AND l2.ip NOT IN ('Non attribuée', '', '—', '127.0.0.1', 'SYSTEM')
AND l2.ip IS NOT NULL
ORDER BY l2.id DESC LIMIT 1
)
WHERE (ip = 'Non attribuée' OR ip IS NULL OR ip = '' OR ip = '—')
AND mac LIKE '__:__:__:__:__:__'
AND EXISTS (
SELECT 1 FROM connection_logs l2
WHERE UPPER(l2.mac) = UPPER(connection_logs.mac)
AND l2.ip NOT IN ('Non attribuée', '', '—', '127.0.0.1', 'SYSTEM')
AND l2.ip IS NOT NULL
)
''')
except Exception as e_clean:
print(f"[ap-db] Avertissement nettoyage MAC : {e_clean}", flush=True)
c.commit()
_db_initialized = True
finally:
c.close()
def db():
if not _db_initialized:
init_db()
c = sqlite3.connect(DB_FILE, timeout=30.0)
c.execute('PRAGMA busy_timeout = 30000')
return c
def init_device_types_table(c):
c.execute('''
CREATE TABLE IF NOT EXISTS custom_device_types(
id TEXT PRIMARY KEY,
label TEXT NOT NULL,
icon TEXT NOT NULL,
desc TEXT DEFAULT "",
sort_order INTEGER DEFAULT 0
)
''')
try:
count = c.execute('SELECT COUNT(*) FROM custom_device_types').fetchone()[0]
if count == 0:
defaults = [
('phone', 'Smartphone', '📱', 'iPhone, Android, Galaxy...', 1),
('tablet', 'Tablette', 'tablet_svg', 'iPad, Galaxy Tab, Kindle...', 2),
('laptop', 'PC Portable', '💻', 'MacBook, ThinkPad, Laptop...', 3),
('desktop', 'Ordinateur fixe', '🖥️', 'PC Bureau, Mac Pro, Tour...', 4),
('tv', 'Smart TV / Box', '📺', 'Apple TV, Chromecast, Box...', 5),
('console', 'Console de jeux', '🎮', 'PlayStation, Switch, Xbox...', 6),
('iot', 'Objet connecté', '📟', 'IoT, Caméra, Domotique, RPi...', 7),
('generic', 'Standard / Autre', '💻', 'Appareil générique / inconnu', 8)
]
c.executemany('INSERT INTO custom_device_types(id, label, icon, desc, sort_order) VALUES(?,?,?,?,?)', defaults)
c.commit()
except Exception as e:
print(f"[ap-error] Erreur init_device_types_table: {e}", flush=True)
def password_hash(value, salt=None):
salt = salt or secrets.token_bytes(16)
digest = hashlib.pbkdf2_hmac('sha256', value.encode(), salt, 240000)
return salt.hex() + ':' + digest.hex()
def password_ok(value, stored):
try:
salt, digest = stored.split(':', 1)
actual = hashlib.pbkdf2_hmac('sha256', value.encode(), bytes.fromhex(salt), 240000).hex()
return hmac.compare_digest(actual, digest)
except (ValueError, TypeError): return False
def totp_code(secret, counter=None):
counter = int(time.time() // 30) if counter is None else counter
key = base64.b32decode(secret + '=' * (-len(secret) % 8), casefold=True)
raw = hmac.new(key, counter.to_bytes(8, 'big'), hashlib.sha1).digest()
offset = raw[-1] & 15
number = int.from_bytes(raw[offset:offset + 4], 'big') & 0x7fffffff
return f'{number % 1000000:06d}'
def totp_ok(secret, code):
code = str(code or '').strip()
if not re.fullmatch(r'\d{6}', code): return False
counter = int(time.time() // 30)
return any(hmac.compare_digest(totp_code(secret, counter + drift), code) for drift in (-1, 0, 1))
def auth_state():
c = db(); row = c.execute('SELECT username,totp_secret FROM auth_users LIMIT 1').fetchone()
has_pk = bool(c.execute('SELECT 1 FROM auth_passkeys LIMIT 1').fetchone())
rows = dict(c.execute("SELECT key,value FROM preferences").fetchall()); c.close()
conn = connection_name() if callable(globals().get('connection_name')) else ''
eth_list = detect_ethernet_interfaces() if callable(globals().get('detect_ethernet_interfaces')) else []
admin_ok = bool(row)
wifi_ok = bool(conn or rows.get('ap_ssid'))
return {
'version': APP_VERSION,
'configured': admin_ok,
'admin_configured': admin_ok,
'wifi_configured': wifi_ok,
'setup_completed': admin_ok and wifi_ok,
'two_factor': bool(row and row[1]),
'has_passkeys': has_pk,
'ethernet_interfaces': eth_list,
'app_name': rows.get('app_name', 'Administration de l’AP Wi‑Fi'),
'app_short_name': rows.get('app_short_name', 'AP Manageur'),
'language': rows.get('language', 'fr'),
'is_starting': not app_startup_done,
'boot_time': SERVER_BOOT_TIME,
'username': row[0] if row else 'admin'
}
RECOVERY_COUNT = 8
def recovery_table(c):
c.execute('CREATE TABLE IF NOT EXISTS recovery_codes(code_hash TEXT PRIMARY KEY, used INTEGER NOT NULL DEFAULT 0)')
def recovery_hash(code):
return hashlib.sha256(re.sub(r'[^A-Z0-9]', '', str(code or '').upper()).encode()).hexdigest()
def recovery_generate():
alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
codes = []
for _ in range(RECOVERY_COUNT):
raw = ''.join(secrets.choice(alphabet) for _ in range(10))
codes.append(raw[:5] + '-' + raw[5:])
c = db(); recovery_table(c); c.execute('DELETE FROM recovery_codes')
c.executemany('INSERT INTO recovery_codes(code_hash) VALUES(?)', [(recovery_hash(x),) for x in codes]); c.commit(); c.close()
return codes
def recovery_use(code):
cleaned = re.sub(r'[^A-Za-z0-9]', '', str(code or ''))
if len(cleaned) != 10: return False
c = db(); recovery_table(c)
cur = c.execute('UPDATE recovery_codes SET used=1 WHERE code_hash=? AND used=0', (recovery_hash(cleaned),))
c.commit(); ok = cur.rowcount == 1; c.close(); return ok
def recovery_remaining():
c = db(); recovery_table(c); n = c.execute('SELECT COUNT(*) FROM recovery_codes WHERE used=0').fetchone()[0]; c.close(); return n
def recovery_clear():
c = db(); recovery_table(c); c.execute('DELETE FROM recovery_codes'); c.commit(); c.close()
def second_factor_ok(secret, code):
return totp_ok(secret, code) or recovery_use(code)
# ==============================================================================
# WEBAUTHN / PASSKEYS HELPER FUNCTIONS
# ==============================================================================
passkey_pending_challenges = {}
P256_P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF
P256_A = P256_P - 3
P256_B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B
P256_GX = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296
P256_GY = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5
P256_N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
def _ec_inv(k, m): return pow(k, m - 2, m)
def _ec_point_add(p1, p2):
if p1 is None: return p2
if p2 is None: return p1
x1, y1 = p1; x2, y2 = p2
if x1 == x2:
if (y1 + y2) % P256_P == 0: return None
l = (3 * x1 * x1 + P256_A) * _ec_inv(2 * y1, P256_P) % P256_P
else:
l = (y2 - y1) * _ec_inv(x2 - x1, P256_P) % P256_P
x3 = (l * l - x1 - x2) % P256_P
y3 = (l * (x1 - x3) - y1) % P256_P
return x3, y3
def _ec_point_mul(k, p):
res = None; cur = p
while k > 0:
if k & 1: res = _ec_point_add(res, cur)
cur = _ec_point_add(cur, cur)
k >>= 1
return res
def b64url_decode(s):
if isinstance(s, bytes): s = s.decode('ascii')
s = str(s).replace('-', '+').replace('_', '/')
while len(s) % 4: s += '='
return base64.b64decode(s)
def b64url_encode(b):
if isinstance(b, str): b = b.encode('utf-8')
return base64.b64encode(b).decode('ascii').replace('+', '-').replace('/', '_').rstrip('=')
def decode_cbor(data, offset=0):
if offset >= len(data): raise ValueError('Fin de données CBOR inattendue')
b = data[offset]; major = b >> 5; info = b & 0x1f; offset += 1
if info < 24: val = info
elif info == 24: val = data[offset]; offset += 1
elif info == 25: val = int.from_bytes(data[offset:offset+2], 'big'); offset += 2
elif info == 26: val = int.from_bytes(data[offset:offset+4], 'big'); offset += 4
elif info == 27: val = int.from_bytes(data[offset:offset+8], 'big'); offset += 8
else: raise ValueError(f'Info CBOR non supportée : {info}')
if major == 0: return val, offset
elif major == 1: return -1 - val, offset
elif major == 2: return data[offset:offset+val], offset+val
elif major == 3: return data[offset:offset+val].decode('utf-8', errors='replace'), offset+val
elif major == 4:
arr = []
for _ in range(val): item, offset = decode_cbor(data, offset); arr.append(item)
return arr, offset
elif major == 5:
m = {}
for _ in range(val):
k, offset = decode_cbor(data, offset); v, offset = decode_cbor(data, offset); m[k] = v
return m, offset
elif major == 7:
if info == 20: return False, offset
if info == 21: return True, offset
if info == 22: return None, offset
return val, offset
else: raise ValueError(f'Type majeur CBOR non supporté : {major}')
def parse_der_signature(sig_bytes):
if not sig_bytes or sig_bytes[0] != 0x30:
raise ValueError('Signature DER invalide')
idx = 2
if sig_bytes[1] & 0x80:
idx += (sig_bytes[1] & 0x7f)
if sig_bytes[idx] != 0x02:
raise ValueError('Entier r invalide dans la signature DER')
r_len = sig_bytes[idx+1]
r = int.from_bytes(sig_bytes[idx+2 : idx+2+r_len], 'big')
idx = idx + 2 + r_len
if sig_bytes[idx] != 0x02:
raise ValueError('Entier s invalide dans la signature DER')
s_len = sig_bytes[idx+1]
s = int.from_bytes(sig_bytes[idx+2 : idx+2+s_len], 'big')
return r, s
def verify_es256_signature(pub_x_bytes, pub_y_bytes, sig_bytes, signed_data):
try:
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes
pub_num = ec.EllipticCurvePublicNumbers(
int.from_bytes(pub_x_bytes, 'big'),
int.from_bytes(pub_y_bytes, 'big'),
ec.SECP256R1()
)
pub_num.public_key().verify(sig_bytes, signed_data, ec.ECDSA(hashes.SHA256()))
return True
except Exception:
pass
try:
r, s = parse_der_signature(sig_bytes)
if not (1 <= r < P256_N and 1 <= s < P256_N):
return False
z = int.from_bytes(hashlib.sha256(signed_data).digest(), 'big')
w = _ec_inv(s, P256_N)
u1 = (z * w) % P256_N
u2 = (r * w) % P256_N
pub_pt = (int.from_bytes(pub_x_bytes, 'big'), int.from_bytes(pub_y_bytes, 'big'))
pt = _ec_point_add(_ec_point_mul(u1, (P256_GX, P256_GY)), _ec_point_mul(u2, pub_pt))
return pt is not None and (pt[0] % P256_N) == (r % P256_N)
except Exception:
return False
def verify_rs256_signature(n_bytes, e_bytes, sig_bytes, signed_data):
try:
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
pub_num = rsa.RSAPublicNumbers(int.from_bytes(e_bytes, 'big'), int.from_bytes(n_bytes, 'big'))
pub_num.public_key().verify(sig_bytes, signed_data, padding.PKCS1v15(), hashes.SHA256())
return True
except Exception:
pass
try:
sig_int = int.from_bytes(sig_bytes, 'big')
e_int = int.from_bytes(e_bytes, 'big')
n_int = int.from_bytes(n_bytes, 'big')
m = pow(sig_int, e_int, n_int)
em = m.to_bytes((n_int.bit_length() + 7) // 8, 'big')
sha = hashlib.sha256(signed_data).digest()
oid = bytes.fromhex('3031300d060960864801650304020105000420')
return em.endswith(oid + sha)
except Exception:
return False
def create_user(username, password, secret=None):
if not re.fullmatch(r'[A-Za-z0-9_.-]{3,32}', username or ''): raise ValueError('Nom utilisateur invalide')
if not 8 <= len(password) <= 128: raise ValueError('Le mot de passe doit contenir entre 8 et 128 caractères')
c = db(); c.execute('DELETE FROM auth_users'); c.execute('INSERT INTO auth_users VALUES(?,?,?)', (username, password_hash(password), secret)); c.commit(); c.close()
def verify_user(username, password):
c = db(); row = c.execute('SELECT username,password_hash,totp_secret FROM auth_users WHERE username=?', (username.strip(),)).fetchone(); c.close()
return row if row and password_ok(password, row[1]) else None
def parse_os(user_agent):
if not user_agent: return 'Inconnu'
ua = user_agent.lower()
if 'windows nt 10.0' in ua or 'windows nt 11.0' in ua: return 'Windows 10/11'
elif 'windows nt 6.3' in ua: return 'Windows 8.1'
elif 'windows nt 6.2' in ua: return 'Windows 8'
elif 'windows nt 6.1' in ua: return 'Windows 7'
elif 'windows' in ua: return 'Windows'
elif 'iphone' in ua:
m = re.search(r'cpu iphone os ([0-9_]+)', ua)
return 'iOS ' + m.group(1).replace('_', '.') if m else 'iOS'
elif 'ipad' in ua: return 'iPadOS'
elif 'macintosh' in ua or 'mac os x' in ua:
m = re.search(r'mac os x ([0-9_]+)', ua)
return 'macOS ' + m.group(1).replace('_', '.') if m else 'macOS'
elif 'android' in ua:
m = re.search(r'android ([0-9.]+)', ua)
return 'Android ' + m.group(1) if m else 'Android'
elif 'cros' in ua: return 'ChromeOS'
elif 'linux' in ua: return 'Linux'
return 'Autre'
def parse_browser(user_agent):
if not user_agent: return 'Inconnu'
ua = user_agent.lower()
if 'edg/' in ua or 'edge/' in ua:
m = re.search(r'edg[e]?/([0-9.]+)', ua)
return 'Microsoft Edge' + (' ' + m.group(1).split('.')[0] if m else '')
elif 'opr/' in ua or 'opera/' in ua:
m = re.search(r'(?:opr|opera)/([0-9.]+)', ua)
return 'Opera' + (' ' + m.group(1).split('.')[0] if m else '')
elif 'samsungbrowser/' in ua:
m = re.search(r'samsungbrowser/([0-9.]+)', ua)
return 'Samsung Internet' + (' ' + m.group(1).split('.')[0] if m else '')
elif 'firefox/' in ua or 'fxios/' in ua:
m = re.search(r'(?:firefox|fxios)/([0-9.]+)', ua)
return 'Firefox' + (' ' + m.group(1).split('.')[0] if m else '')
elif 'chrome/' in ua or 'crios/' in ua:
m = re.search(r'(?:chrome|crios)/([0-9.]+)', ua)
return 'Chrome' + (' ' + m.group(1).split('.')[0] if m else '')
elif 'safari/' in ua and 'version/' in ua:
m = re.search(r'version/([0-9.]+)', ua)
return 'Safari' + (' ' + m.group(1).split('.')[0] if m else '')
return 'Navigateur Web'
def resolve_device_name(ip):
if not ip or ip in ('127.0.0.1', '::1', 'localhost', 'Non attribuée', '—'):
return 'Serveur local'
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']:
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] != '*':
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})"
def new_session(username, ip='', ua='', custom_name=''):
token = secrets.token_urlsafe(32)
now = time.time()
expires = now + SESSION_TTL
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
os_name = parse_os(ua)
browser_name = parse_browser(ua)
dev_name = (custom_name or '').strip() or resolve_device_name(ip)
sess_data = {
'username': username,
'expires': expires,
'ip': ip,
'ua': ua,
'device_name': dev_name,
'os_name': os_name,
'browser_name': browser_name,
'created_at': now_str,
'last_seen': now_str,
'_last_updated': now
}
sessions[token] = sess_data
try:
c = db()
c.execute('''
INSERT OR REPLACE INTO auth_sessions
(token, username, expires, ip, ua, device_name, os_name, browser_name, created_at, last_seen)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (token, username, expires, ip, ua, dev_name, os_name, browser_name, now_str, now_str))
c.commit(); c.close()
except Exception as e:
print(f"[ap-error] Erreur enregistrement session SQLite: {e}", flush=True)
return token
def delete_session(token):
if not token: return
sessions.pop(token, None)
try:
c = db()
c.execute('DELETE FROM auth_sessions WHERE token=?', (token,))
c.commit(); c.close()
except Exception: pass
def get_session(token):
if not token: return None
now = time.time()
s = sessions.get(token)
if isinstance(s, dict):
if s.get('expires', 0) > now:
return s
else:
delete_session(token)
return None
try:
c = db()
row = c.execute('''
SELECT username, expires, ip, ua, device_name, os_name, browser_name, created_at, last_seen
FROM auth_sessions WHERE token=?
''', (token,)).fetchone()
c.close()
if row:
if row[1] > now:
s = {
'username': row[0],
'expires': row[1],
'ip': row[2] or '',
'ua': row[3] or '',
'device_name': row[4] or '',
'os_name': row[5] or '',
'browser_name': row[6] or '',
'created_at': row[7] or '',
'last_seen': row[8] or '',
'_last_updated': now
}
sessions[token] = s
return s
else:
delete_session(token)
except Exception: pass
return None
def update_session_activity(token, ip, ua, custom_name=''):
if not token: return
now = time.time()
s = sessions.get(token)
if isinstance(s, dict):
last_t = s.get('_last_updated', 0)
need_info = not s.get('ip') or not s.get('os_name') or not s.get('browser_name') or (custom_name and s.get('device_name') != custom_name)
if (now - last_t >= 30) or need_info:
s['_last_updated'] = now
s['last_seen'] = time.strftime('%Y-%m-%d %H:%M:%S')
if custom_name:
s['device_name'] = custom_name
elif ip and not s.get('ip'):
s['ip'] = ip
s['device_name'] = resolve_device_name(ip)
elif not s.get('device_name') and s.get('ip'):
s['device_name'] = resolve_device_name(s['ip'])
if ua and not s.get('ua'):
s['ua'] = ua
s['os_name'] = parse_os(ua)
s['browser_name'] = parse_browser(ua)
elif not s.get('browser_name') and s.get('ua'):
s['browser_name'] = parse_browser(s['ua'])
try:
c = db()
c.execute('''
UPDATE auth_sessions
SET last_seen=?,
ip=CASE WHEN (ip IS NULL OR ip='') THEN ? ELSE ip END,
ua=CASE WHEN (ua IS NULL OR ua='') THEN ? ELSE ua END,
device_name=CASE WHEN ? != '' THEN ? ELSE (CASE WHEN (device_name IS NULL OR device_name='') THEN ? ELSE device_name END) END,
os_name=CASE WHEN (os_name IS NULL OR os_name='') THEN ? ELSE os_name END,
browser_name=CASE WHEN (browser_name IS NULL OR browser_name='') THEN ? ELSE browser_name END
WHERE token=?
''', (s['last_seen'], ip or '', ua or '', custom_name, custom_name, s.get('device_name',''), s.get('os_name',''), s.get('browser_name',''), token))
c.commit(); c.close()
except Exception: pass
def list_sessions(current_token='', lang='fr'):
now = time.time()
is_en = str(lang or '').lower().startswith('en')
unknown_machine = 'Unknown machine' if is_en else 'Machine inconnue'
unknown_os = 'Unknown' if is_en else 'Inconnu'
default_browser = 'Web Browser' if is_en else 'Navigateur Web'
try:
c = db()
c.execute('DELETE FROM auth_sessions WHERE expires < ?', (now,))
c.commit()
rows = c.execute('''
SELECT token, username, expires, ip, ua, device_name, os_name, browser_name, created_at, last_seen
FROM auth_sessions
ORDER BY last_seen DESC, created_at DESC
''').fetchall()
c.close()
except Exception as e:
print(f"[ap-error] Erreur récupération auth_sessions: {e}", flush=True)
rows = []
res = []
for r in rows:
token, uname, expires, ip, ua, dev_name, os_name, browser_name, created_at, last_seen = r
if not os_name or os_name == 'Autre':
os_name = parse_os(ua)
if not browser_name or browser_name == 'Navigateur Web':
browser_name = parse_browser(ua)
if not dev_name or dev_name.startswith('Machine ('):
resolved = resolve_device_name(ip)
if resolved: dev_name = resolved
is_current = bool(current_token and token == current_token)
res.append({
'token': token,
'is_current': is_current,
'username': uname or 'admin',
'ip': ip or '127.0.0.1',
'device_name': dev_name or unknown_machine,
'os_name': os_name or unknown_os,
'browser_name': browser_name or default_browser,
'created_at': created_at or '—',
'last_seen': last_seen or created_at or '—'
})
return res
def parse_api_key_permissions(perms_str):
if isinstance(perms_str, list):
return [str(p).strip().lower() for p in perms_str if str(p).strip()]
if not perms_str:
return []
try:
val = json.loads(perms_str)
if isinstance(val, list):
return [str(p).strip().lower() for p in val if str(p).strip()]
except Exception:
pass
return [p.strip().lower() for p in str(perms_str).split(',') if p.strip()]
_api_keys_cache = {}
_api_keys_cache_lock = threading.Lock()
def get_api_key_by_token(token):
if not token or not isinstance(token, str) or not token.startswith('ap_key_'):
return None
token_hash = hashlib.sha256(token.encode('utf-8')).hexdigest()
now_time = time.time()
with _api_keys_cache_lock:
cached = _api_keys_cache.get(token_hash)
if cached and (now_time - cached.get('_cached_at', 0) < 15):
return cached
try:
c = db()
row = c.execute('''
SELECT id, name, key_hash, prefix, permissions, created_at, expires_at, last_used_at, last_ip, is_active
FROM api_keys WHERE key_hash=?
''', (token_hash,)).fetchone()
c.close()
if row:
key_data = {
'id': row[0],
'name': row[1],
'key_hash': row[2],
'prefix': row[3],
'permissions': parse_api_key_permissions(row[4]),
'created_at': row[5],
'expires_at': row[6],
'last_used_at': row[7],
'last_ip': row[8],
'is_active': int(row[9] or 0),
'_cached_at': now_time
}
with _api_keys_cache_lock:
_api_keys_cache[token_hash] = key_data
return key_data
except Exception as e:
print(f"[ap-api-keys] Erreur récupération clé API: {e}", flush=True)
return None
def update_api_key_usage(key_id, ip=''):
try:
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
c = db()
c.execute('UPDATE api_keys SET last_used_at=?, last_ip=? WHERE id=?', (now_str, ip or '', key_id))
c.commit(); c.close()
except Exception:
pass
def check_api_key_permission(perms, method, path):
if not perms:
return False
if 'admin' in perms:
return True
method = method.upper()
path_only = path.split('?')[0]
# Droits 'read' (lecture seule métriques, statut, abonnés, logs)
if 'read' in perms and method in ('GET', 'HEAD'):
read_prefixes = (
'/api/status', '/api/stats', '/api/clients', '/api/devices',
'/api/device-types', '/api/logs', '/api/network/topology',
'/api/wifi/channel', '/api/vpn/profiles', '/api/vpn/clients',
'/api/vpn/check-ip', '/api/vpn/public-ip', '/api/preferences',
'/api/settings/proxy', '/api/notifications/settings',
'/api/advanced/domains', '/api/advanced/geoip',
'/api/advanced/capture/status', '/api/advanced/capture/packets',
'/api/system/update'
)
if any(path_only == p or path_only.startswith(p + '/') for p in read_prefixes):
return True
# Droits 'wifi'
if 'wifi' in perms:
if method in ('GET', 'HEAD') and path_only in ('/api/wifi/channel', '/api/status'):
return True
if method == 'POST' and path_only in ('/api/ap/control', '/api/ap/mode', '/api/settings', '/api/setup', '/api/stats/refresh'):
return True
# Droits 'clients'
if 'clients' in perms:
if method in ('GET', 'HEAD') and (path_only.startswith('/api/clients') or path_only.startswith('/api/devices')):
return True
if method == 'POST' and (
path_only in ('/api/clients/block', '/api/devices/limits', '/api/devices/rename', '/api/devices/set_type', '/api/devices/delete')
or path_only.startswith('/api/device-types')
):
return True
# Droits 'vpn'
if 'vpn' in perms:
if method in ('GET', 'HEAD') and path_only.startswith('/api/vpn'):
return True
if method == 'POST' and path_only.startswith('/api/vpn'):
return True
# Droits 'backup'
if 'backup' in perms:
if method in ('GET', 'HEAD') and (path_only.startswith('/api/backup') or path_only.startswith('/api/backups')):
return True
if method == 'POST' and (path_only.startswith('/api/backup') or path_only.startswith('/api/backups')):
return True
return False
def extract_token(h):
token = h.headers.get('X-API-Key', '') if hasattr(h, 'headers') else ''
if not token and hasattr(h, 'headers'):
token = h.headers.get('X-Session-Token', '')
if not token and hasattr(h, 'headers'):
auth_hdr = h.headers.get('Authorization', '')
if auth_hdr.lower().startswith('bearer '):
token = auth_hdr[7:].strip()
if not token and hasattr(h, 'headers') and 'Cookie' in h.headers:
for part in h.headers.get('Cookie', '').split(';'):
part = part.strip()
if part.startswith('apAuthToken='):
token = urllib.parse.unquote(part.split('=', 1)[1])
break
if not token and hasattr(h, 'path') and 'token=' in h.path:
try:
parsed = urllib.parse.urlparse(h.path)
token = urllib.parse.parse_qs(parsed.query).get('token', [''])[0]
except Exception: pass
if not token and hasattr(h, 'path') and 'api_key=' in h.path:
try:
parsed = urllib.parse.urlparse(h.path)
token = urllib.parse.parse_qs(parsed.query).get('api_key', [''])[0]
except Exception: pass
return token
def valid_session(h):
token = extract_token(h)
if not token:
return False
# Authentification via clé d'API (ap_key_...)
if token.startswith('ap_key_'):
k = get_api_key_by_token(token)
if not k or not k.get('is_active'):
return False
exp = k.get('expires_at')
if exp and exp.strip():
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
if now_str > exp:
return False
method = getattr(h, 'command', 'GET')
path = getattr(h, 'path', '')
path_only = path.split('?')[0]
perms = k.get('permissions', [])
# La gestion des clés d'API requiert un accès administrateur total
if path_only.startswith('/api/auth/api-keys') and 'admin' not in perms:
return False
if not check_api_key_permission(perms, method, path):
return False
try:
update_api_key_usage(k['id'], request_ip(h))
except Exception:
pass
return True
# Authentification classique de session web
s = get_session(token)
if s is not None:
try:
custom_name = urllib.parse.unquote(h.headers.get('X-Device-Name', '')) if hasattr(h, 'headers') else ''
update_session_activity(token, request_ip(h), h.headers.get('User-Agent', ''), custom_name)
except Exception: pass
return True
return False
def username(h):
token = extract_token(h)
if not token:
return ''
if token.startswith('ap_key_'):
k = get_api_key_by_token(token)
if k:
return f"API:{k.get('name', 'Clé API')}"
return 'API'
s = get_session(token)
return s.get('username', '') if s else ''
def command(*args, timeout=5):
try: return subprocess.check_output(args, text=True, stderr=subprocess.DEVNULL, timeout=timeout).strip()
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError): return ''
def read_json(h):
return json.loads(h.rfile.read(int(h.headers.get('Content-Length', '0'))) or b'{}')
def clean_ip_str(ip_str):
if not ip_str: return ''
s = ip_str.strip()
if s.startswith('[') and ']' in s:
s = s[1:s.index(']')]
elif ':' in s and s.count(':') == 1:
s = s.split(':')[0]
return s.strip()
def is_ip_trusted_proxy(ip_str, trusted_list_str, trust_all_private=True):
ip_clean = clean_ip_str(ip_str)
if not ip_clean: return False
try:
ip = ipaddress.ip_address(ip_clean)
except ValueError:
return False
if trust_all_private and (ip.is_private or ip.is_loopback or ip.is_link_local):
return True
for item in (trusted_list_str or '').split(','):
item = item.strip()
if not item: continue
if item == '*': return True
try:
if '/' in item:
if ip in ipaddress.ip_network(item, strict=False): return True
else:
item_clean = clean_ip_str(item)
if ip == ipaddress.ip_address(item_clean): return True
except ValueError:
pass
return False
def get_reverse_proxy_config():
try:
c = db()
rows = dict(c.execute("SELECT key, value FROM preferences WHERE key LIKE 'reverse_proxy_%'").fetchall())
c.close()
except Exception:
rows = {}
return {
'enabled': rows.get('reverse_proxy_enabled', '1') == '1',
'header': rows.get('reverse_proxy_header', 'auto').lower(),
'trusted_proxies': rows.get('reverse_proxy_trusted_proxies', '127.0.0.1, ::1, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16'),
'trust_all_private': rows.get('reverse_proxy_trust_all_private', '1') == '1'
}
def request_ip(h):
socket_ip = h.client_address[0] if hasattr(h, 'client_address') and h.client_address else '127.0.0.1'
raw_direct = clean_ip_str(h.headers.get('X-Client-Raw-IP', '').strip()) or socket_ip
cfg = get_reverse_proxy_config()
if not cfg['enabled']:
return raw_direct
if not is_ip_trusted_proxy(raw_direct, cfg['trusted_proxies'], cfg['trust_all_private']):
return raw_direct
hdr_pref = cfg['header']
def get_list(hdr):
val = h.headers.get(hdr, '').strip()
if not val: return []
return [p.strip() for p in val.split(',') if p.strip()]
if hdr_pref == 'cf-connecting-ip':
candidates = get_list('CF-Connecting-IP')
elif hdr_pref == 'true-client-ip':
candidates = get_list('True-Client-IP')
elif hdr_pref == 'x-real-ip':
candidates = get_list('X-Real-IP')
elif hdr_pref == 'x-forwarded-for':
candidates = get_list('X-Forwarded-For')
else:
candidates = (get_list('CF-Connecting-IP') or
get_list('True-Client-IP') or
get_list('X-Forwarded-For') or
get_list('X-Real-IP'))
for cand in candidates:
cand_clean = clean_ip_str(cand)
try:
val_ip = ipaddress.ip_address(cand_clean)
return str(val_ip)
except ValueError:
continue
return raw_direct
def log(event, name='Nom non communiqué', ip='Non attribuée', mac='—'):
# Remplacer 127.0.0.1 ou localhost par SYSTEM
if ip in ('127.0.0.1', '::1', 'localhost'):
ip = 'SYSTEM'
mac_clean = str(mac or '—').strip().upper()
if is_valid_mac(mac_clean):
# Vérifier d'abord les caches en mémoire station_live_names et station_live_ips
if (name in ('Nom non communiqué', '', None, 'Inconnu')) and mac_clean in station_live_names:
name = station_live_names[mac_clean]
if (ip in ('Non attribuée', '', None, '—')) and mac_clean in station_live_ips:
ip = station_live_ips[mac_clean]
# Si le nom ou l'IP est non communiqué, vérifier dans la table des abonnés (client_names) et journaux récents
if name in ('Nom non communiqué', '', None, 'Inconnu') or ip in ('Non attribuée', '', None, '—'):
try:
c = db()
row = c.execute('SELECT name, last_ip FROM client_names WHERE UPPER(mac)=?', (mac_clean,)).fetchone()
if row:
if (name in ('Nom non communiqué', '', None, 'Inconnu')) and row[0] and row[0] not in ('Nom non communiqué', 'Inconnu'):
name = row[0]
saved_ip = row[1] or ''
if is_bridge_mode() and saved_ip.startswith('10.42.'):
saved_ip = ''
if (ip in ('Non attribuée', '', None, '—')) and saved_ip and saved_ip not in ('Non attribuée', '—'):
ip = saved_ip
if name in ('Nom non communiqué', '', None, 'Inconnu'):
row_n = c.execute("SELECT name FROM connection_logs WHERE UPPER(mac)=? AND name NOT IN ('Nom non communiqué', '', 'Inconnu') ORDER BY id DESC LIMIT 1", (mac_clean,)).fetchone()
if row_n and row_n[0]:
clean_n = re.sub(r'\s*\[🛡️[^\]]*\]', '', row_n[0]).strip()
if clean_n: name = clean_n
if ip in ('Non attribuée', '', None, '—'):
row_i = c.execute("SELECT ip FROM connection_logs WHERE UPPER(mac)=? AND ip NOT IN ('Non attribuée', '', '—', '127.0.0.1', 'SYSTEM') ORDER BY id DESC LIMIT 1", (mac_clean,)).fetchone()
if row_i and row_i[0]:
ip = row_i[0]
c.close()
except Exception: pass
if name in ('Nom non communiqué', '', None, 'Inconnu'):
name = device_name(ip if ip not in ('Non attribuée', '', '—') else '', mac_clean)
mac = mac_clean
ts = time.strftime('%Y-%m-%d %H:%M:%S')
print(f"[ap-event] [{ts}] {event} | client='{name}' ({mac}) | ip={ip}", flush=True)
try:
c = db(); c.execute('INSERT INTO connection_logs(event_time,event,name,ip,mac) VALUES(?,?,?,?,?)', (ts, event, name, ip, mac)); c.commit(); c.close()
except sqlite3.Error as e:
print(f"[ap-error] Erreur base SQLite: {e}", flush=True)
def logs():
c = db()
rows = c.execute('SELECT event_time,event,name,ip,mac FROM connection_logs ORDER BY id DESC LIMIT 200').fetchall()
vpn_routes = dict(c.execute('SELECT mac, profile_id FROM client_vpn_routes WHERE profile_id > 0').fetchall())
vpn_profiles = {r[0]: {'name': r[1], 'status': r[2], 'iface': r[3]} for r in c.execute('SELECT id, name, status, iface FROM vpn_profiles').fetchall()}
known_clients = {r[0].upper(): {'name': r[1], 'last_ip': r[2]} for r in c.execute('SELECT mac, name, last_ip FROM client_names').fetchall() if r[0]}
c.close()
# Construire la carte des noms et IP récents depuis l'ensemble des journaux
log_names = {}
log_ips = {}
for r in rows:
m = (r[4] or '').upper()
if is_valid_mac(m):
n = (r[2] or '').strip()
if n and n not in ('Nom non communiqué', 'Inconnu') and m not in log_names:
clean_n = re.sub(r'\s*\[🛡️[^\]]*\]', '', n).strip()
if clean_n: log_names[m] = clean_n
ip_val = (r[3] or '').strip()
if ip_val and ip_val not in ('Non attribuée', '', '—', 'SYSTEM', '127.0.0.1') and m not in log_ips:
log_ips[m] = ip_val
result = []
for r in rows:
mac = (r[4] or '').upper()
ev_name = r[2]
ev_ip = r[3]
if ev_ip in ('127.0.0.1', '::1', 'localhost'):
ev_ip = 'SYSTEM'
# Résolution dynamique si le nom ou l'IP est manquant pour un équipement Wi-Fi
if is_valid_mac(mac):
if not ev_name or ev_name in ('Nom non communiqué', 'Inconnu'):
if mac in known_clients and known_clients[mac].get('name') and known_clients[mac]['name'] not in ('Nom non communiqué', 'Inconnu'):
ev_name = known_clients[mac]['name']
elif mac in log_names:
ev_name = log_names[mac]
elif mac in station_live_names:
ev_name = station_live_names[mac]
else:
ev_name = device_name(ev_ip if ev_ip not in ('Non attribuée', '', '—') else '', mac)
if not ev_ip or ev_ip in ('Non attribuée', '', '—'):
if mac in known_clients and known_clients[mac].get('last_ip') and known_clients[mac]['last_ip'] not in ('Non attribuée', '', '—'):
ev_ip = known_clients[mac]['last_ip']
elif mac in log_ips:
ev_ip = log_ips[mac]
elif mac in station_live_ips:
ev_ip = station_live_ips[mac]
else:
ev_ip = 'Non attribuée'
pid = vpn_routes.get(mac, 0)
prof = vpn_profiles.get(pid) if pid > 0 else None
vname = prof['name'] if prof else ''
vrouted = bool(prof and prof['status'] == 'connected' and is_iface_up(prof['iface']))
result.append({
'time': r[0],
'event': r[1],
'name': ev_name,
'ip': ev_ip,
'mac': r[4],
'vpn_profile_name': vname,
'vpn_routed': vrouted
})
return result
MONTHS_FR = ['', 'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre']
MONTHS_SHORT_FR = ['', 'Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil', 'Août', 'Sep', 'Oct', 'Nov', 'Déc']
DAYS_FR = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche']
DAYS_SHORT_FR = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim']
MONTHS_EN = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
MONTHS_SHORT_EN = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
DAYS_EN = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
DAYS_SHORT_EN = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
station_traffic = {}
traffic_lock = threading.Lock()
def format_speed(bps):
if not bps or bps <= 0: return "0 o/s"
if bps < 1024: return f"{int(bps)} o/s"
if bps < 1048576: return f"{bps/1024:.1f} Ko/s"
if bps < 1073741824: return f"{bps/1048576:.2f} Mo/s"
if bps < 1099511627776: return f"{bps/1073741824:.2f} Go/s"
return f"{bps/1099511627776:.2f} To/s"
def format_bytes(b):
if not b or b <= 0: return "0 o"
if b < 1024: return f"{int(b)} o"
if b < 1048576: return f"{b/1024:.1f} Ko"
if b < 1073741824: return f"{b/1048576:.2f} Mo"
if b < 1099511627776: return f"{b/1073741824:.2f} Go"
return f"{b/1099511627776:.2f} To"
def get_top_clients(active_items=None, range_type='day'):
active_map = {}
if active_items is not None:
active_map = {x['mac']: x for x in active_items}
else:
try: active_map = {x['mac']: x for x in clients()}
except Exception: pass
now = datetime.datetime.now()
today_str = now.strftime('%Y-%m-%d')
if range_type == 'day':
start_date = today_str
end_date = today_str
elif range_type == 'week':
mon = now.date() - datetime.timedelta(days=now.weekday())
sun = mon + datetime.timedelta(days=6)
start_date = mon.strftime('%Y-%m-%d')
end_date = sun.strftime('%Y-%m-%d')
elif range_type == 'month':
start_date = now.strftime('%Y-%m-01')
end_date = now.strftime('%Y-%m-31')
elif range_type == 'year':
start_date = now.strftime('%Y-01-01')
end_date = now.strftime('%Y-12-31')
else:
start_date = '1970-01-01'
end_date = '2099-12-31'
try:
c = db()
rows = c.execute('''
SELECT
m.mac AS mac,
COALESCE(NULLIF(n.name, ''), 'Client ' || REPLACE(SUBSTR(m.mac, -5), ':', '')) AS display_name,
COALESCE(n.last_ip, 'Non attribuée') AS last_ip,
COALESCE(n.last_seen, '—') AS last_seen,
COALESCE(t.sum_tx, 0) AS download_bytes,
COALESCE(t.sum_rx, 0) AS upload_bytes,
(COALESCE(t.sum_tx, 0) + COALESCE(t.sum_rx, 0)) AS total_bytes
FROM (
SELECT mac FROM client_traffic_daily WHERE traffic_date >= ? AND traffic_date <= ?
UNION
SELECT mac FROM client_names
) m
LEFT JOIN (
SELECT mac, SUM(tx_bytes) as sum_tx, SUM(rx_bytes) as sum_rx
FROM client_traffic_daily
WHERE traffic_date >= ? AND traffic_date <= ?
GROUP BY mac
) t ON t.mac = m.mac
LEFT JOIN client_names n ON n.mac = m.mac
ORDER BY total_bytes DESC
LIMIT 50
''', (start_date, end_date, start_date, end_date)).fetchall()
c.close()
except Exception as e:
print(f"[ap-error] Erreur récupération top_clients ({range_type}): {e}", flush=True)
rows = []
res = []
for mac, name, ip, last_seen, dl_b, ul_b, tot_b in rows:
if not is_valid_mac(mac):
continue
is_online = mac in active_map
live_client = active_map.get(mac, {})
res.append({
'mac': mac,
'name': name,
'ip': live_client.get('ip', ip),
'last_seen': last_seen,
'download_bytes': dl_b,
'upload_bytes': ul_b,
'total_bytes': tot_b,
'download_str': format_bytes(dl_b),
'upload_str': format_bytes(ul_b),
'total_str': format_bytes(tot_b),
'connected': is_online,
'download_speed_str': live_client.get('download_speed_str', '—') if is_online else '—',
'upload_speed_str': live_client.get('upload_speed_str', '—') if is_online else '—'
})
return res
_cached_stats = None
_cached_topology = None
_metrics_lock = threading.Lock()
_metrics_count = 0
_metrics_last_duration_ms = 0
_metrics_last_time = 0
def compute_stats_internal(active_items=None):
now = datetime.datetime.now()
today_str = now.strftime('%Y-%m-%d')
cur_year = now.strftime('%Y')
cur_month = now.strftime('%Y-%m')
cur_monday = now.date() - datetime.timedelta(days=now.weekday())
cur_week_start = cur_monday.strftime('%Y-%m-%d 00:00:00')
# 0. Heures de la journée (Aujourd'hui : 00h à 23h)
hours = []
hours_map = {}
hour_macs = {h: set() for h in range(24)}
hour_devs = {h: {} for h in range(24)}
for h in range(24):
key = f"{today_str} {h:02d}:00"
label = f"{h:02d}h"
label_en = f"{h:02d}:00"
full_label = f"Aujourd’hui de {h:02d}h00 à {h:02d}h59"
full_label_en = f"Today from {h:02d}:00 to {h:02d}:59"
item = {'period': key, 'hour': h, 'label': label, 'label_en': label_en, 'full_label': full_label, 'full_label_en': full_label_en, 'unique_clients': 0, 'total_connections': 0, 'devices': []}
hours.append(item)
hours_map[h] = item
# 1. Jours (30 derniers jours)
days = []
days_map = {}
for i in range(29, -1, -1):
d = now - datetime.timedelta(days=i)
key = d.strftime('%Y-%m-%d')
label = f"{DAYS_SHORT_FR[d.weekday()]} {d.day:02d}/{d.month:02d}"
label_en = f"{DAYS_SHORT_EN[d.weekday()]} {d.month:02d}/{d.day:02d}"
full_label = f"{DAYS_FR[d.weekday()]} {d.day:02d} {MONTHS_FR[d.month].lower()} {d.year}"
full_label_en = f"{DAYS_EN[d.weekday()]}, {MONTHS_EN[d.month]} {d.day:02d}, {d.year}"
item = {'period': key, 'label': label, 'label_en': label_en, 'full_label': full_label, 'full_label_en': full_label_en, 'unique_clients': 0, 'total_connections': 0, 'devices': []}
days.append(item)
days_map[key] = item
# 2. Semaines (12 dernières semaines)
weeks = []
weeks_map = {}
for i in range(11, -1, -1):
mon = cur_monday - datetime.timedelta(weeks=i)
sun = mon + datetime.timedelta(days=6)
key = mon.strftime('%Y-W%W')
week_num = mon.isocalendar()[1]
label = f"Sem {week_num}"
label_en = f"Wk {week_num}"
full_label = f"Semaine {week_num} (du {mon.day:02d}/{mon.month:02d} au {sun.day:02d}/{sun.month:02d}/{sun.year})"
full_label_en = f"Week {week_num} (from {mon.month:02d}/{mon.day:02d} to {sun.month:02d}/{sun.day:02d}/{sun.year})"
item = {'period': key, 'start': mon.strftime('%Y-%m-%d'), 'end': sun.strftime('%Y-%m-%d'), 'label': label, 'label_en': label_en, 'full_label': full_label, 'full_label_en': full_label_en, 'unique_clients': 0, 'total_connections': 0, 'devices': []}
weeks.append(item)
weeks_map[key] = item
# 3. Mois (12 derniers mois)
months = []
months_map = {}
for i in range(11, -1, -1):
y = now.year
m = now.month - i
while m <= 0:
m += 12
y -= 1
key = f"{y:04d}-{m:02d}"
label = f"{MONTHS_SHORT_FR[m]} {y}"
label_en = f"{MONTHS_SHORT_EN[m]} {y}"
full_label = f"{MONTHS_FR[m]} {y}"
full_label_en = f"{MONTHS_EN[m]} {y}"
item = {'period': key, 'label': label, 'label_en': label_en, 'full_label': full_label, 'full_label_en': full_label_en, 'unique_clients': 0, 'total_connections': 0, 'devices': []}
months.append(item)
months_map[key] = item
# 4. Années (5 dernières années ou depuis la plus ancienne connexion)
min_year = now.year - 4
try:
c = db()
min_row = c.execute("SELECT MIN(event_time) FROM connection_logs WHERE event='connexion' AND mac LIKE '%:%'").fetchone()
c.close()
if min_row and min_row[0]:
log_min_year = int(min_row[0][:4])
if log_min_year < min_year: min_year = log_min_year
except Exception: pass
years = []
years_map = {}
for y in range(min_year, now.year + 1):
key = str(y)
item = {'period': key, 'label': key, 'label_en': key, 'full_label': f"Année {key}", 'full_label_en': f"Year {key}", 'unique_clients': 0, 'total_connections': 0, 'devices': []}
years.append(item)
years_map[key] = item
day_macs = {k: set() for k in days_map}
week_macs = {k: set() for k in weeks_map}
month_macs = {k: set() for k in months_map}
year_macs = {k: set() for k in years_map}
day_devs = {k: {} for k in days_map}
week_devs = {k: {} for k in weeks_map}
month_devs = {k: {} for k in months_map}
year_devs = {k: {} for k in years_map}
today_macs = set()
week_macs_cur = set()
month_macs_cur = set()
year_macs_cur = set()
today_total = 0
week_total = 0
month_total = 0
year_total = 0
try:
c = db()
rows = c.execute('''
SELECT
l.event_time,
l.event,
l.mac,
COALESCE(NULLIF(n.name, ''), NULLIF(l.name, ''), 'Client ' || REPLACE(SUBSTR(l.mac, -5), ':', '')) AS display_name
FROM connection_logs l
LEFT JOIN client_names n ON n.mac = l.mac
WHERE l.event IN ('connexion', 'déconnexion') AND l.mac LIKE '%:%'
ORDER BY l.id ASC
''').fetchall()
# Également récupérer l'historique du trafic journalier stocké en base
try:
traffic_rows = c.execute('''
SELECT
t.mac,
t.traffic_date,
COALESCE(NULLIF(n.name, ''), 'Client ' || REPLACE(SUBSTR(t.mac, -5), ':', '')) AS display_name,
(COALESCE(t.rx_bytes, 0) + COALESCE(t.tx_bytes, 0)) AS total_bytes
FROM client_traffic_daily t
LEFT JOIN client_names n ON n.mac = t.mac
WHERE (t.rx_bytes > 0 OR t.tx_bytes > 0)
''').fetchall()
except Exception:
traffic_rows = []
# Également récupérer les derniers accès connus dans client_names
try:
cn_rows = c.execute('''
SELECT mac, name, last_seen FROM client_names
WHERE last_seen IS NOT NULL AND last_seen != '' AND last_seen != '—'
''').fetchall()
except Exception:
cn_rows = []
c.close()
except Exception as e:
rows = []
traffic_rows = []
cn_rows = []
print(f"[ap-error] Erreur récupération statistiques: {e}", flush=True)
# 1. Événements de journaux de connexion
today_sessions = {} # mac -> [(dt, event, name)]
for et, ev, mac, name in rows:
if not is_valid_mac(mac):
continue
try:
dt = datetime.datetime.strptime(et[:19], '%Y-%m-%d %H:%M:%S')
except Exception:
continue
d_key = dt.strftime('%Y-%m-%d')
dt_monday = dt.date() - datetime.timedelta(days=dt.weekday())
w_key = dt_monday.strftime('%Y-W%W')
m_key = dt.strftime('%Y-%m')
y_key = dt.strftime('%Y')
if ev == 'connexion':
if et.startswith(today_str):
today_macs.add(mac)
today_total += 1
h = dt.hour
if h in hours_map:
hours_map[h]['total_connections'] += 1
hour_macs[h].add(mac)
hour_devs[h][mac] = name
if et >= cur_week_start:
week_macs_cur.add(mac)
week_total += 1
if et.startswith(cur_month):
month_macs_cur.add(mac)
month_total += 1
if et.startswith(cur_year):
year_macs_cur.add(mac)
year_total += 1
if d_key in days_map:
days_map[d_key]['total_connections'] += 1
day_macs[d_key].add(mac)
day_devs[d_key][mac] = name
if w_key in weeks_map:
weeks_map[w_key]['total_connections'] += 1
week_macs[w_key].add(mac)
week_devs[w_key][mac] = name
if m_key in months_map:
months_map[m_key]['total_connections'] += 1
month_macs[m_key].add(mac)
month_devs[m_key][mac] = name
if y_key in years_map:
years_map[y_key]['total_connections'] += 1
year_macs[y_key].add(mac)
year_devs[y_key][mac] = name
if et.startswith(today_str):
today_sessions.setdefault(mac, []).append((dt, ev, name))
# Reconstitution des tranches horaires pour aujourd'hui selon la durée de présence
for mac, ev_list in today_sessions.items():
last_conn_dt = None
dev_name = None
for dt, ev, name in ev_list:
dev_name = name or dev_name
if ev == 'connexion':
if last_conn_dt is not None:
for h in range(last_conn_dt.hour, dt.hour + 1):
if h in hours_map:
hour_macs[h].add(mac)
hour_devs[h][mac] = dev_name
last_conn_dt = dt
elif ev == 'déconnexion':
if last_conn_dt is not None:
for h in range(last_conn_dt.hour, dt.hour + 1):
if h in hours_map:
hour_macs[h].add(mac)
hour_devs[h][mac] = dev_name
last_conn_dt = None
else:
for h in range(0, dt.hour + 1):
if h in hours_map:
hour_macs[h].add(mac)
hour_devs[h][mac] = dev_name
if last_conn_dt is not None:
for h in range(last_conn_dt.hour, min(23, now.hour) + 1):
if h in hours_map:
hour_macs[h].add(mac)
hour_devs[h][mac] = dev_name
# 2. Intégration du trafic journalier (client_traffic_daily) enregistré en base SQLite
for mac, t_date, name, tot_b in traffic_rows:
if not is_valid_mac(mac):
continue
try:
dt = datetime.datetime.strptime(t_date[:10], '%Y-%m-%d')
except Exception:
continue
d_key = t_date[:10]
dt_monday = dt.date() - datetime.timedelta(days=dt.weekday())
w_key = dt_monday.strftime('%Y-W%W')
m_key = dt.strftime('%Y-%m')
y_key = dt.strftime('%Y')
if d_key == today_str:
today_macs.add(mac)
if d_key >= cur_week_start[:10]:
week_macs_cur.add(mac)
if d_key.startswith(cur_month):
month_macs_cur.add(mac)
if d_key.startswith(cur_year):
year_macs_cur.add(mac)
if d_key in days_map:
day_macs[d_key].add(mac)
day_devs[d_key][mac] = name
if w_key in weeks_map:
week_macs[w_key].add(mac)
week_devs[w_key][mac] = name
if m_key in months_map:
month_macs[m_key].add(mac)
month_devs[m_key][mac] = name
if y_key in years_map:
year_macs[y_key].add(mac)
year_devs[y_key][mac] = name
# 3. Intégration des derniers accès enregistrés en base SQLite (client_names.last_seen)
for mac, name, last_seen in cn_rows:
if not is_valid_mac(mac):
continue
ls = str(last_seen).strip()
if len(ls) >= 10:
ls_date = ls[:10]
if ls_date == today_str:
today_macs.add(mac)
try:
ls_h = int(ls[11:13])
if ls_h in hours_map:
hour_macs[ls_h].add(mac)
hour_devs[ls_h][mac] = name
except Exception:
pass
if ls_date >= cur_week_start[:10]:
week_macs_cur.add(mac)
if ls_date.startswith(cur_month):
month_macs_cur.add(mac)
if ls_date.startswith(cur_year):
year_macs_cur.add(mac)
if ls_date in days_map:
day_macs[ls_date].add(mac)
day_devs[ls_date][mac] = name
if active_items is None:
try: active_items = clients()
except Exception: active_items = []
active_count = len(active_items)
cur_h = now.hour
if active_items:
for x in active_items:
m = x.get('mac')
n = x.get('name') or m
if m:
today_macs.add(m)
week_macs_cur.add(m)
month_macs_cur.add(m)
year_macs_cur.add(m)
if cur_h in hours_map:
hour_macs[cur_h].add(m)
hour_devs[cur_h][m] = n
if today_str in days_map:
day_macs[today_str].add(m)
day_devs[today_str][m] = n
for h, item in hours_map.items():
item['unique_clients'] = len(hour_macs[h])
if item['total_connections'] < item['unique_clients']:
item['total_connections'] = item['unique_clients']
item['devices'] = sorted(list(hour_devs[h].values()))
for k, item in days_map.items():
item['unique_clients'] = len(day_macs[k])
if item['total_connections'] < item['unique_clients']:
item['total_connections'] = item['unique_clients']
item['devices'] = sorted(list(day_devs[k].values()))
for k, item in weeks_map.items():
item['unique_clients'] = len(week_macs[k])
if item['total_connections'] < item['unique_clients']:
item['total_connections'] = item['unique_clients']
item['devices'] = sorted(list(week_devs[k].values()))
for k, item in months_map.items():
item['unique_clients'] = len(month_macs[k])
if item['total_connections'] < item['unique_clients']:
item['total_connections'] = item['unique_clients']
item['devices'] = sorted(list(month_devs[k].values()))
for k, item in years_map.items():
item['unique_clients'] = len(year_macs[k])
if item['total_connections'] < item['unique_clients']:
item['total_connections'] = item['unique_clients']
item['devices'] = sorted(list(year_devs[k].values()))
today_total = max(today_total, len(today_macs))
week_total = max(week_total, len(week_macs_cur))
month_total = max(month_total, len(month_macs_cur))
year_total = max(year_total, len(year_macs_cur))
top_clients_by_range = {
'day': get_top_clients(active_items, 'day'),
'week': get_top_clients(active_items, 'week'),
'month': get_top_clients(active_items, 'month'),
'year': get_top_clients(active_items, 'year')
}
top_clients = top_clients_by_range['day']
now_str = time.strftime('%H:%M:%S')
return {
'summary': {
'current': active_count,
'today': {'unique': len(today_macs), 'total': today_total},
'week': {'unique': len(week_macs_cur), 'total': week_total},
'month': {'unique': len(month_macs_cur), 'total': month_total},
'year': {'unique': len(year_macs_cur), 'total': year_total}
},
'hours': hours,
'days': days,
'weeks': weeks,
'months': months,
'years': years,
'top_clients': top_clients,
'top_clients_by_range': top_clients_by_range,
'updated_at': now_str,
'analyzed_at': now_str,
'background_analyzed': True,
'analysis_count': _metrics_count,
'analysis_duration_ms': _metrics_last_duration_ms
}
def stats():
with _metrics_lock:
if _cached_stats is not None:
return _cached_stats
return compute_stats_internal()
def connection_name():
active = command('nmcli','-t','-g','GENERAL.CONNECTION','device','show',INTERFACE)
if active and active != '--': return active
try:
saved = open(CONNECTION_FILE, encoding='utf8').read().strip()
if saved: return saved
except OSError: pass
pref_con = get_pref('ap_connection_name', '')
if pref_con: return pref_con
pref_ssid = get_pref('ap_ssid', '')
if pref_ssid: return 'AP-' + pref_ssid
return os.environ.get('AP_CONNECTION', '')
def save_connection(name):
try: open(CONNECTION_FILE, 'w', encoding='utf8').write(name)
except OSError: pass
def apply_radio_defaults():
"""Applique bande/canal/CCMP à la connexion AP déjà créée (sans avoir à ré-enregistrer les réglages)."""
if is_bridge_mode(): return
name = connection_name()
if not name: return
eff_channel = get_effective_ap_channel(AP_BAND)
band = command('nmcli','-t','-g','802-11-wireless.band','connection','show',name)
chan = command('nmcli','-t','-g','802-11-wireless.channel','connection','show',name)
key = command('nmcli','-t','-g','802-11-wireless-security.key-mgmt','connection','show',name)
if band == AP_BAND and chan == str(eff_channel): return
args = ['nmcli','connection','modify',name,'802-11-wireless.band',AP_BAND,'802-11-wireless.channel',str(eff_channel)]
if key in ('wpa-psk','sae'): args += ['802-11-wireless-security.pairwise','ccmp','802-11-wireless-security.group','ccmp']
r = subprocess.run(args, text=True, capture_output=True)
print(f"[ap-api] Radio {name} : bande={AP_BAND} canal={eff_channel}{' (auto)' if is_auto_channel() else ''} -> {'OK' if not r.returncode else r.stderr.strip()}", flush=True)
if not r.returncode and command('nmcli','-t','-g','GENERAL.STATE','device','show',INTERFACE).startswith('100'):
subprocess.run(['nmcli','connection','up',name], text=True, capture_output=True)
def security(value):
values = {'wpa1':('wpa-psk','wpa','optional'), 'wpa2':('wpa-psk','rsn','optional'), 'wpa3':('sae',None,'required')}
value = str(value or 'wpa2').lower()
if value not in values: raise ValueError('Sécurité Wi-Fi invalide')
key, proto, pmf = values[value]; return value, key, proto, pmf
def get_pref(key, default=None):
try:
c = db(); row = c.execute("SELECT value FROM preferences WHERE key=?", (key,)).fetchone(); c.close()
if row and row[0] is not None: return row[0]
except Exception: pass
return default
def set_pref(key, value):
try:
c = db(); c.execute("INSERT OR REPLACE INTO preferences(key,value) VALUES(?,?)", (key, str(value))); c.commit(); c.close()
except Exception: pass
def current_mode():
try:
# Pendant l'assistant de configuration initial (setup non terminé), utiliser le mode AP par défaut
if callable(globals().get('auth_state')):
st = auth_state()
if not st.get('setup_completed'):
return 'ap'
except Exception: pass
name = connection_name()
if name:
slave_type = (command('nmcli','-t','-g','connection.slave-type','connection','show',name) or command('nmcli','-t','-g','connection.port-type','connection','show',name)).lower()
if slave_type == 'bridge':
return 'bridge'
master = (command('nmcli','-t','-g','connection.master','connection','show',name) or command('nmcli','-t','-g','connection.controller','connection','show',name))
if master:
return 'bridge'
if os.path.exists(f'/sys/class/net/{INTERFACE}/master'):
return 'bridge'
try:
pref = get_pref('mode', 'ap')
return str(pref).lower() if pref else 'ap'
except Exception:
return 'ap'
def is_bridge_mode():
return current_mode() == 'bridge'
def get_max_clients():
try: return int(get_pref('max_clients', os.environ.get('AP_MAX_CLIENTS', 0)) or 0)
except (ValueError, TypeError): return 0
def set_max_clients(val):
try: n = max(0, int(val if val is not None else 0))
except (ValueError, TypeError): n = 0
set_pref('max_clients', n)
try:
conf_dir = '/etc/NetworkManager/dnsmasq-shared.d'
conf = os.path.join(conf_dir, '20-max-clients.conf')
if n > 0:
os.makedirs(conf_dir, exist_ok=True)
with open(conf, 'w', encoding='utf8') as f: f.write(f"# Limite dynamique de baux DHCP\ndhcp-lease-max={n}\n")
else:
if os.path.exists(conf): os.remove(conf)
except OSError: pass
return n
def ensure_dnsmasq_dns():
"""Garantit que dnsmasq fournit toujours les serveurs AP_DNS aux clients Wi-Fi."""
dns_env = os.environ.get('AP_DNS', '1.1.1.1,9.9.9.9').strip()
if not dns_env:
return
parts = [p.strip() for p in re.split(r'[,;\s]+', dns_env) if p.strip()]
if not parts:
return
clean_dns = ','.join(parts)
try:
conf_dir = '/etc/NetworkManager/dnsmasq-shared.d'
os.makedirs(conf_dir, exist_ok=True)
conf_file = os.path.join(conf_dir, '15-ap-dns.conf')
lines = [
"# Configuration DNS distribuée aux clients Wi-Fi (AP_DNS)",
f"dhcp-option=6,{clean_dns}",
"no-resolv"
]
for s in parts:
lines.append(f"server={s}")
with open(conf_file, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines) + '\n')
except OSError:
pass
# =====================================================================
# Système de notifications multi-canaux (Email SMTP, Gotify, Discord)
# =====================================================================
DEFAULT_NOTIFICATION_TEMPLATES = {
"new_device": {
"title": "📱 Nouvel appareil détecté",
"message": "L'appareil « {name} » vient de se connecter pour la première fois au réseau Wi-Fi."
},
"device_connected": {
"title": "📶 Appareil connecté",
"message": "L'appareil « {name} » s'est connecté au réseau Wi-Fi."
},
"device_disconnected": {
"title": "📴 Appareil déconnecté",
"message": "L'appareil « {name} » s'est déconnecté du réseau Wi-Fi."
},
"admin_login": {
"title": "🔒 Connexion au compte administrateur",
"message": "Connexion réussie au compte administrateur « {user} »."
},
"admin_login_failed": {
"title": "⚠️ Échec de connexion administrateur",
"message": "Une tentative de connexion au compte administrateur a échoué (mot de passe invalide)."
},
"device_blocked": {
"title": "🛑 Équipement Wi-Fi bloqué / débloqué",
"message": "L'appareil « {name} » a été {action} le réseau Wi-Fi."
},
"settings_changed": {
"title": "⚙️ Modification réglages Wi-Fi / AP",
"message": "Les réglages du point d'accès Wi-Fi ont été modifiés (SSID : {ssid})."
},
"vpn_client_connected": {
"title": "🛡️ Client routé via VPN",
"message": "L'appareil « {name} » ({ip}) est désormais connecté et routé via le VPN « {vpn} »."
},
"vpn_client_disconnected": {
"title": "🌐 Client déconnecté du VPN",
"message": "L'appareil « {name} » ({ip}) n'est plus routé via le VPN « {vpn} »."
},
"vpn_profile_connected": {
"title": "🛡️ Tunnel VPN connecté",
"message": "Le profil VPN « {name} » ({type}) est désormais connecté avec succès (interface {iface})."
},
"vpn_profile_disconnected": {
"title": "⚠️ Tunnel VPN déconnecté",
"message": "Le profil VPN « {name} » ({type}) a été déconnecté (interface {iface})."
},
"quota_exceeded": {
"title": "⚠️ Quota de données dépassé",
"message": "L'appareil « {name} » ({ip}) a dépassé son quota de {quota} (consommé : {consumption}). L'accès Internet a été coupé."
},
"stats_report": {
"title": "📊 Rapport statistiques & métriques Wi‑Fi",
"message": "📊 Rapport Wi‑Fi ({date}) :\n• {clients_count} appareil(s) connecté(s) (↓ {traffic_down} • ↑ {traffic_up})\n• Aujourd'hui : {today_unique} visiteur(s) unique(s) ({today_total} sessions)\n• Cette semaine : {week_unique} unique(s) | Ce mois : {month_unique} unique(s)\n• VPN : {active_vpns} tunnel(s) actif(s) ({vpn_routed_clients} appareil(s) routé(s))\n• Passerelle WAN : {gateway_status} ({gateway_ip})\n• Top clients (Consommation de données) :\n{top_clients}"
},
"backup_success": {
"title": "💾 Sauvegarde créée avec succès",
"message": "La sauvegarde « {filename} » ({size}) a été créée avec succès ({trigger})."
},
"backup_remote_success": {
"title": "☁️ Sauvegarde téléversée sur le stockage distant",
"message": "La sauvegarde « {filename} » ({size}) a été téléversée avec succès sur {provider} ({host})."
},
"update_available": {
"title": "🚀 Mise à jour disponible pour AP Manageur",
"message": "Une nouvelle version de AP Manageur est prête sur le dépôt ({latest_commit}) ! Exécutez « {cmd} » pour mettre à jour."
}
}
DEFAULT_NOTIFICATIONS_CONFIG = {
"email": {
"enabled": False,
"smtp_host": "",
"smtp_port": 587,
"smtp_secure": "starttls",
"smtp_user": "",
"smtp_pass": "",
"from_addr": "",
"to_addr": ""
},
"gotify": {
"enabled": False,
"server_url": "",
"token": "",
"priority": 5
},
"discord": {
"enabled": False,
"webhook_url": "",
"bot_name": "AP Manageur"
},
"ntfy": {
"enabled": False,
"server_url": "https://ntfy.sh",
"topic": "",
"token": "",
"priority": 3
},
"pushbullet": {
"enabled": False,
"api_token": "",
"device_iden": ""
},
"pushover": {
"enabled": False,
"user_key": "",
"api_token": "",
"priority": 0
},
"slack": {
"enabled": False,
"webhook_url": "",
"bot_name": "AP Manageur"
},
"telegram": {
"enabled": False,
"bot_token": "",
"chat_id": "",
"thread_id": ""
},
"webhook": {
"enabled": False,
"url": "",
"method": "POST",
"headers": ""
},
"events": {
"new_device": True, # Nouvel équipement Wi-Fi (première connexion)
"device_connected": False, # Reconnexion d'un équipement Wi-Fi connu
"device_disconnected": False, # Déconnexion d'un équipement Wi-Fi
"admin_login": True, # Connexion réussie au compte admin
"admin_login_failed": True, # Tentative de connexion admin échouée
"device_blocked": True, # Appareil bloqué ou débloqué
"settings_changed": True, # Modification des réglages Wi-Fi / AP
"vpn_client_connected": True, # Connexion / Assignation d'un client au VPN
"vpn_client_disconnected": True, # Déconnexion / Retrait d'un client du VPN
"vpn_profile_connected": True, # Connexion d'un profil VPN (tunnel actif)
"vpn_profile_disconnected": True, # Déconnexion d'un profil VPN (tunnel coupé)
"quota_exceeded": True, # Quota de données dépassé par un équipement Wi-Fi
"stats_report": False, # Rapport planifié des statistiques et métriques (Tâche Cron)
"backup_success": True, # Sauvegarde créée avec succès (locale)
"backup_remote_success": True, # Sauvegarde envoyée sur le stockage distant (si configuré)
"update_available": True # Nouvelle mise à jour disponible (image Docker / Git)
},
"stats_report_schedule": {
"enabled": False,
"mode": "daily",
"day": "*",
"hour": 8,
"minute": 0,
"cron_expr": "0 8 * * *",
"top_range": "day"
},
"templates": DEFAULT_NOTIFICATION_TEMPLATES
}
def get_notifications_config():
raw = get_pref('notifications_config')
if not raw:
return json.loads(json.dumps(DEFAULT_NOTIFICATIONS_CONFIG))
try:
cfg = json.loads(raw)
res = json.loads(json.dumps(DEFAULT_NOTIFICATIONS_CONFIG))
for section in ('email', 'gotify', 'discord', 'ntfy', 'pushbullet', 'pushover', 'slack', 'telegram', 'webhook', 'events', 'templates', 'stats_report_schedule'):
if section in cfg and isinstance(cfg[section], dict):
if section == 'templates':
for ev, tmpl in cfg['templates'].items():
if isinstance(tmpl, dict) and ev in res['templates']:
res['templates'][ev].update(tmpl)
else:
res[section].update(cfg[section])
return res
except Exception:
return json.loads(json.dumps(DEFAULT_NOTIFICATIONS_CONFIG))
def get_notifications_settings_public():
cfg = get_notifications_config()
email_cfg = cfg.get('email', {})
has_pass = bool(email_cfg.get('smtp_pass'))
email_cfg['smtp_pass_set'] = has_pass
email_cfg['smtp_pass'] = ''
return cfg
def save_notifications_settings(data):
if not isinstance(data, dict):
raise ValueError("Données de configuration invalides")
current = get_notifications_config()
if 'email' in data and isinstance(data['email'], dict):
ne = data['email']
current['email']['enabled'] = bool(ne.get('enabled', False))
current['email']['smtp_host'] = str(ne.get('smtp_host', '')).strip()
try: current['email']['smtp_port'] = int(ne.get('smtp_port') or 587)
except (ValueError, TypeError): current['email']['smtp_port'] = 587
current['email']['smtp_secure'] = str(ne.get('smtp_secure', 'starttls')).strip().lower()
current['email']['smtp_user'] = str(ne.get('smtp_user', '')).strip()
new_pass = str(ne.get('smtp_pass', ''))
if new_pass:
current['email']['smtp_pass'] = new_pass
current['email']['from_addr'] = str(ne.get('from_addr', '')).strip()
current['email']['to_addr'] = str(ne.get('to_addr', '')).strip()
if 'gotify' in data and isinstance(data['gotify'], dict):
ng = data['gotify']
current['gotify']['enabled'] = bool(ng.get('enabled', False))
current['gotify']['server_url'] = str(ng.get('server_url', '')).strip().rstrip('/')
current['gotify']['token'] = str(ng.get('token', '')).strip()
try: current['gotify']['priority'] = min(10, max(1, int(ng.get('priority') or 5)))
except (ValueError, TypeError): current['gotify']['priority'] = 5
if 'discord' in data and isinstance(data['discord'], dict):
nd = data['discord']
current['discord']['enabled'] = bool(nd.get('enabled', False))
current['discord']['webhook_url'] = str(nd.get('webhook_url', '')).strip()
current['discord']['bot_name'] = str(nd.get('bot_name', '')).strip() or "AP Manageur"
if 'ntfy' in data and isinstance(data['ntfy'], dict):
nn = data['ntfy']
current['ntfy']['enabled'] = bool(nn.get('enabled', False))
current['ntfy']['server_url'] = str(nn.get('server_url', 'https://ntfy.sh')).strip().rstrip('/')
current['ntfy']['topic'] = str(nn.get('topic', '')).strip()
current['ntfy']['token'] = str(nn.get('token', '')).strip()
try: current['ntfy']['priority'] = min(5, max(1, int(nn.get('priority') or 3)))
except (ValueError, TypeError): current['ntfy']['priority'] = 3
if 'pushbullet' in data and isinstance(data['pushbullet'], dict):
np = data['pushbullet']
current['pushbullet']['enabled'] = bool(np.get('enabled', False))
current['pushbullet']['api_token'] = str(np.get('api_token', '')).strip()
current['pushbullet']['device_iden'] = str(np.get('device_iden', '')).strip()
if 'pushover' in data and isinstance(data['pushover'], dict):
npo = data['pushover']
current['pushover']['enabled'] = bool(npo.get('enabled', False))
current['pushover']['user_key'] = str(npo.get('user_key', '')).strip()
current['pushover']['api_token'] = str(npo.get('api_token', '')).strip()
try: current['pushover']['priority'] = min(2, max(-2, int(npo.get('priority') or 0)))
except (ValueError, TypeError): current['pushover']['priority'] = 0
if 'slack' in data and isinstance(data['slack'], dict):
nsl = data['slack']
current['slack']['enabled'] = bool(nsl.get('enabled', False))
current['slack']['webhook_url'] = str(nsl.get('webhook_url', '')).strip()
current['slack']['bot_name'] = str(nsl.get('bot_name', '')).strip() or "AP Manageur"
if 'telegram' in data and isinstance(data['telegram'], dict):
ntg = data['telegram']
current['telegram']['enabled'] = bool(ntg.get('enabled', False))
current['telegram']['bot_token'] = str(ntg.get('bot_token', '')).strip()
current['telegram']['chat_id'] = str(ntg.get('chat_id', '')).strip()
current['telegram']['thread_id'] = str(ntg.get('thread_id', '')).strip()
if 'webhook' in data and isinstance(data['webhook'], dict):
nwh = data['webhook']
current['webhook']['enabled'] = bool(nwh.get('enabled', False))
current['webhook']['url'] = str(nwh.get('url', '')).strip()
current['webhook']['method'] = str(nwh.get('method', 'POST')).strip().upper()
if current['webhook']['method'] not in ('POST', 'PUT', 'GET'): current['webhook']['method'] = 'POST'
current['webhook']['headers'] = str(nwh.get('headers', '')).strip()
if 'events' in data and isinstance(data['events'], dict):
for k in current['events']:
if k in data['events']:
current['events'][k] = bool(data['events'][k])
if 'templates' in data and isinstance(data['templates'], dict):
if 'templates' not in current or not isinstance(current['templates'], dict):
current['templates'] = json.loads(json.dumps(DEFAULT_NOTIFICATION_TEMPLATES))
for ev, tmpl in data['templates'].items():
if isinstance(tmpl, dict) and ev in DEFAULT_NOTIFICATION_TEMPLATES:
current['templates'][ev] = {
'title': str(tmpl.get('title', '')).strip(),
'message': str(tmpl.get('message', '')).strip()
}
if 'stats_report_schedule' in data and isinstance(data['stats_report_schedule'], dict):
ss = data['stats_report_schedule']
cur_s = current.setdefault('stats_report_schedule', {})
cur_s['enabled'] = bool(ss.get('enabled', False))
cur_s['mode'] = str(ss.get('mode', 'daily')).strip()
cur_s['day'] = str(ss.get('day', '*')).strip()
try: cur_s['hour'] = min(23, max(0, int(ss.get('hour', 8))))
except (ValueError, TypeError): cur_s['hour'] = 8
try: cur_s['minute'] = min(59, max(0, int(ss.get('minute', 0))))
except (ValueError, TypeError): cur_s['minute'] = 0
cron_raw = str(ss.get('cron_expr', '')).strip()
if not cron_raw or len(cron_raw.split()) != 5:
cron_raw = f"{cur_s['minute']} {cur_s['hour']} * * {cur_s['day']}"
cur_s['cron_expr'] = cron_raw
top_r = str(ss.get('top_range', 'day')).strip().lower()
if top_r not in ('day', 'week', 'month', 'year', 'all_ranges'):
top_r = 'day'
cur_s['top_range'] = top_r
if 'events' in current and isinstance(current['events'], dict):
current['events']['stats_report'] = cur_s['enabled']
set_pref('notifications_config', json.dumps(current))
return True
def send_email_notification(cfg, title, message, details=None, level="info"):
host = cfg.get('smtp_host', '').strip()
port = int(cfg.get('smtp_port') or 587)
secure = cfg.get('smtp_secure', 'starttls').lower()
user = cfg.get('smtp_user', '').strip()
password = cfg.get('smtp_pass', '')
from_addr = cfg.get('from_addr', '').strip() or user
to_addr = cfg.get('to_addr', '').strip()
if not host:
raise ValueError("Hôte SMTP manquant")
if not to_addr:
raise ValueError("Adresse email de destination manquante")
if not from_addr:
raise ValueError("Adresse email d'expédition manquante")
recipients = [a.strip() for a in re.split(r'[,;]+', to_addr) if a.strip()]
if not recipients:
raise ValueError("Aucun destinataire valide")
msg = MIMEMultipart('alternative')
msg['Subject'] = f"[AP Manageur] {title}"
msg['From'] = from_addr
msg['To'] = ', '.join(recipients)
msg['Date'] = time.strftime('%a, %d %b %Y %H:%M:%S +0000', time.gmtime())
lines = [f"{title}", "=" * len(title), message, ""]
if details:
for k, v in details.items():
lines.append(f"• {k} : {v}")
lines += ["", "--", "Notification automatique envoyée par AP Manageur"]
msg.attach(MIMEText('\n'.join(lines), 'plain', 'utf-8'))
color_map = {
"info": "#1e6ef0",
"success": "#13a06a",
"warning": "#f6ad55",
"danger": "#e53935"
}
badge_color = color_map.get(level, "#1e6ef0")
rows_html = ""
if details:
for k, v in details.items():
rows_html += f"
{k}
{v}
"
html = f"""
AP Manageur • Alerte
{title}
{message}
{"
" + rows_html + "
" if rows_html else ""}
Notification générée automatiquement par le point d'accès Wi-Fi AP Manageur à {time.strftime('%H:%M:%S le %d/%m/%Y')}.
"""
msg.attach(MIMEText(html, 'html', 'utf-8'))
if secure == 'ssl' or port == 465:
server = smtplib.SMTP_SSL(host, port, timeout=12)
else:
server = smtplib.SMTP(host, port, timeout=12)
if secure == 'starttls':
server.starttls()
if user and password:
server.login(user, password)
server.sendmail(from_addr, recipients, msg.as_string())
server.quit()
return True
def send_gotify_notification(cfg, title, message, details=None, priority=5):
server_url = (cfg.get('server_url') or '').strip()
token = (cfg.get('token') or '').strip()
if not server_url:
raise ValueError("URL du serveur Gotify manquante")
if not token:
raise ValueError("Token d'application Gotify manquant")
# Normalisation du protocole et de l'URL
if not (server_url.startswith('http://') or server_url.startswith('https://')):
server_url = 'http://' + server_url
server_url = server_url.rstrip('/')
if server_url.endswith('/message'):
server_url = server_url[:-len('/message')].rstrip('/')
# Détection des erreurs courantes de token (jeton Client au lieu d'Application)
# Dans Gotify v3+, les tokens d'app commencent par 'gtfya.' et les clients par 'gtfyc.'
# Dans Gotify v2, les tokens d'app commencent par 'A' et les clients par 'C'
if token.startswith('gtfyc.') or (token.startswith('C') and not token.startswith('gtfya.') and len(token) >= 10):
raise ValueError(
"Le token fourni commence par 'gtfyc.' ou 'C' (jeton Client Gotify). "
"Gotify exige un jeton d'Application créé dans l'onglet 'APPS' "
"(commençant par 'gtfya.' en v3 ou 'A' en v2) pour publier des alertes."
)
try:
p = int(cfg.get('priority') or priority or 5)
except (ValueError, TypeError):
p = 5
p = max(0, min(10, p))
msg_body = message
if details and isinstance(details, dict):
msg_body += '\n\n' + '\n'.join(f'• **{k}** : `{v}`' for k, v in details.items())
payload = {
"title": f"AP Manageur - {title}",
"message": msg_body,
"priority": p,
"extras": {
"client::display": {
"contentType": "text/markdown"
}
}
}
# Authentification triple : URL param (?token=...) + headers X-Gotify-Key et Authorization: Bearer
# Assure une compatibilité totale avec Gotify v2 et v3.1.1 et tous reverse-proxies
post_url = f"{server_url}/message?token={urllib.parse.quote(token)}"
headers = {
'Content-Type': 'application/json',
'X-Gotify-Key': token,
'Authorization': f'Bearer {token}',
'User-Agent': 'AP-Manageur/1.0'
}
ctx = None
if server_url.startswith('https://'):
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
def _post_payload(p_dict):
data = json.dumps(p_dict).encode('utf-8')
req = urllib.request.Request(
post_url,
data=data,
headers=headers,
method='POST'
)
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
if resp.status not in (200, 201, 202, 204):
raise RuntimeError(f"Code HTTP Gotify inattendu : {resp.status}")
return True
try:
return _post_payload(payload)
except urllib.error.HTTPError as e:
body = ""
try:
body = e.read().decode('utf-8', errors='ignore')
except Exception:
pass
err_desc = ""
try:
err_json = json.loads(body)
err_desc = err_json.get('errorDescription') or err_json.get('error') or ""
except Exception:
err_desc = body[:200] if body else ""
# En cas d'erreur 400 (Bad Request), retenter sans extras si un plugin strict le rejette
if e.code == 400 and 'extras' in payload:
try:
simple_payload = {
"title": f"AP Manageur - {title}",
"message": msg_body,
"priority": p
}
return _post_payload(simple_payload)
except Exception:
pass
if e.code == 401:
raise RuntimeError(
f"Erreur Gotify 401 (Non autorisé) : {err_desc or 'Jeton non reconnu'}. "
"Assurez-vous d'utiliser un token créé dans l'onglet 'APPS' de Gotify 3.1.1 (et non dans 'CLIENTS')."
)
elif e.code == 403:
raise RuntimeError(f"Erreur Gotify 403 (Interdit) : {err_desc or 'Accès refusé'}.")
elif e.code == 404:
raise RuntimeError(f"Erreur Gotify 404 (Introuvable) : L'adresse '{server_url}/message' est introuvable. Vérifiez l'URL de votre serveur Gotify.")
elif e.code == 400:
raise RuntimeError(f"Erreur Gotify 400 (Requête invalide) : {err_desc or 'Message ou titre rejeté'}.")
else:
raise RuntimeError(f"Erreur serveur Gotify HTTP {e.code} : {err_desc or e.reason}")
except urllib.error.URLError as e:
reason_str = str(e.reason)
if "Connection refused" in reason_str:
raise RuntimeError(f"Connexion refusée vers {server_url}. Vérifiez que Gotify est bien démarré et que le port/IP est correct.")
elif "Name or service not known" in reason_str or "getaddrinfo failed" in reason_str:
raise RuntimeError(f"Hôte introuvable : Impossible de résoudre '{server_url}'. Vérifiez le nom de domaine.")
elif "timed out" in reason_str.lower():
raise RuntimeError(f"Délai d'attente dépassé (10s) en joignant Gotify sur {server_url}.")
elif "CERTIFICATE_VERIFY_FAILED" in reason_str:
raise RuntimeError(f"Erreur certificat SSL vers {server_url} : {reason_str}")
else:
raise RuntimeError(f"Impossible de joindre Gotify ({server_url}) : {reason_str}")
def send_discord_notification(cfg, title, message, details=None, level="info"):
webhook_url = (cfg.get('webhook_url') or '').strip()
if not webhook_url or not webhook_url.startswith('http'):
raise ValueError("URL du Webhook Discord invalide")
color_map = {
"info": 0x38BDF8, # Bleu clair
"success": 0x32D583, # Vert
"warning": 0xF6AD55, # Orange
"danger": 0xFF6B6B # Rouge
}
color = color_map.get(level, 0x38BDF8)
bot_name = (cfg.get('bot_name') or '').strip() or "AP Manageur"
fields = []
if details and isinstance(details, dict):
for k, v in details.items():
fields.append({"name": str(k), "value": f"`{v}`" if any(c in str(v) for c in (':', '.')) else str(v), "inline": True})
embed = {
"title": title,
"description": message,
"color": color,
"fields": fields,
"footer": {
"text": "AP Manageur • Système de notifications"
},
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat()
}
payload = {
"username": bot_name,
"embeds": [embed]
}
data = json.dumps(payload).encode('utf-8')
req = urllib.request.Request(
webhook_url,
data=data,
headers={
'Content-Type': 'application/json',
'User-Agent': 'AP-Manageur/1.0'
},
method='POST'
)
ctx = None
if webhook_url.startswith('https://'):
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
try:
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
if resp.status not in (200, 204):
raise RuntimeError(f"Code HTTP Discord inattendu : {resp.status}")
return True
except urllib.error.HTTPError as e:
body = ""
try:
body = e.read().decode('utf-8', errors='ignore')
except Exception:
pass
err_desc = ""
try:
err_json = json.loads(body)
err_desc = err_json.get('message') or ""
except Exception:
err_desc = body[:200] if body else ""
raise RuntimeError(f"Erreur HTTP Discord {e.code} : {err_desc or e.reason}")
except urllib.error.URLError as e:
raise RuntimeError(f"Impossible de joindre Discord : {e.reason}")
def send_ntfy_notification(cfg, title, message, details=None, priority=3):
server_url = (cfg.get('server_url') or '').strip() or 'https://ntfy.sh'
topic = (cfg.get('topic') or '').strip()
token = (cfg.get('token') or '').strip()
if not topic:
raise ValueError("Topic ntfy manquant")
if not (server_url.startswith('http://') or server_url.startswith('https://')):
server_url = 'https://' + server_url
server_url = server_url.rstrip('/')
post_url = f"{server_url}/{urllib.parse.quote(topic)}"
try:
p = int(cfg.get('priority') or priority or 3)
except (ValueError, TypeError):
p = 3
p = max(1, min(5, p))
msg_body = message
if details and isinstance(details, dict):
msg_body += "\n\n" + "\n".join(f"• {k} : {v}" for k, v in details.items())
payload = {
"topic": topic,
"title": f"AP Manageur - {title}",
"message": msg_body,
"priority": p,
"tags": ["warning" if p >= 4 else "bell"]
}
headers = {
'Content-Type': 'application/json',
'User-Agent': 'AP-Manageur/1.0'
}
if token:
headers['Authorization'] = f"Bearer {token}"
ctx = None
if server_url.startswith('https://'):
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
data = json.dumps(payload).encode('utf-8')
req = urllib.request.Request(post_url, data=data, headers=headers, method='POST')
try:
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
if resp.status not in (200, 201, 202, 204):
raise RuntimeError(f"Code HTTP ntfy inattendu : {resp.status}")
return True
except urllib.error.HTTPError as e:
body = ""
try: body = e.read().decode('utf-8', errors='ignore')
except Exception: pass
raise RuntimeError(f"Erreur HTTP ntfy {e.code} : {body[:200] or e.reason}")
except urllib.error.URLError as e:
raise RuntimeError(f"Impossible de joindre ntfy ({server_url}) : {e.reason}")
def send_pushbullet_notification(cfg, title, message, details=None):
token = (cfg.get('api_token') or '').strip()
if not token:
raise ValueError("Jeton d'accès (Access Token) Pushbullet manquant")
post_url = "https://api.pushbullet.com/v2/pushes"
body_text = message
if details and isinstance(details, dict):
body_text += "\n\n" + "\n".join(f"• {k} : {v}" for k, v in details.items())
payload = {
"type": "note",
"title": f"AP Manageur - {title}",
"body": body_text
}
device_iden = (cfg.get('device_iden') or '').strip()
if device_iden:
payload["device_iden"] = device_iden
data = json.dumps(payload).encode('utf-8')
headers = {
'Access-Token': token,
'Content-Type': 'application/json',
'User-Agent': 'AP-Manageur/1.0'
}
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
req = urllib.request.Request(post_url, data=data, headers=headers, method='POST')
try:
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
if resp.status not in (200, 201, 204):
raise RuntimeError(f"Code HTTP Pushbullet inattendu : {resp.status}")
return True
except urllib.error.HTTPError as e:
body = ""
try: body = e.read().decode('utf-8', errors='ignore')
except Exception: pass
raise RuntimeError(f"Erreur HTTP Pushbullet {e.code} : {body[:200] or e.reason}")
except urllib.error.URLError as e:
raise RuntimeError(f"Impossible de joindre Pushbullet : {e.reason}")
def send_pushover_notification(cfg, title, message, details=None, priority=0):
user_key = (cfg.get('user_key') or '').strip()
api_token = (cfg.get('api_token') or '').strip()
if not user_key:
raise ValueError("Clé utilisateur (User Key) Pushover manquante")
if not api_token:
raise ValueError("Jeton d'application (API Token) Pushover manquant")
post_url = "https://api.pushover.net/1/messages.json"
msg_body = message
if details and isinstance(details, dict):
msg_body += "\n\n" + "\n".join(f"• {k} : {v}" for k, v in details.items())
try:
p = int(cfg.get('priority') or priority or 0)
except (ValueError, TypeError):
p = 0
p = max(-2, min(2, p))
payload = {
"token": api_token,
"user": user_key,
"title": f"AP Manageur - {title}",
"message": msg_body,
"priority": p
}
data = urllib.parse.urlencode(payload).encode('utf-8')
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'AP-Manageur/1.0'
}
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
req = urllib.request.Request(post_url, data=data, headers=headers, method='POST')
try:
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
if resp.status not in (200, 201):
raise RuntimeError(f"Code HTTP Pushover inattendu : {resp.status}")
return True
except urllib.error.HTTPError as e:
body = ""
try: body = e.read().decode('utf-8', errors='ignore')
except Exception: pass
raise RuntimeError(f"Erreur HTTP Pushover {e.code} : {body[:200] or e.reason}")
except urllib.error.URLError as e:
raise RuntimeError(f"Impossible de joindre Pushover : {e.reason}")
def send_slack_notification(cfg, title, message, details=None, level="info"):
webhook_url = (cfg.get('webhook_url') or '').strip()
if not webhook_url or not webhook_url.startswith('http'):
raise ValueError("URL du Webhook entrant Slack invalide")
bot_name = (cfg.get('bot_name') or '').strip() or "AP Manageur"
color_map = {
"info": "#38BDF8",
"success": "#32D583",
"warning": "#F6AD55",
"danger": "#FF6B6B"
}
color = color_map.get(level, "#38BDF8")
fields = []
if details and isinstance(details, dict):
for k, v in details.items():
fields.append({"title": str(k), "value": str(v), "short": True})
attachment = {
"color": color,
"title": f"AP Manageur - {title}",
"text": message,
"fields": fields,
"footer": "AP Manageur",
"ts": int(time.time())
}
payload = {
"username": bot_name,
"attachments": [attachment]
}
data = json.dumps(payload).encode('utf-8')
headers = {
'Content-Type': 'application/json',
'User-Agent': 'AP-Manageur/1.0'
}
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
req = urllib.request.Request(webhook_url, data=data, headers=headers, method='POST')
try:
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
if resp.status not in (200, 204):
raise RuntimeError(f"Code HTTP Slack inattendu : {resp.status}")
return True
except urllib.error.HTTPError as e:
body = ""
try: body = e.read().decode('utf-8', errors='ignore')
except Exception: pass
raise RuntimeError(f"Erreur HTTP Slack {e.code} : {body[:200] or e.reason}")
except urllib.error.URLError as e:
raise RuntimeError(f"Impossible de joindre Slack : {e.reason}")
def send_telegram_notification(cfg, title, message, details=None):
bot_token = (cfg.get('bot_token') or '').strip()
chat_id = (cfg.get('chat_id') or '').strip()
if not bot_token:
raise ValueError("Jeton de bot Telegram (Bot Token) manquant")
if not chat_id:
raise ValueError("Identifiant de discussion (Chat ID) Telegram manquant")
post_url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
def escape_html(s):
return str(s).replace('&', '&').replace('<', '<').replace('>', '>')
text = f"{escape_html(title)}\n\n{escape_html(message)}"
if details and isinstance(details, dict):
text += "\n\n" + "\n".join(f"• {escape_html(k)} : {escape_html(v)}" for k, v in details.items())
payload = {
"chat_id": chat_id,
"text": text,
"parse_mode": "HTML",
"disable_web_page_preview": True
}
thread_id = (cfg.get('thread_id') or '').strip()
if thread_id:
try: payload["message_thread_id"] = int(thread_id)
except (ValueError, TypeError): pass
data = json.dumps(payload).encode('utf-8')
headers = {
'Content-Type': 'application/json',
'User-Agent': 'AP-Manageur/1.0'
}
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
req = urllib.request.Request(post_url, data=data, headers=headers, method='POST')
try:
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
if resp.status not in (200, 201):
raise RuntimeError(f"Code HTTP Telegram inattendu : {resp.status}")
return True
except urllib.error.HTTPError as e:
body = ""
try: body = e.read().decode('utf-8', errors='ignore')
except Exception: pass
err_msg = ""
try:
j = json.loads(body)
err_msg = j.get('description') or ""
except Exception:
err_msg = body[:200]
raise RuntimeError(f"Erreur HTTP Telegram {e.code} : {err_msg or e.reason}")
except urllib.error.URLError as e:
raise RuntimeError(f"Impossible de joindre Telegram : {e.reason}")
def send_custom_webhook_notification(cfg, title, message, details=None, level="info"):
url = (cfg.get('url') or '').strip()
if not url or not url.startswith('http'):
raise ValueError("URL du Webhook personnalisé invalide")
method = (cfg.get('method') or 'POST').strip().upper()
if method not in ('POST', 'PUT', 'GET'):
method = 'POST'
headers_str = (cfg.get('headers') or '').strip()
headers = {
'User-Agent': 'AP-Manageur/1.0'
}
if headers_str:
try:
custom_h = json.loads(headers_str)
if isinstance(custom_h, dict):
for hk, hv in custom_h.items():
headers[str(hk)] = str(hv)
except Exception:
for line in headers_str.splitlines():
if ':' in line:
hk, hv = line.split(':', 1)
headers[hk.strip()] = hv.strip()
payload = {
"service": "AP Manageur",
"title": title,
"message": message,
"level": level,
"details": details or {},
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat()
}
ctx = None
if url.startswith('https://'):
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
if method == 'GET':
query = urllib.parse.urlencode({"title": title, "message": message})
final_url = f"{url}{'&' if '?' in url else '?'}{query}"
req = urllib.request.Request(final_url, headers=headers, method='GET')
else:
if 'Content-Type' not in headers:
headers['Content-Type'] = 'application/json'
data = json.dumps(payload).encode('utf-8')
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
if resp.status not in (200, 201, 202, 204):
raise RuntimeError(f"Code HTTP Webhook inattendu : {resp.status}")
return True
except urllib.error.HTTPError as e:
body = ""
try: body = e.read().decode('utf-8', errors='ignore')
except Exception: pass
raise RuntimeError(f"Erreur HTTP Webhook {e.code} : {body[:200] or e.reason}")
except urllib.error.URLError as e:
raise RuntimeError(f"Impossible de joindre le Webhook ({url}) : {e.reason}")
def test_notifications(channel='all', test_config=None):
cfg = get_notifications_config()
all_channels = ('email', 'gotify', 'discord', 'ntfy', 'pushbullet', 'pushover', 'slack', 'telegram', 'webhook')
if isinstance(test_config, dict):
for sec in all_channels:
if sec in test_config and isinstance(test_config[sec], dict):
if sec == 'email' and not test_config['email'].get('smtp_pass') and cfg.get('email', {}).get('smtp_pass'):
test_config['email']['smtp_pass'] = cfg['email']['smtp_pass']
cfg[sec].update(test_config[sec])
channel = (channel or 'all').lower()
results = {}
title = "🧪 Notification de test"
message = "Ceci est un test envoyé depuis le tableau de bord AP Manageur pour vérifier le bon acheminement de vos alertes."
details = {
"Statut": "Opérationnel",
"Horodatage": time.strftime('%d/%m/%Y %H:%M:%S'),
"Service": f"AP Manageur {APP_VERSION}"
}
if channel in ('all', 'email'):
if channel == 'email' or cfg.get('email', {}).get('enabled'):
try:
send_email_notification(cfg.get('email', {}), title, message, details, level="success")
results['email'] = {'ok': True, 'message': f"Email envoyé avec succès à {cfg.get('email', {}).get('to_addr')}"}
except Exception as e:
results['email'] = {'ok': False, 'error': str(e)}
if channel in ('all', 'gotify'):
if channel == 'gotify' or cfg.get('gotify', {}).get('enabled'):
try:
send_gotify_notification(cfg.get('gotify', {}), title, message, details, priority=5)
results['gotify'] = {'ok': True, 'message': "Message de test Gotify envoyé avec succès"}
except Exception as e:
results['gotify'] = {'ok': False, 'error': str(e)}
if channel in ('all', 'discord'):
if channel == 'discord' or cfg.get('discord', {}).get('enabled'):
try:
send_discord_notification(cfg.get('discord', {}), title, message, details, level="success")
results['discord'] = {'ok': True, 'message': "Webhook Discord exécuté avec succès"}
except Exception as e:
results['discord'] = {'ok': False, 'error': str(e)}
if channel in ('all', 'ntfy'):
if channel == 'ntfy' or cfg.get('ntfy', {}).get('enabled'):
try:
send_ntfy_notification(cfg.get('ntfy', {}), title, message, details, priority=3)
results['ntfy'] = {'ok': True, 'message': f"Message ntfy envoyé avec succès sur le topic « {cfg.get('ntfy', {}).get('topic')} »"}
except Exception as e:
results['ntfy'] = {'ok': False, 'error': str(e)}
if channel in ('all', 'pushbullet'):
if channel == 'pushbullet' or cfg.get('pushbullet', {}).get('enabled'):
try:
send_pushbullet_notification(cfg.get('pushbullet', {}), title, message, details)
results['pushbullet'] = {'ok': True, 'message': "Push Pushbullet envoyé avec succès"}
except Exception as e:
results['pushbullet'] = {'ok': False, 'error': str(e)}
if channel in ('all', 'pushover'):
if channel == 'pushover' or cfg.get('pushover', {}).get('enabled'):
try:
send_pushover_notification(cfg.get('pushover', {}), title, message, details, priority=0)
results['pushover'] = {'ok': True, 'message': "Notification Pushover délivrée avec succès"}
except Exception as e:
results['pushover'] = {'ok': False, 'error': str(e)}
if channel in ('all', 'slack'):
if channel == 'slack' or cfg.get('slack', {}).get('enabled'):
try:
send_slack_notification(cfg.get('slack', {}), title, message, details, level="success")
results['slack'] = {'ok': True, 'message': "Notification envoyée sur Slack avec succès"}
except Exception as e:
results['slack'] = {'ok': False, 'error': str(e)}
if channel in ('all', 'telegram'):
if channel == 'telegram' or cfg.get('telegram', {}).get('enabled'):
try:
send_telegram_notification(cfg.get('telegram', {}), title, message, details)
results['telegram'] = {'ok': True, 'message': f"Message Telegram envoyé avec succès au chat {cfg.get('telegram', {}).get('chat_id')}"}
except Exception as e:
results['telegram'] = {'ok': False, 'error': str(e)}
if channel in ('all', 'webhook'):
if channel == 'webhook' or cfg.get('webhook', {}).get('enabled'):
try:
send_custom_webhook_notification(cfg.get('webhook', {}), title, message, details, level="success")
results['webhook'] = {'ok': True, 'message': f"Requête Webhook exécutée avec succès vers {cfg.get('webhook', {}).get('url')}"}
except Exception as e:
results['webhook'] = {'ok': False, 'error': str(e)}
if not results:
results['general'] = {'ok': False, 'error': "Aucun canal de notification n'est activé à tester"}
return results
def dispatch_notification(event_type, title, message, details=None, priority=5, level="info", vars_dict=None, force=False):
"""Envoie de façon asynchrone la notification aux canaux configurés si l'événement est actif."""
cfg = get_notifications_config()
events = cfg.get('events', {})
if not force and event_type != 'test' and not events.get(event_type, False):
return
# Préparation des variables de substitution
safe_vars = {
'date': time.strftime('%d/%m/%Y %H:%M:%S'),
'heure': time.strftime('%H:%M:%S'),
'time': time.strftime('%d/%m/%Y %H:%M:%S')
}
if details and isinstance(details, dict):
for k, v in details.items():
val_str = str(v)
safe_vars[str(k).lower()] = val_str
clean_k = re.sub(r'[^a-zA-Z0-9_]', '', str(k).lower())
if clean_k:
safe_vars[clean_k] = val_str
if vars_dict and isinstance(vars_dict, dict):
for k, v in vars_dict.items():
val_str = str(v)
safe_vars[str(k).lower()] = val_str
# Alias fréquents
if 'nom' in safe_vars and 'name' not in safe_vars:
safe_vars['name'] = safe_vars['nom']
if 'name' in safe_vars and 'nom' not in safe_vars:
safe_vars['nom'] = safe_vars['name']
if 'compte' in safe_vars and 'user' not in safe_vars:
safe_vars['user'] = safe_vars['compte']
if 'identifiant' in safe_vars and 'user' not in safe_vars:
safe_vars['user'] = safe_vars['identifiant']
if 'identifianttente' in safe_vars and 'user' not in safe_vars:
safe_vars['user'] = safe_vars['identifianttente']
if 'machine' in safe_vars and 'device' not in safe_vars:
safe_vars['device'] = safe_vars['machine']
if 'navigateur' in safe_vars and 'browser' not in safe_vars:
safe_vars['browser'] = safe_vars['navigateur']
if 'securite' in safe_vars and 'security' not in safe_vars:
safe_vars['security'] = safe_vars['securite']
if 'profilvpn' in safe_vars and 'vpn' not in safe_vars:
safe_vars['vpn'] = safe_vars['profilvpn']
if 'profil_vpn' in safe_vars and 'vpn' not in safe_vars:
safe_vars['vpn'] = safe_vars['profil_vpn']
if 'vpn_name' in safe_vars and 'vpn' not in safe_vars:
safe_vars['vpn'] = safe_vars['vpn_name']
if 'profil' in safe_vars and 'name' not in safe_vars:
safe_vars['name'] = safe_vars['profil']
if 'profile' in safe_vars and 'name' not in safe_vars:
safe_vars['name'] = safe_vars['profile']
if 'interface' in safe_vars and 'iface' not in safe_vars:
safe_vars['iface'] = safe_vars['interface']
if 'consumption' in safe_vars and 'consommation' not in safe_vars:
safe_vars['consommation'] = safe_vars['consumption']
if 'consommation' in safe_vars and 'consumption' not in safe_vars:
safe_vars['consumption'] = safe_vars['consommation']
if 'usage' in safe_vars and 'consommation' not in safe_vars:
safe_vars['consommation'] = safe_vars['usage']
if 'usage' in safe_vars and 'consumption' not in safe_vars:
safe_vars['consumption'] = safe_vars['usage']
if 'quota' in safe_vars and 'limite' not in safe_vars:
safe_vars['limite'] = safe_vars['quota']
if 'limite' in safe_vars and 'quota' not in safe_vars:
safe_vars['quota'] = safe_vars['limite']
def render_tmpl(text):
if not text:
return ""
return re.sub(r'\{([a-zA-Z0-9_]+)\}', lambda m: safe_vars.get(m.group(1).lower(), '{' + m.group(1) + '}'), text)
pref_lang = 'fr'
try: pref_lang = get_pref('language', 'fr')
except Exception: pass
final_title = title
final_message = message
if pref_lang and pref_lang.startswith('en'):
final_title = translate_api_text(final_title, pref_lang)
final_message = translate_api_text(final_message, pref_lang)
templates = cfg.get('templates', {})
tmpl = templates.get(event_type) if isinstance(templates, dict) else None
if tmpl and isinstance(tmpl, dict):
custom_t = (tmpl.get('title') or '').strip()
custom_m = (tmpl.get('message') or '').strip()
if custom_t:
final_title = render_tmpl(custom_t)
if custom_m:
final_message = render_tmpl(custom_m)
def _worker():
if cfg.get('email', {}).get('enabled'):
try:
send_email_notification(cfg['email'], final_title, final_message, details, level=level)
print(f"[ap-notif] Email envoyé pour {event_type}", flush=True)
except Exception as e:
print(f"[ap-notif] Erreur envoi Email ({event_type}) : {e}", flush=True)
if cfg.get('gotify', {}).get('enabled'):
try:
send_gotify_notification(cfg['gotify'], final_title, final_message, details, priority=priority)
print(f"[ap-notif] Gotify envoyé pour {event_type}", flush=True)
except Exception as e:
print(f"[ap-notif] Erreur envoi Gotify ({event_type}) : {e}", flush=True)
if cfg.get('discord', {}).get('enabled'):
try:
send_discord_notification(cfg['discord'], final_title, final_message, details, level=level)
print(f"[ap-notif] Discord envoyé pour {event_type}", flush=True)
except Exception as e:
print(f"[ap-notif] Erreur envoi Discord ({event_type}) : {e}", flush=True)
if cfg.get('ntfy', {}).get('enabled'):
try:
send_ntfy_notification(cfg['ntfy'], final_title, final_message, details, priority=3)
print(f"[ap-notif] ntfy envoyé pour {event_type}", flush=True)
except Exception as e:
print(f"[ap-notif] Erreur envoi ntfy ({event_type}) : {e}", flush=True)
if cfg.get('pushbullet', {}).get('enabled'):
try:
send_pushbullet_notification(cfg['pushbullet'], final_title, final_message, details)
print(f"[ap-notif] Pushbullet envoyé pour {event_type}", flush=True)
except Exception as e:
print(f"[ap-notif] Erreur envoi Pushbullet ({event_type}) : {e}", flush=True)
if cfg.get('pushover', {}).get('enabled'):
try:
send_pushover_notification(cfg['pushover'], final_title, final_message, details, priority=0)
print(f"[ap-notif] Pushover envoyé pour {event_type}", flush=True)
except Exception as e:
print(f"[ap-notif] Erreur envoi Pushover ({event_type}) : {e}", flush=True)
if cfg.get('slack', {}).get('enabled'):
try:
send_slack_notification(cfg['slack'], final_title, final_message, details, level=level)
print(f"[ap-notif] Slack envoyé pour {event_type}", flush=True)
except Exception as e:
print(f"[ap-notif] Erreur envoi Slack ({event_type}) : {e}", flush=True)
if cfg.get('telegram', {}).get('enabled'):
try:
send_telegram_notification(cfg['telegram'], final_title, final_message, details)
print(f"[ap-notif] Telegram envoyé pour {event_type}", flush=True)
except Exception as e:
print(f"[ap-notif] Erreur envoi Telegram ({event_type}) : {e}", flush=True)
if cfg.get('webhook', {}).get('enabled'):
try:
send_custom_webhook_notification(cfg['webhook'], final_title, final_message, details, level=level)
print(f"[ap-notif] Webhook envoyé pour {event_type}", flush=True)
except Exception as e:
print(f"[ap-notif] Erreur envoi Webhook ({event_type}) : {e}", flush=True)
threading.Thread(target=_worker, daemon=True).start()
def detect_ethernet_interfaces():
eths = []
try:
import glob
for path in sorted(glob.glob('/sys/class/net/*')):
iface = os.path.basename(path)
if iface in ('lo', INTERFACE) or iface.startswith(('docker', 'veth', 'br', 'virbr')):
continue
type_file = os.path.join(path, 'type')
if os.path.exists(type_file):
try:
if open(type_file).read().strip() == '1':
if not os.path.exists(os.path.join(path, 'wireless')) and not os.path.exists(os.path.join(path, 'phy80211')):
eths.append(iface)
except OSError: pass
except Exception: pass
return eths
CREATED_BRIDGE_FILE = '/run/ap-created-bridge'
def get_iface_ip_info(iface):
"""Récupère l'IP CIDR, la passerelle par défaut et la MAC d'une interface."""
ip_cidr = None
gw = None
mac = None
try:
out = command('ip', '-4', '-o', 'addr', 'show', 'dev', iface)
m = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+/\d+)', out)
if m: ip_cidr = m.group(1)
except Exception: pass
try:
out = command('ip', 'route', 'show', 'default')
m = re.search(rf'default via (\d+\.\d+\.\d+\.\d+)\s+dev\s+{re.escape(iface)}', out)
if m: gw = m.group(1)
except Exception: pass
try:
mac_file = f'/sys/class/net/{iface}/address'
if os.path.exists(mac_file):
mac = open(mac_file).read().strip()
except Exception: pass
return ip_cidr, gw, mac
def clean_stale_router_leases():
"""Supprime les baux dnsmasq obsolètes et nettoie les IP 10.42.x.x en mode pont."""
global station_live_ips
try:
station_live_ips = {k: v for k, v in station_live_ips.items() if not v.startswith('10.42.')}
except Exception: pass
import glob
for lf in glob.glob('/var/lib/NetworkManager/dnsmasq*.leases') + glob.glob('/data/nm-state/dnsmasq*.leases') + ['/var/lib/misc/dnsmasq.leases']:
try: open(lf, 'w').close()
except OSError: pass
try:
c = db()
c.execute("UPDATE client_names SET last_ip='Non attribuée' WHERE last_ip LIKE '10.42.%'")
c.commit(); c.close()
except Exception: pass
try:
subprocess.run(['ip', 'neigh', 'flush', 'to', '10.42.0.0/16'], capture_output=True)
subprocess.run(['ip', 'neigh', 'flush', 'dev', INTERFACE], capture_output=True)
except Exception: pass
def find_bin(name):
if not name: return None
for candidate in [name, f'/usr/sbin/{name}', f'/sbin/{name}', f'/usr/local/sbin/{name}', f'/usr/bin/{name}', f'/bin/{name}']:
p = shutil.which(candidate)
if p and os.path.isfile(p) and os.access(p, os.X_OK):
return p
return shutil.which(name) or name
def run_cmd(*args):
if not args: return None
cmd = list(args)
cmd[0] = find_bin(cmd[0])
try:
return subprocess.run(cmd, capture_output=True)
except Exception:
return 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)."""
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)."""
iface = iface or INTERFACE
try:
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')
except Exception:
pass
def _ap_iptables_bins():
"""Retourne les binaires iptables actifs à synchroniser (iptables par défaut + iptables-legacy si sa politique FORWARD est DROP)."""
bins = []
default_bin = find_bin('iptables')
if default_bin:
bins.append(default_bin)
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)
if r.returncode == 0 and ('-P FORWARD DROP' in r.stdout or 'DOCKER' in r.stdout):
bins.append(legacy_bin)
except Exception:
pass
return bins
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)
if r.returncode == 0:
m = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+/\d+)', r.stdout)
if m:
net = ipaddress.ip_network(m.group(1), strict=False)
return str(net)
except Exception:
pass
return '10.42.0.0/24'
def setup_ap_nat(iface=None):
"""Garantit le transfert (FORWARD) et le NAT (MASQUERADE) en mode AP, même sur un hôte Docker (politique FORWARD DROP)."""
iface = iface or INTERFACE
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)
except Exception:
pass
subnet = _get_ap_subnet(iface)
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)
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)
# 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)
# 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)
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)
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)
def ensure_ap_nat_active(iface=None):
"""Vérifie que les règles NAT/FORWARD du mode AP sont toujours présentes (utile après autoconnect ou rechargement Docker)."""
iface = iface or INTERFACE
if not iface or is_bridge_mode() or not is_iface_up(iface):
return
try:
ipt = find_bin('iptables')
if not ipt:
return
r_fwd = subprocess.run([ipt, '-w', '2', '-C', 'FORWARD', '-j', 'AP_NAT_FORWARD'], capture_output=True, timeout=2)
r_nat = subprocess.run([ipt, '-w', '2', '-t', 'nat', '-C', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True, timeout=2)
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."""
seen = set()
for candidate in (find_bin('iptables'), find_bin('iptables-legacy')):
if not candidate:
continue
rp = os.path.realpath(candidate)
if rp in seen:
continue
seen.add(rp)
try:
while subprocess.run([candidate, '-w', '5', '-D', 'FORWARD', '-j', 'AP_NAT_FORWARD'], capture_output=True).returncode == 0:
pass
subprocess.run([candidate, '-w', '5', '-F', 'AP_NAT_FORWARD'], capture_output=True)
subprocess.run([candidate, '-w', '5', '-X', 'AP_NAT_FORWARD'], capture_output=True)
while subprocess.run([candidate, '-w', '5', '-t', 'nat', '-D', 'POSTROUTING', '-j', 'AP_NAT_POST'], capture_output=True).returncode == 0:
pass
subprocess.run([candidate, '-w', '5', '-t', 'nat', '-F', 'AP_NAT_POST'], capture_output=True)
subprocess.run([candidate, '-w', '5', '-t', 'nat', '-X', 'AP_NAT_POST'], capture_output=True)
except Exception:
pass
HOSTAPD_CONF_FILE = '/run/ap-hostapd.conf'
HOSTAPD_PID_FILE = '/run/ap-hostapd.pid'
HOSTAPD_LOG_FILE = '/run/ap-hostapd.log'
def is_hostapd_running():
"""Retourne True si l'instance hostapd (mode pont) est en cours d'exécution."""
try:
if os.path.exists(HOSTAPD_PID_FILE):
pid = int(open(HOSTAPD_PID_FILE).read().strip())
os.kill(pid, 0)
return True
except Exception:
pass
try:
r = subprocess.run(['pgrep', '-f', HOSTAPD_CONF_FILE], capture_output=True, text=True)
return r.returncode == 0 and bool(r.stdout.strip())
except Exception:
return False
def stop_hostapd(iface=None):
"""Arrête proprement hostapd et détache l'interface Wi-Fi du pont sans jamais toucher au pont hôte."""
iface = iface or INTERFACE
try:
if os.path.exists(HOSTAPD_PID_FILE):
try:
pid = int(open(HOSTAPD_PID_FILE).read().strip())
os.kill(pid, signal.SIGTERM)
for _ in range(15):
try:
os.kill(pid, 0)
time.sleep(0.1)
except OSError:
break
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
except Exception:
pass
try: os.remove(HOSTAPD_PID_FILE)
except OSError: pass
subprocess.run(['pkill', '-f', HOSTAPD_CONF_FILE], capture_output=True)
except Exception:
pass
if iface:
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True)
def ensure_nm_manages_wifi(iface=None):
"""Rend le contrôle de l'interface Wi-Fi à NetworkManager (pour le mode AP/NAT) et attend qu'elle soit prête."""
iface = iface or INTERFACE
if not iface:
return
was_unmanaged = (command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface) or '').startswith('10')
stop_hostapd(iface)
if was_unmanaged:
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
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.2)
subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'yes'], capture_output=True)
for _ in range(35):
st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface)
if st and not st.startswith('10') and not st.startswith('20'): # 10=unmanaged, 20=unavailable
break
time.sleep(0.2)
if was_unmanaged:
time.sleep(0.3)
def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=None):
"""Démarre le point d'accès Wi-Fi en mode pont directement via hostapd (bridge=br0) sans que NetworkManager ne touche au pont hôte."""
iface = iface or INTERFACE
bridge_name = bridge_name or 'br0'
hostapd_bin = find_bin('hostapd')
if not hostapd_bin:
raise RuntimeError("Le binaire 'hostapd' est introuvable dans le conteneur. Veuillez reconstruire l'image Docker.")
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 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)
subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'no'], capture_output=True)
for _ in range(25):
st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface)
if not st or st.startswith('10'): # 10 = unmanaged
break
time.sleep(0.2)
# 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(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)
# 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)
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'
channel = str(get_effective_ap_channel(band)).strip()
sec_norm = (sec or 'wpa2').lower()
def _build_conf(enable_ht=True):
lines = [
f"interface={iface}",
f"bridge={bridge_name}",
"driver=nl80211",
f"ssid={ssid}",
"utf8_ssid=1",
f"country_code={country}",
"ieee80211d=1",
f"hw_mode={hw_mode}",
f"channel={channel}",
"auth_algs=1",
"ignore_broadcast_ssid=0",
"wmm_enabled=1",
"ctrl_interface=/run/hostapd",
"ctrl_interface_group=0",
]
if enable_ht:
lines.append("ieee80211n=1")
if hw_mode == 'a':
lines.append("ieee80211ac=1")
if sec_norm == 'wpa1':
lines += [
"wpa=1",
"wpa_key_mgmt=WPA-PSK",
"wpa_pairwise=TKIP CCMP",
f"wpa_passphrase={password}",
]
elif sec_norm == 'wpa3':
lines += [
"wpa=2",
"wpa_key_mgmt=SAE",
"rsn_pairwise=CCMP",
f"sae_password={password}",
f"wpa_passphrase={password}",
"ieee80211w=2",
]
else:
lines += [
"wpa=2",
"wpa_key_mgmt=WPA-PSK",
"rsn_pairwise=CCMP",
f"wpa_passphrase={password}",
]
return '\n'.join(lines) + '\n'
os.makedirs('/run/hostapd', exist_ok=True)
def _try_launch(enable_ht=True):
with open(HOSTAPD_CONF_FILE, 'w', encoding='utf-8') as f:
f.write(_build_conf(enable_ht=enable_ht))
os.chmod(HOSTAPD_CONF_FILE, 0o600)
try: os.remove(HOSTAPD_LOG_FILE)
except OSError: pass
r = subprocess.run(
[hostapd_bin, '-B', '-P', HOSTAPD_PID_FILE, '-f', HOSTAPD_LOG_FILE, HOSTAPD_CONF_FILE],
capture_output=True, text=True, timeout=15
)
if r.returncode != 0:
err = (r.stderr or r.stdout or '').strip()
if os.path.exists(HOSTAPD_LOG_FILE):
try:
log_tail = open(HOSTAPD_LOG_FILE, encoding='utf-8', errors='replace').read().strip()
if log_tail:
last_line = log_tail.splitlines()[-1]
err = last_line if not err else f"{err} | {last_line}"
except OSError:
pass
return False, err or 'hostapd a refusé de démarrer'
ap_ready = False
for _ in range(30):
time.sleep(0.2)
if not is_hostapd_running():
break
iw_out = command('iw', 'dev', iface, 'info') 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-ENABLED' in log_txt and 'type AP' in iw_out and has_master:
ap_ready = True
break
if ap_ready:
# Vérification de stabilité courte (0,4s) pour s'assurer qu'aucun événement NM résiduel n'a désactivé l'AP
time.sleep(0.4)
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 os.path.exists(f'/sys/class/net/{iface}/master') and 'AP-DISABLED' not in log_txt:
return True, ''
return False, 'Interface AP instable après initialisation initiale'
if is_hostapd_running():
iw_out = command('iw', 'dev', iface, 'info') 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)
return True, ''
return False, 'hostapd démarré mais interface non passée en mode AP'
err = ''
if os.path.exists(HOSTAPD_LOG_FILE):
try: err = open(HOSTAPD_LOG_FILE, encoding='utf-8', errors='replace').read().strip()
except OSError: pass
return False, err or 'hostapd s’est arrêté immédiatement'
ok, err = _try_launch(enable_ht=True)
if not ok:
print(f"[ap-bridge] 1er démarrage hostapd incomplet ({err}), relance propre...", flush=True)
stop_hostapd(iface)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
time.sleep(0.5)
ok, err2 = _try_launch(enable_ht=True)
if not ok:
print(f"[ap-bridge] hostapd (802.11n) a échoué ({err2}), nouvelle tentative sans 802.11n...", flush=True)
stop_hostapd(iface)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
time.sleep(0.3)
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)
setup_bridge_dns_redirection(bridge_name, iface)
time.sleep(0.3)
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)
HOST_DBUS_SOCKET = '/run/host-dbus/system_bus_socket'
_host_dbus_missing_warned = False
def sync_host_resolved_bridge_dns(bridge_name='br0', gateway_ip=None):
"""Configure dynamiquement en RAM le DNS + DefaultRoute sur br0 dans le systemd-resolved de l'hôte via D-Bus (sans modifier aucun fichier du Raspberry Pi)."""
global _host_dbus_missing_warned
bridge_name = bridge_name or 'br0'
ifindex_path = f'/sys/class/net/{bridge_name}/ifindex'
if not os.path.exists(ifindex_path):
return False
if not os.path.exists(HOST_DBUS_SOCKET):
if not _host_dbus_missing_warned:
_host_dbus_missing_warned = True
print(f"[ap-bridge] INFO : socket {HOST_DBUS_SOCKET} absent. Pour préserver le DNS hôte (systemd-resolved) en mode Pont, montez '- /run/dbus/system_bus_socket:{HOST_DBUS_SOCKET}' dans docker-compose.yml.", flush=True)
return False
try:
import dbus
except Exception as e:
print(f"[ap-bridge] python3-dbus indisponible pour configurer systemd-resolved : {e}", flush=True)
return False
try:
ifindex = int(open(ifindex_path).read().strip())
gw = (gateway_ip or '').strip()
if not gw:
_, gw, _ = get_iface_ip_info(bridge_name)
dns_candidates = []
if gw:
dns_candidates.append(gw)
for s in get_dns_servers():
if s and s not in dns_candidates:
dns_candidates.append(s)
if not dns_candidates:
dns_candidates = ['1.1.1.1', '9.9.9.9']
addrs = []
valid_ips = []
for ip_s in dns_candidates:
try:
packed = socket.inet_pton(socket.AF_INET, ip_s)
addrs.append(dbus.Struct((dbus.Int32(socket.AF_INET), dbus.ByteArray(packed)), signature='iay'))
valid_ips.append(ip_s)
except OSError:
continue
if not addrs:
return False
bus = dbus.bus.BusConnection(f'unix:path={HOST_DBUS_SOCKET}')
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))
try:
mgr.FlushCaches()
except Exception:
pass
finally:
try: bus.close()
except Exception: pass
print(f"[ap-bridge] DNS systemd-resolved hôte configuré sur {bridge_name} (ifindex={ifindex}) : {', '.join(valid_ips)} (DefaultRoute=yes)", flush=True)
return True
except Exception as e:
if 'LinkBusy' in str(e) or 'managed' in str(e).lower():
print(f"[ap-bridge] {bridge_name} déjà géré par le réseau hôte (DNS préservé).", flush=True)
return True
print(f"[ap-bridge] Avertissement configuration DNS systemd-resolved hôte sur {bridge_name} : {e}", flush=True)
return False
def ensure_host_resolved_bridge_dns(bridge_name=None):
"""Vérifie en mode Pont que br0 dispose bien de serveurs DNS et DefaultRoute=yes dans systemd-resolved hôte."""
if not is_bridge_mode():
return
bridge_name = bridge_name or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0')) or 'br0'
ifindex_path = f'/sys/class/net/{bridge_name}/ifindex'
if not os.path.exists(ifindex_path) or not os.path.exists(HOST_DBUS_SOCKET):
return
try:
import dbus
ifindex = int(open(ifindex_path).read().strip())
bus = dbus.bus.BusConnection(f'unix:path={HOST_DBUS_SOCKET}')
needs_sync = False
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_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'))
if not cur_dns or not cur_def:
needs_sync = True
finally:
try: bus.close()
except Exception: pass
if needs_sync:
sync_host_resolved_bridge_dns(bridge_name)
except Exception:
pass
def revert_host_resolved_bridge_dns(bridge_name='br0'):
"""Réinitialise la configuration DNS dynamique de br0 dans systemd-resolved hôte avant suppression du pont."""
bridge_name = bridge_name or 'br0'
ifindex_path = f'/sys/class/net/{bridge_name}/ifindex'
if not os.path.exists(ifindex_path) or not os.path.exists(HOST_DBUS_SOCKET):
return
try:
import dbus
ifindex = int(open(ifindex_path).read().strip())
bus = dbus.bus.BusConnection(f'unix:path={HOST_DBUS_SOCKET}')
try:
obj = bus.get_object('org.freedesktop.resolve1', '/org/freedesktop/resolve1')
mgr = dbus.Interface(obj, 'org.freedesktop.resolve1.Manager')
mgr.RevertLink(dbus.Int32(ifindex))
finally:
try: bus.close()
except Exception: pass
except Exception:
pass
def setup_bridge(bridge_name='br0', bridge_eth=None):
teardown_ap_nat()
bridge_name = bridge_name or 'br0'
bridge_path = f'/sys/class/net/{bridge_name}'
if not bridge_eth:
bridge_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
if not bridge_eth:
candidates = detect_ethernet_interfaces()
if candidates: bridge_eth = candidates[0]
# Vérifier si l'interface Ethernet est déjà asservie à ce pont
eth_master = None
if bridge_eth and os.path.exists(f'/sys/class/net/{bridge_eth}/master'):
try: eth_master = os.path.basename(os.readlink(f'/sys/class/net/{bridge_eth}/master'))
except OSError: pass
bridge_already_existed = os.path.exists(bridge_path)
# Si le pont n'existe pas encore au niveau noyau, le créer directement via iproute2 (sans profil NetworkManager)
if not bridge_already_existed:
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)
try: open(CREATED_BRIDGE_FILE, 'w').write(f"{bridge_name}:{bridge_eth or ''}")
except OSError: pass
# Asservir l'Ethernet physique s'il n'est pas déjà dans le pont et que le pont n'existait pas déjà avec IP
migrated_gw = None
has_bridge_ip = bool(get_iface_ip_info(bridge_name)[0])
if bridge_eth and os.path.exists(f'/sys/class/net/{bridge_eth}') and eth_master != bridge_name and not has_bridge_ip and not bridge_already_existed:
ip_cidr, gw, mac = get_iface_ip_info(bridge_eth)
migrated_gw = gw
if mac:
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'address', mac], capture_output=True)
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'up'], capture_output=True)
subprocess.run(['ip', 'link', 'set', 'dev', bridge_eth, 'master', bridge_name], capture_output=True)
# Transférer l'adresse IP et la passerelle au pont pour ne JAMAIS perdre le ping et l'accès à l'hôte
if ip_cidr:
subprocess.run(['ip', 'addr', 'flush', 'dev', bridge_eth], capture_output=True)
subprocess.run(['ip', 'addr', 'add', ip_cidr, 'dev', bridge_name], capture_output=True)
if gw:
subprocess.run(['ip', 'route', 'replace', 'default', 'via', gw, 'dev', bridge_name], capture_output=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:
# Si le pont hôte existe déjà : verrouiller sa MAC actuelle (sans la modifier) pour éviter que l'ajout de wlan0 ne change la MAC de br0 et ne coupe le DNS hôte
try:
cur_mac = open(f'{bridge_path}/address').read().strip()
assign_type = open(f'{bridge_path}/addr_assign_type').read().strip()
if cur_mac and assign_type != '3':
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'address', cur_mac], capture_output=True)
except OSError:
pass
if not is_iface_up(bridge_name):
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'up'], capture_output=True)
try:
subprocess.run(['sysctl', '-w', 'net.ipv4.ip_forward=1'], capture_output=True)
except Exception: pass
clean_stale_router_leases()
for ipt in _ap_iptables_bins():
if subprocess.run([ipt, '-w', '5', '-C', 'FORWARD', '-i', bridge_name, '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True).returncode != 0:
subprocess.run([ipt, '-w', '5', '-I', 'FORWARD', '1', '-i', bridge_name, '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True)
setup_bridge_dns_redirection(bridge_name, INTERFACE)
sync_host_resolved_bridge_dns(bridge_name, migrated_gw)
def teardown_bridge(bridge_name='br0', bridge_eth=None):
stop_hostapd(INTERFACE)
teardown_bridge_dns_redirection(bridge_name, INTERFACE)
bridge_name = bridge_name or 'br0'
bridge_path = f'/sys/class/net/{bridge_name}'
was_created_by_us = False
saved_eth = bridge_eth
if os.path.exists(CREATED_BRIDGE_FILE):
try:
content = open(CREATED_BRIDGE_FILE).read().strip().split(':')
if content and content[0] == bridge_name:
was_created_by_us = True
if len(content) > 1 and content[1]: saved_eth = content[1]
except Exception: pass
conns = command('nmcli', '-t', '-g', 'NAME', 'connection', 'show').splitlines()
for c in conns:
if c.startswith(('ap-bridge-eth-', f"ap-bridge-{bridge_name}")):
try: subprocess.run(['nmcli', '--wait', '2', 'connection', 'down', c], capture_output=True, timeout=3)
except Exception: pass
try: subprocess.run(['nmcli', '--wait', '2', 'connection', 'delete', c], capture_output=True, timeout=3)
except Exception: pass
# Détecter si une interface Ethernet physique de l'hôte est asservie à ce pont
slaved_eth = None
eth_candidates = [saved_eth, bridge_eth] + detect_ethernet_interfaces()
for cand in eth_candidates:
if cand and os.path.exists(f'/sys/class/net/{cand}/master'):
try:
master = os.path.basename(os.readlink(f'/sys/class/net/{cand}/master'))
if master == bridge_name:
slaved_eth = cand
break
except OSError: pass
# Ne restaurer et ne détruire le pont QUE si nous l'avons créé nous-mêmes (préserver impérativement la configuration hôte)
if was_created_by_us and os.path.exists(bridge_path):
revert_host_resolved_bridge_dns(bridge_name)
if slaved_eth:
ip_cidr, gw, _ = get_iface_ip_info(bridge_name)
subprocess.run(['ip', 'link', 'set', 'dev', slaved_eth, 'nomaster'], capture_output=True)
if ip_cidr:
subprocess.run(['ip', 'addr', 'flush', 'dev', bridge_name], capture_output=True)
subprocess.run(['ip', 'addr', 'add', ip_cidr, 'dev', slaved_eth], capture_output=True)
if gw:
subprocess.run(['ip', 'route', 'replace', 'default', 'via', gw, 'dev', slaved_eth], capture_output=True)
print(f"[ap-bridge] IP {ip_cidr} et passerelle {gw} restaurées sur {slaved_eth}.", flush=True)
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'down'], capture_output=True)
subprocess.run(['ip', 'link', 'delete', 'name', bridge_name, 'type', 'bridge'], capture_output=True)
print(f"[ap-bridge] Pont créé {bridge_name} nettoyé et supprimé.", flush=True)
try:
if os.path.exists(CREATED_BRIDGE_FILE): os.remove(CREATED_BRIDGE_FILE)
except OSError: pass
GITEA_API_COMMITS_URL = os.environ.get(
'AP_UPDATE_CHECK_URL',
'https://gitea.yoann-nas.fr/api/v1/repos/yoannmultigaming/apmanageur/commits?limit=1'
)
GITEA_REPO_URL = os.environ.get(
'AP_UPDATE_REPO_URL',
'https://gitea.yoann-nas.fr/yoannmultigaming/apmanageur'
)
_update_lock = threading.Lock()
_update_cache = {
'time': 0,
'checking': False,
'data': {
'available': False,
'enabled': True,
'interval': 7200,
'current_commit': '',
'current_commit_full': '',
'latest_commit': '',
'latest_commit_full': '',
'commit_msg': '',
'author': '',
'date': '',
'html_url': GITEA_REPO_URL,
'docker_command': 'docker compose pull && docker compose up -d',
'last_checked': '',
'error': None
}
}
def get_current_commit():
"""Récupère le SHA du commit actuel (variable AP_GIT_COMMIT, git rev-parse ou version.json)."""
env_c = os.environ.get('AP_GIT_COMMIT', '').strip()
if env_c:
return env_c
# 1. Priorité au dépôt Git réel si disponible
try:
c = command('git', 'rev-parse', 'HEAD')
if c and len(c.strip()) >= 7:
git_sha = c.strip()
# Mettre à jour version.json s'il existe et est désynchronisé
for v_path in (
os.path.join(BASE_DIR, 'version.json'),
os.path.join(os.getcwd(), 'version.json'),
'version.json'
):
if os.path.isfile(v_path):
try:
with open(v_path, 'r', encoding='utf-8') as f:
vdata = json.load(f)
need_save = False
if vdata.get('commit') != git_sha:
vdata['commit'] = git_sha
need_save = True
if vdata.get('version') != APP_VERSION:
vdata['version'] = APP_VERSION
need_save = True
if need_save:
with open(v_path, 'w', encoding='utf-8') as f:
json.dump(vdata, f, indent=2, ensure_ascii=False)
except Exception:
pass
return git_sha
except Exception:
pass
# 2. Sinon, lecture de version.json (conteneur Docker où .git n'est pas présent)
for path in (
'/data/version.json',
os.path.join(BASE_DIR, 'version.json'),
'/app/version.json',
'/var/www/html/version.json',
os.path.join(os.getcwd(), 'version.json'),
'version.json'
):
if os.path.isfile(path):
try:
with open(path, 'r', encoding='utf-8') as f:
vdata = json.load(f)
c = vdata.get('commit', '').strip()
if c:
return c
except Exception:
pass
return ''
def sync_version_files():
"""Synchronise la version du logiciel (APP_VERSION) vers tous les fichiers :
- version.json (/app, /var/www/html, /data, BASE_DIR, etc.)
- setup.html (badges de version)
- index.html (variable JS APP_VERSION, badges et balises de version)
"""
try:
cur_version = str(APP_VERSION).strip()
cur_commit = get_current_commit()
now_iso = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
# 1. Mise à jour de tous les emplacements de version.json
v_paths = [
os.path.join(BASE_DIR, 'version.json'),
os.path.join(os.getcwd(), 'version.json'),
'version.json',
'/app/version.json',
'/var/www/html/version.json',
'/data/version.json'
]
done_vpaths = set()
for vp in v_paths:
try:
norm_p = os.path.abspath(vp)
if norm_p in done_vpaths:
continue
done_vpaths.add(norm_p)
folder = os.path.dirname(norm_p)
if not os.path.isfile(norm_p) and not os.path.isdir(folder):
continue
vdata = {}
if os.path.isfile(norm_p):
try:
with open(norm_p, 'r', encoding='utf-8') as f:
vdata = json.load(f)
except Exception:
vdata = {}
if not isinstance(vdata, dict):
vdata = {}
vdata['version'] = cur_version
if cur_commit and not vdata.get('commit'):
vdata['commit'] = cur_commit
if not vdata.get('build_date'):
vdata['build_date'] = now_iso
with open(norm_p, 'w', encoding='utf-8') as f:
json.dump(vdata, f, indent=2, ensure_ascii=False)
except Exception:
pass
# 2. Synchronisation de setup.html
setup_paths = [
os.path.join(BASE_DIR, 'setup.html'),
os.path.join(os.getcwd(), 'setup.html'),
'setup.html',
'/app/setup.html',
'/var/www/html/setup.html'
]
done_spaths = set()
for sp in setup_paths:
try:
norm_sp = os.path.abspath(sp)
if norm_sp in done_spaths or not os.path.isfile(norm_sp):
continue
done_spaths.add(norm_sp)
with open(norm_sp, 'r', encoding='utf-8') as f:
content = f.read()
new_content = re.sub(
r'(]*class="[^"]*app-version[^"]*"[^>]*>)[^<]*()',
rf'\g<1>{cur_version}\g<2>',
content
)
if new_content == content:
new_content = re.sub(
r'[^<]*',
f'{cur_version}',
content
)
if new_content != content:
with open(norm_sp, 'w', encoding='utf-8') as f:
f.write(new_content)
except Exception:
pass
# 3. Synchronisation de index.html
index_paths = [
os.path.join(BASE_DIR, 'index.html'),
os.path.join(os.getcwd(), 'index.html'),
'index.html',
'/app/index.html',
'/var/www/html/index.html'
]
done_ipaths = set()
for ip in index_paths:
try:
norm_ip = os.path.abspath(ip)
if norm_ip in done_ipaths or not os.path.isfile(norm_ip):
continue
done_ipaths.add(norm_ip)
with open(norm_ip, 'r', encoding='utf-8') as f:
content = f.read()
# Remplacer la constante JS
new_content = re.sub(
r'(const|let|var)\s+APP_VERSION\s*=\s*["\'][^"\']+["\'];',
f'let APP_VERSION = "{cur_version}";',
content
)
# Remplacer les badges HTML portant la classe app-version
new_content = re.sub(
r'(]*class="[^"]*app-version[^"]*"[^>]*>)[^<]*()',
rf'\g<1>{cur_version}\g<2>',
new_content
)
# Remplacer advUpdateVersionTag
new_content = re.sub(
r'(id="advUpdateVersionTag"[^>]*>)[^<]*()',
rf'\g<1>AP Manageur {cur_version}\g<2>',
new_content
)
if new_content != content:
with open(norm_ip, 'w', encoding='utf-8') as f:
f.write(new_content)
except Exception:
pass
except Exception as e_sync:
print(f"[ap-version] Erreur synchronisation version : {e_sync}", flush=True)
# Synchronisation initiale à l'import
sync_version_files()
def check_gitea_update(force_refresh=False):
"""Vérifie si une nouvelle version est disponible sur le dépôt Gitea (cache selon intervalle, non bloquant)."""
enabled = get_pref('update_checker_enabled', '1') == '1'
try:
interval = int(get_pref('update_checker_interval', '7200'))
if interval < 60:
interval = 7200
except Exception:
interval = 7200
now = time.time()
with _update_lock:
if not enabled and not force_refresh:
cur = get_current_commit()
return {
'available': False,
'enabled': False,
'interval': interval,
'current_commit': cur[:7] if cur else '',
'current_commit_full': cur,
'latest_commit': '',
'latest_commit_full': '',
'commit_msg': '',
'author': '',
'date': '',
'html_url': GITEA_REPO_URL,
'docker_command': 'docker compose pull && docker compose up -d',
'last_checked': _update_cache.get('data', {}).get('last_checked', ''),
'error': None
}
cache_ttl = min(interval, 1800)
if not force_refresh and _update_cache['time'] > 0 and (now - _update_cache['time'] < cache_ttl):
res = dict(_update_cache['data'])
res['enabled'] = enabled
res['interval'] = interval
return res
if _update_cache['checking'] and not force_refresh:
res = dict(_update_cache['data'])
res['enabled'] = enabled
res['interval'] = interval
return res
_update_cache['checking'] = True
def _worker():
current_sha = get_current_commit()
latest_sha = ''
msg = ''
author = ''
date_str = ''
html_url = GITEA_REPO_URL
err_msg = None
available = False
try:
req = urllib.request.Request(
GITEA_API_COMMITS_URL,
headers={'User-Agent': 'AP-Manageur-Update-Checker/1.0', 'Accept': 'application/json'}
)
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
with urllib.request.urlopen(req, timeout=6.0, context=ctx) as resp:
if resp.status == 200:
data = json.loads(resp.read().decode('utf-8'))
if isinstance(data, list) and len(data) > 0:
first = data[0]
latest_sha = (first.get('sha') or '').strip()
c_info = first.get('commit') or {}
msg = (c_info.get('message') or '').strip()
author = (c_info.get('author') or {}).get('name', '')
date_str = (c_info.get('author') or {}).get('date', '')
html_url = first.get('html_url') or GITEA_REPO_URL
if current_sha and latest_sha:
c_low = current_sha.lower().strip()
l_low = latest_sha.lower().strip()
if not l_low.startswith(c_low) and not c_low.startswith(l_low):
available = True
else:
available = False
else:
available = False
except Exception as e:
err_msg = str(e)
with _update_lock:
_update_cache['time'] = time.time()
_update_cache['checking'] = False
_update_cache['data'] = {
'available': available,
'enabled': enabled,
'interval': interval,
'current_commit': current_sha[:7] if current_sha else '',
'current_commit_full': current_sha,
'latest_commit': latest_sha[:7] if latest_sha else '',
'latest_commit_full': latest_sha,
'commit_msg': msg,
'author': author,
'date': date_str,
'html_url': html_url,
'docker_command': 'docker compose pull && docker compose up -d',
'last_checked': time.strftime('%Y-%m-%d %H:%M:%S'),
'error': err_msg
}
if available and latest_sha:
try:
last_notif = get_pref('last_notified_update_commit')
if last_notif != latest_sha:
set_pref('last_notified_update_commit', latest_sha)
dispatch_notification(
'update_available',
"🚀 Nouvelle mise à jour disponible",
f"Une nouvelle version de AP Manageur est prête sur le dépôt ({latest_sha[:7]}) ! Message : {msg or 'Nouvelle version'}.",
details={
"Version actuelle": current_sha[:7] if current_sha else 'Inconnue',
"Nouvelle version": latest_sha[:7],
"Auteur": author or 'yoannmultigaming',
"Message de commit": msg or 'Nouvelle version',
"Date": date_str or time.strftime('%d/%m/%Y %H:%M:%S'),
"Commande": "docker compose pull && docker compose up -d"
},
priority=7,
level="success",
vars_dict={
"current_commit": current_sha[:7] if current_sha else 'Inconnue',
"latest_commit": latest_sha[:7],
"latest_commit_full": latest_sha,
"author": author or '',
"message": msg or '',
"cmd": "docker compose pull && docker compose up -d",
"date": date_str or time.strftime('%d/%m/%Y %H:%M:%S')
}
)
except Exception as e_notif:
print(f"[Notifications] Erreur envoi notif mise à jour : {e_notif}", flush=True)
elif not available:
try:
if get_pref('last_notified_update_commit'):
set_pref('last_notified_update_commit', '')
except Exception:
pass
if force_refresh:
_worker()
with _update_lock:
res = dict(_update_cache['data'])
res['enabled'] = enabled
res['interval'] = interval
return res
else:
threading.Thread(target=_worker, daemon=True).start()
with _update_lock:
res = dict(_update_cache['data'])
res['enabled'] = enabled
res['interval'] = interval
return res
_status_cache = {'time': 0, 'data': None}
_status_cache_lock = threading.Lock()
def invalidate_status_cache():
with _status_cache_lock:
_status_cache['time'] = 0
_status_cache['data'] = None
def status(force_refresh=False):
now = time.time()
with _status_cache_lock:
if not force_refresh and _status_cache['data'] is not None and (now - _status_cache['time'] < 2.0):
cached = dict(_status_cache['data'])
if cached.get('active'):
cached['uptime_seconds'] = ap_uptime()
return cached
name = connection_name()
db_ssid = get_pref('ap_ssid', '') or ''
db_pass = get_pref('ap_password', '') or ''
db_sec = (get_pref('ap_security', '') or '').lower()
db_auto = get_pref('ap_autoconnect', None)
nm_ssid = command('nmcli','-t','-g','802-11-wireless.ssid','connection','show',name) if name else ''
nm_pass = command('nmcli','--show-secrets','-t','-g','802-11-wireless-security.psk','connection','show',name) if name else ''
key = command('nmcli','-t','-g','802-11-wireless-security.key-mgmt','connection','show',name).lower() if name else ''
proto = command('nmcli','-t','-g','802-11-wireless-security.proto','connection','show',name).lower() if name else ''
ssid = nm_ssid or db_ssid
password = nm_pass or db_pass
if key:
sec = 'wpa3' if key == 'sae' else 'wpa1' if proto == 'wpa' else 'wpa2'
else:
sec = db_sec if db_sec in ('wpa1', 'wpa2', 'wpa3') else 'wpa2'
mode = current_mode()
state = command('nmcli','-t','-g','GENERAL.STATE','device','show',INTERFACE)
# CORRECTION : "30 (disconnected)" contient "connected" ; seul le code 100 signifie connecté.
if mode == 'bridge':
active = is_hostapd_running() or (is_iface_up(INTERFACE) and os.path.exists(f'/sys/class/net/{INTERFACE}/master'))
else:
active = state.startswith('100')
nm_auto = command('nmcli','-t','-g','connection.autoconnect','connection','show',name).lower() if name else ''
if nm_auto in ('yes', 'no') and mode != 'bridge':
auto = (nm_auto == 'yes')
elif db_auto is not None:
auto = str(db_auto).lower() in ('1', 'true', 'yes', 'oui')
else:
auto = False
if active and uptime_start() is None:
mark_ap_started()
master = (command('nmcli','-t','-g','connection.master','connection','show',name) or command('nmcli','-t','-g','connection.controller','connection','show',name)) if name else ''
if not master and os.path.exists(f'/sys/class/net/{INTERFACE}/master'):
try: master = os.path.basename(os.readlink(f'/sys/class/net/{INTERFACE}/master'))
except OSError: pass
b_name = master or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
eff_chan = get_effective_ap_channel(AP_BAND)
res = {'version':APP_VERSION,'ssid':ssid or 'SSID inconnu','password':password,'security':sec,'autoconnect':auto,'mode':mode,'bridge_name':b_name,'bridge_eth':b_eth,'ethernet_interfaces':detect_ethernet_interfaces(),'interface':INTERFACE,'connection':name,'active':active,'configured':bool(name or db_ssid),'uptime_seconds':ap_uptime() if active else 0,'max_clients':get_max_clients(),'dns':get_dns_servers(),'is_starting':not app_startup_done,'boot_time':SERVER_BOOT_TIME,'channel':eff_chan,'channel_auto':is_auto_channel(),'band':AP_BAND,'update':check_gitea_update(force_refresh=False)}
with _status_cache_lock:
_status_cache['time'] = now
_status_cache['data'] = res
return res
def blocked_set():
c = db(); rows = c.execute('SELECT mac FROM blocked_clients').fetchall(); c.close(); return {r[0] for r in rows}
station_live_ips = {}
def arp_listener():
"""Écoute passivement les trames réseau (IPv4, ARP, DHCP, mDNS, LLMNR, NetBIOS) pour capturer en temps réel l'IP et le vrai nom d'hôte des clients."""
try:
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))
except Exception as e:
print(f"[ap-arp] Écouteur réseau passif indisponible : {e}", flush=True)
return
while True:
try:
raw = s.recv(2048)
if len(raw) < 14: continue
eth_type = raw[12:14]
is_bridge = is_bridge_mode()
# 1. Trame IPv4 (0x0800)
if eth_type == b'\x08\x00' and len(raw) >= 34:
smac = ':'.join(f'{b:02x}' for b in raw[6:12]).upper()
sip = socket.inet_ntoa(raw[26:30])
valid_sip = None
if sip and not sip.startswith(('0.', '127.', '169.254.', '255.')):
if not (is_bridge and sip.startswith('10.42.')) and not (not is_bridge and not sip.startswith('10.42.')):
station_live_ips[smac] = sip
valid_sip = sip
# Inspection des paquets UDP (protocole 17) pour extraire le vrai nom d'hôte
if raw[23] == 17:
try:
ihl = (raw[14] & 0x0F) * 4
if len(raw) >= 14 + ihl + 8:
udp_hdr = raw[14 + ihl : 14 + ihl + 8]
sport, dport = struct.unpack('!HH', udp_hdr[:4])
udp_payload = raw[14 + ihl + 8 :]
# A. DHCP (ports 67 / 68) : Option 12 (Host Name) et Option 81 (Client FQDN)
if sport in (67, 68) or dport in (67, 68):
dhcp_host = extract_dhcp_hostname_from_udp(udp_payload)
if dhcp_host:
record_live_device_name(smac, dhcp_host, valid_sip)
# B. mDNS (5353) et LLMNR (5355) : diffusion du nom d'hôte .local
elif dport in (5353, 5355) or sport in (5353, 5355):
mdns_host = extract_dns_name_from_packet(udp_payload)
if mdns_host and not mdns_host.startswith('_') and not mdns_host.endswith('.arpa'):
record_live_device_name(smac, mdns_host, valid_sip)
# C. NetBIOS (port 137)
elif dport == 137 or sport == 137:
nb_host = parse_netbios_response(udp_payload)
if nb_host:
record_live_device_name(smac, nb_host, valid_sip)
except Exception:
pass
# 2. Trame ARP (0x0806)
elif eth_type == b'\x08\x06' and len(raw) >= 42:
smac = ':'.join(f'{b:02x}' for b in raw[22:28]).upper()
sip = socket.inet_ntoa(raw[28:32])
if sip and not sip.startswith(('0.', '127.', '169.254.', '255.')):
if is_bridge and sip.startswith('10.42.'):
continue
if not is_bridge and not sip.startswith('10.42.'):
continue
station_live_ips[smac] = sip
except Exception:
time.sleep(0.2)
def lease_ip(mac):
mac = (mac or '').upper()
if is_bridge_mode(): return ''
for l_mac, l_ip, _ in reversed(lease_entries()):
if l_mac == mac and re.fullmatch(r'\d{1,3}(?:\.\d{1,3}){3}', l_ip): return l_ip
return ''
def clients():
is_bridge = is_bridge_mode()
if is_bridge:
for k in list(station_live_ips.keys()):
if station_live_ips[k].startswith('10.42.'):
del station_live_ips[k]
vpn_routes = {}
vpn_profiles = {}
custom_types = {}
try:
c_vpn = db()
for row in c_vpn.execute('SELECT mac, profile_id, kill_switch FROM client_vpn_routes').fetchall():
vpn_routes[row[0].upper()] = {'profile_id': row[1], 'kill_switch': row[2]}
for row in c_vpn.execute('SELECT id, name, type, status, iface FROM vpn_profiles').fetchall():
vpn_profiles[row[0]] = {'name': row[1], 'type': row[2], 'status': row[3], 'iface': row[4]}
cn_cols = {r[1] for r in c_vpn.execute('PRAGMA table_info(client_names)').fetchall()}
if 'device_type' in cn_cols:
for row in c_vpn.execute('SELECT mac, COALESCE(device_type, "") FROM client_names').fetchall():
if row[0] and row[1]:
custom_types[row[0].upper()] = row[1]
c_vpn.close()
except Exception: pass
neigh = command('ip','neigh','show'); ipmac = {}
for line in neigh.splitlines():
m = re.search(r'^(\S+).*?lladdr ([0-9a-f:]{17})', line, re.I)
if m:
nip = m.group(1)
nmac = m.group(2).upper()
if is_bridge and nip.startswith('10.42.'):
continue
if not is_bridge and not nip.startswith('10.42.'):
continue
if 'FAILED' in line:
continue
ipmac[nmac] = nip
output = []; dump = command('iw','dev',INTERFACE,'station','dump'); blocked_macs = blocked_set()
# Sur Raspberry Pi (brcmfmac), hostapd_cli all_sta peut fournir signal= même quand iw station dump omet signal:
hostapd_signals = {}
if is_hostapd_running():
h_out = command('hostapd_cli', '-p', '/run/hostapd', '-i', INTERFACE, 'all_sta')
if h_out:
cur_mac = None
for hline in h_out.splitlines():
hline = hline.strip()
if re.fullmatch(r'[0-9a-fA-F:]{17}', hline):
cur_mac = hline.upper()
elif cur_mac and hline.startswith('signal='):
try:
sv = int(hline.split('=', 1)[1].strip())
if -120 <= sv < 0:
hostapd_signals[cur_mac] = sv
except ValueError:
pass
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, 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], 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, False, link_rate
except ValueError:
pass
# 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)
# CORRECTION : « iw station dump » liste aussi les appareils qui n'ont jamais fini l'authentification
# (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, 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
raw_tx = int(tx_m.group(1)) if tx_m else 0
now_ts = time.time()
rx_rate = 0.0
tx_rate = 0.0
delta_rx = 0
delta_tx = 0
with traffic_lock:
prev = station_traffic.get(mac)
if prev:
dt = now_ts - prev['last_time']
if dt >= 0.8:
delta_rx = raw_rx - prev['last_rx'] if raw_rx >= prev['last_rx'] else raw_rx
delta_tx = raw_tx - prev['last_tx'] if raw_tx >= prev['last_tx'] else raw_tx
rx_rate = delta_rx / dt
tx_rate = delta_tx / dt
station_traffic[mac] = {
'last_rx': raw_rx,
'last_tx': raw_tx,
'last_time': now_ts,
'rx_rate': rx_rate,
'tx_rate': tx_rate
}
else:
rx_rate = prev['rx_rate']
tx_rate = prev['tx_rate']
else:
delta_rx = raw_rx
delta_tx = raw_tx
station_traffic[mac] = {
'last_rx': raw_rx,
'last_tx': raw_tx,
'last_time': now_ts,
'rx_rate': 0.0,
'tx_rate': 0.0
}
if delta_rx > 0 or delta_tx > 0:
try:
c = db()
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
today_str = time.strftime('%Y-%m-%d')
c.execute('''
INSERT INTO client_traffic(mac, rx_bytes, tx_bytes, last_updated)
VALUES(?, ?, ?, ?)
ON CONFLICT(mac) DO UPDATE SET
rx_bytes = client_traffic.rx_bytes + excluded.rx_bytes,
tx_bytes = client_traffic.tx_bytes + excluded.tx_bytes,
last_updated = excluded.last_updated
''', (mac, delta_rx, delta_tx, now_str))
c.execute('''
INSERT INTO client_traffic_daily(mac, traffic_date, rx_bytes, tx_bytes)
VALUES(?, ?, ?, ?)
ON CONFLICT(mac, traffic_date) DO UPDATE SET
rx_bytes = client_traffic_daily.rx_bytes + excluded.rx_bytes,
tx_bytes = client_traffic_daily.tx_bytes + excluded.tx_bytes
''', (mac, today_str, delta_rx, delta_tx))
c.commit()
c.close()
except Exception as e:
print(f"[ap-error] Erreur sauvegarde client_traffic: {e}", flush=True)
# 1. IP capturée en direct par l'écouteur réseau ou par la table des voisins
ip = station_live_ips.get(mac, '') or ipmac.get(mac, '')
if not ip and not is_bridge:
ip = lease_ip(mac)
# 2. Historique base de données (si non obsolète) et nom personnalisé
custom_name = None
try:
c = db()
cn_cols = {row[1] for row in c.execute('PRAGMA table_info(client_names)').fetchall()}
has_cust = 'is_custom' in cn_cols
q = 'SELECT last_ip, name, COALESCE(is_custom, 0) FROM client_names WHERE UPPER(mac)=?' if has_cust else 'SELECT last_ip, name, 0 FROM client_names WHERE UPPER(mac)=?'
row = c.execute(q, (mac,)).fetchone()
c.close()
if row:
if row[2] and row[1]: # is_custom == 1 : nom personnalisé défini par l'utilisateur
custom_name = row[1]
if not ip and row[0] and row[0] != 'Non attribuée':
saved_ip = row[0]
if is_bridge and not saved_ip.startswith('10.42.'):
ip = saved_ip
elif not is_bridge and saved_ip.startswith('10.42.'):
ip = saved_ip
except sqlite3.Error: pass
if not ip or (is_bridge and ip.startswith('10.42.')):
ip = 'Non attribuée'
blocked = mac in blocked_macs
if custom_name:
name = custom_name
station_live_names[mac] = custom_name
_device_name_cache[mac] = (custom_name, time.time() + 86400)
elif mac in station_live_names:
name = station_live_names[mac]
else:
name = device_name(ip if ip != 'Non attribuée' else '', mac)
if not custom_name and (name.startswith('Client ') or name == 'Nom non communiqué') and ip != 'Non attribuée':
res_n = resolve_client_hostname_now(ip, mac)
if res_n:
name = res_n
now_ts = time.strftime('%Y-%m-%d %H:%M:%S')
try:
c = db()
c.execute('''
INSERT INTO client_names(mac, name, last_ip, last_seen, is_custom)
VALUES(?, ?, ?, ?, 0)
ON CONFLICT(mac) DO UPDATE SET
name = CASE
WHEN client_names.is_custom = 1 THEN client_names.name
WHEN excluded.name NOT LIKE 'Client %' AND excluded.name != 'Nom non communiqué' AND excluded.name != '' THEN excluded.name
WHEN client_names.name IS NULL OR client_names.name = '' OR client_names.name = 'Nom non communiqué' THEN excluded.name
ELSE client_names.name
END,
last_ip = CASE
WHEN excluded.last_ip NOT IN ('Non attribuée', '', '—') THEN excluded.last_ip
ELSE client_names.last_ip
END,
last_seen = excluded.last_seen
''', (mac.upper(), name, ip, now_ts))
c.commit()
c.close()
except sqlite3.Error: pass
vroute = vpn_routes.get(mac)
vpid = vroute['profile_id'] if vroute else 0
vprof = vpn_profiles.get(vpid) if vpid > 0 else None
v_is_up = bool(vprof and vprof['status'] == 'connected' and is_iface_up(vprof['iface']))
v_pub_ip = vpn_public_ip_cache.get(vprof['iface'], {}).get('ip', '') if (vprof and v_is_up) else ''
v_pub_geo = get_ip_geo(v_pub_ip) if v_pub_ip else None
output.append({
'name': name,
'ip': ip,
'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),
'upload_speed': round(rx_rate),
'download_speed_str': format_speed(tx_rate),
'upload_speed_str': format_speed(rx_rate),
'raw_rx': raw_rx,
'raw_tx': raw_tx,
'vpn_profile_id': vpid,
'vpn_profile_name': vprof['name'] if vprof else '',
'vpn_profile_type': vprof['type'] if vprof else '',
'vpn_profile_status': vprof['status'] if vprof else '',
'vpn_routed': v_is_up,
'lan_isolated': v_is_up,
'vpn_public_ip': v_pub_ip,
'vpn_public_ip_geo': v_pub_geo,
'kill_switch': vroute['kill_switch'] if vroute else 0,
'limits': get_client_limits_dict(mac)
})
return output
def known_device(mac):
name, ip = '', 'Non attribuée'
is_bridge = is_bridge_mode()
try:
c = db(); row = c.execute('SELECT name,last_ip FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close()
if row:
name = row[0] or ''
saved_ip = row[1] or ''
if is_bridge and saved_ip.startswith('10.42.'):
saved_ip = ''
elif not is_bridge and not saved_ip.startswith('10.42.'):
saved_ip = ''
ip = saved_ip or ip
except sqlite3.Error: pass
return name or device_name(ip, mac), ip
def set_blocked(mac, blocked):
mac = mac.upper()
if not re.fullmatch(r'[0-9A-F]{2}(:[0-9A-F]{2}){5}', mac): raise ValueError('Adresse MAC invalide')
name, ip = known_device(mac)
c = db()
if blocked: c.execute('INSERT OR IGNORE INTO blocked_clients VALUES(?,?)',(mac,time.strftime('%Y-%m-%d %H:%M:%S'))); command('iw','dev',INTERFACE,'station','del',mac)
else: c.execute('DELETE FROM blocked_clients WHERE mac=?',(mac,))
c.commit(); c.close(); log('blocage' if blocked else 'déblocage', name, ip, mac)
dispatch_notification('device_blocked', "🛑 Équipement Wi-Fi bloqué" if blocked else "✅ Équipement Wi-Fi débloqué", f"L'appareil « {name} » a été {'bloqué et éjecté du' if blocked else 'débloqué sur le'} réseau Wi-Fi.", details={"Nom": name, "IP": ip, "MAC": mac, "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=5, level="warning" if blocked else "success", vars_dict={"name": name, "ip": ip, "mac": mac, "action": "bloqué et éjecté du" if blocked else "débloqué sur le"})
def blocked_list():
c = db(); rows = c.execute('SELECT b.mac,b.blocked_at,n.name FROM blocked_clients b LEFT JOIN client_names n ON n.mac=b.mac ORDER BY b.blocked_at DESC').fetchall(); c.close()
return [{'mac':r[0],'blocked_at':r[1],'name':r[2] or 'Client ' + r[0].replace(':', '')[-4:]} for r in rows]
quota_alerted_macs = set()
last_sync_limits_time = 0
limits_lock = threading.RLock()
def get_client_traffic_usage(mac, period='total'):
mac = (mac or '').upper()
c = db()
try:
if period == 'daily':
today_str = time.strftime('%Y-%m-%d')
row = c.execute("SELECT rx_bytes + tx_bytes FROM client_traffic_daily WHERE mac=? AND traffic_date=?", (mac, today_str)).fetchone()
return int(row[0]) if row and row[0] is not None else 0
elif period == 'monthly':
month_prefix = time.strftime('%Y-%m-') + '%'
row = c.execute("SELECT SUM(rx_bytes + tx_bytes) FROM client_traffic_daily WHERE mac=? AND traffic_date LIKE ?", (mac, month_prefix)).fetchone()
return int(row[0]) if row and row[0] is not None else 0
else:
row = c.execute("SELECT rx_bytes + tx_bytes FROM client_traffic WHERE mac=?", (mac,)).fetchone()
return int(row[0]) if row and row[0] is not None else 0
except Exception:
return 0
finally:
c.close()
def get_client_limits_dict(target_mac=None):
c = db()
try:
has_table = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='client_limits'").fetchone())
if not has_table: return None if target_mac else {}
query = "SELECT mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, updated_at FROM client_limits"
params = ()
if target_mac:
query += " WHERE mac=?"
params = (target_mac.upper(),)
rows = c.execute(query, params).fetchall()
res = {}
for r in rows:
m = (r[0] or '').upper()
q_en = bool(r[1])
q_bytes = int(r[2] or 0)
q_period = r[3] or 'total'
bw_en = bool(r[4])
r_down = int(r[5] or 0)
r_up = int(r[6] or 0)
usage = get_client_traffic_usage(m, q_period)
exceeded = q_en and q_bytes > 0 and usage >= q_bytes
pct = min(100.0, round((usage / q_bytes) * 100.0, 1)) if (q_bytes > 0) else 0.0
remaining = max(0, q_bytes - usage) if q_bytes > 0 else 0
res[m] = {
'mac': m,
'quota_enabled': q_en,
'quota_bytes': q_bytes,
'quota_bytes_str': format_bytes(q_bytes) if q_bytes > 0 else 'Illimité',
'quota_period': q_period,
'quota_period_label': 'Total cumulé' if q_period == 'total' else ('Par mois' if q_period == 'monthly' else 'Par jour'),
'bandwidth_enabled': bw_en,
'rate_down_kbps': r_down,
'rate_up_kbps': r_up,
'rate_down_str': f"{r_down // 1000} Mbps" if r_down >= 1000 else (f"{r_down} Kbps" if r_down > 0 else 'Illimité'),
'rate_up_str': f"{r_up // 1000} Mbps" if r_up >= 1000 else (f"{r_up} Kbps" if r_up > 0 else 'Illimité'),
'usage_bytes': usage,
'usage_bytes_str': format_bytes(usage),
'usage_percent': pct,
'remaining_bytes': remaining,
'remaining_bytes_str': format_bytes(remaining),
'quota_exceeded': exceeded,
'quota_action': r[7] or 'block',
'updated_at': r[8] or ''
}
return res.get(target_mac.upper()) if target_mac else res
except Exception as e:
print(f"[ap-limits] Erreur get_client_limits_dict: {e}", flush=True)
return None if target_mac else {}
finally:
c.close()
def save_client_limits(mac, data):
mac = (mac or '').strip().upper()
if not re.fullmatch(r'[0-9A-F]{2}(:[0-9A-F]{2}){5}', mac):
raise ValueError('Adresse MAC invalide')
quota_enabled = 1 if data.get('quota_enabled') else 0
try: quota_bytes = max(0, int(data.get('quota_bytes', 0)))
except (ValueError, TypeError): quota_bytes = 0
quota_period = str(data.get('quota_period', 'total')).strip().lower()
if quota_period not in ('total', 'daily', 'monthly'): quota_period = 'total'
bandwidth_enabled = 1 if data.get('bandwidth_enabled') else 0
try: rate_down_kbps = max(0, int(data.get('rate_down_kbps', 0)))
except (ValueError, TypeError): rate_down_kbps = 0
try: rate_up_kbps = max(0, int(data.get('rate_up_kbps', 0)))
except (ValueError, TypeError): rate_up_kbps = 0
quota_action = str(data.get('quota_action', 'block')).strip().lower()
reset_usage = bool(data.get('reset_usage', False))
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
c = db()
try:
if reset_usage:
c.execute("UPDATE client_traffic SET rx_bytes=0, tx_bytes=0 WHERE mac=?", (mac,))
today_str = time.strftime('%Y-%m-%d')
c.execute("UPDATE client_traffic_daily SET rx_bytes=0, tx_bytes=0 WHERE mac=? AND traffic_date=?", (mac, today_str))
if mac in quota_alerted_macs:
quota_alerted_macs.discard(mac)
c.execute('''
INSERT INTO client_limits (mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(mac) DO UPDATE SET
quota_enabled=excluded.quota_enabled,
quota_bytes=excluded.quota_bytes,
quota_period=excluded.quota_period,
bandwidth_enabled=excluded.bandwidth_enabled,
rate_down_kbps=excluded.rate_down_kbps,
rate_up_kbps=excluded.rate_up_kbps,
quota_action=excluded.quota_action,
updated_at=excluded.updated_at
''', (mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, now_str))
c.commit()
finally:
c.close()
threading.Thread(target=sync_client_bandwidth_and_quotas, kwargs={'force': True}, daemon=True).start()
return get_client_limits_dict(mac)
last_applied_limits_state = None
def sync_client_bandwidth_and_quotas(force=False):
global last_sync_limits_time, last_applied_limits_state
now_ts = time.time()
if not force and now_ts - last_sync_limits_time < 3:
return
last_sync_limits_time = now_ts
with limits_lock:
try:
c = db()
has_table = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='client_limits'").fetchone())
if not has_table:
c.close()
return
rows = c.execute("SELECT mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action FROM client_limits").fetchall()
c.close()
limits = {}
for r in rows:
limits[r[0].upper()] = {
'quota_enabled': bool(r[1]),
'quota_bytes': int(r[2] or 0),
'quota_period': r[3] or 'total',
'bandwidth_enabled': bool(r[4]),
'rate_down_kbps': int(r[5] or 0),
'rate_up_kbps': int(r[6] or 0),
'quota_action': r[7] or 'block'
}
# 1. Vérifier les quotas dépassés et appareils bloqués
quota_blocked_macs = set()
mac_to_ip = get_all_mac_to_ips()
for mac, lim in limits.items():
if lim['quota_enabled'] and lim['quota_bytes'] > 0:
usage = get_client_traffic_usage(mac, lim['quota_period'])
if usage >= lim['quota_bytes']:
quota_blocked_macs.add(mac)
if mac not in quota_alerted_macs:
quota_alerted_macs.add(mac)
name, ip = known_device(mac)
q_str = format_bytes(lim['quota_bytes'])
u_str = format_bytes(usage)
msg = f"L'appareil « {name} » ({ip or mac}) a dépassé son quota de {q_str} (consommé : {u_str}). L'accès Internet a été coupé."
log('quota_depasse', name, ip, mac)
dispatch_notification(
'quota_exceeded',
"⚠️ Quota de données dépassé",
msg,
details={
"Nom": name,
"IP": ip or "—",
"MAC": mac,
"Quota": q_str,
"Consommation": u_str,
"Action": "Accès Internet coupé"
},
priority=5,
level="warning",
vars_dict={
"name": name,
"nom": name,
"ip": ip or "—",
"mac": mac,
"quota": q_str,
"consumption": u_str,
"consommation": u_str,
"usage": u_str,
"action": "L'accès Internet a été coupé"
}
)
else:
if mac in quota_alerted_macs:
quota_alerted_macs.discard(mac)
try:
manually_blocked = blocked_set()
except Exception:
manually_blocked = set()
all_blocked_macs = set(quota_blocked_macs) | set(manually_blocked)
active_rate_limits = {
mac: lim for mac, lim in limits.items()
if lim['bandwidth_enabled'] and (lim['rate_down_kbps'] > 0 or lim['rate_up_kbps'] > 0)
}
# Optimisation majeure : si l'état des blocages et débits n'a pas changé, éviter de relancer les sous-processus système
current_state = (
frozenset(all_blocked_macs),
frozenset((m, lim['rate_down_kbps'], lim['rate_up_kbps']) for m, lim in active_rate_limits.items()),
tuple(sorted((m, mac_to_ip.get(m, '')) for m in all_blocked_macs | set(active_rate_limits.keys())))
)
if not force and last_applied_limits_state == current_state:
return
last_applied_limits_state = current_state
# 2. Couche 2 Pont Ethernet (L2 Bridge) : nftables family bridge (Priorité -350, avant le broute VPN -300)
nft_bin = find_bin('nft')
if nft_bin:
try:
if all_blocked_macs:
nft_cmds = [
"add table bridge ap_quota_block",
"flush table bridge ap_quota_block",
"add chain bridge ap_quota_block prerouting { type filter hook prerouting priority -350; policy accept; }",
"add chain bridge ap_quota_block forward { type filter hook forward priority -350; policy accept; }",
# Exemptions fondamentales : ARP et DHCP (IPv4 + IPv6)
"add rule bridge ap_quota_block prerouting ether type arp accept",
"add rule bridge ap_quota_block forward ether type arp accept",
"add rule bridge ap_quota_block prerouting ether type ip udp sport 67-68 udp dport 67-68 accept",
"add rule bridge ap_quota_block forward ether type ip udp sport 67-68 udp dport 67-68 accept",
"add rule bridge ap_quota_block prerouting ether type ip6 udp sport 546-547 udp dport 546-547 accept",
"add rule bridge ap_quota_block forward ether type ip6 udp sport 546-547 udp dport 546-547 accept",
"add rule bridge ap_quota_block prerouting ether type ip6 icmpv6 type { 133, 134, 135, 136 } accept",
"add rule bridge ap_quota_block forward ether type ip6 icmpv6 type { 133, 134, 135, 136 } accept",
]
for b_mac in all_blocked_macs:
cm = b_mac.strip().lower()
if cm:
nft_cmds.append(f"add rule bridge ap_quota_block prerouting ether saddr {cm} drop")
nft_cmds.append(f"add rule bridge ap_quota_block prerouting ether daddr {cm} drop")
nft_cmds.append(f"add rule bridge ap_quota_block forward ether saddr {cm} drop")
nft_cmds.append(f"add rule bridge ap_quota_block forward ether daddr {cm} drop")
subprocess.run([nft_bin, '-f', '-'], input="\n".join(nft_cmds), text=True, capture_output=True, timeout=5)
else:
subprocess.run([nft_bin, 'delete', 'table', 'bridge', 'ap_quota_block'], capture_output=True, timeout=3)
except Exception as e:
print(f"[ap-limits] Erreur nftables bridge : {e}", flush=True)
# 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 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)
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-D', 'FORWARD', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-D', 'INPUT', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
if all_blocked_macs:
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-I', 'FORWARD', '1', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-I', 'INPUT', '1', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-A', 'AP_QUOTA_BLOCK', '-p', 'ARP', '-j', 'ACCEPT'], capture_output=True, timeout=5)
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-A', 'AP_QUOTA_BLOCK', '-p', 'IPv4', '--ip-proto', 'udp', '--ip-dport', '67:68', '-j', 'ACCEPT'], capture_output=True, timeout=5)
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-A', 'AP_QUOTA_BLOCK', '-p', 'IPv4', '--ip-proto', 'udp', '--ip-sport', '67:68', '-j', 'ACCEPT'], capture_output=True, timeout=5)
for b_mac in all_blocked_macs:
cm = b_mac.strip().lower()
if cm:
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-A', 'AP_QUOTA_BLOCK', '-s', cm, '-j', 'DROP'], capture_output=True, timeout=5)
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-A', 'AP_QUOTA_BLOCK', '-d', cm, '-j', 'DROP'], capture_output=True, timeout=5)
except Exception as e:
print(f"[ap-limits] Erreur ebtables : {e}", flush=True)
# 4. Couche 3 (IPv4 & IPv6) : iptables et ip6tables (filter & mangle avec verrou -w 5 et test -C)
iptables_bin = find_bin('iptables')
ip6tables_bin = find_bin('ip6tables')
for bin_cmd, is_v6 in [(iptables_bin, False), (ip6tables_bin, True)]:
if not bin_cmd: continue
try:
for tbl, chain in [('filter', 'FORWARD'), ('filter', 'INPUT'), ('mangle', 'PREROUTING')]:
# Créer et vider la chaîne
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-N', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-F', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
# Vérifier si la règle de saut existe
check_r = subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-C', chain, '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
has_jump = (check_r.returncode == 0)
if all_blocked_macs:
if not has_jump:
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-I', chain, '1', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
else:
if has_jump:
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-D', chain, '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
if all_blocked_macs:
if not is_v6:
for tbl in ['filter', 'mangle']:
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-p', 'udp', '--dport', '67:68', '-j', 'RETURN'], capture_output=True, timeout=5)
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-p', 'udp', '--sport', '67:68', '-j', 'RETURN'], capture_output=True, timeout=5)
else:
for tbl in ['filter', 'mangle']:
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-p', 'udp', '--dport', '546:547', '-j', 'RETURN'], capture_output=True, timeout=5)
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-p', 'udp', '--sport', '546:547', '-j', 'RETURN'], capture_output=True, timeout=5)
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-p', 'ipv6-icmp', '-j', 'RETURN'], capture_output=True, timeout=5)
for b_mac in all_blocked_macs:
cm = b_mac.strip().lower()
if cm:
for tbl in ['filter', 'mangle']:
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-m', 'mac', '--mac-source', cm, '-j', 'DROP'], capture_output=True, timeout=5)
if not is_v6:
ip = mac_to_ip.get(b_mac)
if ip and ip not in ('Non attribuée', '—'):
for tbl in ['filter', 'mangle']:
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-s', ip, '-j', 'DROP'], capture_output=True, timeout=5)
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-d', ip, '-j', 'DROP'], capture_output=True, timeout=5)
except Exception as e:
print(f"[ap-limits] Erreur iptables/ip6tables ({bin_cmd}) : {e}", flush=True)
# 5. Maintenir le filtrage isolé pour ne pas impacter la résolution de l'hôte
if all_blocked_macs:
try:
subprocess.run(['sysctl', '-w', 'net.bridge.bridge-nf-call-iptables=0'], capture_output=True, timeout=3)
subprocess.run(['sysctl', '-w', 'net.bridge.bridge-nf-call-ip6tables=0'], capture_output=True, timeout=3)
except Exception: pass
# 6. Limitation de bande passante & Drop direct avec Traffic Control (tc)
tc_bin = find_bin('tc')
target_iface = INTERFACE
if tc_bin and target_iface:
try:
subprocess.run([tc_bin, 'qdisc', 'del', 'dev', target_iface, 'root'], capture_output=True, timeout=3)
subprocess.run([tc_bin, 'qdisc', 'del', 'dev', target_iface, 'ingress'], capture_output=True, timeout=3)
except Exception: pass
if active_rate_limits or all_blocked_macs:
subprocess.run([tc_bin, 'qdisc', 'add', 'dev', target_iface, 'root', 'handle', '1:', 'htb', 'default', '999'], capture_output=True, timeout=3)
subprocess.run([tc_bin, 'class', 'add', 'dev', target_iface, 'parent', '1:', 'classid', '1:999', 'htb', 'rate', '1000mbit', 'ceil', '1000mbit'], capture_output=True, timeout=3)
subprocess.run([tc_bin, 'qdisc', 'add', 'dev', target_iface, 'handle', 'ffff:', 'ingress'], capture_output=True, timeout=3)
# Pour chaque client bloqué : drop immédiat en TC (ingress et egress)
for b_mac in all_blocked_macs:
b_ip = mac_to_ip.get(b_mac)
if b_ip and b_ip not in ('Non attribuée', '—'):
subprocess.run([
tc_bin, 'filter', 'add', 'dev', target_iface, 'parent', 'ffff:', 'protocol', 'ip', 'prio', '1',
'u32', 'match', 'ip', 'src', b_ip, 'action', 'drop'
], capture_output=True, timeout=3)
subprocess.run([
tc_bin, 'filter', 'add', 'dev', target_iface, 'parent', '1:', 'protocol', 'ip', 'prio', '1',
'u32', 'match', 'ip', 'dst', b_ip, 'action', 'drop'
], capture_output=True, timeout=3)
cls_idx = 10
for mac, lim in active_rate_limits.items():
if mac in all_blocked_macs:
continue
ip = mac_to_ip.get(mac)
if not ip or ip in ('Non attribuée', '—'):
continue
if lim['rate_down_kbps'] > 0:
rate_str = f"{lim['rate_down_kbps']}kbit"
class_id = f"1:{cls_idx}"
subprocess.run([tc_bin, 'class', 'add', 'dev', target_iface, 'parent', '1:', 'classid', class_id, 'htb', 'rate', rate_str, 'ceil', rate_str], capture_output=True, timeout=3)
subprocess.run([tc_bin, 'filter', 'add', 'dev', target_iface, 'protocol', 'ip', 'parent', '1:', 'prio', '2', 'u32', 'match', 'ip', 'dst', ip, 'flowid', class_id], capture_output=True, timeout=3)
cls_idx += 1
if lim['rate_up_kbps'] > 0:
rate_str = f"{lim['rate_up_kbps']}kbit"
burst_str = f"{max(32, lim['rate_up_kbps'] // 8)}k"
subprocess.run([
tc_bin, 'filter', 'add', 'dev', target_iface, 'parent', 'ffff:', 'protocol', 'ip', 'prio', '2',
'u32', 'match', 'ip', 'src', ip,
'police', 'rate', rate_str, 'burst', burst_str, 'drop', 'flowid', ':1'
], capture_output=True, timeout=3)
# 7. Conntrack flush : coupe immédiatement les flux et téléchargements en cours
conntrack_bin = find_bin('conntrack')
if conntrack_bin and all_blocked_macs:
for b_mac in all_blocked_macs:
b_ip = mac_to_ip.get(b_mac)
if b_ip and b_ip not in ('Non attribuée', '—'):
subprocess.run([conntrack_bin, '-D', '-s', b_ip], capture_output=True, timeout=3)
subprocess.run([conntrack_bin, '-D', '-d', b_ip], capture_output=True, timeout=3)
except Exception as e:
print(f"[ap-limits] Erreur synchronisation quotas & débits : {e}", flush=True)
def all_devices(lang='fr'):
"""Récupère l'ensemble des équipements qui se sont déjà connectés au réseau depuis la base de données SQLite."""
is_en = str(lang or '').lower().startswith('en')
c = db()
names_dict = {}
cn_cols = {row[1] for row in c.execute('PRAGMA table_info(client_names)').fetchall()}
has_dev_type = 'device_type' in cn_cols
has_cust = 'is_custom' in cn_cols
if has_dev_type and has_cust:
query = 'SELECT mac, name, last_ip, last_seen, COALESCE(device_type, ""), COALESCE(is_custom, 0) FROM client_names'
elif has_dev_type:
query = 'SELECT mac, name, last_ip, last_seen, COALESCE(device_type, ""), 0 FROM client_names'
else:
query = 'SELECT mac, name, last_ip, last_seen, "", 0 FROM client_names'
for r in c.execute(query).fetchall():
m = (r[0] or '').upper()
if m and is_valid_mac(m):
names_dict[m] = {
'name': r[1] or '',
'last_ip': r[2] or '',
'last_seen': r[3] or '',
'device_type': r[4] or '',
'is_custom': bool(r[5]) if len(r) > 5 else False
}
logs_dict = {}
try:
rows = c.execute('''
SELECT mac, MIN(event_time), MAX(event_time),
(SELECT name FROM connection_logs WHERE mac = l.mac AND name != '' AND name != 'Nom non communiqué' ORDER BY id DESC LIMIT 1),
(SELECT ip FROM connection_logs WHERE mac = l.mac AND ip != '' AND ip != 'Non attribuée' ORDER BY id DESC LIMIT 1)
FROM connection_logs l
WHERE l.event IN ('connexion', 'déconnexion', 'blocage', 'déblocage', 'rejet_limite', 'quota_depasse')
GROUP BY mac
''').fetchall()
for r in rows:
m = (r[0] or '').upper()
if m and is_valid_mac(m):
logs_dict[m] = {
'first_seen': r[1] or '',
'last_seen': r[2] or '',
'name': r[3] or '',
'last_ip': r[4] or ''
}
except Exception: pass
blocked_dict = {}
try:
for r in c.execute('SELECT mac, blocked_at FROM blocked_clients').fetchall():
m = (r[0] or '').upper()
if m and is_valid_mac(m): blocked_dict[m] = r[1] or ''
except Exception: pass
vpn_routes = {}
try:
p_dict = dict(c.execute('SELECT id, name FROM vpn_profiles').fetchall())
for r in c.execute('SELECT mac, profile_id FROM client_vpn_routes WHERE profile_id > 0').fetchall():
m = (r[0] or '').upper()
if m and is_valid_mac(m): vpn_routes[m] = {'profile_id': r[1], 'profile_name': p_dict.get(r[1], 'VPN')}
except Exception: pass
traffic_dict = {}
try:
for r in c.execute('SELECT mac, rx_bytes, tx_bytes FROM client_traffic').fetchall():
m = (r[0] or '').upper()
if m and is_valid_mac(m):
rx = r[1] or 0
tx = r[2] or 0
traffic_dict[m] = {'rx': rx, 'tx': tx, 'total': rx + tx}
except Exception: pass
c.close()
raw_limits = get_client_limits_dict() or {}
limits_dict = {m: v for m, v in raw_limits.items() if is_valid_mac(m)}
live_clients = {}
try:
for cl in clients():
m = (cl.get('mac') or '').upper()
if m and is_valid_mac(m): live_clients[m] = cl
except Exception: pass
valid_wifi_macs = set()
phantom_macs = []
candidate_macs = set(names_dict.keys()) | set(logs_dict.keys()) | set(blocked_dict.keys()) | set(live_clients.keys()) | set(limits_dict.keys())
for m in candidate_macs:
if not is_valid_mac(m):
continue
is_live = m in live_clients
has_logs = m in logs_dict
is_blocked = m in blocked_dict
has_limits = m in limits_dict
has_traffic = traffic_dict.get(m, {}).get('total', 0) > 0
if is_live or has_logs or is_blocked or has_limits or has_traffic:
valid_wifi_macs.add(m)
else:
phantom_macs.append(m)
if phantom_macs:
try:
c_clean = db()
c_clean.executemany("DELETE FROM client_names WHERE UPPER(mac)=?", [(pm,) for pm in phantom_macs])
c_clean.commit()
c_clean.close()
except Exception:
pass
all_macs = sorted(valid_wifi_macs)
devices = []
for mac in all_macs:
live = live_clients.get(mac)
is_conn = live is not None
is_block = mac in blocked_dict
nd = names_dict.get(mac, {})
ld = logs_dict.get(mac, {})
td = traffic_dict.get(mac, {'rx': 0, 'tx': 0, 'total': 0})
vd = vpn_routes.get(mac)
name = ''
if nd.get('is_custom') and nd.get('name'):
name = nd['name']
elif live and live.get('name') and live['name'] not in ('Nom non communiqué', 'Inconnu'):
name = live['name']
elif not name and nd.get('name') and nd['name'] not in ('Nom non communiqué', 'Inconnu'):
name = nd['name']
elif not name and ld.get('name'):
name = ld['name']
if not name or name.startswith('Client '):
if mac in station_live_names:
name = station_live_names[mac]
if not name:
name = 'Client ' + mac.replace(':', '')[-4:]
ip = ''
if live and live.get('ip') and live['ip'] not in ('Non attribuée', '—'):
ip = live['ip']
if not ip and nd.get('last_ip') and nd['last_ip'] not in ('Non attribuée', '—'):
ip = nd['last_ip']
if not ip and ld.get('last_ip') and ld['last_ip'] not in ('Non attribuée', '—'):
ip = ld['last_ip']
if not ip:
ip = 'Non attribuée'
first_seen = ld.get('first_seen') or nd.get('last_seen') or '—'
last_seen = nd.get('last_seen') or ld.get('last_seen') or '—'
online_label = 'Currently online' if is_en else 'Actuellement en ligne'
unknown_label = 'Unknown' if is_en else 'Inconnue'
last_seen_str = online_label if is_conn else (last_seen if last_seen != '—' else unknown_label)
custom_type = nd.get('device_type') or (live.get('device_type') if live else '')
dev_type = custom_type if custom_type else guess_device_type(name, mac)
devices.append({
'mac': mac,
'name': name,
'ip': ip,
'connected': is_conn,
'status': 'connected' if is_conn else 'offline',
'blocked': is_block,
'blocked_at': blocked_dict.get(mac, ''),
'first_seen': first_seen,
'last_seen': last_seen,
'last_seen_display': last_seen_str,
'device_type': dev_type,
'signal_dbm': live.get('signal_dbm') if live else None,
'download_speed_str': live.get('download_speed_str', '') if live else '',
'upload_speed_str': live.get('upload_speed_str', '') if live else '',
'traffic_total_str': format_bytes(td['total']) if td['total'] > 0 else '0 o',
'traffic_total_bytes': td['total'],
'vpn_profile_name': vd['profile_name'] if vd else '',
'limits': limits_dict.get(mac, None)
})
def _dev_sort(d):
conn_rank = 0 if d['connected'] else 1
ts = 0
ls = d.get('last_seen') or ''
if re.match(r'^\d{4}-\d{2}-\d{2}', ls):
try: ts = time.mktime(time.strptime(ls, '%Y-%m-%d %H:%M:%S'))
except Exception: pass
return (conn_rank, -ts, d['name'].lower())
devices.sort(key=_dev_sort)
return {
'devices': devices,
'total': len(devices),
'connected_count': sum(1 for d in devices if d['connected']),
'offline_count': sum(1 for d in devices if not d['connected']),
'blocked_count': sum(1 for d in devices if d['blocked'])
}
def get_default_gateway():
try:
res = command('ip', 'route', 'show', 'default')
m = re.search(r'default via (\S+)(?: dev (\S+))?', res)
if m:
return {'gateway_ip': m.group(1), 'interface': m.group(2) or ''}
except Exception: pass
try:
with open('/proc/net/route') as f:
for line in f:
fields = line.strip().split()
if len(fields) >= 3 and fields[1] == '00000000':
gw_hex = fields[2]
gw_ip = socket.inet_ntoa(struct.pack('= 2 and parts[1] not in ('127.0.0.1', '127.0.0.53'):
dns.append(parts[1])
except Exception: pass
return dns or ['1.1.1.1', '8.8.8.8']
def guess_device_type(name, mac=''):
n = (name or '').lower()
if any(k in n for k in ('iphone', 'android', 'galaxy', 'pixel', 'xiaomi', 'redmi', 'huawei', 'oneplus', 'oppo', 'mobile', 'smartphone', 'sm-')):
return 'phone'
if any(k in n for k in ('ipad', 'tablet', 'tab', 'kindle')):
return 'tablet'
if any(k in n for k in ('macbook', 'laptop', 'portable', 'thinkpad', 'zenbook', 'notebook', 'dell-xps', 'hp-envy', 'surface')):
return 'laptop'
if any(k in n for k in ('pc', 'desktop', 'bureau', 'workstation', 'imac', 'mac-pro', 'tower')):
return 'desktop'
if any(k in n for k in ('tv', 'chromecast', 'roku', 'firestick', 'apple-tv', 'bravia', 'smarttv', 'shield')):
return 'tv'
if any(k in n for k in ('playstation', 'ps4', 'ps5', 'xbox', 'switch', 'nintendo')):
return 'console'
if any(k in n for k in ('esp_', 'esp32', 'esp8266', 'tasmota', 'shelly', 'camera', 'cam', 'printer', 'imprimante', 'nas', 'synology', 'raspberry', 'rpi')):
return 'iot'
return 'generic'
def compute_topology_internal(active_items=None, active_status=None):
st = active_status if active_status is not None else status()
cl = active_items if active_items is not None else clients()
bl = blocked_list()
gw = get_default_gateway()
iface = st.get('interface') or INTERFACE
ap_net = get_ap_ip(iface)
wifi_radio = get_wifi_channel_freq(iface)
dns = get_dns_servers()
total_rx_rate = 0
total_tx_rate = 0
for c in cl:
c['device_type'] = c.get('device_type') or guess_device_type(c.get('name', ''), c.get('mac', ''))
sig = c.get('signal_dbm')
if sig is None:
c['signal_rating'] = 'Inconnu'
c['signal_level'] = 0
elif sig >= -50:
c['signal_rating'] = 'Excellent'
c['signal_level'] = 4
elif sig >= -60:
c['signal_rating'] = 'Bon'
c['signal_level'] = 3
elif sig >= -70:
c['signal_rating'] = 'Moyen'
c['signal_level'] = 2
else:
c['signal_rating'] = 'Faible'
c['signal_level'] = 1
total_rx_rate += c.get('upload_speed', 0)
total_tx_rate += c.get('download_speed', 0)
wan_ip = gw.get('gateway_ip') or ('192.168.1.1' if not is_bridge_mode() else 'Passerelle LAN')
wan_if = gw.get('interface') or ('eth0' if os.path.exists('/sys/class/net/eth0') else 'WAN')
vpn_profiles_list = []
try:
c_topo = db()
p_rows = c_topo.execute('SELECT id, name, type, status, iface, table_id FROM vpn_profiles').fetchall()
c_topo.close()
for pid, pname, ptype, pstatus, piface, ptable in p_rows:
piface = piface or (f"wg_ap{pid}" if ptype == "wireguard" else f"tun_ap{pid}")
is_up = bool(pstatus == 'connected' and is_iface_up(piface))
client_macs = [c['mac'] for c in cl if c.get('vpn_profile_id') == pid and c.get('vpn_routed')]
pub_ip = vpn_public_ip_cache.get(piface, {}).get('ip', '') if is_up else ''
pub_geo = get_ip_geo(pub_ip) if pub_ip else None
vpn_profiles_list.append({
'id': pid,
'name': pname,
'type': ptype,
'status': 'connected' if is_up else 'disconnected',
'iface': piface,
'table_id': ptable,
'public_ip': pub_ip,
'public_ip_geo': pub_geo,
'connected': is_up,
'client_count': len(client_macs),
'client_macs': client_macs
})
except Exception as e:
print(f"[ap-error] Erreur récupération vpn_profiles topologie: {e}", flush=True)
now_str = time.strftime('%H:%M:%S')
return {
'internet': {
'status': 'online' if st.get('active') else 'standby',
'gateway_ip': wan_ip,
'interface': wan_if,
'dns': dns,
},
'vpn_profiles': vpn_profiles_list,
'active_vpn_count': sum(1 for p in vpn_profiles_list if p.get('connected')),
'ap': {
'ssid': st.get('ssid') or 'AP Wi-Fi',
'active': st.get('active', False),
'interface': iface,
'ip': ap_net.get('ip') or ('10.42.0.1' if st.get('mode') == 'nat' else 'IP Pont LAN'),
'cidr': ap_net.get('cidr') or '24',
'mode': 'NAT (Routeur Wi-Fi)' if st.get('mode') == 'nat' else 'Pont réseau (Bridge)',
'mode_key': 'nat' if st.get('mode') == 'nat' else 'bridge',
'channel': wifi_radio.get('channel') or get_effective_ap_channel(AP_BAND),
'channel_auto': is_auto_channel(),
'frequency_mhz': wifi_radio.get('freq_mhz') or 2437,
'band': '5 GHz' if (wifi_radio.get('freq_mhz') or 0) > 4000 else '2.4 GHz',
'uptime_seconds': st.get('uptime_seconds', 0),
'security': st.get('security', 'wpa2').upper(),
'max_clients': st.get('max_clients', 30)
},
'clients': cl,
'blocked': bl,
'blocked_count': len(bl),
'total_clients_count': len(cl),
'total_download_rate': total_tx_rate,
'total_upload_rate': total_rx_rate,
'total_download_str': format_speed(total_tx_rate),
'total_upload_str': format_speed(total_rx_rate),
'updated_at': now_str,
'analyzed_at': now_str,
'background_analyzed': True,
'analysis_count': _metrics_count,
'analysis_duration_ms': _metrics_last_duration_ms
}
def network_topology():
with _metrics_lock:
if _cached_topology is not None:
return _cached_topology
return compute_topology_internal()
def update_background_metrics(items=None, st=None):
global _cached_stats, _cached_topology, _metrics_count, _metrics_last_duration_ms, _metrics_last_time
t0 = time.time()
try:
active_items = items if items is not None else clients()
active_status = st if st is not None else status()
new_stats = compute_stats_internal(active_items)
new_topo = compute_topology_internal(active_items, active_status)
_metrics_count += 1
_metrics_last_duration_ms = max(1, int((time.time() - t0) * 1000))
_metrics_last_time = time.time()
new_stats['analysis_count'] = _metrics_count
new_stats['analysis_duration_ms'] = _metrics_last_duration_ms
new_topo['analysis_count'] = _metrics_count
new_topo['analysis_duration_ms'] = _metrics_last_duration_ms
with _metrics_lock:
_cached_stats = new_stats
_cached_topology = new_topo
except Exception as e:
print(f"[ap-metrics] Erreur analyse métriques arrière-plan : {e}", flush=True)
def match_cron_field(pattern, value):
pattern = pattern.strip()
if pattern == '*':
return True
for part in pattern.split(','):
part = part.strip()
if not part:
continue
if '/' in part:
sub, step_str = part.split('/', 1)
try: step = int(step_str)
except ValueError: continue
if step <= 0: continue
if sub == '*':
if value % step == 0:
return True
elif '-' in sub:
try:
s_str, e_str = sub.split('-', 1)
start, end = int(s_str), int(e_str)
if start <= value <= end and (value - start) % step == 0:
return True
except ValueError: pass
elif '-' in part:
try:
s_str, e_str = part.split('-', 1)
start, end = int(s_str), int(e_str)
if start <= value <= end:
return True
except ValueError: pass
else:
try:
if int(part) == value:
return True
except ValueError: pass
return False
def match_cron(expr, dt):
"""Vérifie si un objet datetime correspond à l'expression cron (min heure dom mois dow)."""
parts = expr.strip().split()
if len(parts) != 5:
return False
min_pat, hour_pat, dom_pat, month_pat, dow_pat = parts
if not match_cron_field(min_pat, dt.minute):
return False
if not match_cron_field(hour_pat, dt.hour):
return False
if not match_cron_field(dom_pat, dt.day):
return False
if not match_cron_field(month_pat, dt.month):
return False
cron_dow = (dt.weekday() + 1) % 7 # Sunday=0, Monday=1..Saturday=6
if not match_cron_field(dow_pat, cron_dow):
if cron_dow == 0 and match_cron_field(dow_pat, 7):
return True
return False
return True
def format_top_clients_text(c_list, limit=5):
items = []
compact_items = []
valid = [c for c in c_list if c.get('total_bytes', 0) > 0]
to_show = valid[:limit] if valid else c_list[:limit]
for idx, c in enumerate(to_show, 1):
c_name = c.get('name') or c.get('mac', 'Inconnu')
tot = c.get('total_str', '0 o')
dl = c.get('download_str', '0 o')
ul = c.get('upload_str', '0 o')
status_dot = "🟢 " if c.get('connected') else "⚪ "
items.append(f" {idx}. {status_dot}{c_name} : {tot} (↓ {dl} • ↑ {ul})")
compact_items.append(f"{idx}. {c_name} ({tot})")
text_out = "\n".join(items) if items else " Aucun transfert enregistré"
compact = ", ".join(compact_items) if compact_items else "Aucun transfert enregistré"
return text_out, compact
def generate_stats_report_vars(top_range=None):
"""Rassemble toutes les variables dynamiques pour le message de rapport de statistiques et métriques."""
cfg = get_notifications_config()
sched = cfg.get('stats_report_schedule', {})
if not top_range:
top_range = sched.get('top_range', 'day')
top_range = str(top_range).strip().lower()
if top_range not in ('day', 'week', 'month', 'year', 'all_ranges'):
top_range = 'day'
st_data = stats()
topo_data = network_topology()
st = status()
summary = st_data.get('summary', {})
today_info = summary.get('today', {})
week_info = summary.get('week', {})
month_info = summary.get('month', {})
year_info = summary.get('year', {})
clients_list = clients()
clients_cnt = len(clients_list)
vpn_profs = topo_data.get('vpn_profiles', [])
active_vpn_cnt = sum(1 for p in vpn_profs if p.get('connected'))
vpn_clients_cnt = sum(1 for c in clients_list if c.get('vpn_active') or c.get('profile_id'))
inet = topo_data.get('internet', {})
gw_online = inet.get('status') == 'online'
gw_status_str = "En ligne" if gw_online else "En veille / Hors ligne"
gw_ip = inet.get('gateway_ip') or '192.168.1.1'
ap_info = topo_data.get('ap', {})
ssid = ap_info.get('ssid', 'AP Wi-Fi')
chan = ap_info.get('channel', 6)
band = ap_info.get('band', '2.4 GHz')
mode = ap_info.get('mode', 'NAT')
now_dt = datetime.datetime.now()
date_str = now_dt.strftime('%d/%m/%Y %H:%M:%S')
heure_str = now_dt.strftime('%H:%M:%S')
down_str = topo_data.get('total_download_str', '0 o/s')
up_str = topo_data.get('total_upload_str', '0 o/s')
# Calcul des top clients pour chaque période (Jour, Semaine, Mois, Année)
tc_day = get_top_clients(clients_list, 'day')
tc_week = get_top_clients(clients_list, 'week')
tc_month = get_top_clients(clients_list, 'month')
tc_year = get_top_clients(clients_list, 'year')
top_day_str, top_day_compact = format_top_clients_text(tc_day)
top_week_str, top_week_compact = format_top_clients_text(tc_week)
top_month_str, top_month_compact = format_top_clients_text(tc_month)
top_year_str, top_year_compact = format_top_clients_text(tc_year)
top_all_ranges_str = (
"• Top Aujourd'hui :\n" + top_day_str + "\n"
"• Top Cette semaine :\n" + top_week_str + "\n"
"• Top Ce mois-ci :\n" + top_month_str + "\n"
"• Top Cette année :\n" + top_year_str
)
top_all_ranges_compact = (
f"Jour: {top_day_compact} | Sem.: {top_week_compact} | Mois: {top_month_compact} | An: {top_year_compact}"
)
range_map = {
'day': (top_day_str, top_day_compact, "Aujourd'hui"),
'week': (top_week_str, top_week_compact, "Cette semaine"),
'month': (top_month_str, top_month_compact, "Ce mois-ci"),
'year': (top_year_str, top_year_compact, "Cette année"),
'all_ranges': (top_all_ranges_str, top_all_ranges_compact, "Toutes périodes")
}
selected_top_str, selected_top_compact, selected_label = range_map.get(top_range, (top_day_str, top_day_compact, "Aujourd'hui"))
return {
'clients_count': str(clients_cnt),
'clients': str(clients_cnt),
'today_unique': str(today_info.get('unique', 0)),
'today_total': str(today_info.get('total', 0)),
'week_unique': str(week_info.get('unique', 0)),
'week_total': str(week_info.get('total', 0)),
'month_unique': str(month_info.get('unique', 0)),
'month_total': str(month_info.get('total', 0)),
'year_unique': str(year_info.get('unique', 0)),
'year_total': str(year_info.get('total', 0)),
'traffic_down': down_str,
'traffic_up': up_str,
'download_rate': down_str,
'upload_rate': up_str,
'active_vpns': str(active_vpn_cnt),
'vpn_count': str(active_vpn_cnt),
'vpn_routed_clients': str(vpn_clients_cnt),
'gateway_status': gw_status_str,
'gateway_ip': str(gw_ip),
'ssid': str(ssid),
'channel': str(chan),
'band': str(band),
'mode': str(mode),
# Période active / sélectionnée
'top_clients': selected_top_str,
'top_clients_compact': selected_top_compact,
'top_conso': selected_top_str,
'top_consommation': selected_top_str,
'top_range_label': selected_label,
# Spécifique Jour
'top_clients_day': top_day_str,
'top_clients_day_compact': top_day_compact,
'top_jour': top_day_str,
'top_day': top_day_str,
# Spécifique Semaine
'top_clients_week': top_week_str,
'top_clients_week_compact': top_week_compact,
'top_semaine': top_week_str,
'top_week': top_week_str,
# Spécifique Mois
'top_clients_month': top_month_str,
'top_clients_month_compact': top_month_compact,
'top_mois': top_month_str,
'top_month': top_month_str,
# Spécifique Année
'top_clients_year': top_year_str,
'top_clients_year_compact': top_year_compact,
'top_annee': top_year_str,
'top_year': top_year_str,
# Toutes périodes réunies
'top_clients_all': top_all_ranges_str,
'top_clients_all_compact': top_all_ranges_compact,
'top_tous': top_all_ranges_str,
'date': date_str,
'heure': heure_str,
'time': heure_str
}
def trigger_manual_stats_report():
"""Déclenche immédiatement l'envoi d'un rapport de statistiques de test vers tous les canaux configurés."""
cfg = get_notifications_config()
sched = cfg.get('stats_report_schedule', {})
top_range = sched.get('top_range', 'day')
vars_dict = generate_stats_report_vars(top_range=top_range)
top_lbl = vars_dict.get('top_range_label', "Aujourd'hui")
title = "📊 Rapport statistiques & métriques Wi‑Fi"
message = (
"📊 Rapport Wi‑Fi ({date}) :\n"
"• {clients_count} appareil(s) connecté(s) (↓ {traffic_down} • ↑ {traffic_up})\n"
"• Aujourd'hui : {today_unique} visiteur(s) unique(s) ({today_total} sessions)\n"
"• Cette semaine : {week_unique} unique(s) | Ce mois : {month_unique} unique(s)\n"
"• VPN : {active_vpns} tunnel(s) actif(s) ({vpn_routed_clients} appareil(s) routé(s))\n"
"• Passerelle WAN : {gateway_status} ({gateway_ip})\n"
f"• Top clients ({top_lbl}) :\n{{top_clients}}"
)
details = {
"Clients actifs": f"{vars_dict.get('clients_count', 0)} appareil(s)",
"Visiteurs aujourd'hui": f"{vars_dict.get('today_unique', 0)} uniques ({vars_dict.get('today_total', 0)} sessions)",
"Débits réseau": f"↓ {vars_dict.get('traffic_down', '0 o/s')} • ↑ {vars_dict.get('traffic_up', '0 o/s')}",
"Tunnels VPN": f"{vars_dict.get('active_vpns', 0)} actif(s) ({vars_dict.get('vpn_routed_clients', 0)} client(s) routé(s))",
"Passerelle WAN": f"{vars_dict.get('gateway_status')} ({vars_dict.get('gateway_ip')})",
"Point d'accès": f"SSID: {vars_dict.get('ssid')} • Ch.{vars_dict.get('channel')} ({vars_dict.get('band')})",
f"Top clients ({top_lbl})": vars_dict.get('top_clients_compact', 'Aucun transfert')
}
dispatch_notification(
event_type='stats_report',
title=title,
message=message,
details=details,
priority=4,
level="info",
vars_dict=vars_dict,
force=True
)
return True, "Rapport de statistiques et métriques envoyé avec succès à tous les canaux actifs"
_last_stats_report_minute = None
def stats_report_scheduler_loop():
"""Boucle d'arrière-plan vérifiant les expressions Cron et déclenchant les rapports statistiques."""
global _last_stats_report_minute
while True:
try:
now = datetime.datetime.now()
cur_key = f"{now.year}-{now.month:02d}-{now.day:02d} {now.hour:02d}:{now.minute:02d}"
if cur_key != _last_stats_report_minute:
cfg = get_notifications_config()
events = cfg.get('events', {})
sched = cfg.get('stats_report_schedule', {})
is_active = events.get('stats_report', False) or sched.get('enabled', False)
if is_active:
cron_expr = sched.get('cron_expr', '').strip()
if not cron_expr:
m = sched.get('minute', 0)
h = sched.get('hour', 8)
d = sched.get('day', '*')
cron_expr = f"{m} {h} * * {d}"
if match_cron(cron_expr, now):
_last_stats_report_minute = cur_key
print(f"[ap-notif] Déclenchement tâche cron rapport statistiques ({cron_expr}) à {cur_key}", flush=True)
try:
top_range = sched.get('top_range', 'day')
vars_dict = generate_stats_report_vars(top_range=top_range)
top_lbl = vars_dict.get('top_range_label', "Aujourd'hui")
title = "📊 Rapport statistiques & métriques Wi‑Fi"
message = (
"📊 Rapport Wi‑Fi ({date}) :\n"
"• {clients_count} appareil(s) connecté(s) (↓ {traffic_down} • ↑ {traffic_up})\n"
"• Aujourd'hui : {today_unique} visiteur(s) unique(s) ({today_total} sessions)\n"
"• Cette semaine : {week_unique} unique(s) | Ce mois : {month_unique} unique(s)\n"
"• VPN : {active_vpns} tunnel(s) actif(s) ({vpn_routed_clients} appareil(s) routé(s))\n"
"• Passerelle WAN : {gateway_status} ({gateway_ip})\n"
f"• Top clients ({top_lbl}) :\n{{top_clients}}"
)
details = {
"Clients actifs": f"{vars_dict.get('clients_count', 0)} appareil(s)",
"Visiteurs aujourd'hui": f"{vars_dict.get('today_unique', 0)} uniques ({vars_dict.get('today_total', 0)} sessions)",
"Débits réseau": f"↓ {vars_dict.get('traffic_down', '0 o/s')} • ↑ {vars_dict.get('traffic_up', '0 o/s')}",
"Tunnels VPN": f"{vars_dict.get('active_vpns', 0)} actif(s) ({vars_dict.get('vpn_routed_clients', 0)} client(s) routé(s))",
"Passerelle WAN": f"{vars_dict.get('gateway_status')} ({vars_dict.get('gateway_ip')})",
"Point d'accès": f"SSID: {vars_dict.get('ssid')} • Ch.{vars_dict.get('channel')} ({vars_dict.get('band')})",
f"Top clients ({top_lbl})": vars_dict.get('top_clients_compact', 'Aucun transfert')
}
dispatch_notification(
event_type='stats_report',
title=title,
message=message,
details=details,
priority=4,
level="info",
vars_dict=vars_dict
)
except Exception as e:
print(f"[ap-notif] Erreur lors de l'envoi planifié du rapport statistiques : {e}", flush=True)
except Exception as e:
print(f"[ap-notif] Erreur boucle scheduler stats : {e}", flush=True)
time.sleep(20)
IP_WAIT = 15 # secondes d'attente de l'IP avant de journaliser une connexion sans IP
pending = {}
def update_logs(items):
global last_macs
now = time.time(); current = {x['mac']:x for x in items}; announced = set()
for mac,x in current.items():
if mac in last_macs: announced.add(mac); continue
# Le client apparaît dans « iw station dump » dès l'association Wi-Fi, avant le DHCP :
# on attend son IP (ou IP_WAIT s) pour ne plus journaliser « Non attribuée » à tort.
first = pending.setdefault(mac, now)
if x['ip'] not in ('', 'Non attribuée') or now - first >= IP_WAIT:
# Si le nom est générique ou inconnu, tenter une résolution active du vrai nom d'hôte avant de journaliser
if mac in station_live_names:
x['name'] = station_live_names[mac]
elif x['name'].startswith('Client ') or x['name'] == 'Nom non communiqué':
real_n = resolve_client_hostname_now(x['ip'] if x['ip'] != 'Non attribuée' else '', mac)
if real_n:
x['name'] = real_n
record_live_device_name(mac, real_n, x['ip'] if x['ip'] != 'Non attribuée' else None)
v_badge = f" [🛡️ {x['vpn_profile_name']}]" if x.get('vpn_routed') and x.get('vpn_profile_name') else ""
log('connexion', f"{x['name']}{v_badge}", x['ip'], mac); pending.pop(mac, None); announced.add(mac)
try:
c_cnt = db()
cnt = c_cnt.execute("SELECT COUNT(*) FROM connection_logs WHERE mac=? AND event='connexion'", (mac,)).fetchone()[0]
c_cnt.close()
except Exception: cnt = 1
if cnt <= 1:
dispatch_notification('new_device', "📱 Nouvel appareil détecté", f"L'appareil « {x['name']} » vient de se connecter pour la première fois au réseau Wi-Fi.", details={"Nom": x['name'], "IP": x['ip'], "MAC": mac, "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=6, level="warning")
else:
dispatch_notification('device_connected', "📶 Appareil connecté", f"L'appareil « {x['name']} » s'est connecté au réseau Wi-Fi.", details={"Nom": x['name'], "IP": x['ip'], "MAC": mac, "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=3, level="info")
if x.get('vpn_routed') and x.get('vpn_profile_name'):
dispatch_notification('vpn_client_connected', "🛡️ Client routé via VPN", f"L'appareil « {x['name']} » ({x['ip']}) s'est connecté au réseau Wi-Fi sous le tunnel VPN « {x['vpn_profile_name']} ».", details={"Nom": x['name'], "IP": x['ip'], "MAC": mac, "Profil VPN": x['vpn_profile_name'], "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=4, level="success", vars_dict={"name": x['name'], "ip": x['ip'], "mac": mac, "vpn": x['vpn_profile_name'], "date": time.strftime('%d/%m/%Y %H:%M:%S')})
for mac in [m for m in pending if m not in current]: pending.pop(mac, None)
for mac in last_macs - set(current):
name, ip = 'Nom non communiqué', 'Non attribuée'
mac_u = str(mac or '').strip().upper()
try:
c = db()
# 1. Vérification dans la table des appareils / abonnés (client_names)
row = c.execute('SELECT name, last_ip FROM client_names WHERE UPPER(mac)=?', (mac_u,)).fetchone()
if row:
if row[0] and row[0] != 'Nom non communiqué':
name = row[0]
saved_ip = row[1] or ''
if is_bridge_mode() and saved_ip.startswith('10.42.'):
saved_ip = ''
if saved_ip and saved_ip != 'Non attribuée':
ip = saved_ip
# 2. Si le nom ou l'IP manque encore, chercher dans les logs de connexion récents
if name == 'Nom non communiqué' or ip == 'Non attribuée':
row_log = c.execute("SELECT name, ip FROM connection_logs WHERE UPPER(mac)=? AND ip NOT IN ('Non attribuée', '', '—') ORDER BY id DESC LIMIT 1", (mac_u,)).fetchone()
if row_log:
if (name == 'Nom non communiqué' or not name) and row_log[0] and row_log[0] != 'Nom non communiqué':
clean_n = re.sub(r'\s*\[🛡️[^\]]*\]', '', row_log[0]).strip()
if clean_n: name = clean_n
if (ip == 'Non attribuée' or not ip) and row_log[1] and row_log[1] != 'Non attribuée':
ip = row_log[1]
c.close()
except sqlite3.Error: pass
if (ip == 'Non attribuée' or not ip) and mac_u in station_live_ips:
ip = station_live_ips[mac_u]
if name == 'Nom non communiqué' or not name:
name = device_name(ip if ip != 'Non attribuée' else '', mac_u)
log('déconnexion', name, ip, mac_u)
dispatch_notification('device_disconnected', "📴 Appareil déconnecté", f"L'appareil « {name} » s'est déconnecté du réseau Wi-Fi.", details={"Nom": name, "IP": ip, "MAC": mac, "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=2, level="info")
try:
c_v = db()
row_v = c_v.execute('SELECT p.name FROM client_vpn_routes r JOIN vpn_profiles p ON p.id = r.profile_id WHERE r.mac=? AND r.profile_id > 0', (mac,)).fetchone()
c_v.close()
if row_v and row_v[0]:
vpn_pname = row_v[0]
dispatch_notification('vpn_client_disconnected', "🌐 Client VPN déconnecté", f"L'appareil « {name} » ({ip}) routé via le VPN « {vpn_pname} » s'est déconnecté du réseau Wi-Fi.", details={"Nom": name, "IP": ip, "MAC": mac, "Profil VPN": vpn_pname, "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=3, level="info", vars_dict={"name": name, "ip": ip, "mac": mac, "vpn": vpn_pname, "date": time.strftime('%d/%m/%Y %H:%M:%S')})
except Exception: pass
last_macs = announced
def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=False):
ssid, password = str(data.get('ssid','')).strip(), str(data.get('password',''))
sec, key, proto, pmf = security(data.get('security','wpa2'))
if not ssid or len(ssid)>32 or not 8<=len(password)<=63: raise ValueError('SSID ou mot de passe Wi-Fi invalide')
if 'max_clients' in data:
set_max_clients(data.get('max_clients'))
raw_auto = data.get('autoconnect', True)
autoconnect = raw_auto if isinstance(raw_auto, bool) else str(raw_auto).lower() in ('1', 'true', 'yes', 'oui')
mode = str(data.get('mode', '')).lower()
if mode not in ('ap', 'bridge'):
mode = get_pref('mode', 'ap').lower()
if mode not in ('ap', 'bridge'): mode = 'ap'
bridge_name = str(data.get('bridge_name', '')).strip() or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
bridge_eth = str(data.get('bridge_eth', '')).strip()
if not bridge_eth:
bridge_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
if mode == 'bridge' and not bridge_eth:
candidates = detect_ethernet_interfaces()
if candidates: bridge_eth = candidates[0]
old_name = connection_name()
target_name = 'AP-' + ssid
name = target_name
# Persister l'intégralité de la configuration Wi-Fi en BDD SQLite pour survie au redémarrage du conteneur
prev_mode = (get_pref('mode', 'ap') or 'ap').lower()
if prev_mode != mode:
station_live_ips.clear()
set_pref('ap_ssid', ssid)
set_pref('ap_password', password)
set_pref('ap_security', sec)
set_pref('ap_autoconnect', '1' if autoconnect else '0')
set_pref('mode', mode)
set_pref('bridge_name', bridge_name)
if bridge_eth: set_pref('bridge_eth', bridge_eth)
set_pref('ap_connection_name', name)
print(f"[ap-wifi] Configuration AP: SSID='{ssid}', Sécurité={sec}, Mode={mode}, Autoconnect={'oui' if autoconnect else 'non'}", flush=True)
# Arrêter et supprimer proprement toute ancienne connexion NM / instance hostapd pour éviter tout conflit
stop_hostapd(INTERFACE)
to_delete = {n for n in (old_name, target_name) if n}
for c in to_delete:
subprocess.run(['nmcli', 'connection', 'down', c], capture_output=True, text=True)
subprocess.run(['nmcli', 'connection', 'delete', c], capture_output=True, text=True)
if mode == 'bridge':
teardown_ap_nat()
# Arrêter le dnsmasq interne pour que les clients reçoivent l'IP de la box et non 10.42.0.x
subprocess.run(['pkill', '-f', 'dnsmasq.*shared'], text=True, capture_output=True)
for lf in ['/var/lib/misc/dnsmasq.leases', '/var/lib/NetworkManager/dnsmasq.leases']:
try:
if os.path.exists(lf): open(lf, 'w').close()
except OSError: pass
save_connection(name)
if start_now:
# Prépare le pont noyau sans JAMAIS rendre br0 géré par NetworkManager (préserve l'IP et le DNS de l'hôte)
setup_bridge(bridge_name, bridge_eth)
start_bridge_hostapd(ssid, password, sec=sec, bridge_name=bridge_name, iface=INTERFACE)
mark_ap_started()
else:
teardown_bridge(bridge_name, bridge_eth)
ensure_nm_manages_wifi(INTERFACE)
add_args = [
'nmcli', 'connection', 'add',
'type', 'wifi',
'ifname', INTERFACE,
'con-name', name,
'ssid', ssid
]
r = subprocess.run(add_args, text=True, capture_output=True)
if r.returncode:
raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé de créer la connexion Wi-Fi')
modify_args = [
'nmcli', 'connection', 'modify', name,
'802-11-wireless.mode', 'ap',
'802-11-wireless-security.key-mgmt', key,
'802-11-wireless-security.psk', password,
'802-11-wireless-security.pmf', pmf,
'ipv4.method', 'shared',
'ipv6.method', 'ignore',
'802-11-wireless.band', AP_BAND,
'802-11-wireless.channel', str(get_effective_ap_channel(AP_BAND, force_rescan=is_auto_channel())),
'connection.autoconnect', 'yes' if autoconnect else 'no'
]
if proto: modify_args += ['802-11-wireless-security.proto', proto]
if sec in ('wpa2', 'wpa3'):
modify_args += ['802-11-wireless-security.pairwise', 'ccmp', '802-11-wireless-security.group', 'ccmp']
# Note : ipv4.dns est interdit par NetworkManager lorsque ipv4.method=shared.
# Les serveurs DNS (AP_DNS) sont distribués aux clients Wi-Fi via dnsmasq (ensure_dnsmasq_dns / dhcp-option=6).
r = subprocess.run(modify_args, text=True, capture_output=True)
if r.returncode:
raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé la configuration AP')
ensure_dnsmasq_dns()
save_connection(name)
if start_now:
r = subprocess.run(['nmcli', 'connection', 'up', name], text=True, capture_output=True)
if r.returncode:
raise RuntimeError(r.stderr.strip() or 'Impossible de démarrer le point d’accès')
setup_ap_nat(INTERFACE)
mark_ap_started()
else:
teardown_ap_nat()
invalidate_status_cache()
if not silent:
log('création' if initial else 'enregistrement_modifie', f"Réseau Wi-Fi {ssid} ({'Mode Pont' if mode == 'bridge' else 'Mode AP'})", ip=caller_ip or 'Non attribuée', mac='AP')
dispatch_notification('settings_changed', "⚙️ Modification réglages Wi-Fi / AP", f"Les réglages du point d'accès Wi-Fi ont été modifiés.", details={"SSID": ssid, "Mode": "Mode Pont" if mode == 'bridge' else "Mode AP", "Sécurité": sec.upper(), "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=5, level="warning")
return name
def restore_ap_from_db(force_start=False):
"""Restaure au redémarrage du conteneur le profil Wi-Fi (SSID, mot de passe, sécurité, mode, démarrage auto) depuis la BDD SQLite."""
db_ssid = (get_pref('ap_ssid', '') or '').strip()
db_pass = get_pref('ap_password', '') or ''
db_sec = (get_pref('ap_security', 'wpa2') or 'wpa2').lower()
if db_sec not in ('wpa1', 'wpa2', 'wpa3'):
db_sec = 'wpa2'
db_mode = (get_pref('mode', 'ap') or 'ap').lower()
if db_mode not in ('ap', 'bridge'):
db_mode = 'ap'
db_auto_raw = get_pref('ap_autoconnect', '1')
autoconnect = str(db_auto_raw).lower() in ('1', 'true', 'yes', 'oui')
b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
# Migration transparente : si la BDD n'a pas encore le SSID mais qu'un profil NM existe déjà, le sauvegarder en BDD
if not db_ssid:
existing = connection_name()
if existing:
nm_ssid = command('nmcli', '-t', '-g', '802-11-wireless.ssid', 'connection', 'show', existing)
nm_pass = command('nmcli', '--show-secrets', '-t', '-g', '802-11-wireless-security.psk', 'connection', 'show', existing)
if nm_ssid and nm_pass:
nm_key = command('nmcli', '-t', '-g', '802-11-wireless-security.key-mgmt', 'connection', 'show', existing).lower()
nm_proto = command('nmcli', '-t', '-g', '802-11-wireless-security.proto', 'connection', 'show', existing).lower()
nm_sec = 'wpa3' if nm_key == 'sae' else 'wpa1' if nm_proto == 'wpa' else 'wpa2'
nm_auto = command('nmcli', '-t', '-g', 'connection.autoconnect', 'connection', 'show', existing).lower() == 'yes'
nm_slave = (command('nmcli', '-t', '-g', 'connection.slave-type', 'connection', 'show', existing) or command('nmcli', '-t', '-g', 'connection.port-type', 'connection', 'show', existing)).lower()
nm_mode = 'bridge' if nm_slave == 'bridge' else db_mode
set_pref('ap_ssid', nm_ssid)
set_pref('ap_password', nm_pass)
set_pref('ap_security', nm_sec)
set_pref('ap_autoconnect', '1' if nm_auto else '0')
set_pref('mode', nm_mode)
set_pref('ap_connection_name', existing)
db_ssid, db_pass, db_sec, autoconnect, db_mode = nm_ssid, nm_pass, nm_sec, nm_auto, nm_mode
print(f"[ap-api] Configuration Wi-Fi existante '{nm_ssid}' migrée dans la BDD SQLite.", flush=True)
if not db_ssid or not db_pass:
# Aucun profil Wi-Fi configuré (setup non effectué) : laisser l'Ethernet hôte libre
teardown_bridge(b_name, b_eth)
return False
target_name = get_pref('ap_connection_name', '') or ('AP-' + db_ssid)
should_start = bool(force_start or autoconnect)
# Mode Pont : géré nativement via hostapd (br0 reste non géré par NetworkManager)
if db_mode == 'bridge':
save_connection(target_name)
if should_start:
print(f"[ap-api] Démarrage du Wi-Fi Pont '{db_ssid}' depuis la BDD (pont={b_name}, sécurité={db_sec})...", flush=True)
try:
setup_bridge(b_name, b_eth)
start_bridge_hostapd(db_ssid, db_pass, sec=db_sec, bridge_name=b_name, iface=INTERFACE)
mark_ap_started()
invalidate_status_cache()
return True
except Exception as e:
print(f"[ap-api] Erreur démarrage Pont hostapd : {e}", flush=True)
return False
else:
print(f"[ap-api] Profil Wi-Fi Pont '{db_ssid}' restauré depuis la BDD (démarrage automatique désactivé).", flush=True)
stop_hostapd(INTERFACE)
teardown_ap_nat()
invalidate_status_cache()
return True
# Mode AP (NAT) : géré via NetworkManager + règles NAT/FORWARD
ensure_nm_manages_wifi(INTERFACE)
nm_exists = subprocess.run(['nmcli', 'connection', 'show', target_name], capture_output=True, text=True).returncode == 0
needs_rebuild = not nm_exists
if nm_exists:
nm_ssid = command('nmcli', '-t', '-g', '802-11-wireless.ssid', 'connection', 'show', target_name)
nm_pass = command('nmcli', '--show-secrets', '-t', '-g', '802-11-wireless-security.psk', 'connection', 'show', target_name)
nm_key = command('nmcli', '-t', '-g', '802-11-wireless-security.key-mgmt', 'connection', 'show', target_name).lower()
nm_proto = command('nmcli', '-t', '-g', '802-11-wireless-security.proto', 'connection', 'show', target_name).lower()
nm_sec = 'wpa3' if nm_key == 'sae' else 'wpa1' if nm_proto == 'wpa' else 'wpa2'
nm_auto = command('nmcli', '-t', '-g', 'connection.autoconnect', 'connection', 'show', target_name).lower() == 'yes'
nm_slave = (command('nmcli', '-t', '-g', 'connection.slave-type', 'connection', 'show', target_name) or command('nmcli', '-t', '-g', 'connection.port-type', 'connection', 'show', target_name)).lower()
nm_mode = 'bridge' if nm_slave == 'bridge' else 'ap'
if (nm_ssid != db_ssid or nm_pass != db_pass or nm_sec != db_sec or nm_auto != autoconnect or nm_mode != 'ap'):
needs_rebuild = True
if needs_rebuild:
print(f"[ap-api] Reconstruction du profil Wi-Fi '{db_ssid}' depuis la BDD (mode=ap, sécurité={db_sec}, autoconnect={'oui' if autoconnect else 'non'})...", flush=True)
try:
configure_ap({
'ssid': db_ssid,
'password': db_pass,
'security': db_sec,
'mode': 'ap',
'autoconnect': autoconnect,
'bridge_name': b_name,
'bridge_eth': b_eth
}, initial=False, start_now=should_start, silent=True)
return True
except Exception as e:
print(f"[ap-api] Erreur restauration Wi-Fi depuis la BDD : {e}", flush=True)
return False
# Le profil NM existe déjà et correspond à la BDD
save_connection(target_name)
if should_start:
teardown_bridge(b_name, b_eth)
ensure_nm_manages_wifi(INTERFACE)
state = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', INTERFACE)
if not state.startswith('100'):
print(f"[ap-api] Démarrage automatique du Wi-Fi '{db_ssid}' (mode=ap)...", flush=True)
r = subprocess.run(['nmcli', 'connection', 'up', target_name], capture_output=True, text=True)
if r.returncode != 0:
print(f"[ap-api] Erreur démarrage automatique '{target_name}' : {r.stderr.strip()}", flush=True)
return False
setup_ap_nat(INTERFACE)
mark_ap_started()
else:
print(f"[ap-api] Profil Wi-Fi '{db_ssid}' restauré depuis la BDD (démarrage automatique désactivé).", flush=True)
teardown_ap_nat()
teardown_bridge(b_name, b_eth)
invalidate_status_cache()
return True
# =====================================================================
# Module d'analyse réseau avancé & Capture Wireshark (PCAP)
# =====================================================================
capture_running = False
capture_thread = None
capture_lock = threading.Lock()
capture_packets = []
capture_pcap_bytes = bytearray(struct.pack(' {'domain', 'count', 'first_seen', 'last_seen', 'last_seen_str', 'last_client_ip', 'last_client_name', 'proto'}
capture_iface_used = ''
capture_started_at = 0.0
# =====================================================================
# Moteur GeoIP & Détection Pays pour adresses IP (Wireshark / Capture)
# =====================================================================
geoip_lock = threading.Lock()
GEOIP_CACHE = {} # ip -> {'is_ip': True, 'is_local': bool, 'code': str, 'country': str, 'flag': str}
geoip_queue = queue.Queue(maxsize=2000)
geoip_pending = set()
def country_code_to_flag(code):
if not code or len(code) != 2:
return '🌐'
c = code.upper()
try:
return chr(0x1F1E6 + ord(c[0]) - ord('A')) + chr(0x1F1E6 + ord(c[1]) - ord('A'))
except Exception:
return '🌐'
# Plages IP publiques courantes pré-renseignées pour détection instantanée (0ms)
KNOWN_NETWORKS = [
# Cloudflare
(ipaddress.ip_network('1.0.0.0/8'), 'US', 'Cloudflare', '🇺🇸'),
(ipaddress.ip_network('104.16.0.0/12'), 'US', 'Cloudflare', '🇺🇸'),
(ipaddress.ip_network('172.64.0.0/13'), 'US', 'Cloudflare', '🇺🇸'),
# Google
(ipaddress.ip_network('8.8.8.0/24'), 'US', 'Google DNS', '🇺🇸'),
(ipaddress.ip_network('8.8.4.0/24'), 'US', 'Google DNS', '🇺🇸'),
(ipaddress.ip_network('142.250.0.0/15'), 'US', 'Google', '🇺🇸'),
(ipaddress.ip_network('172.217.0.0/16'), 'US', 'Google', '🇺🇸'),
(ipaddress.ip_network('216.58.192.0/19'), 'US', 'Google', '🇺🇸'),
(ipaddress.ip_network('173.194.0.0/16'), 'US', 'Google', '🇺🇸'),
# Quad9
(ipaddress.ip_network('9.9.9.0/24'), 'CH', 'Quad9 DNS', '🇨🇭'),
(ipaddress.ip_network('149.112.112.0/24'), 'CH', 'Quad9 DNS', '🇨🇭'),
# Cisco OpenDNS
(ipaddress.ip_network('208.67.220.0/22'), 'US', 'Cisco OpenDNS', '🇺🇸'),
# Microsoft & Azure
(ipaddress.ip_network('13.64.0.0/11'), 'US', 'Microsoft Azure', '🇺🇸'),
(ipaddress.ip_network('20.0.0.0/8'), 'US', 'Microsoft', '🇺🇸'),
(ipaddress.ip_network('40.64.0.0/10'), 'US', 'Microsoft', '🇺🇸'),
(ipaddress.ip_network('52.96.0.0/12'), 'US', 'Microsoft Office365', '🇺🇸'),
# Apple
(ipaddress.ip_network('17.0.0.0/8'), 'US', 'Apple', '🇺🇸'),
# GitHub
(ipaddress.ip_network('140.82.112.0/20'), 'US', 'GitHub', '🇺🇸'),
(ipaddress.ip_network('185.199.108.0/22'), 'US', 'GitHub Pages', '🇺🇸'),
# Fastly
(ipaddress.ip_network('151.101.0.0/16'), 'US', 'Fastly CDN', '🇺🇸'),
(ipaddress.ip_network('199.232.0.0/16'), 'US', 'Fastly CDN', '🇺🇸'),
# Amazon AWS
(ipaddress.ip_network('3.0.0.0/8'), 'US', 'Amazon AWS', '🇺🇸'),
(ipaddress.ip_network('52.0.0.0/11'), 'US', 'Amazon AWS', '🇺🇸'),
(ipaddress.ip_network('54.0.0.0/8'), 'US', 'Amazon AWS', '🇺🇸'),
# Fournisseurs & Hébergeurs Français
(ipaddress.ip_network('51.0.0.0/8'), 'FR', 'OVHcloud', '🇫🇷'),
(ipaddress.ip_network('141.94.0.0/16'), 'FR', 'OVHcloud', '🇫🇷'),
(ipaddress.ip_network('164.132.0.0/16'), 'FR', 'OVHcloud', '🇫🇷'),
(ipaddress.ip_network('37.187.0.0/16'), 'FR', 'OVHcloud', '🇫🇷'),
(ipaddress.ip_network('178.32.0.0/15'), 'FR', 'OVHcloud', '🇫🇷'),
(ipaddress.ip_network('91.121.0.0/16'), 'FR', 'OVHcloud', '🇫🇷'),
(ipaddress.ip_network('62.210.0.0/16'), 'FR', 'Scaleway', '🇫🇷'),
(ipaddress.ip_network('163.172.0.0/16'), 'FR', 'Scaleway', '🇫🇷'),
(ipaddress.ip_network('51.15.0.0/16'), 'FR', 'Scaleway', '🇫🇷'),
(ipaddress.ip_network('195.154.0.0/16'), 'FR', 'Scaleway', '🇫🇷'),
(ipaddress.ip_network('212.83.128.0/18'), 'FR', 'Scaleway', '🇫🇷'),
(ipaddress.ip_network('80.10.0.0/15'), 'FR', 'Orange', '🇫🇷'),
(ipaddress.ip_network('90.0.0.0/8'), 'FR', 'Orange', '🇫🇷'),
(ipaddress.ip_network('86.200.0.0/13'), 'FR', 'Orange', '🇫🇷'),
(ipaddress.ip_network('193.252.0.0/16'), 'FR', 'Orange', '🇫🇷'),
(ipaddress.ip_network('83.192.0.0/12'), 'FR', 'Orange', '🇫🇷'),
(ipaddress.ip_network('82.64.0.0/14'), 'FR', 'Free', '🇫🇷'),
(ipaddress.ip_network('212.27.32.0/19'), 'FR', 'Free', '🇫🇷'),
(ipaddress.ip_network('78.250.0.0/15'), 'FR', 'Free', '🇫🇷'),
(ipaddress.ip_network('88.160.0.0/11'), 'FR', 'Free', '🇫🇷'),
(ipaddress.ip_network('91.68.0.0/14'), 'FR', 'Free', '🇫🇷'),
(ipaddress.ip_network('92.128.0.0/11'), 'FR', 'SFR', '🇫🇷'),
(ipaddress.ip_network('93.0.0.0/11'), 'FR', 'SFR', '🇫🇷'),
(ipaddress.ip_network('84.96.0.0/12'), 'FR', 'SFR', '🇫🇷'),
(ipaddress.ip_network('86.64.0.0/12'), 'FR', 'SFR', '🇫🇷'),
(ipaddress.ip_network('109.8.0.0/13'), 'FR', 'SFR', '🇫🇷'),
(ipaddress.ip_network('176.128.0.0/11'), 'FR', 'Bouygues Telecom', '🇫🇷'),
(ipaddress.ip_network('185.24.0.0/14'), 'FR', 'Bouygues Telecom', '🇫🇷'),
(ipaddress.ip_network('89.80.0.0/12'), 'FR', 'Bouygues Telecom', '🇫🇷'),
# Hetzner (Allemagne)
(ipaddress.ip_network('88.198.0.0/16'), 'DE', 'Hetzner', '🇩🇪'),
(ipaddress.ip_network('138.201.0.0/16'), 'DE', 'Hetzner', '🇩🇪'),
(ipaddress.ip_network('144.76.0.0/16'), 'DE', 'Hetzner', '🇩🇪'),
(ipaddress.ip_network('168.119.0.0/16'), 'DE', 'Hetzner', '🇩🇪'),
(ipaddress.ip_network('159.69.0.0/16'), 'DE', 'Hetzner', '🇩🇪'),
]
def init_geoip_cache():
try:
c = db()
rows = c.execute("SELECT ip, code, country, flag FROM geoip_cache").fetchall()
c.close()
with geoip_lock:
for r in rows:
GEOIP_CACHE[r[0]] = {
'is_ip': True,
'is_local': False,
'code': r[1] or '',
'country': r[2] or '',
'flag': r[3] or '🌐'
}
except Exception as e:
print(f"[geoip] Initialisation cache: {e}", flush=True)
def save_geoip_cache_db(ip_str, code, country, flag):
try:
c = db()
c.execute("""
INSERT OR REPLACE INTO geoip_cache (ip, code, country, flag, created_at)
VALUES (?, ?, ?, ?, ?)
""", (ip_str, code, country, flag, time.time()))
c.commit()
c.close()
except Exception:
pass
def enqueue_geoip_lookup(ip_str):
with geoip_lock:
if ip_str in geoip_pending or ip_str in GEOIP_CACHE:
return
geoip_pending.add(ip_str)
try:
geoip_queue.put_nowait(ip_str)
except queue.Full:
pass
def resolve_ip_country_online(ip_str):
# 1. Tentative avec ip-api.com
try:
url = f"http://ip-api.com/json/{ip_str}?fields=status,country,countryCode"
req = urllib.request.Request(url, headers={'User-Agent': 'APManageur-GeoIP/1.0'})
with urllib.request.urlopen(req, timeout=2.0) as resp:
data = json.loads(resp.read().decode('utf-8', errors='ignore'))
if data.get('status') == 'success':
code = (data.get('countryCode') or '').strip().upper()
cname = (data.get('country') or '').strip()
if code:
return {'code': code, 'country': cname, 'flag': country_code_to_flag(code)}
except Exception:
pass
# 2. Fallback avec freeipapi.com
try:
url = f"https://freeipapi.com/api/json/{ip_str}"
req = urllib.request.Request(url, headers={'User-Agent': 'APManageur-GeoIP/1.0'})
with urllib.request.urlopen(req, timeout=2.0) as resp:
data = json.loads(resp.read().decode('utf-8', errors='ignore'))
code = (data.get('countryCode') or '').strip().upper()
cname = (data.get('countryName') or '').strip()
if code:
return {'code': code, 'country': cname, 'flag': country_code_to_flag(code)}
except Exception:
pass
return None
def geoip_worker():
while True:
try:
ip_str = geoip_queue.get(timeout=10)
except queue.Empty:
continue
try:
res = resolve_ip_country_online(ip_str)
if res:
geo = {
'is_ip': True,
'is_local': False,
'code': res['code'],
'country': res['country'],
'flag': res['flag']
}
with geoip_lock:
GEOIP_CACHE[ip_str] = geo
save_geoip_cache_db(ip_str, res['code'], res['country'], res['flag'])
except Exception:
pass
finally:
with geoip_lock:
geoip_pending.discard(ip_str)
geoip_queue.task_done()
time.sleep(0.35)
def get_ip_geo(ip_str):
if not ip_str or not isinstance(ip_str, str):
return None
ip_str = ip_str.strip()
if ':' in ip_str and len(ip_str) == 17 and ip_str.count(':') == 5:
return None
try:
ip_obj = ipaddress.ip_address(ip_str)
except Exception:
return None
if ip_obj.is_private or ip_obj.is_loopback or ip_obj.is_link_local:
return {
'is_ip': True,
'is_local': True,
'code': 'LAN',
'country': 'Réseau local',
'flag': '🏠'
}
if ip_obj.is_multicast:
return {
'is_ip': True,
'is_local': True,
'code': 'MCAST',
'country': 'Multicast',
'flag': '📡'
}
if str(ip_obj) == '255.255.255.255' or ip_obj.is_reserved:
return {
'is_ip': True,
'is_local': True,
'code': 'BCAST',
'country': 'Diffusion',
'flag': '📡'
}
ip_norm = str(ip_obj)
with geoip_lock:
if ip_norm in GEOIP_CACHE:
return GEOIP_CACHE[ip_norm]
for net, code, name, flag in KNOWN_NETWORKS:
try:
if ip_obj in net:
res = {'is_ip': True, 'is_local': False, 'code': code, 'country': name, 'flag': flag}
with geoip_lock:
GEOIP_CACHE[ip_norm] = res
save_geoip_cache_db(ip_norm, code, name, flag)
return res
except Exception:
continue
enqueue_geoip_lookup(ip_norm)
return {'is_ip': True, 'is_local': False, 'code': 'WAN', 'country': 'IP Publique', 'flag': '🌐'}
try:
init_geoip_cache()
threading.Thread(target=geoip_worker, daemon=True).start()
except Exception as _e_geo:
print(f"[geoip] Erreur démarrage service: {_e_geo}", flush=True)
def extract_tls_sni(data):
try:
if len(data) < 44 or data[0] != 0x16: return ''
if len(data) < 6 or data[5] != 1: return ''
pos = 43
if pos >= len(data): return ''
sess_id_len = data[pos]
pos += 1 + sess_id_len
if pos + 2 > len(data): return ''
ciphers_len = struct.unpack('!H', data[pos:pos+2])[0]
pos += 2 + ciphers_len
if pos >= len(data): return ''
comp_len = data[pos]
pos += 1 + comp_len
if pos + 2 > len(data): return ''
ext_total_len = struct.unpack('!H', data[pos:pos+2])[0]
pos += 2
end_ext = min(len(data), pos + ext_total_len)
while pos + 4 <= end_ext:
ext_type, ext_len = struct.unpack('!HH', data[pos:pos+4])
pos += 4
if ext_type == 0: # SNI extension
if pos + 5 <= end_ext:
name_len = struct.unpack('!H', data[pos+3:pos+5])[0]
name_bytes = data[pos+5:pos+5+name_len]
return name_bytes.decode('utf-8', errors='ignore').lower().strip()
break
pos += ext_len
except Exception: pass
return ''
def extract_http_host(data):
try:
if not data.startswith((b'GET ', b'POST ', b'HEAD ', b'PUT ', b'DELETE ', b'OPTIONS ', b'CONNECT ')):
return ''
lines = data.split(b'\r\n')
for line in lines[1:]:
if line.lower().startswith(b'host:'):
host = line.split(b':', 1)[1].strip().decode('utf-8', errors='ignore')
return host.split(':')[0].lower().strip()
except Exception: pass
return ''
def hex_dump(data, max_len=256):
lines = []
chunk = data[:max_len]
for i in range(0, len(chunk), 16):
sub = chunk[i:i+16]
hex_part = ' '.join(f'{b:02x}' for b in sub)
ascii_part = ''.join(chr(b) if 32 <= b < 127 else '.' for b in sub)
lines.append(f'{i:04x} {hex_part:<48} {ascii_part}')
if len(data) > max_len:
lines.append(f'... ({len(data) - max_len} octets supplémentaires)')
return '\n'.join(lines)
def parse_packet(raw, ts):
if len(raw) < 14:
return None
dst_mac = ':'.join(f'{b:02x}' for b in raw[:6])
src_mac = ':'.join(f'{b:02x}' for b in raw[6:12])
ethertype = struct.unpack('!H', raw[12:14])[0]
t_str = time.strftime('%H:%M:%S', time.localtime(ts)) + f'.{int((ts % 1) * 1000):03d}'
pkt = {
'ts': ts,
'time': t_str,
'src': src_mac,
'dst': dst_mac,
'src_mac': src_mac,
'dst_mac': dst_mac,
'proto': 'Ethernet',
'len': len(raw),
'info': f'EtherType 0x{ethertype:04x}',
'details': f'Ethernet II, Src: {src_mac}, Dst: {dst_mac}, Type: 0x{ethertype:04x}',
'hexdump': hex_dump(raw),
'src_geo': None,
'dst_geo': None
}
if ethertype == 0x0806 and len(raw) >= 28:
htype, ptype, hlen, plen, oper = struct.unpack('!HHBBH', raw[14:22])
if hlen == 6 and plen == 4 and len(raw) >= 42:
sha = ':'.join(f'{b:02x}' for b in raw[22:28])
spa = socket.inet_ntoa(raw[28:32])
tha = ':'.join(f'{b:02x}' for b in raw[32:38])
tpa = socket.inet_ntoa(raw[38:42])
pkt['proto'] = 'ARP'
pkt['src'] = spa
pkt['dst'] = tpa
pkt['src_geo'] = get_ip_geo(spa)
pkt['dst_geo'] = get_ip_geo(tpa)
if oper == 1:
pkt['info'] = f'Who has {tpa}? Tell {spa}'
elif oper == 2:
pkt['info'] = f'{spa} is at {sha}'
else:
pkt['info'] = f'ARP opcode={oper}'
pkt['details'] = f'Address Resolution Protocol ({oper})\nSender MAC: {sha}\nSender IP: {spa}\nTarget MAC: {tha}\nTarget IP: {tpa}'
return pkt
if ethertype == 0x0800 and len(raw) >= 34:
ver_ihl = raw[14]
ihl = (ver_ihl & 0x0f) * 4
if len(raw) < 14 + ihl: return pkt
total_len, ident, flags_frag, ttl, proto, chksum = struct.unpack('!HHHBBH', raw[16:26])
src_ip = socket.inet_ntoa(raw[26:30])
dst_ip = socket.inet_ntoa(raw[30:34])
pkt['src'] = src_ip
pkt['dst'] = dst_ip
pkt['src_geo'] = get_ip_geo(src_ip)
pkt['dst_geo'] = get_ip_geo(dst_ip)
ip_payload = raw[14 + ihl:]
if proto == 1 and len(ip_payload) >= 4:
icmp_type, icmp_code = ip_payload[0], ip_payload[1]
pkt['proto'] = 'ICMP'
if icmp_type == 8 and len(ip_payload) >= 8:
ident_i, seq_i = struct.unpack('!HH', ip_payload[4:8])
pkt['info'] = f'Echo (ping) request id=0x{ident_i:04x}, seq={seq_i}, ttl={ttl}'
elif icmp_type == 0 and len(ip_payload) >= 8:
ident_i, seq_i = struct.unpack('!HH', ip_payload[4:8])
pkt['info'] = f'Echo (ping) reply id=0x{ident_i:04x}, seq={seq_i}'
elif icmp_type == 3:
codes = {0:'Net unreach', 1:'Host unreach', 2:'Protocol unreach', 3:'Port unreach'}
pkt['info'] = f'Destination unreachable ({codes.get(icmp_code, f"code {icmp_code}")})'
elif icmp_type == 11:
pkt['info'] = 'Time-to-live exceeded in transit'
else:
pkt['info'] = f'ICMP Type={icmp_type}, Code={icmp_code}'
pkt['details'] = f'Internet Control Message Protocol\nType: {icmp_type}\nCode: {icmp_code}\nSrc: {src_ip} -> Dst: {dst_ip}'
return pkt
if proto == 17 and len(ip_payload) >= 8:
src_p, dst_p, udp_len, _ = struct.unpack('!HHHH', ip_payload[:8])
udp_payload = ip_payload[8:udp_len] if udp_len <= len(ip_payload) else ip_payload[8:]
if 53 in (src_p, dst_p) and len(udp_payload) >= 12:
txid, flags, qdcount, ancount = struct.unpack('!HHHH', udp_payload[:8])
is_resp = bool(flags & 0x8000)
pkt['proto'] = 'DNS'
qname = ''
try:
labels = []
off = 12
while off < len(udp_payload):
l = udp_payload[off]
if l == 0: break
if (l & 0xc0) == 0xc0: off += 2; break
off += 1
labels.append(udp_payload[off:off+l].decode('utf-8', errors='ignore'))
off += l
qname = '.'.join(labels)
except Exception: pass
if qname:
pkt['domain'] = qname
pkt['domain_source'] = 'DNS'
if not is_resp:
pkt['info'] = f'Standard query 0x{txid:04x} A {qname}' if qname else f'Standard query 0x{txid:04x}'
else:
pkt['info'] = f'Standard query response 0x{txid:04x}' + (f' {qname}' if qname else '')
pkt['details'] = f'Domain Name System ({"Response" if is_resp else "Query"})\nTransaction ID: 0x{txid:04x}\nQuestions: {qdcount}, Answers: {ancount}\nQuery: {qname}'
return pkt
if 67 in (src_p, dst_p) or 68 in (src_p, dst_p):
pkt['proto'] = 'DHCP'
msg_type = 'Message'
if len(udp_payload) >= 240 and udp_payload[236:240] == b'\x63\x82\x53\x63':
off = 240
while off + 1 < len(udp_payload):
opt = udp_payload[off]
if opt == 255: break
if opt == 0: off += 1; continue
opt_len = udp_payload[off+1]
if opt == 53 and opt_len >= 1 and off + 2 < len(udp_payload):
t = udp_payload[off+2]
names = {1:'Discover', 2:'Offer', 3:'Request', 4:'Decline', 5:'ACK', 6:'NAK', 7:'Release', 8:'Inform'}
msg_type = names.get(t, f'Type {t}')
break
off += 2 + opt_len
pkt['info'] = f'DHCP {msg_type}'
pkt['details'] = f'Dynamic Host Configuration Protocol\nMessage: {msg_type}\nPort: {src_p} -> {dst_p}'
return pkt
if 5353 in (src_p, dst_p):
pkt['proto'] = 'mDNS'
pkt['info'] = f'Multicast DNS ({src_p} -> {dst_p})'
return pkt
pkt['proto'] = 'UDP'
pkt['info'] = f'{src_p} → {dst_p} Len={len(udp_payload)}'
pkt['details'] = f'User Datagram Protocol, Src Port: {src_p}, Dst Port: {dst_p}, Length: {udp_len}'
return pkt
if proto == 6 and len(ip_payload) >= 20:
src_p, dst_p, seq, ack, off_flags = struct.unpack('!HHIIH', ip_payload[:14])
tcp_off = (off_flags >> 12) * 4
tcp_flags = off_flags & 0x01ff
flag_names = []
if tcp_flags & 0x002: flag_names.append('SYN')
if tcp_flags & 0x001: flag_names.append('FIN')
if tcp_flags & 0x004: flag_names.append('RST')
if tcp_flags & 0x008: flag_names.append('PSH')
if tcp_flags & 0x010: flag_names.append('ACK')
if tcp_flags & 0x020: flag_names.append('URG')
flags_str = '[' + ', '.join(flag_names) + ']' if flag_names else ''
tcp_payload = ip_payload[tcp_off:] if len(ip_payload) >= tcp_off else b''
if 443 in (src_p, dst_p) or 8443 in (src_p, dst_p):
pkt['proto'] = 'TLS'
tls_desc = ''
sni = extract_tls_sni(tcp_payload)
if sni:
pkt['domain'] = sni
pkt['domain_source'] = 'TLS'
if len(tcp_payload) >= 5 and tcp_payload[0] in (0x14, 0x15, 0x16, 0x17):
content_type = tcp_payload[0]
if content_type == 0x16 and len(tcp_payload) >= 6:
hs_type = tcp_payload[5]
names = {1:'Client Hello', 2:'Server Hello', 11:'Certificate', 12:'Server Key Exchange', 14:'Server Hello Done', 16:'Client Key Exchange'}
tls_desc = names.get(hs_type, f'Handshake ({hs_type})')
if sni:
tls_desc += f' [SNI: {sni}]'
elif content_type == 0x17:
tls_desc = f'Application Data [{len(tcp_payload)} B]'
elif content_type == 0x15:
tls_desc = 'Encrypted Alert'
pkt['info'] = f'{src_p} → {dst_p} {flags_str} {tls_desc}'.strip()
pkt['details'] = f'Transport Layer Security\nSrc Port: {src_p}, Dst Port: {dst_p}\n{flags_str}\nPayload: {len(tcp_payload)} bytes' + (f'\nServer Name Indication (SNI): {sni}' if sni else '')
return pkt
if 80 in (src_p, dst_p) or 8080 in (src_p, dst_p):
pkt['proto'] = 'HTTP'
http_line = ''
host = extract_http_host(tcp_payload)
if host:
pkt['domain'] = host
pkt['domain_source'] = 'HTTP'
if tcp_payload.startswith((b'GET ', b'POST ', b'HEAD ', b'PUT ', b'DELETE ')):
http_line = tcp_payload.split(b'\r\n')[0].decode('utf-8', errors='ignore')
elif tcp_payload.startswith(b'HTTP/1.'):
http_line = tcp_payload.split(b'\r\n')[0].decode('utf-8', errors='ignore')
if host and host not in http_line:
http_line = (http_line + f' [Host: {host}]').strip()
pkt['info'] = f'{src_p} → {dst_p} {flags_str} {http_line}'.strip()
pkt['details'] = f'Hypertext Transfer Protocol\n{http_line}' + (f'\nHost: {host}' if host else '')
return pkt
pkt['proto'] = 'TCP'
pkt['info'] = f'{src_p} → {dst_p} {flags_str} Seq={seq} Ack={ack} Len={len(tcp_payload)}'
pkt['details'] = f'Transmission Control Protocol, Src Port: {src_p}, Dst Port: {dst_p}\nFlags: {flags_str}, Seq: {seq}, Ack: {ack}'
return pkt
if ethertype == 0x86dd and len(raw) >= 54:
try:
src_ip6 = socket.inet_ntop(socket.AF_INET6, raw[22:38])
dst_ip6 = socket.inet_ntop(socket.AF_INET6, raw[38:54])
pkt['src'] = src_ip6
pkt['dst'] = dst_ip6
pkt['src_geo'] = get_ip_geo(src_ip6)
pkt['dst_geo'] = get_ip_geo(dst_ip6)
pkt['proto'] = 'IPv6'
pkt['info'] = f'IPv6 {src_ip6} → {dst_ip6}'
pkt['details'] = f'Internet Protocol Version 6, Src: {src_ip6}, Dst: {dst_ip6}'
except Exception:
pass
return pkt
def get_wifi_interface():
global INTERFACE
env_iface = os.environ.get('AP_INTERFACE', '').strip()
if env_iface and os.path.exists(f'/sys/class/net/{env_iface}'):
INTERFACE = env_iface
return env_iface
if INTERFACE and os.path.exists(f'/sys/class/net/{INTERFACE}'):
return INTERFACE
try:
for d in os.listdir('/sys/class/net'):
p = os.path.join('/sys/class/net', d)
if os.path.isdir(os.path.join(p, 'wireless')) or os.path.isdir(os.path.join(p, 'phy80211')):
INTERFACE = d
return d
except Exception: pass
try:
out = subprocess.check_output(['iw', 'dev'], text=True, stderr=subprocess.DEVNULL)
for line in out.splitlines():
parts = line.strip().split()
if len(parts) >= 2 and parts[0] == 'Interface':
INTERFACE = parts[1]
return parts[1]
except Exception: pass
return INTERFACE or 'wls16b1'
def start_capture(target_iface=None):
global capture_running, capture_thread, capture_pcap_bytes, capture_iface_used, capture_started_at
with capture_lock:
if capture_running:
return True, f"Capture déjà en cours sur {capture_iface_used}"
if not capture_pcap_bytes:
capture_pcap_bytes = bytearray(struct.pack(' 0:
recv_iface = sll[0]
if recv_iface and recv_iface != iface:
continue
ts = time.time()
pkt_dict = parse_packet(raw_pkt, ts)
if not pkt_dict: continue
with capture_lock:
capture_id_counter += 1
pkt_dict['id'] = capture_id_counter
capture_packets.append(pkt_dict)
sec = int(ts)
usec = int((ts - sec) * 1e6)
capture_pcap_bytes.extend(struct.pack(' 1000:
oldest = min(captured_domains.keys(), key=lambda k: captured_domains[k]['count'])
del captured_domains[oldest]
captured_domains[dom] = {
'domain': dom,
'count': 1,
'first_seen': ts,
'last_seen': ts,
'last_seen_str': pkt_dict.get('time', ''),
'last_client_ip': client_ip or '',
'last_client_name': client_name or '',
'proto': pkt_dict.get('proto', 'DNS')
}
else:
entry = captured_domains[dom]
entry['count'] += 1
entry['last_seen'] = ts
entry['last_seen_str'] = pkt_dict.get('time', '')
if client_ip:
entry['last_client_ip'] = client_ip
if client_name:
entry['last_client_name'] = client_name
if len(capture_packets) > 50000:
del capture_packets[:500]
if len(capture_pcap_bytes) > 50 * 1024 * 1024:
header = capture_pcap_bytes[:24]
capture_pcap_bytes = header + capture_pcap_bytes[10 * 1024 * 1024:]
except socket.timeout:
continue
except Exception:
if not capture_running: break
time.sleep(0.05)
if sock:
try: sock.close()
except Exception: pass
# =====================================================================
# GESTION DU ROUTAGE VPN PAR CLIENT (WireGuard & OpenVPN)
# =====================================================================
VPN_DIR_WG = '/etc/wireguard'
VPN_DIR_OVPN = '/etc/openvpn'
VPN_RUN_DIR = '/run/ap-vpn'
VPN_SCRIPT_DIR = '/run/ap-vpn/scripts'
vpn_lock = threading.RLock()
connecting_vpn_pids = set()
connecting_vpn_pids_lock = threading.RLock()
def ensure_vpn_dirs():
for d in (VPN_DIR_WG, VPN_DIR_OVPN, VPN_RUN_DIR, VPN_SCRIPT_DIR):
try:
os.makedirs(d, exist_ok=True)
os.chmod(d, 0o700)
except OSError: pass
def get_next_vpn_table_id():
c = db()
rows = c.execute('SELECT table_id FROM vpn_profiles').fetchall()
c.close()
used = {r[0] for r in rows if r[0]}
for tid in range(101, 300):
if tid not in used:
return tid
return 101
def is_iface_up(iface):
if not iface: return False
p = f'/sys/class/net/{iface}'
if not os.path.exists(p): return False
try:
with open(f'{p}/flags', 'r') as f:
flags = int(f.read().strip(), 16)
return bool(flags & 1) # IFF_UP
except Exception: pass
try:
with open(f'{p}/operstate', 'r') as f:
return f.read().strip().lower() == 'up'
except Exception: pass
return False
def read_iface_traffic(iface):
rx, tx = 0, 0
if not iface: return rx, tx
# 1. Si c'est WireGuard, lecture des compteurs du pilote noyau WireGuard (wg show)
if iface.startswith('wg_'):
try:
res = subprocess.run(['wg', 'show', iface, 'transfer'], capture_output=True, text=True, timeout=2)
if res.returncode == 0 and res.stdout.strip():
wg_rx, wg_tx = 0, 0
for line in res.stdout.splitlines():
parts = line.strip().split()
if len(parts) >= 3:
try:
wg_rx += int(parts[1])
wg_tx += int(parts[2])
except ValueError: pass
rx = max(rx, wg_rx)
tx = max(tx, wg_tx)
except Exception:
pass
# 2. Lecture /proc/net/dev (universel pour interfaces kernel dont tun/tap/wg)
try:
with open('/proc/net/dev', 'r') as f:
for line in f:
if ':' in line:
dname, ddata = line.split(':', 1)
if dname.strip() == iface:
cols = ddata.split()
if len(cols) >= 9:
rx = max(rx, int(cols[0]))
tx = max(tx, int(cols[8]))
except Exception: pass
# 3. Sysfs /sys/class/net//statistics
p = f'/sys/class/net/{iface}/statistics'
try:
with open(f'{p}/rx_bytes', 'r') as f: rx = max(rx, int(f.read().strip()))
except (OSError, ValueError): pass
try:
with open(f'{p}/tx_bytes', 'r') as f: tx = max(tx, int(f.read().strip()))
except (OSError, ValueError): pass
return rx, tx
def get_wireguard_handshake_info(iface):
if not iface or not iface.startswith('wg_'):
return None, None
try:
res = subprocess.run(['wg', 'show', iface, 'latest-handshakes'], capture_output=True, text=True, timeout=2)
if res.returncode == 0 and res.stdout.strip():
for line in res.stdout.splitlines():
parts = line.strip().split()
if len(parts) >= 2:
ts = int(parts[1])
if ts > 0:
diff = max(0, int(time.time()) - ts)
if diff < 120:
return f"Handshake actif (il y a {diff}s)", diff
elif diff < 3600:
return f"Dernier handshake il y a {diff // 60} min", diff
else:
return f"Dernier handshake il y a {diff // 3600} h", diff
else:
return "En attente du handshake (non reçu)", -1
except Exception:
pass
return None, None
vpn_public_ip_cache = {}
def get_vpn_public_ip(iface, force_refresh=False):
if not iface or not is_iface_up(iface):
return ''
now = time.time()
cached = vpn_public_ip_cache.get(iface)
if not force_refresh and cached and (now - cached.get('time', 0)) < 60:
return cached.get('ip', '')
detected_ip = ''
# 1. Requête Cloudflare directe sans résolution DNS (ultra-rapide < 250ms)
try:
res = subprocess.run(['curl', '-4', '-s', '-k', '--interface', iface, '--max-time', '2', 'https://1.1.1.1/cdn-cgi/trace'],
capture_output=True, text=True, timeout=3)
if res.returncode == 0:
m = re.search(r'^ip=([0-9.]+)', res.stdout, re.M)
if m:
detected_ip = m.group(1).strip()
except Exception:
pass
# 2. Requête alternative via les fournisseurs IP publics usuels
if not detected_ip:
urls = [
'https://api.ipify.org',
'https://icanhazip.com',
'https://ifconfig.me/ip',
'https://ipinfo.io/ip'
]
for url in urls:
try:
res = subprocess.run(['curl', '-4', '-s', '--interface', iface, '--max-time', '2', url],
capture_output=True, text=True, timeout=3)
if res.returncode == 0:
ip_match = re.search(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', res.stdout)
if ip_match:
detected_ip = ip_match.group(0).strip()
break
except Exception:
pass
# 3. Requête Python native avec socket SO_BINDTODEVICE
if not detected_ip:
try:
class BoundHTTPConnection(http.client.HTTPSConnection):
def connect(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.sock.setsockopt(socket.SOL_SOCKET, 25, (iface + '\0').encode('utf-8'))
except Exception:
pass
self.sock.settimeout(3.5)
self.sock.connect((self.host, self.port))
if self._tunnel_host:
self._tunnel()
self.sock = self._context.wrap_socket(self.sock, server_hostname=self.host)
class BoundHandler(urllib.request.HTTPSHandler):
def https_open(self, req):
return self.do_open(BoundHTTPConnection, req)
opener = urllib.request.build_opener(BoundHandler)
req = urllib.request.Request('https://api.ipify.org', headers={'User-Agent': 'curl/7.88.1'})
with opener.open(req, timeout=3.5) as resp:
content = resp.read().decode('utf-8', errors='ignore').strip()
ip_match = re.search(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', content)
if ip_match:
detected_ip = ip_match.group(0).strip()
except Exception:
pass
ts_now = time.strftime('%H:%M:%S')
if detected_ip:
vpn_public_ip_cache[iface] = {'ip': detected_ip, 'time': now, 'last_tested': ts_now}
try: enqueue_geoip_lookup(detected_ip)
except Exception: pass
else:
if cached:
cached['last_tested'] = ts_now
else:
vpn_public_ip_cache[iface] = {'ip': '', 'time': now, 'last_tested': ts_now}
return detected_ip
def format_vpn_bytes(b):
if not b or b <= 0: return "0 o"
if b < 1024: return f"{int(b)} o"
if b < 1048576: return f"{b / 1024:.1f} Ko"
if b < 1073741824: return f"{b / 1048576:.2f} Mo"
if b < 1099511627776: return f"{b / 1073741824:.2f} Go"
return f"{b / 1099511627776:.2f} To"
def prepare_wireguard_config_text(raw_config, table_id=None):
content = raw_config.replace('\r\n', '\n').replace('\r', '\n').strip()
content = re.sub(r"^\s*DNS\s*=.*$", r"# \g<0> (DNS géré localement)", content, flags=re.MULTILINE|re.IGNORECASE)
# Neutraliser ListenPort pour attribuer un port dynamique par tunnel et éviter les conflits d'adresses
content = re.sub(r"^\s*ListenPort\s*=.*$", r"# \g<0> (Port dynamique)", content, flags=re.MULTILINE|re.IGNORECASE)
# Désactiver la gestion automatique des routes par wg-quick (Table = off)
# Cela évite que wg-quick échoue avec 'RTNETLINK answers: File exists' lors d'un 'route add'
# AP Manageur applique lui-même les routes de façon sécurisée et idempotente avec 'ip route replace'
if re.search(r"^\s*Table\s*=", content, re.MULTILINE|re.IGNORECASE):
content = re.sub(r"^\s*Table\s*=.*$", "Table = off", content, flags=re.MULTILINE|re.IGNORECASE)
else:
content = re.sub(r"(\[Interface\])", "\\1\nTable = off", content, flags=re.IGNORECASE, count=1)
return content
def prepare_openvpn_config_text(raw_config, script_path, auth_path=None):
lines = raw_config.replace('\r\n', '\n').replace('\r', '\n').splitlines()
filtered = []
for line in lines:
s = line.strip()
if s.startswith(('route-noexec', 'script-security', 'route-up', 'auth-user-pass')):
continue
filtered.append(line)
extra = [
"",
"# Directives injectées par AP Manageur pour routage isolé PBR",
"route-noexec",
"script-security 2",
f'route-up "{script_path}"'
]
if auth_path:
extra.append(f'auth-user-pass "{auth_path}"')
return "\n".join(filtered) + "\n" + "\n".join(extra) + "\n"
def list_vpn_profiles():
c = db()
rows = c.execute('SELECT id, name, type, config_content, auth_user, auth_pass, table_id, iface, auto_connect, status, last_error, created_at, updated_at FROM vpn_profiles ORDER BY id ASC').fetchall()
client_counts = {}
for r in c.execute('SELECT profile_id, count(*) FROM client_vpn_routes WHERE profile_id > 0 GROUP BY profile_id').fetchall():
client_counts[r[0]] = r[1]
c.close()
result = []
for r in rows:
pid = r[0]
vtype = r[2]
iface = r[7] or (f"wg_ap{pid}" if vtype == "wireguard" else f"tun_ap{pid}")
raw_status = r[9]
actual_up = is_iface_up(iface)
is_connecting_now = False
with connecting_vpn_pids_lock:
is_connecting_now = pid in connecting_vpn_pids
if actual_up:
status = "connected"
elif is_connecting_now:
status = "connecting"
elif raw_status == "error":
status = "error"
else:
status = "disconnected"
rx, tx = read_iface_traffic(iface) if actual_up else (0, 0)
cache_entry = vpn_public_ip_cache.get(iface, {})
pub_ip = cache_entry.get('ip', '') if actual_up else ''
pub_geo = get_ip_geo(pub_ip) if pub_ip else None
last_tested = cache_entry.get('last_tested', '') if actual_up else ''
handshake, handshake_sec = get_wireguard_handshake_info(iface) if (actual_up and vtype == 'wireguard') else (None, None)
result.append({
'id': pid,
'name': r[1],
'type': vtype,
'config_content': r[3],
'auth_user': r[4] or '',
'has_password': bool(r[5]),
'table_id': r[6],
'iface': iface,
'auto_connect': bool(r[8]),
'status': status,
'last_error': r[10] or '',
'created_at': r[11] or '',
'updated_at': r[12] or '',
'rx_bytes': rx,
'tx_bytes': tx,
'rx_formatted': format_vpn_bytes(rx),
'tx_formatted': format_vpn_bytes(tx),
'clients_count': client_counts.get(pid, 0),
'public_ip': pub_ip,
'public_ip_geo': pub_geo,
'last_tested': last_tested,
'handshake': handshake,
'handshake_age_seconds': handshake_sec
})
return result
def get_vpn_profile(pid):
c = db()
row = c.execute('SELECT id, name, type, config_content, auth_user, auth_pass, table_id, iface, auto_connect, status, last_error, created_at, updated_at FROM vpn_profiles WHERE id=?', (pid,)).fetchone()
c.close()
if not row: return None
return {
'id': row[0], 'name': row[1], 'type': row[2], 'config_content': row[3],
'auth_user': row[4], 'auth_pass': row[5], 'table_id': row[6], 'iface': row[7],
'auto_connect': bool(row[8]), 'status': row[9], 'last_error': row[10]
}
def create_or_update_vpn_profile(data):
ensure_vpn_dirs()
pid = data.get('id')
name = str(data.get('name') or 'Profil VPN').strip()
vtype = str(data.get('type') or 'wireguard').strip().lower()
if vtype not in ('wireguard', 'openvpn'): vtype = 'wireguard'
config_content = str(data.get('config_content') or '').strip()
auth_user = str(data.get('auth_user') or '').strip()
auth_pass = str(data.get('auth_pass') or '').strip()
auto_connect = 1 if data.get('auto_connect') else 0
now = time.strftime('%Y-%m-%d %H:%M:%S')
c = db()
if pid:
pid = int(pid)
if not auth_pass:
old = c.execute('SELECT auth_pass FROM vpn_profiles WHERE id=?', (pid,)).fetchone()
if old: auth_pass = old[0]
c.execute('UPDATE vpn_profiles SET name=?, type=?, config_content=?, auth_user=?, auth_pass=?, auto_connect=?, updated_at=? WHERE id=?',
(name, vtype, config_content, auth_user, auth_pass, auto_connect, now, pid))
new_id = pid
else:
table_id = get_next_vpn_table_id()
cur = c.execute('INSERT INTO vpn_profiles (name, type, config_content, auth_user, auth_pass, table_id, iface, auto_connect, status, last_error, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, "", ?, "disconnected", "", ?, ?)',
(name, vtype, config_content, auth_user, auth_pass, table_id, auto_connect, now, now))
new_id = cur.lastrowid
iface = f"wg_ap{new_id}" if vtype == "wireguard" else f"tun_ap{new_id}"
c.execute('UPDATE vpn_profiles SET iface=? WHERE id=?', (iface, new_id))
c.commit(); c.close()
return new_id
def delete_vpn_profile(pid):
disconnect_vpn_profile(pid)
c = db()
c.execute('DELETE FROM vpn_profiles WHERE id=?', (pid,))
c.execute('DELETE FROM client_vpn_routes WHERE profile_id=?', (pid,))
c.commit(); c.close()
for p in (f"{VPN_DIR_WG}/wg_ap{pid}.conf", f"{VPN_DIR_OVPN}/ovpn_ap{pid}.conf", f"{VPN_DIR_OVPN}/ovpn_ap{pid}.auth", f"{VPN_SCRIPT_DIR}/up_{pid}.sh"):
try: os.remove(p)
except OSError: pass
sync_vpn_client_rules()
def connect_vpn_profile(pid, caller_ip=''):
with connecting_vpn_pids_lock:
if pid in connecting_vpn_pids:
return False, 'Connexion déjà en cours pour ce profil'
connecting_vpn_pids.add(pid)
try:
ensure_vpn_dirs()
prof = get_vpn_profile(pid)
if not prof: return False, 'Profil VPN introuvable'
table_id = prof['table_id'] or (100 + pid)
vtype = prof['type']
iface = prof['iface'] or (f"wg_ap{pid}" if vtype == "wireguard" else f"tun_ap{pid}")
c = db()
c.execute('UPDATE vpn_profiles SET status="connecting", last_error="" WHERE id=?', (pid,))
c.commit(); c.close()
# Activer le forwarding IP et désactiver complètement rp_filter (0 = essentiel pour le brouting)
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', 'net.ipv4.conf.all.rp_filter=0'], capture_output=True)
subprocess.run(['sysctl', '-w', 'net.ipv4.conf.default.rp_filter=0'], capture_output=True)
if vtype == 'wireguard':
conf_path = f"{VPN_DIR_WG}/{iface}.conf"
prepared = prepare_wireguard_config_text(prof['config_content'], table_id)
with open(conf_path, 'w', encoding='utf-8') as f:
f.write(prepared)
try: os.chmod(conf_path, 0o600)
except OSError: pass
# 1. Vérifier que le module noyau WireGuard est présent
if not os.path.exists('/sys/module/wireguard'):
subprocess.run(['modprobe', 'wireguard'], capture_output=True)
# 2. Nettoyage préventif de l'interface et de la table PBR (IPv4 et IPv6)
subprocess.run(['wg-quick', 'down', iface], capture_output=True)
subprocess.run(['ip', 'link', 'delete', 'dev', iface], capture_output=True)
subprocess.run(['ip', '-4', 'route', 'flush', 'table', str(table_id)], capture_output=True)
subprocess.run(['ip', '-6', 'route', 'flush', 'table', str(table_id)], capture_output=True)
for _ in range(5):
r_del = subprocess.run(['ip', '-4', 'rule', 'del', 'table', str(table_id)], capture_output=True)
if r_del.returncode != 0: break
for _ in range(5):
r_del = subprocess.run(['ip', '-6', 'rule', 'del', 'table', str(table_id)], capture_output=True)
if r_del.returncode != 0: break
# 3. Pré-résolution DNS de l'Endpoint WireGuard si c'est un nom de domaine
ep_m = re.search(r"^\s*Endpoint\s*=\s*([^:\s]+)\s*:\s*(\d+)", prof['config_content'], re.MULTILINE | re.IGNORECASE)
if ep_m:
ep_host, ep_port = ep_m.group(1).strip(), int(ep_m.group(2))
if not re.match(r"^(\d{1,3}\.){3}\d{1,3}$", ep_host) and ':' not in ep_host:
dns_resolved = False
for _ in range(3):
try:
socket.getaddrinfo(ep_host, ep_port, socket.AF_INET)
dns_resolved = True
break
except Exception:
time.sleep(0.5)
if not dns_resolved:
print(f"[ap-vpn] Attente résolution DNS pour '{ep_host}'...", flush=True)
# 4. Exécution protégée de wg-quick up
with vpn_lock:
res = subprocess.run(['wg-quick', 'up', iface], capture_output=True, text=True, timeout=10)
if res.returncode != 0:
err_msg = res.stderr.strip() or res.stdout.strip() or 'Erreur wg-quick up'
print(f"[ap-vpn] Échec wg-quick up '{iface}' : {err_msg}", flush=True)
c = db()
c.execute('UPDATE vpn_profiles SET status="error", last_error=? WHERE id=?', (err_msg, pid))
c.commit(); c.close()
return False, f"Échec de connexion WireGuard : {err_msg}"
# Routes garanties dans la table PBR (IPv4 et IPv6 avec 'replace' pour éviter tout File exists)
allowed_lines = re.findall(r"^\s*AllowedIPs\s*=\s*(.+)$", prof['config_content'], flags=re.MULTILINE|re.IGNORECASE)
has_custom_routes = False
for a_line in allowed_lines:
for cidr in a_line.split(','):
cidr = cidr.strip()
if not cidr or cidr.startswith('#'): continue
has_custom_routes = True
if ':' in cidr:
subprocess.run(['ip', '-6', 'route', 'replace', cidr, 'dev', iface, 'table', str(table_id)], capture_output=True)
else:
subprocess.run(['ip', '-4', 'route', 'replace', cidr, 'dev', iface, 'table', str(table_id)], capture_output=True)
if not has_custom_routes:
subprocess.run(['ip', '-4', 'route', 'replace', 'default', 'dev', iface, 'table', str(table_id)], capture_output=True)
subprocess.run(['ip', '-6', 'route', 'replace', 'default', 'dev', iface, 'table', str(table_id)], capture_output=True)
elif vtype == 'openvpn':
pid_file = f"{VPN_RUN_DIR}/{iface}.pid"
if os.path.exists(pid_file):
try:
with open(pid_file) as pf: old_pid = pf.read().strip()
if old_pid: subprocess.run(['kill', '-9', old_pid], capture_output=True)
except Exception: pass
subprocess.run(['pkill', '-f', f"ovpn_ap{pid}"], capture_output=True)
script_path = f"{VPN_SCRIPT_DIR}/up_{pid}.sh"
script_content = f"""#!/bin/sh\nTABLE="{table_id}"\nDEV="$dev"\nGW="$route_vpn_gateway"\nif [ -n "$GW" ]; then\n ip route replace default via "$GW" dev "$DEV" table "$TABLE"\nelse\n ip route replace default dev "$DEV" table "$TABLE"\nfi\nsysctl -w net.ipv4.ip_forward=1 2>/dev/null || true\nsysctl -w net.ipv4.conf.all.forwarding=1 2>/dev/null || true\nsysctl -w net.ipv4.conf.all.rp_filter=0 2>/dev/null || true\nsysctl -w "net.ipv4.conf.$DEV.rp_filter=0" 2>/dev/null || true\n"""
with open(script_path, 'w', encoding='utf-8') as f:
f.write(script_content)
os.chmod(script_path, 0o755)
auth_path = None
if prof['auth_user']:
auth_path = f"{VPN_DIR_OVPN}/{iface}.auth"
with open(auth_path, 'w', encoding='utf-8') as f:
f.write(f"{prof['auth_user']}\n{prof['auth_pass']}\n")
os.chmod(auth_path, 0o600)
ovpn_conf = f"{VPN_DIR_OVPN}/{iface}.conf"
prepared_ovpn = prepare_openvpn_config_text(prof['config_content'], script_path, auth_path)
if not re.search(r"^\s*dev\s+", prepared_ovpn, re.MULTILINE):
prepared_ovpn = f"dev {iface}\ndev-type tun\n" + prepared_ovpn
else:
prepared_ovpn = re.sub(r"^\s*dev\s+.*$", f"dev {iface}\ndev-type tun", prepared_ovpn, flags=re.MULTILINE)
with open(ovpn_conf, 'w', encoding='utf-8') as f:
f.write(prepared_ovpn)
os.chmod(ovpn_conf, 0o600)
res = subprocess.run(['openvpn', '--config', ovpn_conf, '--daemon', f"ovpn_ap{pid}", '--writepid', pid_file], capture_output=True, text=True)
if res.returncode != 0:
err_msg = res.stderr.strip() or res.stdout.strip() or 'Erreur openvpn daemon'
c = db()
c.execute('UPDATE vpn_profiles SET status="error", last_error=? WHERE id=?', (err_msg, pid))
c.commit(); c.close()
return False, f"Échec de connexion OpenVPN : {err_msg}"
for _ in range(15):
time.sleep(0.3)
if is_iface_up(iface): break
# Ajustements réseau communs (WireGuard et OpenVPN)
subprocess.run(['sysctl', '-w', f'net.ipv4.conf.{iface}.rp_filter=0'], capture_output=True)
import glob
for p in glob.glob('/proc/sys/net/ipv4/conf/*/rp_filter'):
try:
with open(p, 'w') as f: f.write('0')
except Exception: pass
for p in glob.glob('/proc/sys/net/ipv4/conf/*/forwarding'):
try:
with open(p, 'w') as f: f.write('1')
except Exception: pass
# NAT Masquerade
subprocess.run(['iptables', '-t', 'nat', '-C', 'POSTROUTING', '-o', iface, '-j', 'MASQUERADE'], capture_output=True)
subprocess.run(['iptables', '-t', 'nat', '-I', 'POSTROUTING', '1', '-o', iface, '-j', 'MASQUERADE'], capture_output=True)
# Filtrage FORWARD (essentiel dans Docker / Debian)
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-o', iface, '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', iface, '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', 'br0', '-o', iface, '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', iface, '-o', 'br0', '-j', 'ACCEPT'], capture_output=True)
if INTERFACE:
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', INTERFACE, '-o', iface, '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', iface, '-o', INTERFACE, '-j', 'ACCEPT'], capture_output=True)
# Clamping MSS TCP (évite le blocage des flux HTTPS/TLS sur tunnel VPN MTU 1420)
subprocess.run(['iptables', '-t', 'mangle', '-C', 'FORWARD', '-p', 'tcp', '--tcp-flags', 'SYN,RST', 'SYN', '-o', iface, '-j', 'TCPMSS', '--clamp-mss-to-pmtu'], capture_output=True)
subprocess.run(['iptables', '-t', 'mangle', '-I', 'FORWARD', '1', '-p', 'tcp', '--tcp-flags', 'SYN,RST', 'SYN', '-o', iface, '-j', 'TCPMSS', '--clamp-mss-to-pmtu'], capture_output=True)
# Permettre à la machine locale de router du trafic via l'interface VPN (pour vérification IP publique, ping, etc.)
rule_prio = 9800 + pid * 2
subprocess.run(['ip', 'rule', 'del', 'priority', str(rule_prio)], capture_output=True)
subprocess.run(['ip', 'rule', 'del', 'priority', str(rule_prio + 1)], capture_output=True)
subprocess.run(['ip', 'rule', 'add', 'oif', iface, 'lookup', str(table_id), 'priority', str(rule_prio)], capture_output=True)
time.sleep(0.3)
try:
r_ip = subprocess.run(['ip', '-4', '-o', 'addr', 'show', 'dev', iface], capture_output=True, text=True)
if r_ip.returncode == 0:
m_ip = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+)', r_ip.stdout)
if m_ip:
subprocess.run(['ip', 'rule', 'add', 'from', m_ip.group(1), 'lookup', str(table_id), 'priority', str(rule_prio + 1)], capture_output=True)
except Exception: pass
c = db()
c.execute('UPDATE vpn_profiles SET status="connected", last_error="", iface=? WHERE id=?', (iface, pid))
c.commit(); c.close()
log('vpn_connect', f"Connexion VPN : {prof['name']} ({vtype})", caller_ip or 'SYSTEM', 'VPN')
sync_vpn_client_rules()
try:
vtype_label = "WireGuard" if vtype == "wireguard" else "OpenVPN"
vars_dict = {
"name": prof['name'],
"vpn": prof['name'],
"profil": prof['name'],
"type": vtype_label,
"iface": iface,
"date": datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')
}
dispatch_notification(
'vpn_profile_connected',
title=f"🛡️ Tunnel VPN connecté : {prof['name']}",
message=f"Le profil VPN « {prof['name']} » ({vtype_label}) est désormais connecté avec succès (interface {iface}).",
details=f"Profil: {prof['name']} | Type: {vtype_label} | Interface: {iface}",
vars_dict=vars_dict
)
except Exception as e_notif:
print(f"[ap-vpn] Erreur notification connexion profil : {e_notif}", flush=True)
# Purge conntrack immédiate pour les clients associés afin que le trafic bascule instantanément vers ce tunnel
try:
c_pur = db()
assigned_macs = [r[0] for r in c_pur.execute('SELECT mac FROM client_vpn_routes WHERE profile_id=?', (pid,)).fetchall()]
c_pur.close()
mac_to_ip = get_all_mac_to_ips()
for mac in assigned_macs:
ip = mac_to_ip.get(mac.upper(), '')
if ip and ip not in ('', 'Non attribuée', '—'):
subprocess.run(['conntrack', '-D', '-s', ip], capture_output=True)
subprocess.run(['conntrack', '-D', '-d', ip], capture_output=True)
subprocess.run(['ip', 'neigh', 'flush', 'to', ip], capture_output=True)
except Exception: pass
subprocess.run(['ip', 'route', 'flush', 'cache'], capture_output=True)
# Lancer immédiatement en tâche de fond la vérification de l'IP publique
def _check_ip_bg():
time.sleep(1.0)
get_vpn_public_ip(iface, force_refresh=True)
threading.Thread(target=_check_ip_bg, daemon=True).start()
return True, f"Profil {prof['name']} connecté avec succès"
except Exception as e:
err_msg = str(e)
c = db()
c.execute('UPDATE vpn_profiles SET status="error", last_error=? WHERE id=?', (err_msg, pid))
c.commit(); c.close()
return False, f"Erreur de connexion : {err_msg}"
finally:
with connecting_vpn_pids_lock:
connecting_vpn_pids.discard(pid)
def disconnect_vpn_profile(pid, caller_ip=''):
prof = get_vpn_profile(pid)
if not prof: return False, 'Profil VPN introuvable'
table_id = prof['table_id'] or (100 + pid)
vtype = prof['type']
iface = prof['iface'] or (f"wg_ap{pid}" if vtype == "wireguard" else f"tun_ap{pid}")
try:
if vtype == 'wireguard':
subprocess.run(['wg-quick', 'down', iface], capture_output=True)
subprocess.run(['ip', 'link', 'delete', 'dev', iface], capture_output=True)
elif vtype == 'openvpn':
pid_file = f"{VPN_RUN_DIR}/{iface}.pid"
if os.path.exists(pid_file):
try:
with open(pid_file) as pf: p_id = pf.read().strip()
if p_id: subprocess.run(['kill', '-9', p_id], capture_output=True)
except Exception: pass
try: os.remove(pid_file)
except OSError: pass
subprocess.run(['pkill', '-f', f"ovpn_ap{pid}"], capture_output=True)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
subprocess.run(['ip', 'link', 'delete', 'dev', iface], capture_output=True)
# Nettoyage iptables
subprocess.run(['iptables', '-t', 'nat', '-D', 'POSTROUTING', '-o', iface, '-j', 'MASQUERADE'], capture_output=True)
subprocess.run(['iptables', '-D', 'FORWARD', '-o', iface, '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-D', 'FORWARD', '-i', iface, '-m', 'state', '--state', 'RELATED,ESTABLISHED', '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-t', 'mangle', '-D', 'FORWARD', '-p', 'tcp', '--tcp-flags', 'SYN,RST', 'SYN', '-o', iface, '-j', 'TCPMSS', '--clamp-mss-to-pmtu'], capture_output=True)
subprocess.run(['ip', '-4', 'route', 'flush', 'table', str(table_id)], capture_output=True)
subprocess.run(['ip', '-6', 'route', 'flush', 'table', str(table_id)], capture_output=True)
# Nettoyage règles locales et cache IP
vpn_public_ip_cache.pop(iface, None)
subprocess.run(['ip', '-4', 'rule', 'del', 'oif', iface, 'lookup', str(table_id)], capture_output=True)
subprocess.run(['ip', '-6', 'rule', 'del', 'oif', iface, 'lookup', str(table_id)], capture_output=True)
try:
r_ip = subprocess.run(['ip', '-4', '-o', 'addr', 'show', 'dev', iface], capture_output=True, text=True)
if r_ip.returncode == 0:
m_ip = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+)', r_ip.stdout)
if m_ip:
subprocess.run(['ip', '-4', 'rule', 'del', 'from', m_ip.group(1), 'lookup', str(table_id)], capture_output=True)
except Exception: pass
try:
r_ip6 = subprocess.run(['ip', '-6', '-o', 'addr', 'show', 'dev', iface], capture_output=True, text=True)
if r_ip6.returncode == 0:
m_ip6 = re.search(r'inet6\s+([0-9a-fA-F:]+)', r_ip6.stdout)
if m_ip6:
subprocess.run(['ip', '-6', 'rule', 'del', 'from', m_ip6.group(1), 'lookup', str(table_id)], capture_output=True)
except Exception: pass
c = db()
c.execute('UPDATE vpn_profiles SET status="disconnected", last_error="" WHERE id=?', (pid,))
c.commit(); c.close()
log('vpn_disconnect', f"Déconnexion VPN : {prof['name']} ({vtype})", caller_ip or 'SYSTEM', 'VPN')
sync_vpn_client_rules()
try:
vtype_label = "WireGuard" if vtype == "wireguard" else "OpenVPN"
vars_dict = {
"name": prof['name'],
"vpn": prof['name'],
"profil": prof['name'],
"type": vtype_label,
"iface": iface,
"date": datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')
}
dispatch_notification(
'vpn_profile_disconnected',
title=f"⚠️ Tunnel VPN déconnecté : {prof['name']}",
message=f"Le profil VPN « {prof['name']} » ({vtype_label}) a été déconnecté (interface {iface}).",
details=f"Profil: {prof['name']} | Type: {vtype_label} | Interface: {iface}",
vars_dict=vars_dict
)
except Exception as e_notif:
print(f"[ap-vpn] Erreur notification déconnexion profil : {e_notif}", flush=True)
# Purge conntrack immédiate pour tous les clients du profil désactivé
try:
c_pur = db()
assigned_macs = [r[0] for r in c_pur.execute('SELECT mac FROM client_vpn_routes WHERE profile_id=?', (pid,)).fetchall()]
active_left = c_pur.execute('SELECT COUNT(*) FROM vpn_profiles WHERE status="connected" AND id != ?', (pid,)).fetchone()[0]
c_pur.close()
mac_to_ip = get_all_mac_to_ips()
for mac in assigned_macs:
ip = mac_to_ip.get(mac.upper(), '')
if ip and ip not in ('', 'Non attribuée', '—'):
subprocess.run(['conntrack', '-D', '-s', ip], capture_output=True)
subprocess.run(['conntrack', '-D', '-d', ip], capture_output=True)
subprocess.run(['ip', 'neigh', 'flush', 'to', ip], capture_output=True)
if active_left == 0:
# Tous les profils VPN sont désormais désactivés : purge conntrack complète
subprocess.run(['conntrack', '-F'], capture_output=True)
except Exception: pass
subprocess.run(['ip', 'route', 'flush', 'cache'], capture_output=True)
return True, f"Profil {prof['name']} déconnecté"
except Exception as e:
c = db()
c.execute('UPDATE vpn_profiles SET status="disconnected", last_error=? WHERE id=?', (str(e), pid))
c.commit(); c.close()
sync_vpn_client_rules()
try:
subprocess.run(['conntrack', '-F'], capture_output=True)
subprocess.run(['ip', 'route', 'flush', 'cache'], capture_output=True)
except Exception: pass
return False, str(e)
def list_vpn_clients():
all_devs = all_devices().get('devices', [])
c = db()
routes = {row[0].upper(): {'profile_id': row[1], 'kill_switch': row[2]}
for row in c.execute('SELECT mac, profile_id, kill_switch FROM client_vpn_routes').fetchall()}
profiles = {row[0]: {'id': row[0], 'name': row[1], 'type': row[2], 'status': row[3], 'iface': row[4]}
for row in c.execute('SELECT id, name, type, status, iface FROM vpn_profiles').fetchall()}
c.close()
seen_macs = set()
result = []
for d in all_devs:
mac = (d.get('mac') or '').upper()
if not mac or mac in seen_macs: continue
seen_macs.add(mac)
route = routes.get(mac, {'profile_id': 0, 'kill_switch': 0})
pid = route['profile_id']
prof = profiles.get(pid)
is_conn = bool(d.get('connected'))
eff_status = 'direct'
if pid > 0 and prof:
is_connected = (prof['status'] == 'connected' and is_iface_up(prof['iface']))
if is_connected:
eff_status = 'routed' if is_conn else 'offline'
else:
if is_conn:
eff_status = 'blocked' if route['kill_switch'] else 'direct_fallback'
else:
eff_status = 'offline'
elif pid > 0 and not prof:
eff_status = 'direct'
pid = 0
elif not is_conn:
eff_status = 'offline'
raw_ip = d.get('ip') or ''
ip_val = '' if raw_ip in ('Non attribuée', '—') else raw_ip
result.append({
'mac': mac,
'ip': ip_val,
'name': d.get('name') or ('Client ' + mac.replace(':', '')[-4:]),
'online': is_conn,
'device_type': d.get('device_type') or 'generic',
'profile_id': pid,
'profile_name': prof['name'] if (pid > 0 and prof) else 'Connexion directe (Sans VPN)',
'profile_type': prof['type'] if (pid > 0 and prof) else '',
'profile_status': prof['status'] if (pid > 0 and prof) else '',
'kill_switch': route['kill_switch'],
'routing_status': eff_status,
'lan_isolated': (eff_status == 'routed')
})
for mac, route in routes.items():
if mac in seen_macs: continue
seen_macs.add(mac)
pid = route['profile_id']
prof = profiles.get(pid)
result.append({
'mac': mac,
'ip': '',
'name': 'Client ' + mac.replace(':', '')[-4:],
'online': False,
'device_type': 'generic',
'profile_id': pid,
'profile_name': prof['name'] if (pid > 0 and prof) else 'Connexion directe (Sans VPN)',
'profile_type': prof['type'] if (pid > 0 and prof) else '',
'profile_status': prof['status'] if (pid > 0 and prof) else '',
'kill_switch': route['kill_switch'],
'routing_status': 'offline',
'lan_isolated': False
})
def _vpn_client_sort(c):
conn_rank = 0 if c['online'] else 1
routed_rank = 0 if c['profile_id'] > 0 else 1
return (conn_rank, routed_rank, c['name'].lower())
result.sort(key=_vpn_client_sort)
return result
def assign_client_vpn(mac, profile_id, kill_switch):
mac = (mac or '').strip().upper()
if not mac: return
now = time.strftime('%Y-%m-%d %H:%M:%S')
c = db()
c.execute('INSERT OR REPLACE INTO client_vpn_routes (mac, profile_id, kill_switch, updated_at) VALUES (?, ?, ?, ?)',
(mac, int(profile_id), 1 if kill_switch else 0, now))
c.commit()
prof_name = 'Direct WAN (Sans VPN)'
if int(profile_id) > 0:
row = c.execute('SELECT name FROM vpn_profiles WHERE id=?', (profile_id,)).fetchone()
if row: prof_name = row[0]
c_name_row = c.execute('SELECT name, last_ip FROM client_names WHERE mac=?', (mac,)).fetchone()
c.close()
dev_name = c_name_row[0] if c_name_row else 'Appareil Wi-Fi'
client_ip = (c_name_row[1] if c_name_row and c_name_row[1] != 'Non attribuée' else '') or station_live_ips.get(mac, '')
# 1. Appliquer immédiatement les règles de brouting, ip rule et iptables
sync_vpn_client_rules()
# 2. Vider les connexions conntrack existantes pour ce client afin que la bascule soit instantanée
if client_ip and client_ip not in ('', 'Non attribuée', '—'):
subprocess.run(['conntrack', '-D', '-s', client_ip], capture_output=True)
subprocess.run(['conntrack', '-D', '-d', client_ip], capture_output=True)
subprocess.run(['ip', 'neigh', 'flush', 'to', client_ip], capture_output=True)
subprocess.run(['ip', 'route', 'flush', 'cache'], capture_output=True)
# 3. Journaliser le changement de profil VPN
ks_info = " (Kill-Switch: Actif)" if kill_switch else ""
log('vpn_route', f"Routage VPN : {prof_name}{ks_info}", client_ip or 'Non attribuée', mac)
# 4. Notification d'alerte connexion / déconnexion VPN client
if int(profile_id) > 0:
dispatch_notification(
'vpn_client_connected',
"🛡️ Client routé via VPN",
f"L'appareil « {dev_name} » ({client_ip or mac}) est désormais connecté et routé via le VPN « {prof_name} ».",
details={"Nom": dev_name, "IP": client_ip or "—", "MAC": mac, "Profil VPN": prof_name, "Kill-Switch": "Actif" if kill_switch else "Désactivé", "Date": now},
priority=5,
level="success",
vars_dict={"name": dev_name, "ip": client_ip or "—", "mac": mac, "vpn": prof_name, "date": now}
)
else:
dispatch_notification(
'vpn_client_disconnected',
"🌐 Client déconnecté du VPN",
f"L'appareil « {dev_name} » ({client_ip or mac}) n'est plus routé via le VPN (connexion directe WAN).",
details={"Nom": dev_name, "IP": client_ip or "—", "MAC": mac, "Date": now},
priority=4,
level="info",
vars_dict={"name": dev_name, "ip": client_ip or "—", "mac": mac, "vpn": "Direct WAN", "date": now}
)
def get_local_lan_subnets():
subnets = []
host_ips = []
try:
import ipaddress
# 1. Interfaces principales (pont et Wi-Fi)
for dev in [INTERFACE, get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0')), 'br0', 'eth0']:
if not dev: continue
try:
ip_cidr, _, _ = get_iface_ip_info(dev)
if ip_cidr and '/' in ip_cidr:
iface_obj = ipaddress.IPv4Interface(ip_cidr)
if iface_obj.network.prefixlen >= 16:
subnets.append(str(iface_obj.network))
host_ips.append(str(iface_obj.ip))
except Exception: pass
# 2. Interfaces système locales
r = subprocess.run(['ip', '-4', '-o', 'addr', 'show'], capture_output=True, text=True)
if r.returncode == 0:
for line in r.stdout.splitlines():
parts = line.split()
if len(parts) >= 4:
d = parts[1]
c = parts[3]
if not d.startswith(('wg_', 'tun_', 'ovpn_', 'lo')):
try:
iface_obj = ipaddress.IPv4Interface(c)
if iface_obj.network.prefixlen >= 16 and iface_obj.is_private:
subnets.append(str(iface_obj.network))
host_ips.append(str(iface_obj.ip))
except Exception: pass
except Exception: pass
subnets = list(dict.fromkeys(subnets))
host_ips = list(dict.fromkeys(host_ips))
if not subnets:
subnets = ['10.42.0.0/24', '192.168.1.0/24']
return subnets, host_ips
def get_all_mac_to_ips():
"""Détecte de manière exhaustive l'adresse IP associée à chaque adresse MAC sans appeler clients()."""
mac_to_ip = {}
for m, ip in station_live_ips.items():
if m and ip and ip not in ('Non attribuée', '—'):
mac_to_ip[m.upper()] = ip
try:
r = subprocess.run(['ip', 'neigh', 'show'], capture_output=True, text=True, timeout=1)
if r.returncode == 0:
for line in r.stdout.splitlines():
m = re.search(r'^(\S+).*?lladdr ([0-9a-f:]{17})', line, re.I)
if m and 'FAILED' not in line:
nip = m.group(1)
nmac = m.group(2).upper()
if nmac not in mac_to_ip and not nip.startswith('127.'):
mac_to_ip[nmac] = nip
except Exception: pass
try:
for l_mac, l_ip, _ in lease_entries():
if l_mac and l_ip and l_mac not in mac_to_ip:
mac_to_ip[l_mac.upper()] = l_ip
except Exception: pass
try:
c = db()
for row in c.execute('SELECT mac, last_ip FROM client_names').fetchall():
m = (row[0] or '').upper()
ip = row[1] or ''
if m and ip and m not in mac_to_ip and ip not in ('Non attribuée', '—'):
mac_to_ip[m] = ip
for row in c.execute('SELECT mac, ip FROM connection_logs ORDER BY id DESC LIMIT 100').fetchall():
m = (row[0] or '').upper()
ip = row[1] or ''
if m and ip and m not in mac_to_ip and ip not in ('Non attribuée', '—'):
mac_to_ip[m] = ip
c.close()
except Exception: pass
return mac_to_ip
_last_broute_log_sig = None
def _cleanup_ebtables_vpn():
"""Nettoie proprement nos règles ebtables (chaîne dédiée AP_VPN_NAT en table nat + BROUTING en table broute)."""
for eb in [b for b in (find_bin('ebtables'), find_bin('ebtables-legacy')) if b]:
if os.path.exists('/sys/module/ebtable_broute'):
subprocess.run([eb, '-t', 'broute', '-F', 'BROUTING'], capture_output=True)
while subprocess.run([eb, '-t', 'nat', '-D', 'PREROUTING', '-j', 'AP_VPN_NAT'], capture_output=True).returncode == 0:
pass
subprocess.run([eb, '-t', 'nat', '-F', 'AP_VPN_NAT'], capture_output=True)
subprocess.run([eb, '-t', 'nat', '-X', 'AP_VPN_NAT'], capture_output=True)
def setup_nftables_broute(assigned_macs, local_subnets=None):
"""Active le détournement L2->L3 (mode Pont uniquement) via nftables (meta broute ou ether daddr + pkttype host) avec repli automatique sur ebtables -t nat redirect."""
global _last_broute_log_sig
nft_bin = find_bin('nft')
if not assigned_macs or not is_bridge_mode():
# Aucun client assigné à un VPN ou mode AP (pas de pont) : supprimer les tables pour ne jamais interférer avec l'hôte
if nft_bin:
subprocess.run([nft_bin, 'delete', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
_cleanup_ebtables_vpn()
_last_broute_log_sig = None
return True
for mod in ['nf_tables', 'nft_meta_bridge', 'nft_compat']:
subprocess.run(['modprobe', mod], capture_output=True)
# Obtenir la liste des MACs bloquées (quota dépassé ou blocage manuel) pour ne JAMAIS les router
blocked_macs = set()
try:
blocked_macs.update(blocked_set())
lims = get_client_limits_dict() or {}
for m, l in lims.items():
if l.get('quota_exceeded'):
blocked_macs.add(m.upper())
except Exception: pass
b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0')) or 'br0'
br_mac = ''
try:
br_mac_path = f'/sys/class/net/{b_name}/address'
if os.path.exists(br_mac_path):
br_mac = open(br_mac_path).read().strip().lower()
except OSError:
pass
nft_ok = False
nft_mode = ''
if nft_bin:
subprocess.run([nft_bin, 'add', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
subprocess.run([nft_bin, 'flush', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
r_ch = subprocess.run([nft_bin, 'add', 'chain', 'bridge', 'ap_vpn_broute', 'prerouting', '{ type filter hook prerouting priority -300; policy accept; }'], capture_output=True, text=True)
if r_ch.returncode == 0:
# 1. Exemptions ABSOLUES du détournement L2 :
# DHCP (ports 67/68 UDP) et Broadcast (ff:ff:ff:ff:ff:ff et 255.255.255.255).
# Ces paquets DOIVENT être bridgés en L2 pour que les clients reçoivent leur IP locale de la box !
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'daddr', 'ff:ff:ff:ff:ff:ff', 'accept'], capture_output=True)
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'type', 'ip', 'udp', 'dport', '67-68', 'accept'], capture_output=True)
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'type', 'ip', 'udp', 'sport', '67-68', 'accept'], capture_output=True)
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'type', 'ip', 'ip', 'daddr', '255.255.255.255', 'accept'], capture_output=True)
nft_ok = True
for mac in assigned_macs:
clean_mac = mac.strip().lower()
if not clean_mac: continue
if mac.strip().upper() in blocked_macs:
# Client bloqué : DROP absolu, pas de routage VPN !
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting',
'ether', 'saddr', clean_mac, 'drop'], capture_output=True)
continue
# Essai 1 : meta broute set 1 + meta pkttype set host (noyaux avec CONFIG_NFT_BRIDGE_META)
cmd_v4_1 = [nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting',
'ether', 'saddr', clean_mac, 'ether', 'type', 'ip',
'meta', 'broute', 'set', '1', 'meta', 'pkttype', 'set', 'host', 'accept']
res = subprocess.run(cmd_v4_1, capture_output=True, text=True)
if res.returncode == 0:
nft_mode = 'nftables (meta broute + pkttype host)'
else:
# Essai 2 : réécriture ether daddr vers MAC du pont + meta pkttype set host (sans meta broute, compatible Raspberry Pi OS sans CONFIG_NFT_BRIDGE_META)
res2 = None
if br_mac:
cmd_v4_2 = [nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting',
'ether', 'saddr', clean_mac, 'ether', 'type', 'ip',
'ether', 'daddr', 'set', br_mac, 'meta', 'pkttype', 'set', 'host', 'accept']
res2 = subprocess.run(cmd_v4_2, capture_output=True, text=True)
if res2 is not None and res2.returncode == 0:
nft_mode = f'nftables (ether daddr {br_mac} + pkttype host)'
else:
nft_ok = False
break
# Bloquer les fuites IPv6 pour forcer la bascule complète en IPv4 via le VPN
cmd_v6 = [nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting',
'ether', 'saddr', clean_mac, 'ether', 'type', 'ip6', 'drop']
subprocess.run(cmd_v6, capture_output=True)
if not nft_ok:
subprocess.run([nft_bin, 'delete', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
if nft_ok:
_cleanup_ebtables_vpn()
sig = ('nft', nft_mode, tuple(sorted(m.strip().lower() for m in assigned_macs if m.strip())), tuple(sorted(blocked_macs)))
if sig != _last_broute_log_sig:
_last_broute_log_sig = sig
print(f"[ap-vpn] [NFTABLES] Détournement L2->L3 actif via {nft_mode} pour {len(assigned_macs)} client(s).", flush=True)
return True
# Essai 3 : ebtables -t nat PREROUTING -j redirect --redirect-target ACCEPT (valide sous ebtables-nft v1.8.11 ET ebtables-legacy, sans table broute)
for mod in ['ebtable_nat', 'ebt_redirect']:
subprocess.run(['modprobe', mod], capture_output=True)
eb_candidates = []
for name in ('ebtables', 'ebtables-legacy'):
b = find_bin(name)
if b and b not in eb_candidates:
eb_candidates.append(b)
last_err = ''
for eb in eb_candidates:
while subprocess.run([eb, '-t', 'nat', '-D', 'PREROUTING', '-j', 'AP_VPN_NAT'], capture_output=True).returncode == 0:
pass
subprocess.run([eb, '-t', 'nat', '-N', 'AP_VPN_NAT', '-P', 'RETURN'], capture_output=True)
r_fl = subprocess.run([eb, '-t', 'nat', '-F', 'AP_VPN_NAT'], capture_output=True, text=True)
if r_fl.returncode != 0:
last_err = (r_fl.stderr or '').strip()
continue
subprocess.run([eb, '-t', 'nat', '-A', 'AP_VPN_NAT', '-d', 'Broadcast', '-j', 'RETURN'], capture_output=True)
subprocess.run([eb, '-t', 'nat', '-A', 'AP_VPN_NAT', '-p', 'IPv4', '--ip-proto', 'udp', '--ip-dport', '67:68', '-j', 'RETURN'], capture_output=True)
subprocess.run([eb, '-t', 'nat', '-A', 'AP_VPN_NAT', '-p', 'IPv4', '--ip-proto', 'udp', '--ip-sport', '67:68', '-j', 'RETURN'], capture_output=True)
subprocess.run([eb, '-t', 'nat', '-A', 'AP_VPN_NAT', '-p', 'IPv4', '--ip-dst', '255.255.255.255', '-j', 'RETURN'], capture_output=True)
eb_ok = True
for mac in assigned_macs:
clean_mac = mac.strip().lower()
if not clean_mac: continue
if mac.strip().upper() in blocked_macs:
subprocess.run([eb, '-t', 'nat', '-A', 'AP_VPN_NAT', '-s', clean_mac, '-j', 'DROP'], capture_output=True)
continue
r_v4 = subprocess.run([eb, '-t', 'nat', '-A', 'AP_VPN_NAT', '-p', 'IPv4', '-s', clean_mac, '-j', 'redirect', '--redirect-target', 'ACCEPT'], capture_output=True, text=True)
if r_v4.returncode != 0:
eb_ok = False
last_err = (r_v4.stderr or '').strip()
break
subprocess.run([eb, '-t', 'nat', '-A', 'AP_VPN_NAT', '-p', 'IPv6', '-s', clean_mac, '-j', 'DROP'], capture_output=True)
if eb_ok:
r_jmp = subprocess.run([eb, '-t', 'nat', '-I', 'PREROUTING', '1', '-j', 'AP_VPN_NAT'], capture_output=True, text=True)
if r_jmp.returncode == 0:
sig = ('ebtables-nat', os.path.basename(eb), tuple(sorted(m.strip().lower() for m in assigned_macs if m.strip())), tuple(sorted(blocked_macs)))
if sig != _last_broute_log_sig:
_last_broute_log_sig = sig
print(f"[ap-vpn] [EBTABLES-NAT] Détournement L2->L3 actif ({os.path.basename(eb)} -t nat redirect) pour {len(assigned_macs)} client(s).", flush=True)
return True
last_err = (r_jmp.stderr or '').strip()
subprocess.run([eb, '-t', 'nat', '-F', 'AP_VPN_NAT'], capture_output=True)
subprocess.run([eb, '-t', 'nat', '-X', 'AP_VPN_NAT'], capture_output=True)
# Essai 4 : ebtables-legacy -t broute (ultime repli si uniquement le moteur legacy est présent)
eb_leg = find_bin('ebtables-legacy')
if eb_leg:
subprocess.run(['modprobe', 'ebtable_broute'], capture_output=True)
r_fl = subprocess.run([eb_leg, '-t', 'broute', '-F', 'BROUTING'], capture_output=True, text=True)
if r_fl.returncode == 0:
subprocess.run([eb_leg, '-t', 'broute', '-A', 'BROUTING', '-d', 'Broadcast', '-j', 'ACCEPT'], capture_output=True)
subprocess.run([eb_leg, '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv4', '--ip-proto', 'udp', '--ip-dport', '67:68', '-j', 'ACCEPT'], capture_output=True)
subprocess.run([eb_leg, '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv4', '--ip-proto', 'udp', '--ip-sport', '67:68', '-j', 'ACCEPT'], capture_output=True)
subprocess.run([eb_leg, '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv4', '--ip-dst', '255.255.255.255', '-j', 'ACCEPT'], capture_output=True)
leg_ok = True
for mac in assigned_macs:
clean_mac = mac.strip().lower()
if not clean_mac: continue
if mac.strip().upper() in blocked_macs:
subprocess.run([eb_leg, '-t', 'broute', '-A', 'BROUTING', '-s', clean_mac, '-j', 'DROP'], capture_output=True)
continue
r_v4 = subprocess.run([eb_leg, '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv4', '-s', clean_mac, '-j', 'redirect', '--redirect-target', 'DROP'], capture_output=True, text=True)
if r_v4.returncode != 0:
leg_ok = False
last_err = (r_v4.stderr or '').strip()
break
subprocess.run([eb_leg, '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv6', '-s', clean_mac, '-j', 'DROP'], capture_output=True)
if leg_ok:
sig = ('ebtables-legacy', 'broute', tuple(sorted(m.strip().lower() for m in assigned_macs if m.strip())), tuple(sorted(blocked_macs)))
if sig != _last_broute_log_sig:
_last_broute_log_sig = sig
print(f"[ap-vpn] [EBTABLES-LEGACY] Broute actif pour {len(assigned_macs)} client(s).", flush=True)
return True
subprocess.run([eb_leg, '-t', 'broute', '-F', 'BROUTING'], capture_output=True)
sig = ('err', last_err)
if sig != _last_broute_log_sig:
_last_broute_log_sig = sig
print(f"[ap-vpn] Avertissement détournement L2->L3 (mode Pont) : {last_err or 'aucun moteur L2 compatible'}", flush=True)
return False
def sync_vpn_client_rules():
with vpn_lock:
try:
c = db()
profiles = {row[0]: {'id': row[0], 'status': row[1], 'table_id': row[2], 'iface': row[3], 'name': row[4]}
for row in c.execute('SELECT id, status, table_id, iface, name FROM vpn_profiles').fetchall()}
client_routes = {row[0].upper(): {'profile_id': row[1], 'kill_switch': row[2]}
for row in c.execute('SELECT mac, profile_id, kill_switch FROM client_vpn_routes').fetchall()}
c.close()
assigned_macs = [mac for mac, rinfo in client_routes.items() if rinfo.get('profile_id', 0) > 0]
connected_profiles = [p for p in profiles.values() if p['status'] == 'connected' and is_iface_up(p.get('iface', ''))]
# Si aucun appareil n'est routé et aucun VPN n'est actif, désactiver toutes les chaînes pour ne pas impacter l'hôte
if not assigned_macs and not connected_profiles:
while subprocess.run(['iptables', '-D', 'INPUT', '-j', 'AP_VPN_INPUT'], capture_output=True).returncode == 0: pass
subprocess.run(['iptables', '-F', 'AP_VPN_INPUT'], capture_output=True)
while subprocess.run(['iptables', '-D', 'FORWARD', '-j', 'AP_VPN_ISOLATION'], capture_output=True).returncode == 0: pass
subprocess.run(['iptables', '-F', 'AP_VPN_ISOLATION'], capture_output=True)
while subprocess.run(['iptables', '-t', 'nat', '-D', 'PREROUTING', '-j', 'AP_VPN_DNS'], capture_output=True).returncode == 0: pass
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)
_cleanup_ebtables_vpn()
nft_b = find_bin('nft')
if nft_b: subprocess.run([nft_b, 'delete', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
return
# 1. Nettoyage des anciennes règles ip rule (plage 9900 - 29999)
r = subprocess.run(['ip', 'rule', 'show'], capture_output=True, text=True, timeout=2)
if r.returncode == 0:
for line in r.stdout.splitlines():
m = re.match(r"^\s*(\d+):", line)
if m:
prio = int(m.group(1))
if 9900 <= prio <= 29999:
for _ in range(5):
if subprocess.run(['ip', 'rule', 'del', 'priority', str(prio)], capture_output=True, timeout=2).returncode != 0:
break
# 2. Réinitialisation de la chaîne iptables mangle AP_VPN_MANGLE
subprocess.run(['iptables', '-t', 'mangle', '-N', 'AP_VPN_MANGLE'], capture_output=True)
subprocess.run(['iptables', '-t', 'mangle', '-F', 'AP_VPN_MANGLE'], capture_output=True)
subprocess.run(['iptables', '-t', 'mangle', '-D', 'PREROUTING', '-j', 'AP_VPN_MANGLE'], capture_output=True)
subprocess.run(['iptables', '-t', 'mangle', '-I', 'PREROUTING', '1', '-j', 'AP_VPN_MANGLE'], capture_output=True)
# Exemptions indispensables : broadcast et DHCP (maintien du bail IP)
subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-d', '255.255.255.255', '-j', 'RETURN'], capture_output=True)
subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-p', 'udp', '--dport', '67:68', '-j', 'RETURN'], capture_output=True)
subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-p', 'udp', '--sport', '67:68', '-j', 'RETURN'], capture_output=True)
# 3. Réinitialisation de la chaîne NAT DNS pour rediriger les requêtes DNS des clients VPN vers un DNS public (Cloudflare 1.1.1.1)
# afin d'éviter les fuites DNS locales (box) et de garantir la résolution sans toucher au LAN.
subprocess.run(['iptables', '-t', 'nat', '-N', 'AP_VPN_DNS'], capture_output=True)
subprocess.run(['iptables', '-t', 'nat', '-F', 'AP_VPN_DNS'], capture_output=True)
subprocess.run(['iptables', '-t', 'nat', '-D', 'PREROUTING', '-j', 'AP_VPN_DNS'], capture_output=True)
subprocess.run(['iptables', '-t', 'nat', '-I', 'PREROUTING', '1', '-j', 'AP_VPN_DNS'], capture_output=True)
# 4. Réinitialisation des chaînes de filtrage et d'isolation LAN stricte (FORWARD et INPUT)
subprocess.run(['iptables', '-N', 'AP_VPN_ISOLATION'], capture_output=True)
subprocess.run(['iptables', '-F', 'AP_VPN_ISOLATION'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-m', 'conntrack', '--ctstate', 'ESTABLISHED,RELATED', '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-p', 'udp', '--dport', '67:68', '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-p', 'udp', '--sport', '67:68', '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-N', 'AP_VPN_INPUT'], capture_output=True)
subprocess.run(['iptables', '-F', 'AP_VPN_INPUT'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-i', 'lo', '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-m', 'conntrack', '--ctstate', 'ESTABLISHED,RELATED', '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-p', 'udp', '--dport', '67:68', '-j', 'ACCEPT'], capture_output=True)
# 5. Détection des adresses IP des clients et réseaux locaux
mac_to_ip = get_all_mac_to_ips()
local_subnets, host_ips = get_local_lan_subnets()
priv_subnets = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '169.254.0.0/16']
all_isolated_subnets = list(dict.fromkeys(priv_subnets + local_subnets))
# Serveur DNS public cible pour les tunnels VPN (Cloudflare 1.1.1.1 ou premier DNS public configuré)
dns_target = '1.1.1.1'
dns_list = get_dns_servers()
if dns_list:
try:
import ipaddress
if not ipaddress.ip_address(dns_list[0]).is_private:
dns_target = dns_list[0]
except Exception: pass
# 6. Application du brouting L2 (uniquement en mode Pont) : nftables avec repli automatique sur ebtables
assigned_macs = [mac for mac, rinfo in client_routes.items() if rinfo.get('profile_id', 0) > 0]
setup_nftables_broute(assigned_macs)
prio_base = 10000
active_tables = set()
lan_ifaces = list(dict.fromkeys(['br0', 'eth0', 'eth1', 'enp0s3', 'enp1s0'] + ([INTERFACE] if INTERFACE else [])))
for mac, route_info in client_routes.items():
pid = route_info.get('profile_id', 0)
kill_switch = route_info.get('kill_switch', 0)
if pid <= 0: continue
prof = profiles.get(pid)
if not prof: continue
table_id = prof['table_id']
is_connected = (prof['status'] == 'connected' and is_iface_up(prof['iface']))
client_ip = mac_to_ip.get(mac, '')
if is_connected:
active_tables.add(table_id)
# A. Marquer les paquets par MAC et par IP dans iptables mangle
subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-m', 'mac', '--mac-source', mac, '-j', 'MARK', '--set-mark', str(table_id)], capture_output=True)
if client_ip:
subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-s', client_ip, '-j', 'MARK', '--set-mark', str(table_id)], capture_output=True)
# B. Redirection DNS transparente vers un serveur DNS public via le VPN
for proto in ('udp', 'tcp'):
if client_ip:
subprocess.run(['iptables', '-t', 'nat', '-A', 'AP_VPN_DNS', '-s', client_ip, '-p', proto, '--dport', '53', '-j', 'DNAT', '--to-destination', f'{dns_target}:53'], capture_output=True)
subprocess.run(['iptables', '-t', 'nat', '-A', 'AP_VPN_DNS', '-m', 'mac', '--mac-source', mac, '-p', proto, '--dport', '53', '-j', 'DNAT', '--to-destination', f'{dns_target}:53'], capture_output=True)
# C. Isolation stricte de l'hôte AP (INPUT) : le client VPN ne peut pas accéder à l'interface d'administration ou aux services hôte
if client_ip:
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-s', client_ip, '-j', 'DROP'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-m', 'mac', '--mac-source', mac, '-j', 'DROP'], capture_output=True)
# D. Règles de transfert et isolation LAN (FORWARD)
# 1. Autoriser la sortie vers l'interface VPN
if client_ip:
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-s', client_ip, '-o', prof['iface'], '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-m', 'mac', '--mac-source', mac, '-o', prof['iface'], '-j', 'ACCEPT'], capture_output=True)
# 2. Autoriser le retour depuis l'interface VPN
if client_ip:
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-i', prof['iface'], '-d', client_ip, '-j', 'ACCEPT'], capture_output=True)
# 3. INTERDICTION STRICTE d'accès à toutes les ressources du réseau local (sous-réseaux privés RFC1918 et LAN)
for sub in all_isolated_subnets:
if client_ip:
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-s', client_ip, '-d', sub, '-j', 'REJECT', '--reject-with', 'icmp-port-unreachable'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-m', 'mac', '--mac-source', mac, '-d', sub, '-j', 'REJECT', '--reject-with', 'icmp-port-unreachable'], capture_output=True)
# 4. Interdiction de sortir par les interfaces locales (br0, eth0, wlan)
for o_if in lan_ifaces:
if client_ip:
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-s', client_ip, '-o', o_if, '-j', 'DROP'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-m', 'mac', '--mac-source', mac, '-o', o_if, '-j', 'DROP'], capture_output=True)
# 5. Tout autre paquet provenant de ce client qui ne passe pas par l'interface VPN est rejeté
if client_ip:
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-s', client_ip, '-j', 'DROP'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-m', 'mac', '--mac-source', mac, '-j', 'DROP'], capture_output=True)
# E. Routage VPN par adresse IP dans ip rule (tout le trafic vers table_id, AUCUNE exemption LAN)
if client_ip:
subprocess.run(['ip', 'rule', 'add', 'from', client_ip, 'lookup', str(table_id), 'priority', str(prio_base)], capture_output=True)
prio_base += 1
if kill_switch:
subprocess.run(['ip', 'rule', 'add', 'from', client_ip, 'type', 'unreachable', 'priority', str(prio_base)], capture_output=True)
prio_base += 1
else:
if kill_switch:
# Tunnel VPN coupé et Kill-Switch actif : blocage absolu de tout le trafic
subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-m', 'mac', '--mac-source', mac, '-j', 'DROP'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-m', 'mac', '--mac-source', mac, '-j', 'DROP'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-m', 'mac', '--mac-source', mac, '-j', 'DROP'], capture_output=True)
if client_ip:
subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-s', client_ip, '-j', 'DROP'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-s', client_ip, '-j', 'DROP'], capture_output=True)
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-s', client_ip, '-j', 'DROP'], capture_output=True)
subprocess.run(['ip', 'rule', 'add', 'from', client_ip, 'type', 'unreachable', 'priority', str(prio_base)], capture_output=True)
prio_base += 1
# 8. Règles ip rule pour fwmark (garantit le routage par paquet marqué même si l'IP n'est pas encore enregistrée)
for tid in active_tables:
subprocess.run(['ip', 'rule', 'add', 'fwmark', str(tid), 'lookup', str(tid), 'priority', str(prio_base)], capture_output=True)
prio_base += 1
# 9. S'assurer que chaque interface VPN connectée a sa route default dans sa table et masquerade dans iptables
for pid, prof in profiles.items():
if prof['status'] == 'connected' and is_iface_up(prof['iface']):
subprocess.run(['ip', '-4', 'route', 'replace', 'default', 'dev', prof['iface'], 'table', str(prof['table_id'])], capture_output=True)
subprocess.run(['ip', '-6', 'route', 'replace', 'default', 'dev', prof['iface'], 'table', str(prof['table_id'])], capture_output=True)
subprocess.run(['iptables', '-t', 'nat', '-I', 'POSTROUTING', '1', '-o', prof['iface'], '-j', 'MASQUERADE'], capture_output=True)
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-o', prof['iface'], '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', prof['iface'], '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', 'br0', '-o', prof['iface'], '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', prof['iface'], '-o', 'br0', '-j', 'ACCEPT'], capture_output=True)
if INTERFACE:
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', INTERFACE, '-o', prof['iface'], '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', prof['iface'], '-o', INTERFACE, '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['iptables', '-t', 'mangle', '-I', 'FORWARD', '1', '-p', 'tcp', '--tcp-flags', 'SYN,RST', 'SYN', '-o', prof['iface'], '-j', 'TCPMSS', '--clamp-mss-to-pmtu'], capture_output=True)
# Permettre à l'hôte de communiquer via le VPN (oif)
subprocess.run(['ip', 'rule', 'add', 'oif', prof['iface'], 'lookup', str(prof['table_id']), 'priority', str(prio_base)], capture_output=True)
prio_base += 1
try:
r_ip = subprocess.run(['ip', '-4', '-o', 'addr', 'show', 'dev', prof['iface']], capture_output=True, text=True)
if r_ip.returncode == 0:
m_ip = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+)', r_ip.stdout)
if m_ip:
subprocess.run(['ip', 'rule', 'add', 'from', m_ip.group(1), 'lookup', str(prof['table_id']), 'priority', str(prio_base)], capture_output=True)
prio_base += 1
except Exception: pass
# 10. Positionner les chaînes d'isolation et d'interception DNS en première position absolue
subprocess.run(['iptables', '-D', 'FORWARD', '-j', 'AP_VPN_ISOLATION'], capture_output=True)
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-j', 'AP_VPN_ISOLATION'], capture_output=True)
subprocess.run(['iptables', '-D', 'INPUT', '-j', 'AP_VPN_INPUT'], capture_output=True)
subprocess.run(['iptables', '-I', 'INPUT', '1', '-j', 'AP_VPN_INPUT'], capture_output=True)
# 11. Purger conntrack pour les clients VPN assignés afin de couper immédiatement les flux LAN existants
for mac in assigned_macs:
c_ip = mac_to_ip.get(mac, '')
if c_ip and c_ip not in ('', 'Non attribuée', '—'):
subprocess.run(['conntrack', '-D', '-s', c_ip], capture_output=True)
subprocess.run(['conntrack', '-D', '-d', c_ip], capture_output=True)
# 12. Appliquer sysctl rp_filter=0 et forwarding partout
import glob
for p in glob.glob('/proc/sys/net/ipv4/conf/*/rp_filter'):
try:
with open(p, 'w') as f: f.write('0')
except Exception: pass
for p in glob.glob('/proc/sys/net/ipv4/conf/*/forwarding'):
try:
with open(p, 'w') as f: f.write('1')
except Exception: pass
for ifname in ['all', 'default', 'br0']:
subprocess.run(['sysctl', '-w', f'net.ipv4.conf.{ifname}.rp_filter=0'], capture_output=True)
if INTERFACE:
subprocess.run(['sysctl', '-w', f'net.ipv4.conf.{INTERFACE}.rp_filter=0'], capture_output=True)
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)
if os.path.exists('/sys/class/net/br0'):
subprocess.run(['sysctl', '-w', 'net.ipv4.conf.br0.forwarding=1'], capture_output=True)
print(f"[ap-vpn] Synchronisation des règles VPN terminée ({len(active_tables)} profil(s) actif(s), {len(assigned_macs)} client(s) routé(s) - Isolation LAN activée)", flush=True)
except Exception as e:
print(f"[ap-vpn] Erreur synchronisation règles : {e}", flush=True)
def auto_connect_vpn_profiles():
global app_startup_done
time.sleep(1.5)
# 1. Attendre que la route par défaut hôte/Internet soit prête (max 20s)
for _ in range(40):
r_gw = subprocess.run(['ip', 'route', 'show', 'default'], capture_output=True, text=True)
if r_gw.returncode == 0 and r_gw.stdout.strip():
break
time.sleep(0.5)
# 2. Attendre que la résolution DNS soit fonctionnelle (max 15s)
for _ in range(30):
try:
socket.getaddrinfo('one.one.one.one', 53, socket.AF_INET)
break
except Exception:
time.sleep(0.5)
try:
c = db()
rows = c.execute('SELECT id, name FROM vpn_profiles WHERE auto_connect = 1 ORDER BY id ASC').fetchall()
c.close()
total_auto = len(rows)
if total_auto == 0:
app_startup_done = True
return
for pid, name in rows:
print(f"[ap-vpn] Connexion automatique au démarrage du profil '{name}' (ID: {pid})...", flush=True)
for attempt in range(1, 4):
try:
ok, msg = connect_vpn_profile(pid)
if ok:
prof = get_vpn_profile(pid) or {}
vtype = prof.get('type', 'wireguard')
ifc = prof.get('iface') or (f"wg_ap{pid}" if vtype == "wireguard" else f"tun_ap{pid}")
up = False
for _ in range(30):
if is_iface_up(ifc):
up = True
break
time.sleep(0.2)
if up:
print(f"[ap-vpn] Profil '{name}' (ID: {pid}, {ifc}) connecté et actif.", flush=True)
get_vpn_public_ip(ifc, force_refresh=True)
break
print(f"[ap-vpn] Tentative {attempt}/3 pour '{name}' : {msg}", flush=True)
except Exception as e:
print(f"[ap-vpn] Exception tentative {attempt}/3 pour '{name}' : {e}", flush=True)
time.sleep(1.2)
time.sleep(0.5)
# Synchronisation globale complète de toutes les règles une fois tous les tunnels montés
sync_vpn_client_rules()
except Exception as e:
print(f"[ap-vpn] Erreur auto_connect_vpn_profiles : {e}", flush=True)
finally:
app_startup_done = True
print(f"[ap-vpn] Initialisation du démarrage terminée (app_startup_done = True)", flush=True)
def _mark_startup_done_safety():
time.sleep(180)
global app_startup_done
app_startup_done = True
threading.Thread(target=_mark_startup_done_safety, daemon=True).start()
def vpn_healthcheck_loop():
"""Effectue un test périodique de connectivité et rafraîchissement d'IP publique toutes les 5 minutes (300 s) en arrière-plan."""
time.sleep(25)
while True:
try:
c = db()
active_profs = c.execute('SELECT id, name, type, iface FROM vpn_profiles WHERE status = "connected"').fetchall()
c.close()
for pid, name, vtype, iface in active_profs:
iface = iface or (f"wg_ap{pid}" if vtype == "wireguard" else f"tun_ap{pid}")
if is_iface_up(iface):
ip = get_vpn_public_ip(iface, force_refresh=True)
ts = time.strftime('%H:%M:%S')
if ip:
print(f"[ap-vpn-check] [{ts}] Test réussi pour '{name}' ({iface}) : {ip}", flush=True)
else:
print(f"[ap-vpn-check] [{ts}] Échec test de connectivité pour '{name}' ({iface})", flush=True)
except Exception as e:
print(f"[ap-vpn-check] Erreur boucle test 5 min : {e}", flush=True)
time.sleep(300)
def get_iconify_ssl_contexts():
contexts = []
try:
contexts.append(ssl.create_default_context())
except Exception:
pass
try:
contexts.append(ssl._create_unverified_context())
except Exception:
pass
return contexts or [None]
def search_iconify_icons(query, limit=36):
q = (query or '').strip()
if not q:
return []
hosts = [
'https://api.iconify.design',
'https://api.simplesvg.com',
'https://api.unisvg.com'
]
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
'Accept': 'application/json'
}
for host in hosts:
for ctx in get_iconify_ssl_contexts():
try:
url = f"{host}/search?query={urllib.parse.quote(q)}&limit={limit}"
req = urllib.request.Request(url, headers=headers)
kwargs = {'timeout': 5}
if ctx:
kwargs['context'] = ctx
with urllib.request.urlopen(req, **kwargs) as resp:
if resp.status == 200:
raw = json.loads(resp.read().decode('utf-8'))
icons = raw.get('icons', [])
if icons:
return icons
except Exception:
continue
return []
def fetch_iconify_svg(clean_name, color=None):
clean_name = re.sub(r'[^a-zA-Z0-9_\-:/]', '', (clean_name or '').strip())
if not clean_name:
return ''
if ':' in clean_name:
prefix, name = clean_name.split(':', 1)
clean_path = f"{prefix}/{name}"
elif '/' in clean_name:
prefix, name = clean_name.split('/', 1)
clean_path = f"{prefix}/{name}"
else:
prefix = 'mdi'
name = clean_name
clean_path = f"mdi/{clean_name}"
is_emoji_set = any(prefix.lower().startswith(em) for em in ('noto', 'twemoji', 'openmoji', 'emojione', 'joypixels', 'fluent-emoji', 'fxemoji', 'streamline-emojis', 'blobmoji'))
hosts = [
'https://api.iconify.design',
'https://api.simplesvg.com',
'https://api.unisvg.com'
]
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
'Accept': 'image/svg+xml,application/json,*/*'
}
# 1. Essayer les endpoints SVG directs
for host in hosts:
for ctx in get_iconify_ssl_contexts():
try:
url = f"{host}/{clean_path}.svg"
if color and not is_emoji_set and color != 'currentColor':
url += f"?color={urllib.parse.quote(color)}"
req = urllib.request.Request(url, headers=headers)
kwargs = {'timeout': 5}
if ctx:
kwargs['context'] = ctx
with urllib.request.urlopen(req, **kwargs) as resp:
if resp.status == 200:
content = resp.read().decode('utf-8', errors='ignore')
if ''
except Exception:
continue
# 3. Fallback SVG garanti
fallback_color = color or '#38bdf8'
short_label = (name.split('-')[0] if '-' in name else name)[:6].upper()
return f''
_restore_data_lock = threading.Lock()
_restore_data_state = {
'running': False,
'step': 0,
'total_steps': 5,
'percent': 0,
'message': '',
'details': '',
'done': False,
'error': None
}
def _set_restore_progress(step, total_steps, percent, message, details='', done=False, error=None):
with _restore_data_lock:
_restore_data_state['running'] = not done and error is None
_restore_data_state['step'] = step
_restore_data_state['total_steps'] = total_steps
_restore_data_state['percent'] = percent
_restore_data_state['message'] = message
_restore_data_state['details'] = details
_restore_data_state['done'] = done
_restore_data_state['error'] = error
def export_backup_data():
c = db()
try:
preferences = dict(c.execute("SELECT key, value FROM preferences").fetchall())
vpn_profiles = []
for r in c.execute("SELECT id, name, type, config_content, auth_user, auth_pass, table_id, iface, auto_connect, created_at, updated_at FROM vpn_profiles").fetchall():
vpn_profiles.append({
'id': r[0], 'name': r[1], 'type': r[2], 'config_content': r[3],
'auth_user': r[4], 'auth_pass': r[5], 'table_id': r[6], 'iface': r[7],
'auto_connect': r[8], 'created_at': r[9], 'updated_at': r[10]
})
client_vpn_routes = []
for r in c.execute("SELECT r.mac, r.profile_id, r.kill_switch, r.updated_at, p.name FROM client_vpn_routes r LEFT JOIN vpn_profiles p ON p.id=r.profile_id").fetchall():
client_vpn_routes.append({
'mac': r[0], 'profile_id': r[1], 'kill_switch': r[2],
'updated_at': r[3], 'profile_name': r[4] or ''
})
client_names = []
for r in c.execute("SELECT mac, name, last_ip, last_seen, device_type FROM client_names").fetchall():
client_names.append({
'mac': r[0], 'name': r[1], 'last_ip': r[2], 'last_seen': r[3], 'device_type': r[4] or ''
})
custom_device_types = []
has_cdt = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='custom_device_types'").fetchone())
if has_cdt:
for r in c.execute("SELECT id, label, icon, desc, sort_order FROM custom_device_types ORDER BY sort_order ASC, id ASC").fetchall():
custom_device_types.append({
'id': r[0], 'label': r[1], 'icon': r[2], 'desc': r[3], 'sort_order': r[4]
})
blocked_clients = []
for r in c.execute("SELECT mac, blocked_at FROM blocked_clients").fetchall():
blocked_clients.append({
'mac': r[0], 'blocked_at': r[1]
})
auth_users = []
for r in c.execute("SELECT username, password_hash, totp_secret FROM auth_users").fetchall():
auth_users.append({
'username': r[0], 'password_hash': r[1], 'totp_secret': r[2]
})
auth_passkeys = []
has_pk = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='auth_passkeys'").fetchone())
if has_pk:
for r in c.execute("SELECT id, username, public_key, name, device_type, sign_count, created_at, last_used_at FROM auth_passkeys").fetchall():
auth_passkeys.append({
'id': r[0], 'username': r[1], 'public_key': r[2], 'name': r[3],
'device_type': r[4], 'sign_count': r[5], 'created_at': r[6], 'last_used_at': r[7]
})
api_keys = []
has_ak = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='api_keys'").fetchone())
if has_ak:
for r in c.execute("SELECT id, name, key_hash, prefix, permissions, created_at, expires_at, last_used_at, last_ip, is_active FROM api_keys").fetchall():
api_keys.append({
'id': r[0], 'name': r[1], 'key_hash': r[2], 'prefix': r[3],
'permissions': r[4], 'created_at': r[5], 'expires_at': r[6],
'last_used_at': r[7], 'last_ip': r[8], 'is_active': r[9]
})
client_traffic = []
for r in c.execute("SELECT mac, rx_bytes, tx_bytes, last_updated FROM client_traffic").fetchall():
client_traffic.append({
'mac': r[0], 'rx_bytes': r[1], 'tx_bytes': r[2], 'last_updated': r[3]
})
client_traffic_daily = []
for r in c.execute("SELECT mac, traffic_date, rx_bytes, tx_bytes FROM client_traffic_daily").fetchall():
client_traffic_daily.append({
'mac': r[0], 'traffic_date': r[1], 'rx_bytes': r[2], 'tx_bytes': r[3]
})
connection_logs = []
for r in c.execute("SELECT id, event_time, event, name, ip, mac FROM connection_logs ORDER BY id DESC LIMIT 150").fetchall():
connection_logs.append({
'id': r[0], 'event_time': r[1], 'event': r[2], 'name': r[3], 'ip': r[4], 'mac': r[5]
})
client_limits = []
has_cl = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='client_limits'").fetchone())
if has_cl:
for r in c.execute("SELECT mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, updated_at FROM client_limits").fetchall():
client_limits.append({
'mac': r[0], 'quota_enabled': r[1], 'quota_bytes': r[2], 'quota_period': r[3],
'bandwidth_enabled': r[4], 'rate_down_kbps': r[5], 'rate_up_kbps': r[6],
'quota_action': r[7], 'updated_at': r[8]
})
return {
'ap_manageur_backup': {
'version': '1.0',
'app_version': APP_VERSION,
'exported_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
'export_timestamp': int(time.time()),
'app_name': preferences.get('app_name', 'Administration de l’AP Wi‑Fi')
},
'preferences': preferences,
'vpn_profiles': vpn_profiles,
'client_vpn_routes': client_vpn_routes,
'client_names': client_names,
'custom_device_types': custom_device_types,
'client_limits': client_limits,
'blocked_clients': blocked_clients,
'auth_users': auth_users,
'auth_passkeys': auth_passkeys,
'api_keys': api_keys,
'client_traffic': client_traffic,
'client_traffic_daily': client_traffic_daily,
'connection_logs': connection_logs
}
finally:
c.close()
def import_backup_data(payload, options=None):
if options is None:
options = {}
if isinstance(payload, dict) and 'backup' in payload and isinstance(payload['backup'], dict):
backup = payload['backup']
options = {**options, **payload.get('options', {})}
elif isinstance(payload, dict):
backup = payload
else:
raise ValueError("Format de sauvegarde invalide (objet JSON attendu)")
restore_prefs = options.get('restore_preferences', True)
restore_vpn = options.get('restore_vpn', True)
restore_devices = options.get('restore_devices', True)
restore_blocked = options.get('restore_blocked', True)
restore_categories = options.get('restore_categories', True)
restore_auth = options.get('restore_auth', False)
restore_traffic = options.get('restore_traffic', True)
stats = {
'preferences': 0,
'vpn_profiles': 0,
'client_vpn_routes': 0,
'client_names': 0,
'custom_device_types': 0,
'blocked_clients': 0,
'auth_users': 0,
'auth_passkeys': 0
}
ensure_vpn_dirs()
c = db()
try:
_set_restore_progress(2, 5, 40, "Restauration des réglages & préférences...", "Application des réglages système et des catégories...")
time.sleep(0.35)
# 1. Catégories d'appareils
if restore_categories and 'custom_device_types' in backup and isinstance(backup['custom_device_types'], list):
for dt in backup['custom_device_types']:
dt_id = str(dt.get('id', '')).strip()
label = str(dt.get('label', '')).strip()
icon = str(dt.get('icon', '💻')).strip()
desc = str(dt.get('desc', '')).strip()
try: order = int(dt.get('sort_order', 0))
except (ValueError, TypeError): order = 0
if dt_id and label:
c.execute('''
INSERT INTO custom_device_types (id, label, icon, desc, sort_order)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
label=excluded.label,
icon=excluded.icon,
desc=excluded.desc,
sort_order=excluded.sort_order
''', (dt_id, label, icon, desc, order))
stats['custom_device_types'] += 1
_set_restore_progress(3, 5, 65, "Restauration des équipements & quotas...", "Enregistrement des appareils et quotas réseau...")
time.sleep(0.35)
# 2. Noms d'appareils & types
if restore_devices and 'client_names' in backup and isinstance(backup['client_names'], list):
for cn in backup['client_names']:
mac = str(cn.get('mac', '')).strip().upper()
name = str(cn.get('name', '')).strip()
last_ip = str(cn.get('last_ip', '')).strip()
last_seen = str(cn.get('last_seen', '')).strip()
device_type = str(cn.get('device_type', '')).strip()
if mac and name:
c.execute('''
INSERT INTO client_names (mac, name, last_ip, last_seen, device_type)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(mac) DO UPDATE SET
name=excluded.name,
last_ip=CASE WHEN excluded.last_ip != '' THEN excluded.last_ip ELSE client_names.last_ip END,
last_seen=CASE WHEN excluded.last_seen != '' THEN excluded.last_seen ELSE client_names.last_seen END,
device_type=CASE WHEN excluded.device_type != '' THEN excluded.device_type ELSE client_names.device_type END
''', (mac, name, last_ip, last_seen, device_type))
stats['client_names'] += 1
if 'client_limits' in backup and isinstance(backup['client_limits'], list):
for cl in backup['client_limits']:
mac = str(cl.get('mac', '')).strip().upper()
if mac:
c.execute('''
INSERT INTO client_limits (mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(mac) DO UPDATE SET
quota_enabled=excluded.quota_enabled,
quota_bytes=excluded.quota_bytes,
quota_period=excluded.quota_period,
bandwidth_enabled=excluded.bandwidth_enabled,
rate_down_kbps=excluded.rate_down_kbps,
rate_up_kbps=excluded.rate_up_kbps,
quota_action=excluded.quota_action,
updated_at=excluded.updated_at
''', (
mac, 1 if cl.get('quota_enabled') else 0, int(cl.get('quota_bytes', 0) or 0),
str(cl.get('quota_period', 'total')), 1 if cl.get('bandwidth_enabled') else 0,
int(cl.get('rate_down_kbps', 0) or 0), int(cl.get('rate_up_kbps', 0) or 0),
str(cl.get('quota_action', 'block')), str(cl.get('updated_at', ''))
))
try: sync_client_bandwidth_and_quotas(force=True)
except Exception: pass
# 3. Appareils bloqués
if restore_blocked and 'blocked_clients' in backup and isinstance(backup['blocked_clients'], list):
for bl in backup['blocked_clients']:
mac = str(bl.get('mac', '')).strip().upper()
b_at = str(bl.get('blocked_at', '')).strip() or time.strftime('%Y-%m-%d %H:%M:%S')
if mac:
c.execute('INSERT OR IGNORE INTO blocked_clients (mac, blocked_at) VALUES (?, ?)', (mac, b_at))
stats['blocked_clients'] += 1
try: command('iw', 'dev', INTERFACE, 'station', 'del', mac)
except Exception: pass
# 4. Préférences et réglages
if restore_prefs and 'preferences' in backup and isinstance(backup['preferences'], dict):
for k, v in backup['preferences'].items():
c.execute("INSERT INTO preferences(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (str(k), str(v)))
stats['preferences'] += 1
_set_restore_progress(4, 5, 85, "Restauration des profils VPN & routages...", "Configuration des tunnels et assignation du trafic...")
time.sleep(0.35)
# 5. Profils VPN et routage
if restore_vpn and 'vpn_profiles' in backup and isinstance(backup['vpn_profiles'], list):
profile_id_map = {}
for vp in backup['vpn_profiles']:
old_id = vp.get('id')
p_name = str(vp.get('name', 'Profil VPN')).strip()
p_type = str(vp.get('type', 'wireguard')).strip().lower()
if p_type not in ('wireguard', 'openvpn'): p_type = 'wireguard'
p_cfg = str(vp.get('config_content', '')).strip()
p_user = str(vp.get('auth_user', '')).strip()
p_pass = str(vp.get('auth_pass', '')).strip()
p_auto = 1 if vp.get('auto_connect') else 0
now_ts = time.strftime('%Y-%m-%d %H:%M:%S')
existing = c.execute('SELECT id FROM vpn_profiles WHERE name=?', (p_name,)).fetchone()
if existing:
cur_id = existing[0]
c.execute('''
UPDATE vpn_profiles SET
type=?, config_content=?, auth_user=?, auth_pass=?, auto_connect=?, updated_at=?
WHERE id=?
''', (p_type, p_cfg, p_user, p_pass, p_auto, now_ts, cur_id))
profile_id_map[old_id] = cur_id
profile_id_map[p_name] = cur_id
stats['vpn_profiles'] += 1
else:
table_id = get_next_vpn_table_id()
cur = c.execute('''
INSERT INTO vpn_profiles (name, type, config_content, auth_user, auth_pass, table_id, iface, auto_connect, status, last_error, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, "", ?, "disconnected", "", ?, ?)
''', (p_name, p_type, p_cfg, p_user, p_pass, table_id, p_auto, now_ts, now_ts))
new_pid = cur.lastrowid
iface = f"wg_ap{new_pid}" if p_type == "wireguard" else f"tun_ap{new_pid}"
c.execute('UPDATE vpn_profiles SET iface=? WHERE id=?', (iface, new_pid))
profile_id_map[old_id] = new_pid
profile_id_map[p_name] = new_pid
stats['vpn_profiles'] += 1
if 'client_vpn_routes' in backup and isinstance(backup['client_vpn_routes'], list):
for cr in backup['client_vpn_routes']:
mac = str(cr.get('mac', '')).strip().upper()
old_pid = cr.get('profile_id')
p_name = cr.get('profile_name')
kill_sw = 1 if cr.get('kill_switch') else 0
target_pid = profile_id_map.get(old_pid) or profile_id_map.get(p_name) or 0
if mac and target_pid:
now_ts = time.strftime('%Y-%m-%d %H:%M:%S')
c.execute('''
INSERT INTO client_vpn_routes (mac, profile_id, kill_switch, updated_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(mac) DO UPDATE SET
profile_id=excluded.profile_id,
kill_switch=excluded.kill_switch,
updated_at=excluded.updated_at
''', (mac, target_pid, kill_sw, now_ts))
stats['client_vpn_routes'] += 1
try: sync_vpn_client_rules()
except Exception: pass
# 6. Trafic (optionnel)
if restore_traffic and 'client_traffic' in backup and isinstance(backup['client_traffic'], list):
for ct in backup['client_traffic']:
mac = str(ct.get('mac', '')).strip().upper()
try:
rx = int(ct.get('rx_bytes', 0))
tx = int(ct.get('tx_bytes', 0))
except (ValueError, TypeError): rx, tx = 0, 0
lu = str(ct.get('last_updated', '')).strip()
if mac:
c.execute('''
INSERT INTO client_traffic (mac, rx_bytes, tx_bytes, last_updated)
VALUES (?, ?, ?, ?)
ON CONFLICT(mac) DO UPDATE SET
rx_bytes=MAX(client_traffic.rx_bytes, excluded.rx_bytes),
tx_bytes=MAX(client_traffic.tx_bytes, excluded.tx_bytes),
last_updated=excluded.last_updated
''', (mac, rx, tx, lu))
if 'client_traffic_daily' in backup and isinstance(backup['client_traffic_daily'], list):
for ctd in backup['client_traffic_daily']:
mac = str(ctd.get('mac', '')).strip().upper()
t_date = str(ctd.get('traffic_date', '')).strip()
try:
rx = int(ctd.get('rx_bytes', 0))
tx = int(ctd.get('tx_bytes', 0))
except (ValueError, TypeError): rx, tx = 0, 0
if mac and t_date:
c.execute('''
INSERT INTO client_traffic_daily (mac, traffic_date, rx_bytes, tx_bytes)
VALUES (?, ?, ?, ?)
ON CONFLICT(mac, traffic_date) DO UPDATE SET
rx_bytes=MAX(client_traffic_daily.rx_bytes, excluded.rx_bytes),
tx_bytes=MAX(client_traffic_daily.tx_bytes, excluded.tx_bytes)
''', (mac, t_date, rx, tx))
# 7. Authentification (si demandée explicitement)
if restore_auth and 'auth_users' in backup and isinstance(backup['auth_users'], list):
for u in backup['auth_users']:
uname = str(u.get('username', '')).strip()
phash = str(u.get('password_hash', '')).strip()
totp = u.get('totp_secret')
if uname and phash:
c.execute('''
INSERT INTO auth_users (username, password_hash, totp_secret)
VALUES (?, ?, ?)
ON CONFLICT(username) DO UPDATE SET
password_hash=excluded.password_hash,
totp_secret=excluded.totp_secret
''', (uname, phash, totp))
stats['auth_users'] += 1
if 'auth_passkeys' in backup and isinstance(backup['auth_passkeys'], list):
for pk in backup['auth_passkeys']:
pk_id = str(pk.get('id', '')).strip()
pk_uname = str(pk.get('username', '')).strip()
pk_key = str(pk.get('public_key', '')).strip()
pk_name = str(pk.get('name', '')).strip()
pk_dev = str(pk.get('device_type', 'security_key')).strip()
try: pk_count = int(pk.get('sign_count', 0))
except (ValueError, TypeError): pk_count = 0
pk_c_at = str(pk.get('created_at', '')).strip()
pk_u_at = str(pk.get('last_used_at', '')).strip()
if pk_id and pk_uname and pk_key:
c.execute('''
INSERT INTO auth_passkeys (id, username, public_key, name, device_type, sign_count, created_at, last_used_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
name=excluded.name,
sign_count=excluded.sign_count,
last_used_at=excluded.last_used_at
''', (pk_id, pk_uname, pk_key, pk_name, pk_dev, pk_count, pk_c_at, pk_u_at))
stats['auth_passkeys'] += 1
if 'api_keys' in backup and isinstance(backup['api_keys'], list):
for ak in backup['api_keys']:
ak_name = str(ak.get('name', '')).strip()
ak_hash = str(ak.get('key_hash', '')).strip()
ak_prefix = str(ak.get('prefix', '')).strip()
ak_perms = json.dumps(ak.get('permissions')) if isinstance(ak.get('permissions'), list) else str(ak.get('permissions', '[]'))
ak_c_at = str(ak.get('created_at', '')).strip() or time.strftime('%Y-%m-%d %H:%M:%S')
ak_exp = ak.get('expires_at')
ak_act = 1 if ak.get('is_active', 1) else 0
if ak_name and ak_hash and ak_prefix:
c.execute('''
INSERT INTO api_keys (name, key_hash, prefix, permissions, created_at, expires_at, is_active)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(key_hash) DO UPDATE SET
name=excluded.name,
prefix=excluded.prefix,
permissions=excluded.permissions,
expires_at=excluded.expires_at,
is_active=excluded.is_active
''', (ak_name, ak_hash, ak_prefix, ak_perms, ak_c_at, ak_exp, ak_act))
stats['api_keys'] = stats.get('api_keys', 0) + 1
c.commit()
_set_restore_progress(5, 5, 95, "Reconfiguration Wi-Fi & synchronisation...", "Finalisation de la configuration réseau...")
time.sleep(0.35)
finally:
c.close()
return stats
def extract_backup_from_sqlite(db_path):
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
c = conn.cursor()
try:
def table_exists(tname):
return bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (tname,)).fetchone())
preferences = {}
if table_exists('preferences'):
preferences = dict(c.execute("SELECT key, value FROM preferences").fetchall())
vpn_profiles = []
if table_exists('vpn_profiles'):
for r in c.execute("SELECT id, name, type, config_content, auth_user, auth_pass, table_id, iface, auto_connect, created_at, updated_at FROM vpn_profiles").fetchall():
vpn_profiles.append({
'id': r['id'], 'name': r['name'], 'type': r['type'], 'config_content': r['config_content'],
'auth_user': r['auth_user'], 'auth_pass': r['auth_pass'], 'table_id': r['table_id'], 'iface': r['iface'],
'auto_connect': r['auto_connect'], 'created_at': r['created_at'], 'updated_at': r['updated_at']
})
client_vpn_routes = []
if table_exists('client_vpn_routes'):
q = "SELECT r.mac, r.profile_id, r.kill_switch, r.updated_at, p.name FROM client_vpn_routes r LEFT JOIN vpn_profiles p ON p.id=r.profile_id" if table_exists('vpn_profiles') else "SELECT mac, profile_id, kill_switch, updated_at, '' FROM client_vpn_routes"
for r in c.execute(q).fetchall():
client_vpn_routes.append({
'mac': r[0], 'profile_id': r[1], 'kill_switch': r[2],
'updated_at': r[3], 'profile_name': r[4] or ''
})
client_names = []
if table_exists('client_names'):
for r in c.execute("SELECT mac, name, last_ip, last_seen, device_type FROM client_names").fetchall():
client_names.append({
'mac': r['mac'], 'name': r['name'], 'last_ip': r['last_ip'],
'last_seen': r['last_seen'], 'device_type': r['device_type'] or ''
})
custom_device_types = []
if table_exists('custom_device_types'):
for r in c.execute("SELECT id, label, icon, desc, sort_order FROM custom_device_types ORDER BY sort_order ASC, id ASC").fetchall():
custom_device_types.append({
'id': r['id'], 'label': r['label'], 'icon': r['icon'], 'desc': r['desc'], 'sort_order': r['sort_order']
})
blocked_clients = []
if table_exists('blocked_clients'):
for r in c.execute("SELECT mac, blocked_at FROM blocked_clients").fetchall():
blocked_clients.append({'mac': r['mac'], 'blocked_at': r['blocked_at']})
auth_users = []
if table_exists('auth_users'):
for r in c.execute("SELECT username, password_hash, totp_secret FROM auth_users").fetchall():
auth_users.append({'username': r['username'], 'password_hash': r['password_hash'], 'totp_secret': r['totp_secret']})
auth_passkeys = []
if table_exists('auth_passkeys'):
for r in c.execute("SELECT id, username, public_key, name, device_type, sign_count, created_at, last_used_at FROM auth_passkeys").fetchall():
auth_passkeys.append({
'id': r['id'], 'username': r['username'], 'public_key': r['public_key'], 'name': r['name'],
'device_type': r['device_type'], 'sign_count': r['sign_count'], 'created_at': r['created_at'], 'last_used_at': r['last_used_at']
})
client_limits = []
if table_exists('client_limits'):
for r in c.execute("SELECT mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, updated_at FROM client_limits").fetchall():
client_limits.append({
'mac': r['mac'], 'quota_enabled': r['quota_enabled'], 'quota_bytes': r['quota_bytes'],
'quota_period': r['quota_period'], 'bandwidth_enabled': r['bandwidth_enabled'],
'rate_down_kbps': r['rate_down_kbps'], 'rate_up_kbps': r['rate_up_kbps'],
'quota_action': r['quota_action'], 'updated_at': r['updated_at']
})
return {
'ap_manageur_backup': {
'version': '1.0',
'app_version': APP_VERSION,
'exported_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
'export_timestamp': int(time.time()),
'app_name': preferences.get('app_name', 'Administration de l’AP Wi‑Fi (extrait SQLite)')
},
'preferences': preferences,
'vpn_profiles': vpn_profiles,
'client_vpn_routes': client_vpn_routes,
'client_names': client_names,
'custom_device_types': custom_device_types,
'client_limits': client_limits,
'blocked_clients': blocked_clients,
'auth_users': auth_users,
'auth_passkeys': auth_passkeys
}
finally:
conn.close()
def inspect_backup_bytes(raw_bytes, filename=''):
if not raw_bytes:
raise ValueError("Le fichier de sauvegarde est vide")
# 1. Archive ZIP
if raw_bytes[:4] == b'PK\x03\x04' or filename.lower().endswith('.zip'):
try:
with zipfile.ZipFile(io.BytesIO(raw_bytes)) as zf:
namelist = zf.namelist()
json_files = [n for n in namelist if n.lower().endswith('.json')]
target = None
if 'configuration.json' in json_files:
target = 'configuration.json'
elif json_files:
target = json_files[0]
if target:
content = zf.read(target).decode('utf-8')
return json.loads(content)
# Si pas de JSON mais un fichier SQLite est présent dans le zip
sqlite_files = [n for n in namelist if n.lower().endswith(('.sqlite3', '.db'))]
if sqlite_files:
tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.sqlite3')
try:
tmp.write(zf.read(sqlite_files[0]))
tmp.close()
return extract_backup_from_sqlite(tmp.name)
finally:
if os.path.exists(tmp.name):
try: os.unlink(tmp.name)
except OSError: pass
raise ValueError("L'archive ZIP ne contient ni fichier JSON de configuration ni base de données SQLite.")
except zipfile.BadZipFile:
raise ValueError("L'archive ZIP est corrompue ou invalide.")
# 2. Base SQLite brute
if raw_bytes[:16] == b'SQLite format 3\x00' or filename.lower().endswith(('.sqlite3', '.db')):
tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.sqlite3')
try:
tmp.write(raw_bytes)
tmp.close()
return extract_backup_from_sqlite(tmp.name)
finally:
if os.path.exists(tmp.name):
try: os.unlink(tmp.name)
except OSError: pass
# 3. JSON standard
try:
text = raw_bytes.decode('utf-8')
return json.loads(text)
except Exception as e:
raise ValueError(f"Fichier de sauvegarde non reconnu (ni ZIP, ni SQLite, ni JSON) : {e}")
BACKUP_DIR = os.environ.get('AP_BACKUP_DIR', '/data/backups').strip() or '/data/backups'
BACKUP_ALLOWED_EXTS = ('.zip', '.json', '.sqlite', '.sqlite3', '.db')
backup_lock = threading.Lock()
_last_backup_cron_minute = None
def ensure_backup_dir():
try:
os.makedirs(BACKUP_DIR, exist_ok=True)
return True
except OSError as e:
print(f"[ap-backup] Impossible de créer le dossier {BACKUP_DIR} : {e}", flush=True)
return False
def safe_backup_filepath(filename):
fname = str(filename or '').strip()
if not fname or fname in ('.', '..') or os.path.basename(fname) != fname or '/' in fname or '\\' in fname:
raise ValueError('Nom de fichier de sauvegarde invalide')
if not fname.lower().endswith(BACKUP_ALLOWED_EXTS):
raise ValueError('Extension de sauvegarde non autorisée')
ensure_backup_dir()
base_real = os.path.realpath(BACKUP_DIR)
full_path = os.path.realpath(os.path.join(base_real, fname))
if not full_path.startswith(base_real + os.sep):
raise ValueError('Chemin de sauvegarde hors du dossier autorisé')
return full_path, fname
def build_backup_zip_bytes():
backup = export_backup_data()
json_bytes = json.dumps(backup, ensure_ascii=False, indent=2).encode('utf-8')
buf = io.BytesIO()
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zf:
zf.writestr('configuration.json', json_bytes)
if os.path.exists(DB_FILE):
try:
with open(DB_FILE, 'rb') as f_db:
zf.writestr('ap-dashboard.sqlite3', f_db.read())
except Exception as e_db:
print(f"[backup] Inclusion sqlite impossible : {e_db}", flush=True)
readme_text = (
f"Sauvegarde AP Manageur ({APP_VERSION})\n"
f"Date d'export : {datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}\n\n"
"Contenu de cette archive :\n"
"- configuration.json : Configuration complète (réglages Wi-Fi, profils VPN WireGuard & OpenVPN, routage appareils, noms et logos des équipements, catégories, blocage et réglages système).\n"
"- ap-dashboard.sqlite3 : Base de données SQLite brute complète.\n\n"
"Restauration :\n"
"Vous pouvez importer ou restaurer directement cette archive .zip (ou configuration.json) "
"dans AP Manageur (Réglages > Sauvegardes ou Assistant Setup).\n"
)
zf.writestr('README.txt', readme_text.encode('utf-8'))
return buf.getvalue()
def default_backup_schedule():
return {
'enabled': False,
'cron_expr': '0 3 * * *',
'day': '*',
'hour': 3,
'minute': 0,
'retention': 7,
'last_run': '',
'last_file': '',
'last_status': ''
}
def get_backup_schedule():
cfg = default_backup_schedule()
raw = get_pref('backup_schedule', '')
if raw:
try:
loaded = json.loads(raw)
if isinstance(loaded, dict):
cfg.update(loaded)
except Exception:
pass
cfg['enabled'] = bool(cfg.get('enabled', False))
try: cfg['retention'] = max(0, min(365, int(cfg.get('retention', 7))))
except (ValueError, TypeError): cfg['retention'] = 7
if not str(cfg.get('cron_expr', '')).strip() or len(str(cfg.get('cron_expr', '')).strip().split()) != 5:
cfg['cron_expr'] = f"{cfg.get('minute', 0)} {cfg.get('hour', 3)} * * {cfg.get('day', '*')}"
return cfg
def save_backup_schedule(data):
cur = get_backup_schedule()
if 'enabled' in data:
cur['enabled'] = bool(data['enabled'])
if 'day' in data:
cur['day'] = str(data['day']).strip() or '*'
if 'hour' in data:
h_raw = str(data['hour']).strip()
if h_raw == '*':
cur['hour'] = '*'
else:
try: cur['hour'] = max(0, min(23, int(h_raw)))
except (ValueError, TypeError): cur['hour'] = 3
if 'minute' in data:
try: cur['minute'] = max(0, min(59, int(data['minute'])))
except (ValueError, TypeError): cur['minute'] = 0
if 'retention' in data:
try: cur['retention'] = max(0, min(365, int(data['retention'])))
except (ValueError, TypeError): cur['retention'] = 7
cron_raw = str(data.get('cron_expr', '')).strip()
if cron_raw:
parts = cron_raw.split()
if len(parts) != 5:
raise ValueError('Expression Cron invalide : 5 champs attendus (minute heure jour mois jour_semaine)')
cur['cron_expr'] = ' '.join(parts)
else:
cur['cron_expr'] = f"{cur['minute']} {cur['hour']} * * {cur['day']}"
set_pref('backup_schedule', json.dumps(cur, ensure_ascii=False))
return cur
def apply_backup_retention(retention):
try:
keep = int(retention or 0)
except (ValueError, TypeError):
return 0
if keep <= 0 or not os.path.isdir(BACKUP_DIR):
return 0
auto_files = []
for entry in os.listdir(BACKUP_DIR):
if entry.startswith('ap-manageur-backup-auto-') and entry.lower().endswith('.zip'):
full = os.path.join(BACKUP_DIR, entry)
if os.path.isfile(full):
try:
auto_files.append((os.path.getmtime(full), full, entry))
except OSError:
pass
auto_files.sort(key=lambda x: x[0], reverse=True)
removed = 0
for _, full, entry in auto_files[keep:]:
try:
os.remove(full)
removed += 1
except OSError:
pass
if removed:
print(f"[ap-backup] Rétention appliquée : {removed} ancienne(s) sauvegarde(s) automatique(s) supprimée(s) (max={keep}).", flush=True)
return removed
def create_server_backup(trigger='manual'):
with backup_lock:
if not ensure_backup_dir():
raise RuntimeError(f"Dossier de sauvegarde inaccessible : {BACKUP_DIR}")
tag = 'auto' if trigger == 'auto' else 'manual'
now_str = time.strftime('%Y%m%d-%H%M%S')
fname = f"ap-manageur-backup-{tag}-{now_str}.zip"
full_path = os.path.join(BACKUP_DIR, fname)
# Éviter collision si deux sauvegardes dans la même seconde
idx = 1
while os.path.exists(full_path):
fname = f"ap-manageur-backup-{tag}-{now_str}-{idx}.zip"
full_path = os.path.join(BACKUP_DIR, fname)
idx += 1
zip_bytes = build_backup_zip_bytes()
tmp_path = full_path + '.tmp'
with open(tmp_path, 'wb') as f:
f.write(zip_bytes)
os.replace(tmp_path, full_path)
sched = get_backup_schedule()
sched['last_run'] = time.strftime('%Y-%m-%d %H:%M:%S')
sched['last_file'] = fname
sched['last_status'] = 'ok'
set_pref('backup_schedule', json.dumps(sched, ensure_ascii=False))
if tag == 'auto':
apply_backup_retention(sched.get('retention', 7))
# Si téléversement distant automatique activé, lancer en arrière-plan
try:
rcfg = get_backup_remote_config()
if rcfg.get('enabled') and rcfg.get('auto_upload', True):
threading.Thread(target=_bg_upload_backup_to_remote, args=(full_path, fname), daemon=True).start()
except Exception as e_th:
print(f"[ap-backup] Erreur démarrage téléversement distant : {e_th}", flush=True)
st = os.stat(full_path)
# Notification d'événement : Sauvegarde créée avec succès
try:
trigger_label = "automatique (Cron)" if tag == 'auto' else "manuelle"
dispatch_notification(
'backup_success',
"💾 Sauvegarde créée avec succès",
f"La sauvegarde « {fname} » ({format_bytes(st.st_size)}) a été créée avec succès ({trigger_label}).",
details={
"Fichier": fname,
"Taille": format_bytes(st.st_size),
"Déclenchement": trigger_label,
"Date": time.strftime('%d/%m/%Y %H:%M:%S')
},
priority=3,
level="success",
vars_dict={
"filename": fname,
"file": fname,
"size": format_bytes(st.st_size),
"trigger": trigger_label,
"date": time.strftime('%d/%m/%Y %H:%M:%S')
}
)
except Exception as e_notif:
print(f"[ap-backup] Avertissement notification sauvegarde : {e_notif}", flush=True)
return {
'filename': fname,
'size': st.st_size,
'size_str': format_bytes(st.st_size),
'mtime': st.st_mtime,
'created_at': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(st.st_mtime)),
'trigger': tag
}
def _bg_upload_backup_to_remote(full_path, fname):
try:
upload_backup_to_remote(full_path, remote_filename=fname)
except Exception as e:
print(f"[ap-backup] Échec téléversement distant en arrière-plan ({fname}) : {e}", flush=True)
def default_backup_remote_config():
return {
'enabled': False,
'auto_upload': True,
'provider': 'ftp',
'ftp': {'host': '', 'port': 21, 'user': '', 'password': '', 'path': 'backups/', 'tls': 'none'},
'sftp': {'host': '', 'port': 22, 'user': '', 'password': '', 'key': '', 'path': 'backups/'},
'dropbox': {'token': '', 'path': '/AP-Manageur-Backups/'},
'gdrive': {'token': '', 'folder_id': ''},
'webdav': {'url': '', 'user': '', 'password': '', 'path': ''},
's3': {'endpoint': 'https://s3.amazonaws.com', 'region': 'us-east-1', 'bucket': '', 'access_key': '', 'secret_key': '', 'path': 'backups/'},
'webhook': {'url': '', 'method': 'POST', 'headers': '', 'field_name': 'backup'},
'last_upload_time': '',
'last_upload_file': '',
'last_upload_status': '',
'last_upload_error': '',
'uploaded_files': {}
}
def get_backup_remote_config():
cfg = default_backup_remote_config()
raw = get_pref('backup_remote_config', '')
if raw:
try:
loaded = json.loads(raw)
if isinstance(loaded, dict):
for k, v in loaded.items():
if k in ('ftp', 'sftp', 'dropbox', 'gdrive', 'webdav', 's3', 'webhook') and isinstance(v, dict):
cfg[k].update(v)
else:
cfg[k] = v
except Exception:
pass
cfg['enabled'] = bool(cfg.get('enabled', False))
cfg['auto_upload'] = bool(cfg.get('auto_upload', True))
if cfg.get('provider') not in ('ftp', 'sftp', 'dropbox', 'gdrive', 'webdav', 's3', 'webhook'):
cfg['provider'] = 'ftp'
return cfg
def save_backup_remote_config(data):
cur = get_backup_remote_config()
if not isinstance(data, dict):
raise ValueError('Données de configuration distante invalides')
if 'enabled' in data:
cur['enabled'] = bool(data['enabled'])
if 'auto_upload' in data:
cur['auto_upload'] = bool(data['auto_upload'])
if 'provider' in data:
prov = str(data['provider']).strip().lower()
if prov in ('ftp', 'sftp', 'dropbox', 'gdrive', 'webdav', 's3', 'webhook'):
cur['provider'] = prov
for p in ('ftp', 'sftp', 'dropbox', 'gdrive', 'webdav', 's3', 'webhook'):
if p in data and isinstance(data[p], dict):
cur[p].update(data[p])
set_pref('backup_remote_config', json.dumps(cur, ensure_ascii=False))
return cur
def _upload_ftp(cfg, local_path, remote_filename):
import ftplib
host = str(cfg.get('host', '')).strip()
if not host: raise ValueError("Hôte FTP manquant")
try: port = int(cfg.get('port') or 21)
except (ValueError, TypeError): port = 21
user = str(cfg.get('user', '')).strip() or 'anonymous'
password = str(cfg.get('password', ''))
rem_path = str(cfg.get('path', '') or '/').strip()
use_tls = str(cfg.get('tls', 'none')).lower() in ('explicit', 'tls', 'ftps', '1', 'true')
ftp = ftplib.FTP_TLS(timeout=25) if use_tls else ftplib.FTP(timeout=25)
ftp.connect(host, port)
ftp.login(user, password)
if use_tls:
ftp.prot_p()
if rem_path and rem_path != '/':
for part in [p for p in rem_path.split('/') if p]:
try:
ftp.cwd(part)
except ftplib.error_perm:
try:
ftp.mkd(part)
ftp.cwd(part)
except Exception:
pass
with open(local_path, 'rb') as f:
ftp.storbinary(f"STOR {remote_filename}", f)
try: ftp.quit()
except Exception: pass
return True, f"Téléversé sur FTP ({host}:{port})"
def _normalize_sftp_target(sftp, raw_path, filename=""):
"""
Résout le dossier et le fichier cible sur un serveur SFTP :
- Si raw_path est vide, '.' ou './' : utilise le dossier d\'accueil SFTP (sftp.normalize('.')).
- Si raw_path commence par '/' :
- S'il existe tel quel (ex: /volume1/backups, /srv/backups), on l\'utilise.
- Sinon, si home_dir existe et n'est pas '/', on tente sous le home_dir.
- Si raw_path est relatif (ex: 'backups' ou 'backups/') : sous le home_dir (home/backups).
"""
home_dir = ''
try:
home_dir = str(sftp.normalize('.')).rstrip('/')
except Exception:
home_dir = ''
p = str(raw_path or '').strip()
if not p or p in ('.', './'):
target_dir = home_dir or '/'
elif p.startswith('/'):
target_dir = p.rstrip('/')
exists_at_root = False
try:
sftp.stat(target_dir)
exists_at_root = True
except Exception:
pass
if not exists_at_root and home_dir and home_dir != '/' and not target_dir.startswith(home_dir):
cand = f"{home_dir}/{target_dir.lstrip('/')}".rstrip('/')
try:
sftp.stat(cand)
target_dir = cand
except Exception:
# Tester si la racine / est accessible en écriture
can_root = False
try:
sftp.stat('/')
can_root = True
except Exception:
pass
if not can_root:
target_dir = cand
else:
if home_dir and home_dir != '/':
target_dir = f"{home_dir}/{p.lstrip('/')}".rstrip('/')
else:
target_dir = f"/{p.lstrip('/')}".rstrip('/')
target_file = f"{target_dir}/{filename}" if filename else target_dir
return target_dir, target_file
def _mkdir_p_sftp(sftp, remote_dir):
"""Crée récursivement les dossiers distants SFTP s'ils n'existent pas."""
parts = [p for p in remote_dir.split('/') if p]
curr = '/' if remote_dir.startswith('/') else ''
for p in parts:
curr = f"{curr}/{p}" if curr != '/' else f"/{p}"
try:
sftp.stat(curr)
except IOError:
try:
sftp.mkdir(curr)
except IOError:
pass
def _upload_sftp(cfg, local_path, remote_filename):
host = str(cfg.get('host', '')).strip()
if not host: raise ValueError("Hôte SFTP manquant")
try: port = int(cfg.get('port') or 22)
except (ValueError, TypeError): port = 22
user = str(cfg.get('user', '')).strip()
if not user: raise ValueError("Nom d'utilisateur SFTP manquant")
password = str(cfg.get('password', ''))
key_text = str(cfg.get('key', '')).strip()
target_remote_file = ""
try:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
pkey = None
if key_text:
for pkey_class in (paramiko.RSAKey, paramiko.Ed25519Key, paramiko.ECDSAKey):
try:
pkey = pkey_class.from_private_key(io.StringIO(key_text))
break
except Exception: pass
if not pkey:
raise ValueError("Clé privée SSH non reconnue (format PEM / OpenSSH attendu)")
ssh.connect(host, port=port, username=user, password=password or None, pkey=pkey, timeout=25)
sftp = ssh.open_sftp()
target_dir, target_remote_file = _normalize_sftp_target(sftp, cfg.get('path', ''), remote_filename)
_mkdir_p_sftp(sftp, target_dir)
sftp.put(local_path, target_remote_file)
# Vérification physique immédiate après écriture
st = sftp.stat(target_remote_file)
if st.st_size == 0 and os.path.getsize(local_path) > 0:
raise IOError("Fichier téléversé sur SFTP avec une taille de 0 octet")
sftp.close()
ssh.close()
return True, f"Téléversé via SFTP dans {target_dir}"
except ImportError:
pass
except Exception as e_param:
if 'Authentication' in str(e_param) or 'Clé privée' in str(e_param):
raise
print(f"[ap-backup] Avertissement paramiko SFTP ({e_param}), tentative de secours via curl...", flush=True)
curl_bin = find_bin('curl')
if not curl_bin:
raise RuntimeError("Client SFTP introuvable (installez python3-paramiko ou curl)")
raw_p = str(cfg.get('path', '') or '').strip()
if raw_p.startswith('/'):
url_path = '/' + raw_p.rstrip('/') + '/' + remote_filename
else:
url_path = '/' + (raw_p.rstrip('/') + '/' if raw_p else '') + remote_filename
sftp_url = f"sftp://{host}:{port}{url_path}"
curl_cmd = [curl_bin, '-sS', '-k', '--ftp-create-dirs', '--max-time', '120']
key_tmp_name = None
try:
if key_text:
kt = tempfile.NamedTemporaryFile('w', delete=False)
kt.write(key_text + '\n')
kt.flush(); kt.close()
os.chmod(kt.name, 0o600)
key_tmp_name = kt.name
curl_cmd += ['-u', f"{user}:", '--key', key_tmp_name]
else:
curl_cmd += ['-u', f"{user}:{password}"]
curl_cmd += ['-T', local_path, sftp_url]
r = subprocess.run(curl_cmd, capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError(r.stderr.strip() or f"Erreur SFTP (code {r.returncode})")
return True, f"Téléversé via SFTP sur {host}:{port}"
finally:
if key_tmp_name and os.path.exists(key_tmp_name):
try: os.unlink(key_tmp_name)
except OSError: pass
def _upload_dropbox(cfg, local_path, remote_filename):
token = str(cfg.get('token', '')).strip()
if not token: raise ValueError("Jeton d'accès (Access Token) Dropbox manquant")
rem_path = str(cfg.get('path', '') or '/AP-Manageur-Backups/').strip()
if not rem_path.startswith('/'): rem_path = '/' + rem_path
if not rem_path.endswith('/'): rem_path += '/'
dropbox_path = rem_path + remote_filename
url = "https://content.dropboxapi.com/2/files/upload"
dbx_arg = json.dumps({
"path": dropbox_path,
"mode": "overwrite",
"autorename": False,
"mute": False,
"strict_conflict": False
})
with open(local_path, 'rb') as f:
file_bytes = f.read()
req = urllib.request.Request(url, data=file_bytes, method='POST')
req.add_header('Authorization', f'Bearer {token}')
req.add_header('Dropbox-API-Arg', dbx_arg)
req.add_header('Content-Type', 'application/octet-stream')
ctx = ssl.create_default_context()
try:
with urllib.request.urlopen(req, context=ctx, timeout=60) as resp:
res_data = json.loads(resp.read().decode('utf-8'))
return True, f"Téléversé sur Dropbox ({res_data.get('path_display', dropbox_path)})"
except urllib.error.HTTPError as e:
body = ''
try: body = e.read().decode('utf-8', errors='replace')[:300]
except Exception: pass
raise RuntimeError(f"HTTP {e.code} Dropbox : {body or e.reason}")
def _upload_gdrive(cfg, local_path, remote_filename):
token = str(cfg.get('token', '')).strip()
if not token: raise ValueError("Jeton d'accès (Access Token OAuth2) Google Drive manquant")
folder_id = str(cfg.get('folder_id', '')).strip()
url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"
metadata = {"name": remote_filename}
if folder_id:
metadata["parents"] = [folder_id]
boundary = "========GDRIVE_APMANAGEUR_BOUNDARY========"
meta_json = json.dumps(metadata)
with open(local_path, 'rb') as f:
file_bytes = f.read()
ctype = 'text/plain' if remote_filename.lower().endswith('.txt') else 'application/zip'
body = (
f"--{boundary}\r\n"
f"Content-Type: application/json; charset=UTF-8\r\n\r\n"
f"{meta_json}\r\n"
f"--{boundary}\r\n"
f"Content-Type: {ctype}\r\n\r\n"
).encode('utf-8') + file_bytes + f"\r\n--{boundary}--\r\n".encode('utf-8')
req = urllib.request.Request(url, data=body, method='POST')
req.add_header('Authorization', f'Bearer {token}')
req.add_header('Content-Type', f'multipart/related; boundary={boundary}')
ctx = ssl.create_default_context()
try:
with urllib.request.urlopen(req, context=ctx, timeout=60) as resp:
res_data = json.loads(resp.read().decode('utf-8'))
return True, f"Téléversé sur Google Drive (ID: {res_data.get('id', '?')})"
except urllib.error.HTTPError as e:
body = ''
try: body = e.read().decode('utf-8', errors='replace')[:300]
except Exception: pass
raise RuntimeError(f"HTTP {e.code} Google Drive : {body or e.reason}")
def _upload_webdav(cfg, local_path, remote_filename):
server_url = str(cfg.get('url', '')).strip()
if not server_url: raise ValueError("URL WebDAV manquante")
if not server_url.endswith('/'): server_url += '/'
extra_path = str(cfg.get('path', '')).strip().strip('/')
if extra_path:
server_url += '/'.join(urllib.parse.quote(p) for p in extra_path.split('/')) + '/'
target_url = server_url + urllib.parse.quote(remote_filename)
user = str(cfg.get('user', '')).strip()
password = str(cfg.get('password', ''))
with open(local_path, 'rb') as f:
file_bytes = f.read()
req = urllib.request.Request(target_url, data=file_bytes, method='PUT')
if user or password:
auth_str = base64.b64encode(f"{user}:{password}".encode('utf-8')).decode('ascii')
req.add_header('Authorization', f'Basic {auth_str}')
req.add_header('Content-Type', 'application/octet-stream')
ctx = ssl.create_default_context()
try:
with urllib.request.urlopen(req, context=ctx, timeout=60) as resp:
return True, f"Téléversé sur WebDAV (HTTP {resp.status})"
except urllib.error.HTTPError as e:
raise RuntimeError(f"HTTP {e.code} WebDAV : {e.reason}")
def _upload_s3(cfg, local_path, remote_filename):
endpoint = str(cfg.get('endpoint', '') or 'https://s3.amazonaws.com').strip()
bucket = str(cfg.get('bucket', '')).strip()
if not bucket: raise ValueError("Nom du bucket S3 manquant")
region = str(cfg.get('region', '') or 'us-east-1').strip()
access_key = str(cfg.get('access_key', '')).strip()
secret_key = str(cfg.get('secret_key', '')).strip()
if not access_key or not secret_key:
raise ValueError("Clés S3 (Access Key et Secret Key) obligatoires")
prefix = str(cfg.get('path', '') or '').strip().strip('/')
s3_key = f"{prefix}/{remote_filename}" if prefix else remote_filename
rclone_bin = find_bin('rclone')
if rclone_bin:
rc = tempfile.NamedTemporaryFile('w', delete=False)
try:
rc.write(f"[s3remote]\ntype = s3\nprovider = Other\nendpoint = {endpoint}\nregion = {region}\naccess_key_id = {access_key}\nsecret_access_key = {secret_key}\n")
rc.flush(); rc.close()
cmd = [rclone_bin, '--config', rc.name, 'copyto', local_path, f"s3remote:{bucket}/{s3_key}"]
r = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
if r.returncode != 0:
raise RuntimeError(r.stderr.strip() or r.stdout.strip() or f"Code rclone {r.returncode}")
return True, f"Téléversé sur S3 ({bucket}/{s3_key})"
finally:
if os.path.exists(rc.name):
try: os.unlink(rc.name)
except OSError: pass
with open(local_path, 'rb') as f:
payload = f.read()
payload_hash = hashlib.sha256(payload).hexdigest()
now_dt = datetime.datetime.now(datetime.timezone.utc)
amz_date = now_dt.strftime('%Y%m%dT%H%M%SZ')
datestamp = now_dt.strftime('%Y%m%d')
if not endpoint.startswith('http://') and not endpoint.startswith('https://'):
endpoint = 'https://' + endpoint
parsed = urllib.parse.urlparse(endpoint)
host = parsed.netloc
canonical_uri = f"/{bucket}/{urllib.parse.quote(s3_key, safe='/')}"
canonical_headers = f"host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n"
signed_headers = "host;x-amz-content-sha256;x-amz-date"
canonical_req = f"PUT\n{canonical_uri}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}"
algorithm = "AWS4-HMAC-SHA256"
credential_scope = f"{datestamp}/{region}/s3/aws4_request"
string_to_sign = f"{algorithm}\n{amz_date}\n{credential_scope}\n{hashlib.sha256(canonical_req.encode('utf-8')).hexdigest()}"
def _sign(k, m): return hmac.new(k, m.encode('utf-8'), hashlib.sha256).digest()
k_sign = _sign(_sign(_sign(_sign(('AWS4' + secret_key).encode('utf-8'), datestamp), region), 's3'), 'aws4_request')
signature = hmac.new(k_sign, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest()
auth_hdr = f"{algorithm} Credential={access_key}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}"
full_url = f"{endpoint.rstrip('/')}{canonical_uri}"
req = urllib.request.Request(full_url, data=payload, method='PUT')
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)
req.add_header('Content-Type', 'application/octet-stream')
ctx = ssl.create_default_context()
try:
with urllib.request.urlopen(req, context=ctx, timeout=60) as resp:
return True, f"Téléversé sur S3 ({bucket}/{s3_key} - HTTP {resp.status})"
except urllib.error.HTTPError as e:
body = ''
try: body = e.read().decode('utf-8', errors='replace')[:300]
except Exception: pass
raise RuntimeError(f"HTTP {e.code} S3 : {body or e.reason}")
def _upload_webhook(cfg, local_path, remote_filename):
url = str(cfg.get('url', '')).strip()
if not url: raise ValueError("URL du Webhook manquante")
method = str(cfg.get('method', 'POST') or 'POST').strip().upper()
if method not in ('POST', 'PUT'): method = 'POST'
headers_raw = str(cfg.get('headers', ''))
field_name = str(cfg.get('field_name', 'backup') or 'backup').strip()
with open(local_path, 'rb') as f:
file_bytes = f.read()
if method == 'PUT':
body = file_bytes
content_type = 'application/octet-stream'
else:
boundary = "========WEBHOOK_APMANAGEUR_BOUNDARY========"
body = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="{field_name}"; filename="{remote_filename}"\r\n'
f"Content-Type: application/octet-stream\r\n\r\n"
).encode('utf-8') + file_bytes + f"\r\n--{boundary}--\r\n".encode('utf-8')
content_type = f'multipart/form-data; boundary={boundary}'
req = urllib.request.Request(url, data=body, method=method)
req.add_header('Content-Type', content_type)
if headers_raw:
for line in headers_raw.splitlines():
if ':' in line:
k, v = line.split(':', 1)
if k.strip():
req.add_header(k.strip(), v.strip())
ctx = ssl.create_default_context()
try:
with urllib.request.urlopen(req, context=ctx, timeout=60) as resp:
return True, f"Sauvegarde transmise au Webhook (HTTP {resp.status})"
except urllib.error.HTTPError as e:
raise RuntimeError(f"HTTP {e.code} Webhook : {e.reason}")
def upload_backup_to_remote(local_filepath_or_name, custom_cfg=None, remote_filename=None, persist_status=True):
cfg = copy.deepcopy(custom_cfg) if custom_cfg else get_backup_remote_config()
provider = str(cfg.get('provider', 'ftp')).strip().lower()
if os.path.isabs(local_filepath_or_name) and os.path.isfile(local_filepath_or_name):
local_path = local_filepath_or_name
fname = remote_filename or os.path.basename(local_filepath_or_name)
else:
full_p, clean_n = safe_backup_filepath(local_filepath_or_name)
local_path = full_p
fname = remote_filename or clean_n
if not os.path.isfile(local_path):
raise FileNotFoundError(f"Fichier de sauvegarde introuvable : {fname}")
p_cfg = cfg.get(provider, {}) if isinstance(cfg.get(provider), dict) else {}
now_ts = time.strftime('%Y-%m-%d %H:%M:%S')
try:
if provider == 'ftp':
ok, msg = _upload_ftp(p_cfg, local_path, fname)
elif provider == 'sftp':
ok, msg = _upload_sftp(p_cfg, local_path, fname)
elif provider == 'dropbox':
ok, msg = _upload_dropbox(p_cfg, local_path, fname)
elif provider == 'gdrive':
ok, msg = _upload_gdrive(p_cfg, local_path, fname)
elif provider == 'webdav':
ok, msg = _upload_webdav(p_cfg, local_path, fname)
elif provider == 's3':
ok, msg = _upload_s3(p_cfg, local_path, fname)
elif provider == 'webhook':
ok, msg = _upload_webhook(p_cfg, local_path, fname)
else:
raise ValueError(f"Protocole de stockage distant inconnu : {provider}")
if persist_status:
saved = get_backup_remote_config()
saved['last_upload_time'] = now_ts
saved['last_upload_file'] = fname
saved['last_upload_status'] = 'ok'
saved['last_upload_error'] = ''
up_files = saved.get('uploaded_files', {})
if not isinstance(up_files, dict):
up_files = {}
up_files[fname] = {'time': now_ts, 'provider': provider}
saved['uploaded_files'] = up_files
set_pref('backup_remote_config', json.dumps(saved, ensure_ascii=False))
# Notification d'événement : Sauvegarde envoyée sur l'hôte distant
if not fname.startswith('ap-manageur-test-'):
try:
st_size_str = ""
if os.path.isfile(local_path):
st_size_str = format_bytes(os.path.getsize(local_path))
prov_name = {'ftp':'FTP','sftp':'SFTP','gdrive':'Google Drive','dropbox':'Dropbox','webdav':'WebDAV','s3':'S3 / MinIO','webhook':'Webhook'}.get(provider, provider.upper())
target_host = p_cfg.get('host') or p_cfg.get('url') or p_cfg.get('endpoint') or p_cfg.get('bucket') or prov_name
dispatch_notification(
'backup_remote_success',
"☁️ Sauvegarde téléversée sur le stockage distant",
f"La sauvegarde « {fname} » {f'({st_size_str}) ' if st_size_str else ''}a été téléversée avec succès sur {prov_name} ({target_host}).",
details={
"Fichier": fname,
"Taille": st_size_str or "Inconnue",
"Stockage distant": prov_name,
"Cible": str(target_host),
"Date": time.strftime('%d/%m/%Y %H:%M:%S')
},
priority=4,
level="success",
vars_dict={
"filename": fname,
"file": fname,
"size": st_size_str or "",
"provider": prov_name,
"host": str(target_host),
"cible": str(target_host),
"date": time.strftime('%d/%m/%Y %H:%M:%S')
}
)
except Exception as e_notif:
print(f"[ap-backup] Avertissement notification stockage distant : {e_notif}", flush=True)
print(f"[ap-backup] Sauvegarde {fname} transmise vers {provider.upper()} : {msg}", flush=True)
return True, msg
except Exception as e:
err_msg = str(e)
if persist_status:
try:
saved = get_backup_remote_config()
saved['last_upload_time'] = now_ts
saved['last_upload_file'] = fname
saved['last_upload_status'] = 'error'
saved['last_upload_error'] = err_msg[:300]
set_pref('backup_remote_config', json.dumps(saved, ensure_ascii=False))
except Exception: pass
print(f"[ap-backup] Échec téléversement {fname} vers {provider.upper()} : {err_msg}", flush=True)
raise RuntimeError(f"Échec téléversement distant ({provider.upper()}) : {err_msg}")
def _delete_ftp(cfg, remote_filename):
import ftplib
host = str(cfg.get('host', '')).strip()
if not host: return False, "Hôte FTP manquant"
try: port = int(cfg.get('port') or 21)
except (ValueError, TypeError): port = 21
user = str(cfg.get('user', '')).strip() or 'anonymous'
password = str(cfg.get('password', ''))
rem_path = str(cfg.get('path', '') or '/').strip()
use_tls = str(cfg.get('tls', 'none')).lower() in ('explicit', 'tls', 'ftps', '1', 'true')
ftp = ftplib.FTP_TLS(timeout=20) if use_tls else ftplib.FTP(timeout=20)
try:
ftp.connect(host, port)
ftp.login(user, password)
if use_tls: ftp.prot_p()
if rem_path and rem_path != '/':
for part in [p for p in rem_path.split('/') if p]:
try: ftp.cwd(part)
except Exception: pass
ftp.delete(remote_filename)
return True, f"Fichier {remote_filename} supprimé sur FTP"
except Exception as e:
return False, f"Erreur suppression FTP : {e}"
finally:
try: ftp.quit()
except Exception: pass
def _delete_sftp(cfg, remote_filename):
host = str(cfg.get('host', '')).strip()
if not host: return False, "Hôte SFTP manquant"
try: port = int(cfg.get('port') or 22)
except (ValueError, TypeError): port = 22
user = str(cfg.get('user', '')).strip()
password = str(cfg.get('password', ''))
key_text = str(cfg.get('key', '')).strip()
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
pkey = None
if key_text:
for pkey_class in (paramiko.RSAKey, paramiko.Ed25519Key, paramiko.ECDSAKey):
try:
pkey = pkey_class.from_private_key(io.StringIO(key_text))
break
except Exception: pass
try:
ssh.connect(host, port=port, username=user, password=password or None, pkey=pkey, timeout=20)
sftp = ssh.open_sftp()
_, target_file = _normalize_sftp_target(sftp, cfg.get('path', ''), remote_filename)
try:
sftp.remove(target_file)
return True, f"Fichier {remote_filename} supprimé sur SFTP"
except Exception as e_rm:
return False, f"Erreur suppression SFTP ({target_file}) : {e_rm}"
finally:
try: sftp.close()
except Exception: pass
except Exception as e:
return False, f"Erreur connexion SFTP : {e}"
finally:
try: ssh.close()
except Exception: pass
def _delete_dropbox(cfg, remote_filename):
token = str(cfg.get('token', '')).strip()
if not token: return False, "Jeton Dropbox manquant"
rem_path = str(cfg.get('path', '') or '/AP-Manageur-Backups/').strip()
if not rem_path.startswith('/'): rem_path = '/' + rem_path
if not rem_path.endswith('/'): rem_path += '/'
dropbox_path = rem_path + remote_filename
url = "https://api.dropboxapi.com/2/files/delete_v2"
payload = json.dumps({"path": dropbox_path}).encode('utf-8')
req = urllib.request.Request(url, data=payload, method='POST')
req.add_header('Authorization', f'Bearer {token}')
req.add_header('Content-Type', 'application/json')
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 Dropbox"
except Exception as e:
return False, f"Erreur suppression Dropbox : {e}"
def _delete_gdrive(cfg, remote_filename):
token = str(cfg.get('token', '')).strip()
if not token: return False, "Jeton Google Drive manquant"
folder_id = str(cfg.get('folder_id', '')).strip()
ctx = ssl.create_default_context()
query = f"name = '{remote_filename}' and trashed = false"
if folder_id:
query += f" and '{folder_id}' in parents"
search_url = f"https://www.googleapis.com/drive/v3/files?q={urllib.parse.quote(query)}"
req = urllib.request.Request(search_url, method='GET')
req.add_header('Authorization', f'Bearer {token}')
try:
with urllib.request.urlopen(req, context=ctx, timeout=30) as resp:
data = json.loads(resp.read().decode('utf-8'))
files = data.get('files', [])
for f in files:
file_id = f.get('id')
if file_id:
del_url = f"https://www.googleapis.com/drive/v3/files/{file_id}"
del_req = urllib.request.Request(del_url, method='DELETE')
del_req.add_header('Authorization', f'Bearer {token}')
try:
with urllib.request.urlopen(del_req, context=ctx, timeout=30):
pass
except Exception: pass
return True, f"Fichier {remote_filename} supprimé sur Google Drive"
except Exception as e:
return False, f"Erreur suppression Google Drive : {e}"
def _delete_webdav(cfg, remote_filename):
server_url = str(cfg.get('url', '')).strip()
if not server_url: return False, "URL WebDAV manquante"
if not server_url.endswith('/'): server_url += '/'
extra_path = str(cfg.get('path', '')).strip().strip('/')
if extra_path:
server_url += '/'.join(urllib.parse.quote(p) for p in extra_path.split('/')) + '/'
target_url = server_url + urllib.parse.quote(remote_filename)
user = str(cfg.get('user', '')).strip()
password = str(cfg.get('password', ''))
req = urllib.request.Request(target_url, method='DELETE')
if user or password:
auth_str = base64.b64encode(f"{user}:{password}".encode('utf-8')).decode('ascii')
req.add_header('Authorization', f'Basic {auth_str}')
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 WebDAV"
except Exception as e:
return False, f"Erreur suppression WebDAV : {e}"
def _delete_s3(cfg, remote_filename):
endpoint = str(cfg.get('endpoint', '') or 'https://s3.amazonaws.com').strip()
bucket = str(cfg.get('bucket', '')).strip()
if not bucket: return False, "Bucket S3 manquant"
region = str(cfg.get('region', '') or 'us-east-1').strip()
access_key = str(cfg.get('access_key', '')).strip()
secret_key = str(cfg.get('secret_key', '')).strip()
prefix = str(cfg.get('path', '') or '').strip().strip('/')
s3_key = f"{prefix}/{remote_filename}" if prefix else remote_filename
rclone_bin = find_bin('rclone')
if rclone_bin:
rc = tempfile.NamedTemporaryFile('w', delete=False)
try:
rc.write(f"[s3remote]\ntype = s3\nprovider = Other\nendpoint = {endpoint}\nregion = {region}\naccess_key_id = {access_key}\nsecret_access_key = {secret_key}\n")
rc.flush(); rc.close()
cmd = [rclone_bin, '--config', rc.name, 'deletefile', f"s3remote:{bucket}/{s3_key}"]
r = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
return True, f"Fichier {remote_filename} supprimé sur S3"
except Exception as e:
return False, f"Erreur rclone S3 : {e}"
finally:
if os.path.exists(rc.name):
try: os.unlink(rc.name)
except OSError: pass
payload = b''
payload_hash = hashlib.sha256(payload).hexdigest()
now_dt = datetime.datetime.now(datetime.timezone.utc)
amz_date = now_dt.strftime('%Y%m%dT%H%M%SZ')
datestamp = now_dt.strftime('%Y%m%d')
if not endpoint.startswith('http://') and not endpoint.startswith('https://'):
endpoint = 'https://' + endpoint
parsed = urllib.parse.urlparse(endpoint)
host = parsed.netloc
canonical_uri = f"/{bucket}/{urllib.parse.quote(s3_key, safe='/')}"
canonical_headers = f"host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n"
signed_headers = "host;x-amz-content-sha256;x-amz-date"
canonical_req = f"DELETE\n{canonical_uri}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}"
algorithm = "AWS4-HMAC-SHA256"
credential_scope = f"{datestamp}/{region}/s3/aws4_request"
string_to_sign = f"{algorithm}\n{amz_date}\n{credential_scope}\n{hashlib.sha256(canonical_req.encode('utf-8')).hexdigest()}"
def _sign(k, m): return hmac.new(k, m.encode('utf-8'), hashlib.sha256).digest()
k_sign = _sign(_sign(_sign(_sign(('AWS4' + secret_key).encode('utf-8'), datestamp), region), 's3'), 'aws4_request')
signature = hmac.new(k_sign, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest()
auth_hdr = f"{algorithm} Credential={access_key}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}"
full_url = f"{endpoint.rstrip('/')}{canonical_uri}"
req = urllib.request.Request(full_url, method='DELETE')
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"
except Exception as e:
return False, f"Erreur suppression S3 : {e}"
def delete_remote_file(remote_filename, custom_cfg=None):
cfg = copy.deepcopy(custom_cfg) if custom_cfg else get_backup_remote_config()
provider = str(cfg.get('provider', 'ftp')).strip().lower()
p_cfg = cfg.get(provider, {}) if isinstance(cfg.get(provider), dict) else {}
if provider == 'ftp':
return _delete_ftp(p_cfg, remote_filename)
elif provider == 'sftp':
return _delete_sftp(p_cfg, remote_filename)
elif provider == 'dropbox':
return _delete_dropbox(p_cfg, remote_filename)
elif provider == 'gdrive':
return _delete_gdrive(p_cfg, remote_filename)
elif provider == 'webdav':
return _delete_webdav(p_cfg, remote_filename)
elif provider == 's3':
return _delete_s3(p_cfg, remote_filename)
elif provider == 'webhook':
return True, "Webhook (suppression non requise)"
else:
return False, f"Protocole distant inconnu : {provider}"
def test_backup_remote(custom_cfg=None):
cfg = custom_cfg or get_backup_remote_config()
provider = str(cfg.get('provider', 'ftp')).strip().lower()
now_str = time.strftime('%Y%m%d-%H%M%S')
test_fname = f"ap-manageur-test-{now_str}.txt"
tmp_name = None
try:
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.txt') as tmp:
tmp.write(f"Test de connectivité stockage distant AP Manageur ({provider.upper()}) - {now_str}\n")
tmp_name = tmp.name
ok, msg = upload_backup_to_remote(tmp_name, custom_cfg=cfg, remote_filename=test_fname, persist_status=False)
# Supprimer le fichier texte de test sur le stockage distant une fois le test effectué
del_note = ""
try:
d_ok, d_msg = delete_remote_file(test_fname, custom_cfg=cfg)
if d_ok:
del_note = " (fichier texte de test supprimé)"
print(f"[ap-backup] Fichier texte de test supprimé sur {provider.upper()} : {test_fname}", flush=True)
except Exception as e_del:
print(f"[ap-backup] Avertissement suppression fichier test {test_fname} : {e_del}", flush=True)
return True, f"Connexion et test de transfert réussis ({provider.upper()}) : {msg}{del_note}"
finally:
if tmp_name and os.path.exists(tmp_name):
try: os.unlink(tmp_name)
except OSError: pass
def _list_remote_ftp(cfg):
import ftplib
host = str(cfg.get('host', '')).strip()
if not host: return set()
try: port = int(cfg.get('port') or 21)
except (ValueError, TypeError): port = 21
user = str(cfg.get('user', '')).strip() or 'anonymous'
password = str(cfg.get('password', ''))
rem_path = str(cfg.get('path', '') or '/').strip()
use_tls = str(cfg.get('tls', 'none')).lower() in ('explicit', 'tls', 'ftps', '1', 'true')
ftp = ftplib.FTP_TLS(timeout=15) if use_tls else ftplib.FTP(timeout=15)
try:
ftp.connect(host, port)
ftp.login(user, password)
if use_tls: ftp.prot_p()
if rem_path and rem_path != '/':
for part in [p for p in rem_path.split('/') if p]:
try: ftp.cwd(part)
except Exception: pass
files = set()
try:
for name in ftp.nlst():
base = os.path.basename(name.strip())
if base: files.add(base)
except Exception:
pass
return files
except Exception as e:
print(f"[ap-backup] Erreur listing FTP ({host}) : {e}", flush=True)
return None
finally:
try: ftp.quit()
except Exception: pass
def _list_remote_sftp(cfg):
host = str(cfg.get('host', '')).strip()
if not host: return set()
try: port = int(cfg.get('port') or 22)
except (ValueError, TypeError): port = 22
user = str(cfg.get('user', '')).strip()
password = str(cfg.get('password', ''))
key_text = str(cfg.get('key', '')).strip()
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
pkey = None
if key_text:
for pkey_class in (paramiko.RSAKey, paramiko.Ed25519Key, paramiko.ECDSAKey):
try:
pkey = pkey_class.from_private_key(io.StringIO(key_text))
break
except Exception: pass
try:
ssh.connect(host, port=port, username=user, password=password or None, pkey=pkey, timeout=15)
sftp = ssh.open_sftp()
target_dir, _ = _normalize_sftp_target(sftp, cfg.get('path', ''))
try:
entries = sftp.listdir(target_dir)
files = set()
for e in entries:
files.add(os.path.basename(e.strip()))
return files
except Exception as e_ls:
print(f"[ap-backup] Dossier SFTP non listable ({target_dir}) : {e_ls}", flush=True)
return set()
finally:
try: sftp.close()
except Exception: pass
except Exception as e:
print(f"[ap-backup] Erreur listing SFTP ({host}) : {e}", flush=True)
return None
finally:
try: ssh.close()
except Exception: pass
def _list_remote_dropbox(cfg):
token = str(cfg.get('token', '')).strip()
if not token: return set()
rem_path = str(cfg.get('path', '') or '/AP-Manageur-Backups/').strip()
if rem_path in ('/', ''):
path_arg = ""
else:
if not rem_path.startswith('/'): rem_path = '/' + rem_path
path_arg = rem_path.rstrip('/')
url = "https://api.dropboxapi.com/2/files/list_folder"
payload = json.dumps({"path": path_arg, "recursive": False}).encode('utf-8')
req = urllib.request.Request(url, data=payload, method='POST')
req.add_header('Authorization', f'Bearer {token}')
req.add_header('Content-Type', 'application/json')
ctx = ssl.create_default_context()
try:
with urllib.request.urlopen(req, context=ctx, timeout=20) as resp:
data = json.loads(resp.read().decode('utf-8'))
entries = data.get('entries', [])
return set(e.get('name') for e in entries if e.get('name'))
except urllib.error.HTTPError as e:
if e.code in (404, 409):
return set()
print(f"[ap-backup] HTTP {e.code} listing Dropbox : {e.reason}", flush=True)
return None
except Exception as e:
print(f"[ap-backup] Erreur listing Dropbox : {e}", flush=True)
return None
def _list_remote_gdrive(cfg):
token = str(cfg.get('token', '')).strip()
if not token: return set()
folder_id = str(cfg.get('folder_id', '')).strip()
ctx = ssl.create_default_context()
query = "trashed = false and mimeType != 'application/vnd.google-apps.folder'"
if folder_id:
query += f" and '{folder_id}' in parents"
search_url = f"https://www.googleapis.com/drive/v3/files?q={urllib.parse.quote(query)}&pageSize=1000&fields=files(id,name)"
req = urllib.request.Request(search_url, method='GET')
req.add_header('Authorization', f'Bearer {token}')
try:
with urllib.request.urlopen(req, context=ctx, timeout=20) as resp:
data = json.loads(resp.read().decode('utf-8'))
files = data.get('files', [])
return set(f.get('name') for f in files if f.get('name'))
except Exception as e:
print(f"[ap-backup] Erreur listing Google Drive : {e}", flush=True)
return None
def _list_remote_webdav(cfg):
server_url = str(cfg.get('url', '')).strip()
if not server_url: return set()
if not server_url.endswith('/'): server_url += '/'
extra_path = str(cfg.get('path', '')).strip().strip('/')
if extra_path:
server_url += '/'.join(urllib.parse.quote(p) for p in extra_path.split('/')) + '/'
user = str(cfg.get('user', '')).strip()
password = str(cfg.get('password', ''))
req = urllib.request.Request(server_url, method='PROPFIND')
req.add_header('Depth', '1')
if user or password:
auth_str = base64.b64encode(f"{user}:{password}".encode('utf-8')).decode('ascii')
req.add_header('Authorization', f'Basic {auth_str}')
ctx = ssl.create_default_context()
try:
with urllib.request.urlopen(req, context=ctx, timeout=20) as resp:
body = resp.read().decode('utf-8', errors='ignore')
import xml.etree.ElementTree as ET
root = ET.fromstring(body)
names = set()
for elem in root.iter():
if elem.tag.endswith('href') and elem.text:
p = urllib.parse.unquote(elem.text.strip().rstrip('/'))
b = os.path.basename(p)
if b and b.lower().endswith(BACKUP_ALLOWED_EXTS):
names.add(b)
return names
except urllib.error.HTTPError as e:
if e.code == 404: return set()
print(f"[ap-backup] HTTP {e.code} listing WebDAV : {e.reason}", flush=True)
return None
except Exception as e:
print(f"[ap-backup] Erreur listing WebDAV : {e}", flush=True)
return None
def _list_remote_s3(cfg):
endpoint = str(cfg.get('endpoint', '') or 'https://s3.amazonaws.com').strip()
bucket = str(cfg.get('bucket', '')).strip()
if not bucket: return set()
region = str(cfg.get('region', '') or 'us-east-1').strip()
access_key = str(cfg.get('access_key', '')).strip()
secret_key = str(cfg.get('secret_key', '')).strip()
prefix = str(cfg.get('path', '') or '').strip().strip('/')
rclone_bin = find_bin('rclone')
if rclone_bin:
rc = tempfile.NamedTemporaryFile('w', delete=False)
try:
rc.write(f"[s3remote]\ntype = s3\nprovider = Other\nendpoint = {endpoint}\nregion = {region}\naccess_key_id = {access_key}\nsecret_access_key = {secret_key}\n")
rc.flush(); rc.close()
remote_target = f"s3remote:{bucket}/{prefix}" if prefix else f"s3remote:{bucket}"
cmd = [rclone_bin, '--config', rc.name, 'lsf', remote_target]
r = subprocess.run(cmd, capture_output=True, text=True, timeout=25)
if r.returncode == 0:
lines = [l.strip().rstrip('/') for l in r.stdout.splitlines() if l.strip()]
return set(os.path.basename(l) for l in lines)
except Exception:
pass
finally:
if os.path.exists(rc.name):
try: os.unlink(rc.name)
except OSError: pass
payload = b''
payload_hash = hashlib.sha256(payload).hexdigest()
now_dt = datetime.datetime.now(datetime.timezone.utc)
amz_date = now_dt.strftime('%Y%m%dT%H%M%SZ')
datestamp = now_dt.strftime('%Y%m%d')
if not endpoint.startswith('http://') and not endpoint.startswith('https://'):
endpoint = 'https://' + endpoint
parsed = urllib.parse.urlparse(endpoint)
host = parsed.netloc
query_str = "list-type=2"
if prefix: query_str += f"&prefix={urllib.parse.quote(prefix)}"
canonical_uri = f"/{bucket}"
canonical_headers = f"host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n"
signed_headers = "host;x-amz-content-sha256;x-amz-date"
canonical_req = f"GET\n{canonical_uri}\n{query_str}\n{canonical_headers}\n{signed_headers}\n{payload_hash}"
algorithm = "AWS4-HMAC-SHA256"
credential_scope = f"{datestamp}/{region}/s3/aws4_request"
string_to_sign = f"{algorithm}\n{amz_date}\n{credential_scope}\n{hashlib.sha256(canonical_req.encode('utf-8')).hexdigest()}"
def _sign(k, m): return hmac.new(k, m.encode('utf-8'), hashlib.sha256).digest()
k_sign = _sign(_sign(_sign(_sign(('AWS4' + secret_key).encode('utf-8'), datestamp), region), 's3'), 'aws4_request')
signature = hmac.new(k_sign, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest()
auth_hdr = f"{algorithm} Credential={access_key}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}"
full_url = f"{endpoint.rstrip('/')}{canonical_uri}?{query_str}"
req = urllib.request.Request(full_url, method='GET')
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=20) as resp:
body = resp.read().decode('utf-8', errors='ignore')
import xml.etree.ElementTree as ET
root = ET.fromstring(body)
names = set()
for elem in root.iter():
if elem.tag.endswith('Key') and elem.text:
b = os.path.basename(elem.text.strip())
if b: names.add(b)
return names
except Exception as e:
print(f"[ap-backup] Erreur listing S3 : {e}", flush=True)
return None
def _download_ftp(cfg, remote_filename, dest_path):
import ftplib
host = str(cfg.get('host', '')).strip()
if not host: raise ValueError("Hôte FTP manquant")
try: port = int(cfg.get('port') or 21)
except (ValueError, TypeError): port = 21
user = str(cfg.get('user', '')).strip() or 'anonymous'
password = str(cfg.get('password', ''))
rem_path = str(cfg.get('path', '') or '').strip()
use_tls = str(cfg.get('tls', 'none')).lower() in ('explicit', 'tls', 'ftps', '1', 'true')
ftp = ftplib.FTP_TLS(timeout=25) if use_tls else ftplib.FTP(timeout=25)
try:
ftp.connect(host, port)
ftp.login(user, password)
if use_tls: ftp.prot_p()
if rem_path and rem_path not in ('/', '.'):
for part in [p for p in rem_path.split('/') if p]:
try: ftp.cwd(part)
except Exception: pass
with open(dest_path, 'wb') as f:
ftp.retrbinary(f'RETR {remote_filename}', f.write)
return True
finally:
try: ftp.quit()
except Exception:
try: ftp.close()
except Exception: pass
def _download_sftp(cfg, remote_filename, dest_path):
host = str(cfg.get('host', '')).strip()
if not host: raise ValueError("Hôte SFTP manquant")
try: port = int(cfg.get('port') or 22)
except (ValueError, TypeError): port = 22
user = str(cfg.get('user', '')).strip()
password = str(cfg.get('password', ''))
key_text = str(cfg.get('key', '')).strip()
import paramiko
import io
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
pkey = None
if key_text:
for pkey_class in (paramiko.RSAKey, paramiko.Ed25519Key, paramiko.ECDSAKey):
try:
pkey = pkey_class.from_private_key(io.StringIO(key_text))
break
except Exception: pass
sftp = None
try:
connect_kwargs = {'hostname': host, 'port': port, 'username': user, 'timeout': 20}
if pkey: connect_kwargs['pkey'] = pkey
elif password: connect_kwargs['password'] = password
ssh.connect(**connect_kwargs)
sftp = ssh.open_sftp()
_, target_file = _normalize_sftp_target(sftp, cfg.get('path', ''), remote_filename)
sftp.get(target_file, dest_path)
return True
finally:
if sftp:
try: sftp.close()
except Exception: pass
try: ssh.close()
except Exception: pass
def _download_dropbox(cfg, remote_filename, dest_path):
token = str(cfg.get('token', '')).strip()
if not token: raise ValueError("Jeton Dropbox manquant")
rem_path = str(cfg.get('path', '') or '/AP-Manageur-Backups/').strip()
if not rem_path.startswith('/'): rem_path = '/' + rem_path
if not rem_path.endswith('/'): rem_path += '/'
dbx_path = rem_path + remote_filename
url = "https://content.dropboxapi.com/2/files/download"
req = urllib.request.Request(url, method='POST')
req.add_header('Authorization', f'Bearer {token}')
req.add_header('Dropbox-API-Arg', json.dumps({"path": dbx_path}))
ctx = ssl.create_default_context()
with urllib.request.urlopen(req, context=ctx, timeout=60) as resp:
with open(dest_path, 'wb') as out_f:
while True:
chunk = resp.read(65536)
if not chunk: break
out_f.write(chunk)
return True
def _download_gdrive(cfg, remote_filename, dest_path):
token = str(cfg.get('token', '')).strip()
if not token: raise ValueError("Jeton Google Drive manquant")
folder_id = str(cfg.get('folder_id', '')).strip()
ctx = ssl.create_default_context()
safe_name = remote_filename.replace("'", "\\'")
query = f"trashed = false and name = '{safe_name}'"
if folder_id:
query += f" and '{folder_id}' in parents"
search_url = f"https://www.googleapis.com/drive/v3/files?q={urllib.parse.quote(query)}&fields=files(id,name)"
req = urllib.request.Request(search_url, method='GET')
req.add_header('Authorization', f'Bearer {token}')
file_id = None
with urllib.request.urlopen(req, context=ctx, timeout=20) as resp:
d = json.loads(resp.read().decode('utf-8'))
files = d.get('files', [])
if files: file_id = files[0]['id']
if not file_id:
raise FileNotFoundError(f"Fichier {remote_filename} non trouvé sur Google Drive")
dl_url = f"https://www.googleapis.com/drive/v3/files/{file_id}?alt=media"
dl_req = urllib.request.Request(dl_url, method='GET')
dl_req.add_header('Authorization', f'Bearer {token}')
with urllib.request.urlopen(dl_req, context=ctx, timeout=60) as resp:
with open(dest_path, 'wb') as out_f:
while True:
chunk = resp.read(65536)
if not chunk: break
out_f.write(chunk)
return True
def _download_webdav(cfg, remote_filename, dest_path):
server_url = str(cfg.get('url', '')).strip()
if not server_url: raise ValueError("URL WebDAV manquante")
if not server_url.endswith('/'): server_url += '/'
extra_path = str(cfg.get('path', '')).strip().strip('/')
if extra_path:
server_url += '/'.join(urllib.parse.quote(p) for p in extra_path.split('/')) + '/'
target_url = server_url + urllib.parse.quote(remote_filename)
user = str(cfg.get('user', '')).strip()
password = str(cfg.get('password', ''))
req = urllib.request.Request(target_url, method='GET')
if user or password:
auth_str = base64.b64encode(f"{user}:{password}".encode('utf-8')).decode('ascii')
req.add_header('Authorization', f'Basic {auth_str}')
ctx = ssl.create_default_context()
with urllib.request.urlopen(req, context=ctx, timeout=60) as resp:
with open(dest_path, 'wb') as out_f:
while True:
chunk = resp.read(65536)
if not chunk: break
out_f.write(chunk)
return True
def _download_s3(cfg, remote_filename, dest_path):
endpoint = str(cfg.get('endpoint', '') or 'https://s3.amazonaws.com').strip()
bucket = str(cfg.get('bucket', '')).strip()
if not bucket: raise ValueError("Bucket S3 manquant")
region = str(cfg.get('region', '') or 'us-east-1').strip()
access_key = str(cfg.get('access_key', '')).strip()
secret_key = str(cfg.get('secret_key', '')).strip()
prefix = str(cfg.get('path', '') or '').strip().strip('/')
key = f"{prefix}/{remote_filename}" if prefix else remote_filename
rclone_bin = find_bin('rclone')
if rclone_bin:
rc = tempfile.NamedTemporaryFile('w', delete=False)
try:
rc.write(f"[s3remote]\ntype = s3\nprovider = Other\nendpoint = {endpoint}\nregion = {region}\naccess_key_id = {access_key}\nsecret_access_key = {secret_key}\n")
rc.flush(); rc.close()
cmd = [rclone_bin, '--config', rc.name, 'copyto', f"s3remote:{bucket}/{key}", dest_path]
r = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
if r.returncode != 0:
raise RuntimeError(r.stderr.strip() or f"Erreur rclone copyto ({r.returncode})")
return True
finally:
if os.path.exists(rc.name):
try: os.unlink(rc.name)
except OSError: pass
raise RuntimeError("Client S3 introuvable (rclone requis)")
def download_remote_file(remote_filename, dest_path, custom_cfg=None):
cfg = custom_cfg or get_backup_remote_config()
provider = str(cfg.get('provider', 'ftp')).strip().lower()
p_cfg = cfg.get(provider, {}) if isinstance(cfg.get(provider), dict) else {}
if provider == 'ftp':
return _download_ftp(p_cfg, remote_filename, dest_path)
elif provider == 'sftp':
return _download_sftp(p_cfg, remote_filename, dest_path)
elif provider == 'dropbox':
return _download_dropbox(p_cfg, remote_filename, dest_path)
elif provider == 'gdrive':
return _download_gdrive(p_cfg, remote_filename, dest_path)
elif provider == 'webdav':
return _download_webdav(p_cfg, remote_filename, dest_path)
elif provider == 's3':
return _download_s3(p_cfg, remote_filename, dest_path)
else:
raise ValueError(f"Protocole distant {provider} non pris en charge pour le téléchargement")
def list_remote_files_detailed(custom_cfg=None):
cfg = custom_cfg or get_backup_remote_config()
if not cfg.get('enabled') and not custom_cfg:
return None, "Stockage distant désactivé"
provider = str(cfg.get('provider', 'ftp')).strip().lower()
p_cfg = cfg.get(provider, {}) if isinstance(cfg.get(provider), dict) else {}
ensure_backup_dir()
local_files = set()
try:
local_files = set(os.listdir(BACKUP_DIR))
except Exception:
pass
items = []
if provider == 'ftp':
import ftplib
host = str(p_cfg.get('host', '')).strip()
if not host: return [], ""
try: port = int(p_cfg.get('port') or 21)
except (ValueError, TypeError): port = 21
user = str(p_cfg.get('user', '')).strip() or 'anonymous'
password = str(p_cfg.get('password', ''))
rem_path = str(p_cfg.get('path', '') or '').strip()
use_tls = str(p_cfg.get('tls', 'none')).lower() in ('explicit', 'tls', 'ftps', '1', 'true')
ftp = ftplib.FTP_TLS(timeout=15) if use_tls else ftplib.FTP(timeout=15)
try:
ftp.connect(host, port)
ftp.login(user, password)
if use_tls: ftp.prot_p()
if rem_path and rem_path not in ('/', '.'):
for part in [p for p in rem_path.split('/') if p]:
try: ftp.cwd(part)
except Exception: pass
used_mlsd = False
try:
for line in ftp.mlsd():
name, facts = line
if facts.get('type') == 'file' and name.lower().endswith(BACKUP_ALLOWED_EXTS):
size = int(facts.get('size') or 0)
mtime_str = facts.get('modify', '')
dt_str = ''
if len(mtime_str) >= 14:
dt_str = f"{mtime_str[0:4]}-{mtime_str[4:6]}-{mtime_str[6:8]} {mtime_str[8:10]}:{mtime_str[10:12]}:{mtime_str[12:14]}"
items.append({
'name': name,
'size': size,
'size_str': format_bytes(size),
'date': dt_str,
'is_local': (name in local_files)
})
used_mlsd = True
except Exception:
pass
if not used_mlsd:
try:
for name in ftp.nlst():
base = os.path.basename(name.strip())
if base.lower().endswith(BACKUP_ALLOWED_EXTS):
sz = 0
try: sz = ftp.size(base) or 0
except Exception: pass
items.append({
'name': base,
'size': sz,
'size_str': format_bytes(sz) if sz else '—',
'date': '',
'is_local': (base in local_files)
})
except Exception:
pass
finally:
try: ftp.quit()
except Exception:
try: ftp.close()
except Exception: pass
elif provider == 'sftp':
import paramiko
host = str(p_cfg.get('host', '')).strip()
if not host: return [], ""
try: port = int(p_cfg.get('port') or 22)
except (ValueError, TypeError): port = 22
user = str(p_cfg.get('user', '')).strip()
password = str(p_cfg.get('password', ''))
key_text = str(p_cfg.get('key', '')).strip()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
pkey = None
if key_text:
for pkey_class in (paramiko.RSAKey, paramiko.Ed25519Key, paramiko.ECDSAKey):
try:
pkey = pkey_class.from_private_key(io.StringIO(key_text))
break
except Exception: pass
try:
ssh.connect(host, port=port, username=user, password=password or None, pkey=pkey, timeout=15)
sftp = ssh.open_sftp()
target_dir, _ = _normalize_sftp_target(sftp, p_cfg.get('path', ''))
try:
for attr in sftp.listdir_attr(target_dir):
base = os.path.basename(attr.filename)
if base.lower().endswith(BACKUP_ALLOWED_EXTS):
sz = attr.st_size or 0
mtime = attr.st_mtime or 0
dt_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(mtime)) if mtime else ''
items.append({
'name': base,
'size': sz,
'size_str': format_bytes(sz),
'date': dt_str,
'is_local': (base in local_files)
})
except Exception as e_ls:
print(f"[ap-backup] Erreur listdir_attr SFTP ({target_dir}): {e_ls}", flush=True)
finally:
try: sftp.close()
except Exception: pass
finally:
try: ssh.close()
except Exception: pass
elif provider == 'dropbox':
token = str(p_cfg.get('token', '')).strip()
if token:
rem_path = str(p_cfg.get('path', '') or '/AP-Manageur-Backups/').strip()
path_arg = "" if rem_path in ('/', '') else ('/' + rem_path.strip('/')).rstrip('/')
url = "https://api.dropboxapi.com/2/files/list_folder"
payload = json.dumps({"path": path_arg, "recursive": False}).encode('utf-8')
req = urllib.request.Request(url, data=payload, method='POST')
req.add_header('Authorization', f'Bearer {token}')
req.add_header('Content-Type', 'application/json')
ctx = ssl.create_default_context()
try:
with urllib.request.urlopen(req, context=ctx, timeout=20) as resp:
data = json.loads(resp.read().decode('utf-8'))
for entry in data.get('entries', []):
if entry.get('.tag') == 'file':
base = entry.get('name', '')
if base.lower().endswith(BACKUP_ALLOWED_EXTS):
sz = int(entry.get('size') or 0)
mtime = entry.get('server_modified', '').replace('T', ' ').rstrip('Z')
items.append({
'name': base,
'size': sz,
'size_str': format_bytes(sz),
'date': mtime,
'is_local': (base in local_files)
})
except Exception as e:
print(f"[ap-backup] Erreur listing détaillé Dropbox : {e}", flush=True)
elif provider == 'gdrive':
token = str(p_cfg.get('token', '')).strip()
if token:
folder_id = str(p_cfg.get('folder_id', '')).strip()
ctx = ssl.create_default_context()
query = "trashed = false and mimeType != 'application/vnd.google-apps.folder'"
if folder_id:
query += f" and '{folder_id}' in parents"
search_url = f"https://www.googleapis.com/drive/v3/files?q={urllib.parse.quote(query)}&pageSize=1000&fields=files(id,name,size,modifiedTime)"
req = urllib.request.Request(search_url, method='GET')
req.add_header('Authorization', f'Bearer {token}')
try:
with urllib.request.urlopen(req, context=ctx, timeout=20) as resp:
data = json.loads(resp.read().decode('utf-8'))
for f in data.get('files', []):
base = f.get('name', '')
if base.lower().endswith(BACKUP_ALLOWED_EXTS):
sz = int(f.get('size') or 0)
mtime = f.get('modifiedTime', '').replace('T', ' ').split('.')[0]
items.append({
'name': base,
'size': sz,
'size_str': format_bytes(sz),
'date': mtime,
'id': f.get('id', ''),
'is_local': (base in local_files)
})
except Exception as e:
print(f"[ap-backup] Erreur listing détaillé GDrive : {e}", flush=True)
elif provider == 'webdav':
names = _list_remote_webdav(p_cfg)
if names:
for n in names:
if n.lower().endswith(BACKUP_ALLOWED_EXTS):
items.append({
'name': n,
'size': 0,
'size_str': '—',
'date': '',
'is_local': (n in local_files)
})
elif provider == 's3':
names = _list_remote_s3(p_cfg)
if names:
for n in names:
if n.lower().endswith(BACKUP_ALLOWED_EXTS):
items.append({
'name': n,
'size': 0,
'size_str': '—',
'date': '',
'is_local': (n in local_files)
})
items.sort(key=lambda x: x.get('name', ''), reverse=True)
return items, None
def get_remote_storage_files(cfg=None):
rcfg = cfg or get_backup_remote_config()
if not rcfg.get('enabled'):
return None
provider = str(rcfg.get('provider', 'ftp')).strip().lower()
if provider == 'webhook':
return None
try:
items, err = list_remote_files_detailed(rcfg)
if items is None:
return None
return set(x['name'] for x in items)
except Exception as e:
print(f"[ap-backup] Erreur get_remote_storage_files ({provider}) : {e}", flush=True)
return None
def sync_remote_backups_presence(force=False):
"""Vérifie physiquement sur le service Cloud/Distant quels fichiers sont réellement présents."""
rcfg = get_backup_remote_config()
if not rcfg.get('enabled'):
return False, "Stockage distant désactivé"
provider = str(rcfg.get('provider', 'ftp')).strip().lower()
if provider == 'webhook':
return True, "Webhook (push-only)"
remote_files = get_remote_storage_files(rcfg)
if remote_files is None:
return False, f"Impossible de contacter {provider.upper()}"
up_files = rcfg.get('uploaded_files', {})
if not isinstance(up_files, dict):
up_files = {}
modified = False
now_ts = time.strftime('%Y-%m-%d %H:%M:%S')
ensure_backup_dir()
local_files = set()
try:
local_files = set(os.listdir(BACKUP_DIR))
except Exception:
pass
for fname in local_files:
if not fname.lower().endswith(BACKUP_ALLOWED_EXTS):
continue
if fname in remote_files:
if fname not in up_files or up_files[fname].get('provider') != provider:
up_files[fname] = {'time': up_files.get(fname, {}).get('time', now_ts), 'provider': provider}
modified = True
else:
if fname in up_files:
up_files.pop(fname, None)
modified = True
# Nettoyer les entrées d'uploaded_files qui ne sont plus physiquement sur le cloud
for f in list(up_files.keys()):
if f not in remote_files:
up_files.pop(f, None)
modified = True
# Si last_upload_file n'est plus physiquement présent sur le cloud, nettoyer le statut
if rcfg.get('last_upload_file') and rcfg.get('last_upload_file') not in remote_files:
rcfg['last_upload_status'] = 'missing'
rcfg['last_upload_error'] = 'Fichier absent du stockage distant'
modified = True
if modified:
rcfg['uploaded_files'] = up_files
set_pref('backup_remote_config', json.dumps(rcfg, ensure_ascii=False))
print(f"[ap-backup] Synchro physique cloud terminée avec {provider.upper()} : {len(up_files)} fichier(s) présent(s)", flush=True)
return True, f"{len(up_files)} fichier(s) présent(s) sur {provider.upper()}"
def start_remote_backup_sync_daemon():
"""Vérifie physiquement au démarrage de l'application la présence des sauvegardes sur le stockage distant."""
time.sleep(3)
try:
rcfg = get_backup_remote_config()
if rcfg.get('enabled'):
ok, msg = sync_remote_backups_presence()
print(f"[ap-backup] Vérification présence cloud au démarrage : {msg}", flush=True)
except Exception as e:
print(f"[ap-backup] Avertissement synchro cloud au démarrage : {e}", flush=True)
def list_server_backups():
ensure_backup_dir()
items = []
total_size = 0
rcfg = get_backup_remote_config()
uploaded_files = rcfg.get('uploaded_files', {})
if not isinstance(uploaded_files, dict):
uploaded_files = {}
last_up_file = rcfg.get('last_upload_file', '')
last_up_ok = (rcfg.get('last_upload_status') == 'ok')
cur_provider = rcfg.get('provider', 'ftp')
try:
for entry in os.listdir(BACKUP_DIR):
if not entry.lower().endswith(BACKUP_ALLOWED_EXTS):
continue
full = os.path.join(BACKUP_DIR, entry)
if not os.path.isfile(full):
continue
try:
st = os.stat(full)
total_size += st.st_size
low = entry.lower()
if '-auto-' in low:
trig = 'auto'
elif '-manual-' in low or low.startswith('ap-manageur-'):
trig = 'manual'
else:
trig = 'external'
up_info = uploaded_files.get(entry) if isinstance(uploaded_files, dict) else None
is_uploaded = bool(up_info)
up_prov = (up_info.get('provider') if isinstance(up_info, dict) else '') if is_uploaded else ''
up_time = (up_info.get('time') if isinstance(up_info, dict) else '') if is_uploaded else ''
items.append({
'filename': entry,
'size': st.st_size,
'size_str': format_bytes(st.st_size),
'mtime': st.st_mtime,
'created_at': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(st.st_mtime)),
'trigger': trig,
'remote_uploaded': is_uploaded,
'remote_provider': up_prov,
'remote_uploaded_at': up_time
})
except OSError:
continue
except OSError:
pass
items.sort(key=lambda x: x['mtime'], reverse=True)
return items, total_size
def backup_scheduler_loop():
"""Boucle d'arrière-plan vérifiant l'expression Cron et créant automatiquement les sauvegardes dans BACKUP_DIR."""
global _last_backup_cron_minute
while True:
try:
now = datetime.datetime.now()
cur_key = f"{now.year}-{now.month:02d}-{now.day:02d} {now.hour:02d}:{now.minute:02d}"
if cur_key != _last_backup_cron_minute:
sched = get_backup_schedule()
if sched.get('enabled'):
cron_expr = str(sched.get('cron_expr', '')).strip()
if cron_expr and match_cron(cron_expr, now):
_last_backup_cron_minute = cur_key
print(f"[ap-backup] Déclenchement sauvegarde automatique Cron ({cron_expr}) à {cur_key}...", flush=True)
try:
info = create_server_backup(trigger='auto')
log('sauvegarde_automatique', f"Cron ({info['filename']})", 'SYSTEM', 'BACKUP')
print(f"[ap-backup] Sauvegarde automatique créée : {info['filename']} ({info['size_str']})", flush=True)
except Exception as e_bk:
print(f"[ap-backup] Erreur sauvegarde automatique : {e_bk}", flush=True)
try:
sc = get_backup_schedule()
sc['last_run'] = time.strftime('%Y-%m-%d %H:%M:%S')
sc['last_status'] = f'error: {e_bk}'
set_pref('backup_schedule', json.dumps(sc, ensure_ascii=False))
except Exception:
pass
except Exception as e:
print(f"[ap-backup] Erreur boucle scheduler backup : {e}", flush=True)
time.sleep(20)
API_MSG_I18N = {
'Authentification réussie': {'en-us': 'Authentication successful', 'en-gb': 'Authentication successful'},
'Authentification réussie avec': {'en-us': 'Authentication successful with', 'en-gb': 'Authentication successful with'},
'Erreur export SQLite': {'en-us': 'SQLite export error', 'en-gb': 'SQLite export error'},
'Erreur génération archive ZIP': {'en-us': 'ZIP archive generation error', 'en-gb': 'ZIP archive generation error'},
'Erreur génération sauvegarde': {'en-us': 'Backup generation error', 'en-gb': 'Backup generation error'},
'Erreur lors de la restauration': {'en-us': 'Error during restore', 'en-gb': 'Error during restore'},
'Impossible d’analyser le fichier': {'en-us': 'Unable to parse file', 'en-gb': 'Unable to parse file'},
"Impossible d'analyser le fichier": {'en-us': 'Unable to parse file', 'en-gb': 'Unable to parse file'},
'Passkey enregistrée avec succès !': {'en-us': 'Passkey registered successfully!', 'en-gb': 'Passkey registered successfully!'},
'enregistrée avec succès !': {'en-us': 'registered successfully!', 'en-gb': 'registered successfully!'},
'Clé de sécurité renommée avec succès': {'en-us': 'Security key renamed successfully', 'en-gb': 'Security key renamed successfully'},
'Passkey supprimée avec succès': {'en-us': 'Passkey deleted successfully', 'en-gb': 'Passkey deleted successfully'},
'Double identification activée avec succès !': {'en-us': 'Two-factor authentication enabled successfully!', 'en-gb': 'Two-factor authentication enabled successfully!'},
'Nouveaux codes générés avec succès !': {'en-us': 'New recovery codes generated successfully!', 'en-gb': 'New recovery codes generated successfully!'},
'Double identification désactivée': {'en-us': 'Two-factor authentication disabled', 'en-gb': 'Two-factor authentication disabled'},
'Session déconnectée avec succès': {'en-us': 'Session disconnected successfully', 'en-gb': 'Session disconnected successfully'},
'Machine renommée avec succès': {'en-us': 'Machine renamed successfully', 'en-gb': 'Machine renamed successfully'},
'Activation refusée': {'en-us': 'Activation refused', 'en-gb': 'Activation refused'},
'Désactivation refusée': {'en-us': 'Deactivation refused', 'en-gb': 'Deactivation refused'},
'Code refusé': {'en-us': 'Invalid code', 'en-gb': 'Invalid code'},
'Nom de machine vide': {'en-us': 'Machine name cannot be empty', 'en-gb': 'Machine name cannot be empty'},
'Token de session manquant': {'en-us': 'Missing session token', 'en-gb': 'Missing session token'},
'Impossible de déconnecter la session': {'en-us': 'Unable to disconnect session', 'en-gb': 'Unable to disconnect session'},
'Impossible de renommer la machine': {'en-us': 'Unable to rename machine', 'en-gb': 'Unable to rename machine'},
'Passkey introuvable': {'en-us': 'Passkey not found', 'en-gb': 'Passkey not found'},
'Capture déjà en cours sur': {'en-us': 'Capture already running on', 'en-gb': 'Capture already running on'},
'Capture démarrée sur l': {'en-us': 'Capture started on', 'en-gb': 'Capture started on'},
'Échec de connexion WireGuard': {'en-us': 'WireGuard connection failed', 'en-gb': 'WireGuard connection failed'},
'Échec de connexion OpenVPN': {'en-us': 'OpenVPN connection failed', 'en-gb': 'OpenVPN connection failed'},
'Erreur de connexion': {'en-us': 'Connection error', 'en-gb': 'Connection error'},
"Nom d'icône manquant": {'en-us': 'Missing icon name', 'en-gb': 'Missing icon name'},
'Nom d’icône manquant': {'en-us': 'Missing icon name', 'en-gb': 'Missing icon name'},
'Profil connecté': {'en-us': 'Profile connected', 'en-gb': 'Profile connected'},
'Profil déconnecté': {'en-us': 'Profile disconnected', 'en-gb': 'Profile disconnected'},
'Clé d’API créée avec succès': {'en-us': 'API key created successfully', 'en-gb': 'API key created successfully'},
'Clé d’API activée avec succès': {'en-us': 'API key enabled successfully', 'en-gb': 'API key enabled successfully'},
'Clé d’API désactivée avec succès': {'en-us': 'API key disabled successfully', 'en-gb': 'API key disabled successfully'},
'Clé d’API supprimée avec succès': {'en-us': 'API key deleted successfully', 'en-gb': 'API key deleted successfully'},
'Le nom de la clé API est obligatoire': {'en-us': 'API key name is required', 'en-gb': 'API key name is required'},
'Au moins une autorisation doit être sélectionnée': {'en-us': 'At least one permission must be selected', 'en-gb': 'At least one permission must be selected'},
'Clé API introuvable': {'en-us': 'API key not found', 'en-gb': 'API key not found'},
'Droits administrateur requis': {'en-us': 'Administrator privileges required', 'en-gb': 'Administrator privileges required'},
'Authentification requise': {'en-us': 'Authentication required', 'en-gb': 'Authentication required'},
'Nom d’utilisateur ou mot de passe incorrect': {'en-us': 'Incorrect username or password', 'en-gb': 'Incorrect username or password'},
'Compte non configuré': {'en-us': 'Account not configured', 'en-gb': 'Account not configured'},
'Mot de passe actuel incorrect': {'en-us': 'Incorrect current password', 'en-gb': 'Incorrect current password'},
'Les nouveaux mots de passe ne correspondent pas': {'en-us': 'New passwords do not match', 'en-gb': 'New passwords do not match'},
'Le mot de passe doit contenir au moins 8 caractères': {'en-us': 'Password must be at least 8 characters long', 'en-gb': 'Password must be at least 8 characters long'},
'Le mot de passe doit contenir entre 8 et 128 caractères': {'en-us': 'Password must be between 8 and 128 characters long', 'en-gb': 'Password must be between 8 and 128 characters long'},
'Nom d’utilisateur invalide': {'en-us': 'Invalid username', 'en-gb': 'Invalid username'},
'Nom utilisateur invalide': {'en-us': 'Invalid username', 'en-gb': 'Invalid username'},
'Code 2FA incorrect': {'en-us': 'Incorrect 2FA code', 'en-gb': 'Incorrect 2FA code'},
'Code 2FA invalide': {'en-us': 'Invalid 2FA code', 'en-gb': 'Invalid 2FA code'},
'Code de secours déjà utilisé': {'en-us': 'Backup code already used', 'en-gb': 'Backup code already used'},
'Profil introuvable': {'en-us': 'Profile not found', 'en-gb': 'Profile not found'},
'Profil VPN introuvable': {'en-us': 'VPN profile not found', 'en-gb': 'VPN profile not found'},
'Profil VPN enregistré avec succès': {'en-us': 'VPN profile saved successfully', 'en-gb': 'VPN profile saved successfully'},
'Profil VPN supprimé avec succès': {'en-us': 'VPN profile deleted successfully', 'en-gb': 'VPN profile deleted successfully'},
'Contenu du fichier manquant': {'en-us': 'Missing file content', 'en-gb': 'Missing file content'},
'Format de fichier invalide': {'en-us': 'Invalid file format', 'en-gb': 'Invalid file format'},
'Nom de l’application invalide': {'en-us': 'Invalid application name', 'en-gb': 'Invalid application name'},
'Nom court invalide': {'en-us': 'Invalid short name', 'en-gb': 'Invalid short name'},
'Thème invalide': {'en-us': 'Invalid theme', 'en-gb': 'Invalid theme'},
'Adresse MAC invalide': {'en-us': 'Invalid MAC address', 'en-gb': 'Invalid MAC address'},
'Impossible de se connecter au VPN': {'en-us': 'Unable to connect to VPN', 'en-gb': 'Unable to connect to VPN'},
'Tunnel VPN déconnecté': {'en-us': 'VPN tunnel disconnected', 'en-gb': 'VPN tunnel disconnected'},
'Le tunnel VPN est actuellement déconnecté': {'en-us': 'VPN tunnel is currently disconnected', 'en-gb': 'VPN tunnel is currently disconnected'},
'IP publique introuvable via ce tunnel': {'en-us': 'Public IP not found through this tunnel', 'en-gb': 'Public IP not found through this tunnel'},
'Passkey introuvable': {'en-us': 'Passkey not found', 'en-gb': 'Passkey not found'},
'Passkey inconnue ou non enregistrée': {'en-us': 'Passkey unknown or not registered', 'en-gb': 'Passkey unknown or not registered'},
'Passkey supprimée avec succès': {'en-us': 'Passkey deleted successfully', 'en-gb': 'Passkey deleted successfully'},
'Clé de sécurité renommée avec succès': {'en-us': 'Security key renamed successfully', 'en-gb': 'Security key renamed successfully'},
'Le nom de la clé ne peut pas être vide': {'en-us': 'Key name cannot be empty', 'en-gb': 'Key name cannot be empty'},
'Aucune modification': {'en-us': 'No changes', 'en-gb': 'No changes'},
'Action non autorisée': {'en-us': 'Unauthorized action', 'en-gb': 'Unauthorized action'},
'Erreur interne du serveur': {'en-us': 'Internal server error', 'en-gb': 'Internal server error'},
'Erreur interne': {'en-us': 'Internal error', 'en-gb': 'Internal error'},
'Réglages enregistrés avec succès': {'en-us': 'Settings saved successfully', 'en-gb': 'Settings saved successfully'},
'Réglages enregistrés': {'en-us': 'Settings saved successfully', 'en-gb': 'Settings saved successfully'},
'Personnalisation enregistrée sur le serveur': {'en-us': 'Customization saved to server', 'en-gb': 'Customisation saved to server'},
'Compteur de données remis à zéro': {'en-us': 'Data counter reset to zero', 'en-gb': 'Data counter reset to zero'},
'Limitations enregistrées': {'en-us': 'Limitations saved successfully', 'en-gb': 'Limitations saved successfully'},
'Limitations enregistrées avec succès': {'en-us': 'Limitations saved successfully', 'en-gb': 'Limitations saved successfully'},
'Erreur enregistrement limitations': {'en-us': 'Error saving limitations', 'en-gb': 'Error saving limitations'},
'Sauvegarde restaurée avec succès': {'en-us': 'Backup restored successfully', 'en-gb': 'Backup restored successfully'},
'Format de sauvegarde invalide': {'en-us': 'Invalid backup format', 'en-gb': 'Invalid backup format'},
'Fichier base de données introuvable': {'en-us': 'Database file not found', 'en-gb': 'Database file not found'},
'Appareil renommé avec succès': {'en-us': 'Device renamed successfully', 'en-gb': 'Device renamed successfully'},
'Appareil supprimé de l’historique': {'en-us': 'Device deleted from history', 'en-gb': 'Device deleted from history'},
'Type d’appareil modifié avec succès': {'en-us': 'Device type updated successfully', 'en-gb': 'Device type updated successfully'},
'Type d’appareil non valide': {'en-us': 'Invalid device type', 'en-gb': 'Invalid device type'},
'Le nom de la catégorie est obligatoire': {'en-us': 'Category name is required', 'en-gb': 'Category name is required'},
'Catégorie d’appareil enregistrée avec succès': {'en-us': 'Device category saved successfully', 'en-gb': 'Device category saved successfully'},
'Catégorie supprimée avec succès': {'en-us': 'Category deleted successfully', 'en-gb': 'Category deleted successfully'},
'Catégories réinitialisées avec succès': {'en-us': 'Categories reset to default successfully', 'en-gb': 'Categories reset to default successfully'},
'Assignation VPN du client mise à jour avec succès': {'en-us': 'Client VPN assignment updated successfully', 'en-gb': 'Client VPN assignment updated successfully'},
'Journaux supprimés': {'en-us': 'Logs cleared', 'en-gb': 'Logs cleared'},
'Toutes les données et le point d’accès ont été réinitialisés et supprimés': {'en-us': 'All data and the access point have been reset and removed', 'en-gb': 'All data and the access point have been reset and removed'},
'Double identification activée': {'en-us': 'Two-factor authentication enabled', 'en-gb': 'Two-factor authentication enabled'},
'Double identification désactivée': {'en-us': 'Two-factor authentication disabled', 'en-gb': 'Two-factor authentication disabled'},
'La 2FA n’est pas activée': {'en-us': '2FA is not enabled', 'en-gb': '2FA is not enabled'},
'Identifiants modifiés': {'en-us': 'Credentials updated', 'en-gb': 'Credentials updated'},
'Compte créé': {'en-us': 'Account created', 'en-gb': 'Account created'},
'Un compte existe déjà': {'en-us': 'An account already exists', 'en-gb': 'An account already exists'},
'Session déconnectée avec succès': {'en-us': 'Session logged out successfully', 'en-gb': 'Session logged out successfully'},
'Réglages des notifications enregistrés avec succès': {'en-us': 'Notification settings saved successfully', 'en-gb': 'Notification settings saved successfully'},
'Réglages du proxy inversé enregistrés avec succès !': {'en-us': 'Reverse proxy settings saved successfully!', 'en-gb': 'Reverse proxy settings saved successfully!'},
'SSID ou mot de passe Wi-Fi invalide': {'en-us': 'Invalid Wi-Fi SSID or password', 'en-gb': 'Invalid Wi-Fi SSID or password'},
'Sécurité Wi-Fi invalide': {'en-us': 'Invalid Wi-Fi security setting', 'en-gb': 'Invalid Wi-Fi security setting'},
'Délai d’attente dépassé': {'en-us': 'Request timed out', 'en-gb': 'Request timed out'},
"Délai d'attente dépassé": {'en-us': 'Request timed out', 'en-gb': 'Request timed out'},
'Arrêt des tunnels VPN actifs...': {'en-us': 'Stopping active VPN tunnels...', 'en-gb': 'Stopping active VPN tunnels...'},
'Arrêt du point d’accès Wi-Fi...': {'en-us': 'Stopping Wi-Fi access point...', 'en-gb': 'Stopping Wi-Fi access point...'},
"Arrêt du point d'accès Wi-Fi...": {'en-us': 'Stopping Wi-Fi access point...', 'en-gb': 'Stopping Wi-Fi access point...'},
'Suppression des profils réseau NetworkManager...': {'en-us': 'Deleting NetworkManager connection profiles...', 'en-gb': 'Deleting NetworkManager connection profiles...'},
'Nettoyage du pont réseau et des règles pare-feu...': {'en-us': 'Cleaning network bridge and firewall rules...', 'en-gb': 'Cleaning network bridge and firewall rules...'},
'Suppression de la base de données et des sessions...': {'en-us': 'Deleting database and active sessions...', 'en-gb': 'Deleting database and active sessions...'},
'Toutes les données ont été réinitialisées avec succès.': {'en-us': 'All data has been reset successfully.', 'en-gb': 'All data has been reset successfully.'},
'Démarrage de la réinitialisation...': {'en-us': 'Starting reset process...', 'en-gb': 'Starting reset process...'},
'Réinitialisation déjà en cours': {'en-us': 'Reset already in progress', 'en-gb': 'Reset already in progress'},
'Réinitialisation en cours': {'en-us': 'Reset in progress', 'en-gb': 'Reset in progress'},
'Analyse et vérification de la sauvegarde...': {'en-us': 'Analyzing and verifying backup...', 'en-gb': 'Analyzing and verifying backup...'},
'Inspection du fichier et validation du format...': {'en-us': 'Inspecting file and validating format...', 'en-gb': 'Inspecting file and validating format...'},
'Restauration des réglages & préférences...': {'en-us': 'Restoring settings & preferences...', 'en-gb': 'Restoring settings & preferences...'},
'Application des réglages système et des catégories...': {'en-us': 'Applying system settings and categories...', 'en-gb': 'Applying system settings and categories...'},
'Restauration des équipements & quotas...': {'en-us': 'Restoring devices & quotas...', 'en-gb': 'Restoring devices & quotas...'},
'Enregistrement des appareils et quotas réseau...': {'en-us': 'Registering devices and network quotas...', 'en-gb': 'Registering devices and network quotas...'},
'Restauration des profils VPN & routages...': {'en-us': 'Restoring VPN profiles & routing...', 'en-gb': 'Restoring VPN profiles & routing...'},
'Configuration des tunnels et assignation du trafic...': {'en-us': 'Configuring tunnels and assigning traffic...', 'en-gb': 'Configuring tunnels and assigning traffic...'},
'Reconfiguration Wi-Fi & synchronisation...': {'en-us': 'Wi-Fi reconfiguration & synchronization...', 'en-gb': 'Wi-Fi reconfiguration & synchronization...'},
'Finalisation de la configuration réseau...': {'en-us': 'Finalizing network configuration...', 'en-gb': 'Finalizing network configuration...'},
'Sauvegarde restaurée avec succès !': {'en-us': 'Backup restored successfully!', 'en-gb': 'Backup restored successfully!'},
'Redirection et synchronisation finale...': {'en-us': 'Redirecting and final synchronization...', 'en-gb': 'Redirecting and final synchronization...'},
'Restauration déjà en cours': {'en-us': 'Restoration already in progress', 'en-gb': 'Restoration already in progress'},
'Restauration en cours': {'en-us': 'Restoration in progress', 'en-gb': 'Restoration in progress'}
}
def translate_api_text(text, lang='fr'):
if not text or not isinstance(text, str) or not lang or lang == 'fr':
return text
lang = lang.lower().strip()
if text in API_MSG_I18N:
return API_MSG_I18N[text].get(lang, API_MSG_I18N[text].get('en-us', text))
for k, v in API_MSG_I18N.items():
if k in text:
trans = v.get(lang, v.get('en-us', k))
text = text.replace(k, trans)
return text
_clear_data_lock = threading.Lock()
_clear_data_state = {
'running': False,
'step': 0,
'total_steps': 5,
'percent': 0,
'message': '',
'done': False,
'error': None
}
def _set_clear_progress(step, total_steps, percent, message, done=False, error=None):
with _clear_data_lock:
_clear_data_state['running'] = not done and error is None
_clear_data_state['step'] = step
_clear_data_state['total_steps'] = total_steps
_clear_data_state['percent'] = percent
_clear_data_state['message'] = message
_clear_data_state['done'] = done
_clear_data_state['error'] = error
def run_clear_all_data(caller_ip=''):
try:
# Étape 1 : Arrêt des tunnels VPN actifs
_set_clear_progress(1, 5, 20, "Arrêt des tunnels VPN actifs...")
try:
c_v = db()
v_rows = c_v.execute('SELECT id FROM vpn_profiles').fetchall()
c_v.close()
for (vpid,) in v_rows:
try: disconnect_vpn_profile(vpid, caller_ip=caller_ip)
except Exception: pass
except Exception: pass
time.sleep(0.35)
# Étape 2 : Arrêt du point d'accès Wi-Fi (hostapd)
_set_clear_progress(2, 5, 40, "Arrêt du point d'accès Wi-Fi...")
try:
stop_hostapd(INTERFACE)
except Exception: pass
time.sleep(0.35)
# Étape 3 : Suppression des profils réseau NetworkManager
_set_clear_progress(3, 5, 60, "Suppression des profils réseau NetworkManager...")
try:
name = connection_name()
names_to_delete = set()
if name: names_to_delete.add(name)
r_nm = subprocess.run(['nmcli', '-t', '-g', 'NAME', 'connection', 'show'], capture_output=True, text=True, timeout=3)
if r_nm.returncode == 0:
for line in r_nm.stdout.splitlines():
line = line.strip()
if line.startswith('AP-') or line.startswith('ap-bridge') or line == name:
names_to_delete.add(line)
for n in names_to_delete:
if n:
try: subprocess.run(['nmcli', '--wait', '2', 'connection', 'down', n], capture_output=True, text=True, timeout=3)
except Exception: pass
try: subprocess.run(['nmcli', '--wait', '2', 'connection', 'delete', n], capture_output=True, text=True, timeout=3)
except Exception: pass
except Exception: pass
time.sleep(0.35)
# Étape 4 : Nettoyage du pont réseau et des règles pare-feu
_set_clear_progress(4, 5, 80, "Nettoyage du pont réseau et des règles pare-feu...")
try: teardown_bridge()
except Exception: pass
try: teardown_ap_nat()
except Exception: pass
try:
if os.path.exists(CONNECTION_FILE): os.remove(CONNECTION_FILE)
except OSError: pass
try:
if os.path.exists(UPTIME_FILE): os.remove(UPTIME_FILE)
except OSError: pass
try:
conf = '/etc/NetworkManager/dnsmasq-shared.d/20-max-clients.conf'
if os.path.exists(conf): os.remove(conf)
except OSError: pass
time.sleep(0.35)
# Étape 5 : Purge de la base de données et des sessions
_set_clear_progress(5, 5, 95, "Suppression de la base de données et des sessions...")
c = db()
c.execute('DELETE FROM connection_logs')
c.execute('DELETE FROM blocked_clients')
c.execute('DELETE FROM client_names')
c.execute('DELETE FROM client_traffic')
c.execute('DELETE FROM client_traffic_daily')
c.execute('DELETE FROM client_limits')
c.execute('DELETE FROM vpn_profiles')
c.execute('DELETE FROM client_vpn_routes')
c.execute('DELETE FROM auth_users')
c.execute('DELETE FROM auth_passkeys')
c.execute('DROP TABLE IF EXISTS recovery_codes')
c.execute('DELETE FROM preferences')
c.execute('DELETE FROM auth_sessions')
c.execute('DELETE FROM api_keys')
c.commit()
c.close()
sessions.clear()
with _api_keys_cache_lock: _api_keys_cache.clear()
invalidate_status_cache()
try: sync_vpn_client_rules()
except Exception: pass
with traffic_lock: station_traffic.clear()
log('reinitialisation_donnees', 'Système', caller_ip, 'SYSTEM')
time.sleep(0.35)
_set_clear_progress(5, 5, 100, "Toutes les données ont été réinitialisées avec succès.", done=True)
except Exception as e:
print(f"[ap-data-clear] Erreur pendant la réinitialisation : {e}", flush=True)
_set_clear_progress(5, 5, 100, f"Erreur : {e}", done=True, error=str(e))
class Handler(BaseHTTPRequestHandler):
def get_req_lang(self):
req_lang = self.headers.get('X-Language', '').strip().lower()
if not req_lang:
acc = self.headers.get('Accept-Language', '').strip().lower()
if acc:
req_lang = acc.split(',')[0].split(';')[0].strip()
if not req_lang:
try: req_lang = get_pref('language', 'fr')
except Exception: req_lang = 'fr'
return req_lang or 'fr'
def send_json(self, data, status=200):
req_lang = self.get_req_lang()
if req_lang.startswith('en') and isinstance(data, dict):
data = dict(data)
if 'error' in data and isinstance(data['error'], str):
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('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)
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':
self.send_json({'ok': True, 'version': APP_VERSION, 'commit': get_current_commit()})
return
if self.path in ('/','/index.html','/ap_dashboard.html'):
try: body=open(os.path.join(os.path.dirname(__file__),'index.html'),'rb').read(); self.send_response(200); self.send_header('Content-Type','text/html; charset=utf-8'); self.send_header('Content-Length',str(len(body))); self.end_headers(); self.wfile.write(body)
except OSError: self.send_error(404,'index.html introuvable')
return
if self.path in ('/setup', '/setup.html', '/Setup.html', '/Setup.HTML'):
try:
body = open(os.path.join(os.path.dirname(__file__), 'setup.html'), 'rb').read()
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
except OSError:
self.send_error(404, 'setup.html introuvable')
return
if self.path.startswith('/lang/'):
clean_name = os.path.basename(urllib.parse.urlparse(self.path).path)
lang_path = os.path.join(os.path.dirname(__file__), 'lang', clean_name)
if os.path.isfile(lang_path) and clean_name.endswith('.js'):
try:
body = open(lang_path, 'rb').read()
self.send_response(200)
self.send_header('Content-Type', 'application/javascript; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
return
except OSError: pass
self.send_error(404, 'Fichier de langue introuvable')
return
if self.path.startswith('/themes/'):
clean_name = os.path.basename(urllib.parse.urlparse(self.path).path)
theme_path = os.path.join(os.path.dirname(__file__), 'themes', clean_name)
if os.path.isfile(theme_path) and clean_name.endswith('.css'):
try:
body = open(theme_path, 'rb').read()
self.send_response(200)
self.send_header('Content-Type', 'text/css; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
return
except OSError: pass
self.send_error(404, 'Fichier de thème introuvable')
return
if self.path.startswith('/jeux/'):
clean_name = os.path.basename(urllib.parse.urlparse(self.path).path)
game_path = os.path.join(os.path.dirname(__file__), 'jeux', clean_name)
ext = os.path.splitext(clean_name)[1].lower()
mime_map = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon'
}
if os.path.isfile(game_path) and ext in mime_map:
try:
body = open(game_path, 'rb').read()
self.send_response(200)
self.send_header('Content-Type', mime_map[ext])
self.send_header('Content-Length', str(len(body)))
self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
self.send_header('Pragma', 'no-cache')
self.send_header('Expires', '0')
self.end_headers()
self.wfile.write(body)
return
except OSError: pass
self.send_error(404, 'Jeu introuvable')
return
if self.path == '/favicon.png' or self.path.startswith('/images/'):
clean_name = 'favicon.png' if self.path == '/favicon.png' else os.path.basename(urllib.parse.urlparse(self.path).path)
img_path = os.path.join(os.path.dirname(__file__), 'images', clean_name)
ext = os.path.splitext(clean_name)[1].lower()
mime_map = {'.png': 'image/png', '.svg': 'image/svg+xml', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.ico': 'image/x-icon'}
if os.path.isfile(img_path) and ext in mime_map:
try:
body = open(img_path, 'rb').read()
self.send_response(200)
self.send_header('Content-Type', mime_map[ext])
self.send_header('Content-Length', str(len(body)))
self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
self.send_header('Pragma', 'no-cache')
self.send_header('Expires', '0')
self.end_headers()
self.wfile.write(body)
return
except OSError: pass
if self.path.startswith('/images/'):
self.send_error(404, 'Image introuvable')
return
if self.path == '/api/auth/status': self.send_json(auth_state()); return
if self.path == '/api/data/clear/progress':
with _clear_data_lock:
self.send_json(dict(_clear_data_state))
return
if self.path == '/api/backup/restore/progress':
with _restore_data_lock:
self.send_json(dict(_restore_data_state))
return
if self.path == '/api/device-types':
c = db()
rows = c.execute('SELECT id, label, icon, desc, sort_order FROM custom_device_types ORDER BY sort_order ASC, id ASC').fetchall()
c.close()
items = [{'id': r[0], 'label': r[1], 'icon': r[2], 'desc': r[3], 'sort_order': r[4]} for r in rows]
self.send_json({'ok': True, 'device_types': items}); return
if self.path.startswith('/api/icons/search'):
parsed = urllib.parse.urlparse(self.path)
qs = urllib.parse.parse_qs(parsed.query)
q = (qs.get('q', [''])[0]).strip()
limit = min(int(qs.get('limit', ['36'])[0]), 64)
icons = search_iconify_icons(q, limit=limit)
self.send_json({'ok': True, 'icons': icons, 'total': len(icons)})
return
if self.path.startswith('/api/icons/svg'):
parsed = urllib.parse.urlparse(self.path)
qs = urllib.parse.parse_qs(parsed.query)
name = (qs.get('name', [''])[0]).strip()
color = (qs.get('color', [''])[0]).strip()
as_json = (qs.get('format', [''])[0]).strip().lower() == 'json' or 'application/json' in self.headers.get('Accept', '')
if not name:
if as_json: self.send_json({'error': 'Nom d\'icône manquant'}, 400)
else: self.send_error(400, 'Nom d\'icône manquant')
return
svg_content = fetch_iconify_svg(name, color=color)
if as_json:
self.send_json({'ok': True, 'svg': svg_content, 'name': name})
else:
svg_bytes = svg_content.encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'image/svg+xml; charset=utf-8')
self.send_header('Cache-Control', 'public, max-age=86400')
self.send_header('Content-Length', str(len(svg_bytes)))
self.end_headers()
self.wfile.write(svg_bytes)
return
if self.path.startswith('/api/backup/export'):
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
parsed = urllib.parse.urlparse(self.path)
qs = urllib.parse.parse_qs(parsed.query)
fmt = (qs.get('format', ['zip'])[0]).strip().lower()
now_str = time.strftime('%Y%m%d-%H%M%S')
if fmt == 'sqlite':
if os.path.exists(DB_FILE):
try:
with open(DB_FILE, 'rb') as f:
content = f.read()
self.send_response(200)
self.send_header('Content-Type', 'application/x-sqlite3')
self.send_header('Content-Disposition', f'attachment; filename="ap-manageur-database-{now_str}.sqlite3"')
self.send_header('Content-Length', str(len(content)))
self.end_headers()
self.wfile.write(content)
log('export_base_sqlite', f"{username(self) or 'Administrateur'} (ap-manageur-database-{now_str}.sqlite3)", request_ip(self), 'BACKUP')
return
except Exception as e:
self.send_json({'error': f'Erreur export SQLite: {e}'}, 500); return
else:
self.send_json({'error': 'Fichier base de données introuvable'}, 404); return
elif fmt == 'json':
try:
backup = export_backup_data()
json_bytes = json.dumps(backup, ensure_ascii=False, indent=2).encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Content-Disposition', f'attachment; filename="ap-manageur-backup-{now_str}.json"')
self.send_header('Content-Length', str(len(json_bytes)))
self.end_headers()
self.wfile.write(json_bytes)
log('export_configuration_json', f"{username(self) or 'Administrateur'} (ap-manageur-backup-{now_str}.json)", request_ip(self), 'BACKUP')
return
except Exception as e:
self.send_json({'error': f'Erreur génération sauvegarde: {e}'}, 500); return
else:
# Format par défaut : Archive ZIP unifiée (Configuration JSON + Base SQLite brute)
try:
backup = export_backup_data()
json_bytes = json.dumps(backup, ensure_ascii=False, indent=2).encode('utf-8')
buf = io.BytesIO()
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zf:
zf.writestr('configuration.json', json_bytes)
if os.path.exists(DB_FILE):
try:
with open(DB_FILE, 'rb') as f_db:
zf.writestr('ap-dashboard.sqlite3', f_db.read())
except Exception as e_db:
print(f"[backup] Inclusion sqlite impossible : {e_db}", flush=True)
readme_text = (
f"Sauvegarde AP Manageur ({APP_VERSION})\n"
f"Date d'export : {datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}\n\n"
"Contenu de cette archive :\n"
"- configuration.json : Configuration complète (profils VPN WireGuard & OpenVPN, routage appareils, noms et logos des équipements, catégories, blocage et réglages système).\n"
"- ap-dashboard.sqlite3 : Base de données SQLite brute complète.\n\n"
"Restauration :\n"
"Vous pouvez importer directement cette archive .zip (ou le fichier configuration.json) "
"dans AP Manageur (Réglages > Zone dangereuse > Importer une sauvegarde).\n"
)
zf.writestr('README.txt', readme_text.encode('utf-8'))
zip_bytes = buf.getvalue()
self.send_response(200)
self.send_header('Content-Type', 'application/zip')
self.send_header('Content-Disposition', f'attachment; filename="ap-manageur-sauvegarde-{now_str}.zip"')
self.send_header('Content-Length', str(len(zip_bytes)))
self.end_headers()
self.wfile.write(zip_bytes)
log('export_sauvegarde_complete', f"{username(self) or 'Administrateur'} (ap-manageur-sauvegarde-{now_str}.zip)", request_ip(self), 'BACKUP')
return
except Exception as e:
self.send_json({'error': f'Erreur génération archive ZIP: {e}'}, 500); return
if self.path.startswith('/api/backups/list'):
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
parsed = urllib.parse.urlparse(self.path)
qs = urllib.parse.parse_qs(parsed.query)
if qs.get('sync_remote', ['0'])[0] in ('1', 'true'):
try:
sync_remote_backups_presence(force=True)
except Exception as e_sync:
print(f"[ap-backup] Erreur synchronisation distante : {e_sync}", flush=True)
items, total_size = list_server_backups()
self.send_json({
'ok': True,
'backup_dir': BACKUP_DIR,
'schedule': get_backup_schedule(),
'remote': get_backup_remote_config(),
'backups': items,
'total_count': len(items),
'total_size': total_size,
'total_size_str': format_bytes(total_size)
}); return
if self.path == '/api/backups/remote':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
self.send_json({'ok': True, 'remote': get_backup_remote_config()}); return
if self.path.startswith('/api/backups/remote/files'):
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
rcfg = get_backup_remote_config()
if not rcfg.get('enabled'):
self.send_json({'ok': False, 'error': "Le stockage distant n'est pas activé. Activez-le dans les réglages de sauvegarde.", 'enabled': False}, 400); return
provider = str(rcfg.get('provider', 'ftp')).strip().lower()
try:
items, err = list_remote_files_detailed(rcfg)
if items is None:
self.send_json({'ok': False, 'error': err or f"Impossible de contacter le stockage distant ({provider.upper()})", 'provider': provider}, 500); return
sync_remote_backups_presence(force=True)
prov_names = {'gdrive': 'Google Drive', 'dropbox': 'Dropbox', 'sftp': 'SFTP', 'ftp': 'FTP', 'webdav': 'WebDAV', 's3': 'S3', 'webhook': 'Webhook'}
self.send_json({
'ok': True,
'enabled': True,
'provider': provider,
'provider_name': prov_names.get(provider, provider.upper()),
'files': items,
'count': len(items)
}); return
except Exception as e:
self.send_json({'ok': False, 'error': f"Erreur lors de la lecture des fichiers distants : {e}"}, 500); return
if self.path.startswith('/api/backups/remote/file/download'):
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
parsed = urllib.parse.urlparse(self.path)
qs = urllib.parse.parse_qs(parsed.query)
fname = qs.get('file', [''])[0].strip()
if not fname or not fname.lower().endswith(BACKUP_ALLOWED_EXTS):
self.send_json({'error': 'Nom de fichier invalide'}, 400); return
clean_name = os.path.basename(fname)
with tempfile.NamedTemporaryFile('wb', delete=False, suffix='.zip') as tmp:
tmp_path = tmp.name
try:
download_remote_file(clean_name, tmp_path)
file_sz = os.path.getsize(tmp_path)
self.send_response(200)
self.send_header('Content-Type', 'application/zip')
self.send_header('Content-Disposition', f'attachment; filename="{clean_name}"')
self.send_header('Content-Length', str(file_sz))
self.end_headers()
with open(tmp_path, 'rb') as f:
while True:
chunk = f.read(65536)
if not chunk: break
self.wfile.write(chunk)
log('telechargement_sauvegarde_distante', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP')
return
except Exception as e:
self.send_json({'error': f"Échec du téléchargement depuis le stockage distant : {e}"}, 500); return
finally:
if os.path.exists(tmp_path):
try: os.unlink(tmp_path)
except OSError: pass
if self.path.startswith('/api/backups/download'):
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
parsed = urllib.parse.urlparse(self.path)
qs = urllib.parse.parse_qs(parsed.query)
fname = (qs.get('file', [''])[0]).strip()
try:
full_path, clean_name = safe_backup_filepath(fname)
if not os.path.isfile(full_path):
self.send_json({'error': 'Fichier de sauvegarde introuvable'}, 404); return
content = open(full_path, 'rb').read()
ext = os.path.splitext(clean_name)[1].lower()
ctype = 'application/zip' if ext == '.zip' else ('application/json; charset=utf-8' if ext == '.json' else 'application/x-sqlite3')
self.send_response(200)
self.send_header('Content-Type', ctype)
self.send_header('Content-Disposition', f'attachment; filename="{clean_name}"')
self.send_header('Content-Length', str(len(content)))
self.end_headers()
self.wfile.write(content)
log('export_sauvegarde_complete', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP')
return
except Exception as e:
self.send_json({'error': str(e)}, 400); return
if self.path in ('/api/auth/admin', '/api/auth/user'):
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
c = db()
row = c.execute('SELECT username FROM auth_users LIMIT 1').fetchone()
c.close()
admin_user = row[0] if row else (username(self) or 'admin')
self.send_json({'ok': True, 'username': admin_user}); return
if self.path == '/api/auth/sessions':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
self.send_json(list_sessions(extract_token(self), self.get_req_lang())); return
if self.path == '/api/auth/passkey/list':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
u = username(self) or 'admin'
c = db()
rows = c.execute('SELECT id, name, device_type, sign_count, created_at, last_used_at FROM auth_passkeys WHERE username=? ORDER BY created_at DESC', (u,)).fetchall()
c.close()
is_en = self.get_req_lang().startswith('en')
never_label = 'Never' if is_en else 'Jamais'
items = [{'id': r[0], 'name': r[1], 'device_type': r[2], 'sign_count': r[3], 'created_at': r[4], 'last_used_at': r[5] or never_label} for r in rows]
self.send_json({'ok': True, 'passkeys': items}); return
if self.path == '/api/auth/api-keys':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
token = extract_token(self)
if token.startswith('ap_key_'):
k = get_api_key_by_token(token)
if not k or 'admin' not in k.get('permissions', []):
self.send_json({'error': 'Droits administrateur requis'}, 403); return
try:
c = db()
rows = c.execute('''
SELECT id, name, prefix, permissions, created_at, expires_at, last_used_at, last_ip, is_active
FROM api_keys
ORDER BY id DESC
''').fetchall()
c.close()
keys_list = []
for r in rows:
keys_list.append({
'id': r[0],
'name': r[1],
'prefix': r[2],
'permissions': parse_api_key_permissions(r[3]),
'created_at': r[4],
'expires_at': r[5] or None,
'last_used_at': r[6] or None,
'last_ip': r[7] or '—',
'is_active': int(r[8] or 0)
})
self.send_json({'ok': True, 'api_keys': keys_list})
except Exception as e:
self.send_json({'error': f'Erreur chargement clés API: {e}'}, 500)
return
if self.path == '/api/settings/proxy':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
cfg = get_reverse_proxy_config()
raw_sock = self.client_address[0] if hasattr(self, 'client_address') and self.client_address else '127.0.0.1'
raw_direct = self.headers.get('X-Client-Raw-IP', '').strip()
self.send_json({
'ok': True,
'config': cfg,
'detected': {
'real_ip': request_ip(self),
'raw_direct_ip': raw_direct or raw_sock,
'socket_ip': raw_sock,
'x_client_raw_ip': raw_direct or '—',
'x_forwarded_for': self.headers.get('X-Forwarded-For', '') or '—',
'x_real_ip': self.headers.get('X-Real-IP', '') or '—',
'cf_connecting_ip': self.headers.get('CF-Connecting-IP', '') or '—',
'true_client_ip': self.headers.get('True-Client-IP', '') or '—',
'x_forwarded_proto': self.headers.get('X-Forwarded-Proto', '') or '—',
'host': self.headers.get('X-Forwarded-Host', '') or self.headers.get('Host', '') or '—'
}
})
return
path_only = self.path.split('?')[0]
if path_only == '/api/preferences':
c=db(); rows=dict(c.execute("SELECT key,value FROM preferences").fetchall()); c.close()
self.send_json({
'theme': rows.get('theme', 'dark'),
'language': rows.get('language', 'fr'),
'app_name': rows.get('app_name', 'Administration de l’AP Wi‑Fi'),
'app_short_name': rows.get('app_short_name', 'AP Manageur')
})
return
if path_only == '/api/notifications/settings':
if auth_state().get('configured') and not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
self.send_json(get_notifications_settings_public())
return
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
if path_only == '/api/status': self.send_json(status())
elif path_only == '/api/system/update':
parsed = urllib.parse.urlparse(self.path)
q = urllib.parse.parse_qs(parsed.query)
force = 'force' in q or 'refresh' in q
self.send_json(check_gitea_update(force_refresh=force))
elif path_only == '/api/system/update/settings':
enabled = get_pref('update_checker_enabled', '1') == '1'
try:
interval = int(get_pref('update_checker_interval', '7200'))
if interval < 60: interval = 7200
except Exception:
interval = 7200
up_data = check_gitea_update(force_refresh=False)
self.send_json({
'ok': True,
'enabled': enabled,
'interval': interval,
'update': up_data
})
elif path_only == '/api/clients': self.send_json(clients())
elif path_only == '/api/clients/blocked': self.send_json(blocked_list())
elif path_only == '/api/devices': self.send_json(all_devices(self.get_req_lang()))
elif path_only == '/api/devices/limits':
parsed = urllib.parse.urlparse(self.path)
qs = urllib.parse.parse_qs(parsed.query)
target_mac = (qs.get('mac', [''])[0]).strip().upper()
lim = get_client_limits_dict(target_mac)
self.send_json({'ok': True, 'mac': target_mac, 'limits': lim})
elif path_only == '/api/logs': self.send_json(logs())
elif path_only == '/api/stats': self.send_json(stats())
elif path_only == '/api/network/topology': self.send_json(network_topology())
elif path_only == '/api/wifi/channel':
parsed = urllib.parse.urlparse(self.path)
q = urllib.parse.parse_qs(parsed.query)
force = 'force' in q or 'rescan' in q
eff_chan = get_effective_ap_channel(AP_BAND, force_rescan=force)
with _auto_channel_lock:
details = dict(_auto_channel_cache.get('details') or {})
self.send_json({
'ok': True,
'channel': eff_chan,
'is_auto': is_auto_channel(),
'band': AP_BAND,
'configured_channel': os.environ.get('AP_CHANNEL', ''),
'details': details
})
elif path_only == '/api/vpn/profiles':
self.send_json({'profiles': list_vpn_profiles()})
elif path_only == '/api/vpn/clients':
self.send_json({'clients': list_vpn_clients()})
elif path_only in ('/api/vpn/check-ip', '/api/vpn/public-ip'):
qs = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
pid = int(qs.get('id', [0])[0])
prof = get_vpn_profile(pid)
if not prof: self.send_json({'error':'Profil introuvable'},404); return
iface = prof.get('iface') or (f"wg_ap{pid}" if prof['type'] == 'wireguard' else f"tun_ap{pid}")
if not is_iface_up(iface):
self.send_json({'ok': False, 'error': 'Tunnel VPN déconnecté'}); return
force = qs.get('force', ['1'])[0] == '1'
ip = get_vpn_public_ip(iface, force_refresh=force)
hs, hs_sec = get_wireguard_handshake_info(iface) if prof['type'] == 'wireguard' else (None, None)
if ip:
geo = get_ip_geo(ip)
self.send_json({'ok': True, 'public_ip': ip, 'public_ip_geo': geo, 'handshake': hs, 'handshake_age_seconds': hs_sec, 'iface': iface})
else:
self.send_json({'ok': False, 'error': 'IP publique introuvable via ce tunnel', 'handshake': hs, 'handshake_age_seconds': hs_sec, 'iface': iface})
return
elif path_only == '/api/notifications/settings':
self.send_json(get_notifications_settings_public())
elif path_only == '/api/advanced/capture/status':
with capture_lock:
wifi_if = capture_iface_used or get_wifi_interface()
domain_list = sorted(captured_domains.values(), key=lambda x: (x['count'], x['last_seen']), reverse=True)
dur = int(time.time() - capture_started_at) if (capture_running and capture_started_at > 0) else 0
payload = {
'running': capture_running,
'started_at': capture_started_at if capture_running else 0,
'duration_seconds': dur,
'packet_count': len(capture_packets),
'buffer_packets': len(capture_packets),
'total_captured': capture_id_counter,
'total_packets': capture_id_counter,
'interface': wifi_if,
'wifi_interface': wifi_if,
'stats': dict(capture_stats),
'unique_domains_count': len(captured_domains),
'domains': domain_list[:500],
'pcap_bytes': len(capture_pcap_bytes),
'pcap_size_bytes': len(capture_pcap_bytes)
}
self.send_json(payload)
elif path_only == '/api/advanced/domains':
with capture_lock:
domain_list = sorted(captured_domains.values(), key=lambda x: (x['count'], x['last_seen']), reverse=True)[:500]
tot_dom = len(captured_domains)
self.send_json({
'total_domains': tot_dom,
'domains': domain_list
})
elif path_only == '/api/advanced/capture/packets':
parsed = urllib.parse.urlparse(self.path)
qs = urllib.parse.parse_qs(parsed.query)
try: since = int(qs.get('since', [0])[0])
except Exception: since = 0
try: limit = min(50000, max(1, int(qs.get('limit', [1000])[0])))
except Exception: limit = 1000
with capture_lock:
if since > 0:
pkts = [p for p in capture_packets if p['id'] > since][:limit]
else:
pkts = list(capture_packets[-limit:] if limit < len(capture_packets) else capture_packets)
running = capture_running
buf_count = len(capture_packets)
tot_count = capture_id_counter
try:
for p in pkts:
src_ip = p.get('src')
src_geo = p.get('src_geo') or {}
if src_ip and (not p.get('src_geo') or src_geo.get('code') in ('WAN', 'EXT', '')):
geo = get_ip_geo(src_ip)
if geo and geo.get('code') not in ('WAN', 'EXT', ''):
p['src_geo'] = geo
dst_ip = p.get('dst')
dst_geo = p.get('dst_geo') or {}
if dst_ip and (not p.get('dst_geo') or dst_geo.get('code') in ('WAN', 'EXT', '')):
geo = get_ip_geo(dst_ip)
if geo and geo.get('code') not in ('WAN', 'EXT', ''):
p['dst_geo'] = geo
except Exception as e_geo_update:
print(f"[ap-capture] Erreur rafraîchissement GeoIP: {e_geo_update}", flush=True)
self.send_json({
'running': running,
'packet_count': buf_count,
'buffer_packets': buf_count,
'total_captured': tot_count,
'total_packets': tot_count,
'packets': pkts
})
elif path_only == '/api/advanced/geoip':
parsed = urllib.parse.urlparse(self.path)
qs = urllib.parse.parse_qs(parsed.query)
ip_val = qs.get('ip', [''])[0].strip()
geo = get_ip_geo(ip_val)
self.send_json({'ip': ip_val, 'geo': geo})
elif path_only == '/api/advanced/capture/export':
with capture_lock:
data = bytes(capture_pcap_bytes)
if not data:
data = struct.pack(' Compte Administrateur.')
now = time.time()
for k in [k for k, v in passkey_pending_challenges.items() if now - v.get('time', 0) > 120]:
passkey_pending_challenges.pop(k, None)
raw_chal = secrets.token_bytes(32)
chal_b64 = b64url_encode(raw_chal)
passkey_pending_challenges[chal_b64] = {'type': 'login', 'time': time.time()}
req_host = (self.headers.get('Host') or '').split(':')[0] or 'localhost'
options = {
'ok': True,
'challenge': chal_b64,
'rpId': req_host,
'timeout': 60000,
'userVerification': 'preferred',
'allowCredentials': [{'type': 'public-key', 'id': r[0]} for r in pks]
}
self.send_json(options); return
if self.path == '/api/auth/passkey/login/verify':
c_data_b64 = data.get('response', {}).get('clientDataJSON', '')
if not c_data_b64: raise ValueError('Données clientData manquantes')
c_data_raw = b64url_decode(c_data_b64)
c_data = json.loads(c_data_raw.decode('utf-8'))
if c_data.get('type') != 'webauthn.get':
raise ValueError('Type d’opération clientData invalide')
chal = c_data.get('challenge', '')
p_info = passkey_pending_challenges.pop(chal, None)
if not p_info or p_info.get('type') != 'login':
raise ValueError('Challenge invalide ou expiré. Veuillez réessayer.')
cred_id = str(data.get('id', '')).strip()
c = db()
row = c.execute('SELECT id, username, public_key, name, sign_count FROM auth_passkeys WHERE id=?', (cred_id,)).fetchone()
if not row:
c.close()
raise ValueError('Passkey inconnue ou non enregistrée')
u = row[1]
pk_info = json.loads(row[2])
auth_data_raw = b64url_decode(data.get('response', {}).get('authenticatorData', ''))
sig_raw = b64url_decode(data.get('response', {}).get('signature', ''))
if len(auth_data_raw) < 37:
c.close(); raise ValueError('authenticatorData invalide')
flags = auth_data_raw[32]
if not (flags & 0x01):
c.close(); raise ValueError('Présence utilisateur non vérifiée par le capteur')
c_data_hash = hashlib.sha256(c_data_raw).digest()
signed_data = auth_data_raw + c_data_hash
valid_sig = False
if pk_info.get('alg') == 'ES256':
pub_x = b64url_decode(pk_info['x'])
pub_y = b64url_decode(pk_info['y'])
valid_sig = verify_es256_signature(pub_x, pub_y, sig_raw, signed_data)
elif pk_info.get('alg') == 'RS256':
n_bytes = b64url_decode(pk_info['n'])
e_bytes = b64url_decode(pk_info['e'])
valid_sig = verify_rs256_signature(n_bytes, e_bytes, sig_raw, signed_data)
if not valid_sig:
c.close()
log('echec_connexion_passkey', u, request_ip(self), 'AUTH')
raise ValueError('Signature biométrique ou cryptographique de la Passkey invalide')
new_count = int.from_bytes(auth_data_raw[33:37], 'big')
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
c.execute('UPDATE auth_passkeys SET sign_count=?, last_used_at=? WHERE id=?', (new_count, now_str, cred_id))
c.commit(); c.close()
c_name = str(data.get('device_name', '')).strip() or urllib.parse.unquote(self.headers.get('X-Device-Name', ''))
dispatch_notification('admin_login', "🔑 Connexion par Passkey réussie", f"Connexion immédiate par Passkey « {row[3]} » sans mot de passe ni 2FA.", details={"Compte": u, "Passkey": row[3], "Machine": c_name or "Machine non spécifiée", "Adresse IP": request_ip(self), "Navigateur": parse_browser(self.headers.get('User-Agent', '')), "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=5, level="info")
log('connexion_passkey', u, request_ip(self), 'AUTH')
tok = new_session(u, request_ip(self), self.headers.get('User-Agent', ''), c_name)
self.send_json({'ok': True, 'token': tok, 'message': f'Authentification réussie avec « {row[3]} » !'}); return
if self.path == '/api/auth/passkey/register/options':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
u = username(self) or 'admin'
now = time.time()
for k in [k for k, v in passkey_pending_challenges.items() if now - v.get('time', 0) > 120]:
passkey_pending_challenges.pop(k, None)
raw_chal = secrets.token_bytes(32)
chal_b64 = b64url_encode(raw_chal)
passkey_pending_challenges[chal_b64] = {'type': 'register', 'username': u, 'time': time.time()}
req_host = (self.headers.get('Host') or '').split(':')[0] or 'localhost'
options = {
'ok': True,
'challenge': chal_b64,
'rp': {'name': 'AP Manageur', 'id': req_host},
'user': {
'id': b64url_encode(u.encode('utf-8')),
'name': u,
'displayName': u
},
'pubKeyCredParams': [
{'type': 'public-key', 'alg': -7},
{'type': 'public-key', 'alg': -257}
],
'timeout': 60000,
'attestation': 'none',
'authenticatorSelection': {
'residentKey': 'preferred',
'userVerification': 'preferred'
}
}
self.send_json(options); return
if self.path == '/api/auth/passkey/register/verify':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
u = username(self) or 'admin'
c_data_b64 = data.get('response', {}).get('clientDataJSON', '')
if not c_data_b64: raise ValueError('Données clientData manquantes')
c_data_raw = b64url_decode(c_data_b64)
c_data = json.loads(c_data_raw.decode('utf-8'))
if c_data.get('type') != 'webauthn.create':
raise ValueError('Type clientData incorrect')
chal = c_data.get('challenge', '')
p_info = passkey_pending_challenges.pop(chal, None)
if not p_info or p_info.get('type') != 'register' or p_info.get('username') != u:
raise ValueError('Challenge invalide ou expiré')
att_raw = b64url_decode(data.get('response', {}).get('attestationObject', ''))
att_obj, _ = decode_cbor(att_raw)
auth_data = att_obj.get('authData', b'')
if len(auth_data) < 55:
raise ValueError('authData trop court')
flags = auth_data[32]
if not (flags & 0x01): raise ValueError('Présence utilisateur non vérifiée')
if not (flags & 0x40): raise ValueError('Données d’attestation absentes')
id_len = int.from_bytes(auth_data[53:55], 'big')
cred_id = auth_data[55:55+id_len]
cred_id_b64 = b64url_encode(cred_id)
cose_map, _ = decode_cbor(auth_data[55+id_len:])
alg = cose_map.get(3)
if alg == -7:
x_bytes = cose_map.get(-2, b'')
y_bytes = cose_map.get(-3, b'')
if len(x_bytes) != 32 or len(y_bytes) != 32:
raise ValueError('Coordonnées de clé publique P-256 invalides')
pk_stored = json.dumps({'kty': 'EC', 'crv': 'P-256', 'alg': 'ES256', 'x': b64url_encode(x_bytes), 'y': b64url_encode(y_bytes)})
elif alg == -257:
n_bytes = cose_map.get(-1, b'')
e_bytes = cose_map.get(-2, b'')
pk_stored = json.dumps({'kty': 'RSA', 'alg': 'RS256', 'n': b64url_encode(n_bytes), 'e': b64url_encode(e_bytes)})
else:
raise ValueError(f'Algorithme cryptographique non supporté : {alg}')
p_name = (data.get('name') or '').strip() or 'Passkey'
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
c = db()
c.execute('''
INSERT INTO auth_passkeys(id, username, public_key, name, device_type, sign_count, created_at, last_used_at)
VALUES(?, ?, ?, ?, "security_key", 0, ?, "")
ON CONFLICT(id) DO UPDATE SET public_key=excluded.public_key, name=excluded.name
''', (cred_id_b64, u, pk_stored, p_name, now_str))
c.commit(); c.close()
log('passkey_enregistree', f"{u} ({p_name})", request_ip(self), 'AUTH')
self.send_json({'ok': True, 'message': f'Passkey « {p_name} » enregistrée avec succès !'}); return
if self.path == '/api/auth/passkey/delete':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
cred_id = str(data.get('id', '')).strip()
if not cred_id: raise ValueError('Identifiant de Passkey manquant')
c = db()
c.execute('DELETE FROM auth_passkeys WHERE id=?', (cred_id,))
c.commit(); c.close()
log('passkey_supprimee', username(self) or 'admin', request_ip(self), 'AUTH')
self.send_json({'ok': True, 'message': 'Passkey supprimée avec succès'}); return
if self.path == '/api/auth/passkey/rename':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
cred_id = str(data.get('id', '')).strip()
new_name = str(data.get('name', '')).strip()
if not cred_id: raise ValueError('Identifiant de Passkey manquant')
if not new_name: raise ValueError('Le nom de la clé ne peut pas être vide')
c = db()
row = c.execute('SELECT name FROM auth_passkeys WHERE id=?', (cred_id,)).fetchone()
if not row:
c.close()
raise ValueError('Passkey introuvable')
old_name = row[0]
c.execute('UPDATE auth_passkeys SET name=? WHERE id=?', (new_name, cred_id))
c.commit(); c.close()
log('passkey_renommee', f"{username(self) or 'admin'} ({old_name} -> {new_name})", request_ip(self), 'AUTH')
self.send_json({'ok': True, 'message': 'Clé de sécurité renommée avec succès'}); return
if self.path == '/api/logout':
log('deconnexion_admin', username(self) or 'Administrateur', request_ip(self), 'AUTH')
delete_session(self.headers.get('X-Session-Token',''))
self.send_json({'ok':True}); return
if self.path in ('/api/auth/sessions/revoke', '/api/auth/sessions/delete'):
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
target_token = str(data.get('token', '')).strip()
if not target_token: raise ValueError('Token de session manquant')
s = get_session(target_token)
target_ip = s.get('ip', '—') if s else '—'
target_name = s.get('device_name', '') if s else ''
target_user = s.get('username', 'Administrateur') if s else 'Administrateur'
curr = extract_token(self)
is_self = bool(curr and target_token == curr)
delete_session(target_token)
log('deconnexion_admin', f"{target_user} ({target_name or 'Session'})", target_ip, 'AUTH')
self.send_json({
'ok': True,
'message': 'Session déconnectée avec succès',
'is_self': is_self
})
return
if self.path == '/api/auth/sessions/rename':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
target_token = str(data.get('token', '')).strip()
new_name = str(data.get('name', '')).strip()
if not target_token: raise ValueError('Token de session manquant')
if not new_name: raise ValueError('Nom de machine vide')
if len(new_name) > 64: new_name = new_name[:64]
s = get_session(target_token)
if s:
s['device_name'] = new_name
try:
c = db()
c.execute('UPDATE auth_sessions SET device_name=? WHERE token=?', (new_name, target_token))
c.commit(); c.close()
except Exception as e:
raise RuntimeError(f"Erreur enregistrement nom: {e}")
log('modification_identifiants', f"Renommage machine -> {new_name}", request_ip(self), 'AUTH')
self.send_json({'ok': True, 'message': 'Machine renommée avec succès', 'name': new_name})
return
if self.path == '/api/auth/api-keys/create':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
token = extract_token(self)
if token.startswith('ap_key_'):
k = get_api_key_by_token(token)
if not k or 'admin' not in k.get('permissions', []):
self.send_json({'error': 'Droits administrateur requis'}, 403); return
name = str(data.get('name', '')).strip()
if not name:
self.send_json({'error': 'Le nom de la clé API est obligatoire'}, 400); return
perms = parse_api_key_permissions(data.get('permissions', []))
if not perms:
self.send_json({'error': 'Au moins une autorisation doit être sélectionnée'}, 400); return
expires_in_days = int(data.get('expires_in_days', 0) or 0)
expires_at = None
if expires_in_days > 0:
expires_at = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() + expires_in_days * 86400))
raw_token = f"ap_key_{secrets.token_hex(20)}"
token_hash = hashlib.sha256(raw_token.encode('utf-8')).hexdigest()
prefix = f"ap_key_{raw_token[7:13]}...{raw_token[-4:]}"
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
c = db()
c.execute('''
INSERT INTO api_keys(name, key_hash, prefix, permissions, created_at, expires_at, is_active)
VALUES(?, ?, ?, ?, ?, ?, 1)
''', (name, token_hash, prefix, json.dumps(perms), now_str, expires_at))
new_id = c.execute('SELECT last_insert_rowid()').fetchone()[0]
c.commit(); c.close()
with _api_keys_cache_lock:
_api_keys_cache.clear()
log('cle_api_creee', f"{username(self) or 'admin'} ({name})", request_ip(self), 'SETTINGS')
self.send_json({
'ok': True,
'message': 'Clé d’API créée avec succès',
'api_key': {
'id': new_id,
'name': name,
'prefix': prefix,
'token': raw_token,
'permissions': perms,
'created_at': now_str,
'expires_at': expires_at,
'is_active': 1
}
})
return
if self.path == '/api/auth/api-keys/toggle':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
token = extract_token(self)
if token.startswith('ap_key_'):
k = get_api_key_by_token(token)
if not k or 'admin' not in k.get('permissions', []):
self.send_json({'error': 'Droits administrateur requis'}, 403); return
kid = int(data.get('id', 0))
c = db()
row = c.execute('SELECT name, is_active FROM api_keys WHERE id=?', (kid,)).fetchone()
if not row:
c.close()
self.send_json({'error': 'Clé API introuvable'}, 404); return
new_state = 0 if row[1] else 1
c.execute('UPDATE api_keys SET is_active=? WHERE id=?', (new_state, kid))
c.commit(); c.close()
with _api_keys_cache_lock:
_api_keys_cache.clear()
status_txt = 'activée' if new_state else 'désactivée'
log('cle_api_modifiee', f"{username(self) or 'admin'} ({row[0]} -> {status_txt})", request_ip(self), 'SETTINGS')
self.send_json({'ok': True, 'is_active': new_state, 'message': f'Clé d’API {status_txt} avec succès'})
return
if self.path == '/api/auth/api-keys/delete':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
token = extract_token(self)
if token.startswith('ap_key_'):
k = get_api_key_by_token(token)
if not k or 'admin' not in k.get('permissions', []):
self.send_json({'error': 'Droits administrateur requis'}, 403); return
kid = int(data.get('id', 0))
c = db()
row = c.execute('SELECT name FROM api_keys WHERE id=?', (kid,)).fetchone()
if not row:
c.close()
self.send_json({'error': 'Clé API introuvable'}, 404); return
key_name = row[0]
c.execute('DELETE FROM api_keys WHERE id=?', (kid,))
c.commit(); c.close()
with _api_keys_cache_lock:
_api_keys_cache.clear()
log('cle_api_supprimee', f"{username(self) or 'admin'} ({key_name})", request_ip(self), 'SETTINGS')
self.send_json({'ok': True, 'message': 'Clé d’API supprimée avec succès'})
return
if self.path == '/api/system/update/settings':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
enabled = bool(data.get('enabled', True))
try:
interval = int(data.get('interval', 7200))
if interval < 60: interval = 7200
except (TypeError, ValueError):
interval = 7200
set_pref('update_checker_enabled', '1' if enabled else '0')
set_pref('update_checker_interval', str(interval))
with _update_lock:
if not enabled:
_update_cache['time'] = time.time()
_update_cache['data']['available'] = False
_update_cache['data']['enabled'] = False
_update_cache['data']['interval'] = interval
else:
_update_cache['time'] = 0
invalidate_status_cache()
_update_loop_event.set()
log('modification_preferences', f"Recherche de MAJ: {'activée' if enabled else 'désactivée'}, intervalle={interval}s", request_ip(self), 'SETTINGS')
res = check_gitea_update(force_refresh=enabled)
self.send_json({
'ok': True,
'message': 'Paramètres de mise à jour enregistrés avec succès',
'enabled': enabled,
'interval': interval,
'update': res
})
return
if self.path == '/api/system/update/sync':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
target_commit = str(data.get('commit', '')).strip()
if not target_commit:
chk = check_gitea_update(force_refresh=True)
target_commit = chk.get('latest_commit_full') or chk.get('latest_commit') or ''
if not target_commit:
raise ValueError('Impossible de déterminer le dernier commit')
v_data = {
'version': APP_VERSION,
'commit': target_commit,
'build_date': datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
}
for v_path in ('/data/version.json', os.path.join(BASE_DIR, 'version.json'), 'version.json'):
try:
with open(v_path, 'w', encoding='utf-8') as f:
json.dump(v_data, f, indent=2, ensure_ascii=False)
except Exception:
pass
with _update_lock:
_update_cache['time'] = 0
res = check_gitea_update(force_refresh=True)
self.send_json({'ok': True, 'update': res, 'message': 'Synchronisé avec succès !'})
return
if self.path == '/api/backup/inspect':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
fname = str(data.get('filename', 'sauvegarde')).strip()
b64_content = str(data.get('data_base64', '')).strip()
raw_json = data.get('backup')
if raw_json and isinstance(raw_json, dict):
self.send_json({'ok': True, 'filename': fname, 'backup': raw_json}); return
if b64_content:
try:
raw_bytes = base64.b64decode(b64_content)
backup = inspect_backup_bytes(raw_bytes, fname)
self.send_json({'ok': True, 'filename': fname, 'backup': backup})
except Exception as e:
self.send_json({'error': f'Impossible d’analyser le fichier : {e}'}, 400)
return
if fname:
full_path, clean_name = safe_backup_filepath(fname)
if os.path.isfile(full_path):
try:
with open(full_path, 'rb') as f_read:
raw_bytes = f_read.read()
backup = inspect_backup_bytes(raw_bytes, clean_name)
sz = os.path.getsize(full_path)
self.send_json({'ok': True, 'filename': clean_name, 'size': sz, 'backup': backup})
return
except Exception as e:
self.send_json({'error': f'Impossible d’analyser le fichier local : {e}'}, 400); return
self.send_json({'error': 'Contenu du fichier manquant ou fichier local introuvable'}, 400); return
if self.path == '/api/backup/import':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
try:
was_active = False
try: was_active = bool(status(force_refresh=True).get('active'))
except Exception: pass
_set_restore_progress(1, 5, 20, "Analyse et vérification de la sauvegarde...", "Inspection du fichier et validation du format...")
time.sleep(0.35)
if 'data_base64' in data and data['data_base64']:
raw_bytes = base64.b64decode(data['data_base64'])
backup = inspect_backup_bytes(raw_bytes, data.get('filename', ''))
stats = import_backup_data(backup, data.get('options', {}))
elif 'filename' in data and data['filename'] and not data.get('backup'):
full_path, clean_name = safe_backup_filepath(data['filename'])
if not os.path.isfile(full_path):
_set_restore_progress(1, 5, 20, "Fichier introuvable", error="Fichier de sauvegarde introuvable", done=True)
self.send_json({'error': 'Fichier de sauvegarde introuvable'}, 404); return
with open(full_path, 'rb') as f_read:
raw_bytes = f_read.read()
backup = inspect_backup_bytes(raw_bytes, clean_name)
stats = import_backup_data(backup, data.get('options', {}))
else:
stats = import_backup_data(data)
invalidate_status_cache()
if not was_active and stats.get('preferences', 0) > 0 and get_pref('ap_ssid', '') and get_pref('ap_password', ''):
threading.Thread(target=restore_ap_from_db, daemon=True).start()
log('import_configuration_complete', username(self) or 'Administrateur', request_ip(self), 'BACKUP')
_set_restore_progress(5, 5, 100, "Sauvegarde restaurée avec succès !", "Redirection et synchronisation finale...", done=True)
self.send_json({
'ok': True,
'message': f"Sauvegarde restaurée avec succès ({stats.get('vpn_profiles',0)} profils VPN, {stats.get('client_names',0)} appareils, {stats.get('preferences',0)} réglages restaurés).",
'stats': stats
})
except Exception as e:
_set_restore_progress(5, 5, 100, f"Erreur : {e}", error=str(e), done=True)
self.send_json({'error': f'Erreur lors de la restauration: {e}'}, 400)
return
if self.path == '/api/backups/remote/test':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
custom_cfg = data.get('config') if isinstance(data, dict) and 'config' in data else None
try:
ok, msg = test_backup_remote(custom_cfg)
self.send_json({'ok': ok, 'message': msg}); return
except Exception as e:
self.send_json({'ok': False, 'error': str(e)}, 500); return
if self.path == '/api/backups/remote/files':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
custom_cfg = data.get('config') if (isinstance(data, dict) and data.get('config')) else None
rcfg = custom_cfg or get_backup_remote_config()
if not rcfg.get('enabled') and not custom_cfg:
self.send_json({'ok': False, 'error': "Le stockage distant n'est pas activé.", 'enabled': False}, 400); return
provider = str(rcfg.get('provider', 'ftp')).strip().lower()
try:
items, err = list_remote_files_detailed(rcfg)
if items is None:
self.send_json({'ok': False, 'error': err or f"Impossible de contacter le stockage distant ({provider.upper()})", 'provider': provider}, 500); return
prov_names = {'gdrive': 'Google Drive', 'dropbox': 'Dropbox', 'sftp': 'SFTP', 'ftp': 'FTP', 'webdav': 'WebDAV', 's3': 'S3', 'webhook': 'Webhook'}
self.send_json({
'ok': True,
'enabled': True,
'provider': provider,
'provider_name': prov_names.get(provider, provider.upper()),
'files': items,
'count': len(items)
}); return
except Exception as e:
self.send_json({'ok': False, 'error': f"Erreur lors de la lecture des fichiers distants : {e}"}, 500); return
if self.path == '/api/backups/remote/file/pull':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
fname = str(data.get('filename', '')).strip()
if not fname or not fname.lower().endswith(BACKUP_ALLOWED_EXTS):
self.send_json({'error': 'Nom de fichier invalide'}, 400); return
clean_name = os.path.basename(fname)
custom_cfg = data.get('config') if isinstance(data, dict) and 'config' in data else None
ensure_backup_dir()
full_path = os.path.join(BACKUP_DIR, clean_name)
tmp_dest = full_path + '.download.tmp'
try:
download_remote_file(clean_name, tmp_dest, custom_cfg=custom_cfg)
os.replace(tmp_dest, full_path)
try:
sync_remote_backups_presence(force=True)
except Exception:
pass
log('recuperation_sauvegarde_distante', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP')
backup_data = None
try:
with open(full_path, 'rb') as f_read:
backup_data = inspect_backup_bytes(f_read.read(), clean_name)
except Exception as e_insp:
print(f"[ap-backup] Avertissement inspection pull : {e_insp}", flush=True)
file_size = os.path.getsize(full_path) if os.path.exists(full_path) else 0
items, total_size = list_server_backups()
self.send_json({
'ok': True,
'message': f"Sauvegarde « {clean_name} » importée avec succès !",
'filename': clean_name,
'size': file_size,
'backup': backup_data,
'backups': items
}); return
except Exception as e:
if os.path.exists(tmp_dest):
try: os.unlink(tmp_dest)
except OSError: pass
self.send_json({'error': f"Échec récupération sauvegarde : {e}"}, 500); return
if self.path == '/api/vpn/profiles':
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
pid = create_or_update_vpn_profile(data)
self.send_json({'ok': True, 'message': 'Profil VPN enregistré avec succès', 'id': pid}); return
if self.path == '/api/notifications/settings':
if auth_state().get('configured') and not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
save_notifications_settings(data)
self.send_json({'ok':True, 'message':'Réglages des notifications enregistrés avec succès'}); return
if self.path == '/api/notifications/test':
if auth_state().get('configured') and not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
channel = str(data.get('channel', 'all')).strip().lower()
test_cfg = data.get('config')
results = test_notifications(channel, test_config=test_cfg)
self.send_json({'ok':True, 'results':results}); return
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
if self.path == '/api/clients/block': set_blocked(str(data.get('mac','')),bool(data.get('blocked',True))); self.send_json({'ok':True}); return
if self.path == '/api/devices/limits':
mac = str(data.get('mac', '')).strip().upper()
if not re.fullmatch(r'[0-9A-F]{2}(:[0-9A-F]{2}){5}', mac):
self.send_json({'error': 'Adresse MAC invalide'}, 400); return
try:
updated_lim = save_client_limits(mac, data)
name, ip = known_device(mac)
log('limites_appareil_modifiees', name, ip, mac)
self.send_json({'ok': True, 'message': 'Limitations enregistrées avec succès', 'limits': updated_lim})
except Exception as e:
self.send_json({'error': f'Erreur enregistrement limitations : {e}'}, 400)
return
if self.path == '/api/devices/rename':
mac = str(data.get('mac', '')).strip().upper()
new_name = str(data.get('name', '')).strip()
if not is_valid_mac(mac): raise ValueError('Adresse MAC invalide')
if not new_name: raise ValueError('Nom manquant')
c = db()
cn_cols = {col[1] for col in c.execute('PRAGMA table_info(client_names)').fetchall()}
if 'is_custom' not in cn_cols:
try:
c.execute('ALTER TABLE client_names ADD COLUMN is_custom INTEGER DEFAULT 0')
c.commit()
except Exception: pass
c.execute('''
INSERT INTO client_names(mac, name, last_ip, last_seen, is_custom)
VALUES(?, ?, "Non attribuée", ?, 1)
ON CONFLICT(mac) DO UPDATE SET name=excluded.name, is_custom=1
''', (mac, new_name, time.strftime('%Y-%m-%d %H:%M:%S')))
# Mettre à jour rétroactivement les logs de cet appareil
c.execute('''
UPDATE connection_logs
SET name = ?
WHERE UPPER(mac) = ?
''', (new_name, mac))
c.commit(); c.close()
station_live_names[mac] = new_name
_device_name_cache[mac] = (new_name, time.time() + 86400)
log('appareil_renomme', f"{username(self) or 'admin'} -> {new_name}", request_ip(self), mac)
self.send_json({'ok': True, 'message': 'Appareil renommé avec succès', 'name': new_name}); return
if self.path == '/api/devices/set_type':
mac = str(data.get('mac', '')).strip().upper()
dev_type = str(data.get('device_type', '')).strip().lower()
if not is_valid_mac(mac): raise ValueError('Adresse MAC invalide')
c = db()
known_types = {r[0] for r in c.execute('SELECT id FROM custom_device_types').fetchall()}
known_types.update({'', 'generic', 'phone', 'tablet', 'laptop', 'desktop', 'tv', 'console', 'iot'})
if dev_type not in known_types:
c.close()
raise ValueError(f'Type d’appareil non valide : {dev_type}')
cn_cols = {row[1] for row in c.execute('PRAGMA table_info(client_names)').fetchall()}
if 'device_type' not in cn_cols:
try:
c.execute('ALTER TABLE client_names ADD COLUMN device_type TEXT DEFAULT ""')
c.commit()
except Exception: pass
default_name = 'Client ' + mac.replace(':', '')[-4:]
c.execute('''
INSERT INTO client_names(mac, name, last_ip, last_seen, device_type)
VALUES(?, ?, "Non attribuée", ?, ?)
ON CONFLICT(mac) DO UPDATE SET device_type=excluded.device_type
''', (mac, default_name, time.strftime('%Y-%m-%d %H:%M:%S'), dev_type))
c.commit(); c.close()
self.send_json({'ok': True, 'message': 'Type d’appareil modifié avec succès', 'device_type': dev_type}); return
if self.path == '/api/device-types/save':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
label = str(data.get('label', '')).strip()
icon = str(data.get('icon', '')).strip() or '💻'
desc = str(data.get('desc', '')).strip()
raw_id = str(data.get('id', '')).strip().lower()
orig_id = str(data.get('original_id', '')).strip().lower()
if not label: raise ValueError('Le nom de la catégorie est obligatoire')
if not raw_id:
raw_id = re.sub(r'[^a-z0-9_-]', '', label.lower().replace(' ', '_'))[:24]
if not raw_id:
raw_id = f"type_{int(time.time())}"
if not re.fullmatch(r'[a-z0-9_-]{2,32}', raw_id):
raise ValueError("L'identifiant doit contenir entre 2 et 32 caractères alphanumériques (minuscules, tirets ou underscores)")
c = db()
if orig_id and orig_id != raw_id:
c.execute('UPDATE client_names SET device_type=? WHERE device_type=?', (raw_id, orig_id))
c.execute('DELETE FROM custom_device_types WHERE id=?', (orig_id,))
existing = c.execute('SELECT sort_order FROM custom_device_types WHERE id=?', (raw_id,)).fetchone()
if existing:
sort_order = existing[0]
else:
max_order = c.execute('SELECT COALESCE(MAX(sort_order), 0) FROM custom_device_types').fetchone()[0]
sort_order = max_order + 1
c.execute('''
INSERT INTO custom_device_types(id, label, icon, desc, sort_order)
VALUES(?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET label=excluded.label, icon=excluded.icon, desc=excluded.desc
''', (raw_id, label, icon, desc, sort_order))
c.commit(); c.close()
log('categorie_appareil_enregistree', f"{username(self) or 'admin'} ({label})", request_ip(self), 'SETTINGS')
self.send_json({'ok': True, 'message': 'Catégorie d’appareil enregistrée avec succès', 'id': raw_id}); return
if self.path == '/api/device-types/delete':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
tid = str(data.get('id', '')).strip().lower()
if not tid: raise ValueError("Identifiant manquant")
c = db()
count = c.execute('SELECT COUNT(*) FROM custom_device_types').fetchone()[0]
if count <= 1:
c.close()
raise ValueError("Impossible de supprimer la dernière catégorie d'appareil")
c.execute("UPDATE client_names SET device_type='generic' WHERE device_type=?", (tid,))
c.execute('DELETE FROM custom_device_types WHERE id=?', (tid,))
c.commit(); c.close()
log('categorie_appareil_supprimee', f"{username(self) or 'admin'} ({tid})", request_ip(self), 'SETTINGS')
self.send_json({'ok': True, 'message': 'Catégorie supprimée avec succès'}); return
if self.path == '/api/device-types/reset':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
c = db()
c.execute('DELETE FROM custom_device_types')
defaults = [
('phone', 'Smartphone', '📱', 'iPhone, Android, Galaxy...', 1),
('tablet', 'Tablette', 'tablet_svg', 'iPad, Galaxy Tab, Kindle...', 2),
('laptop', 'PC Portable', '💻', 'MacBook, ThinkPad, Laptop...', 3),
('desktop', 'Ordinateur fixe', '🖥️', 'PC Bureau, Mac Pro, Tour...', 4),
('tv', 'Smart TV / Box', '📺', 'Apple TV, Chromecast, Box...', 5),
('console', 'Console de jeux', '🎮', 'PlayStation, Switch, Xbox...', 6),
('iot', 'Objet connecté', '📟', 'IoT, Caméra, Domotique, RPi...', 7),
('generic', 'Standard / Autre', '💻', 'Appareil générique / inconnu', 8)
]
c.executemany('INSERT INTO custom_device_types(id, label, icon, desc, sort_order) VALUES(?,?,?,?,?)', defaults)
c.commit(); c.close()
log('categories_appareils_reinitialisees', username(self) or 'admin', request_ip(self), 'SETTINGS')
self.send_json({'ok': True, 'message': 'Catégories réinitialisées avec succès'}); return
if self.path == '/api/devices/delete':
mac = str(data.get('mac', '')).strip().upper()
if not mac: raise ValueError('Adresse MAC manquante')
c = db()
c.execute('DELETE FROM client_names WHERE UPPER(mac)=?', (mac,))
c.execute('DELETE FROM client_traffic WHERE UPPER(mac)=?', (mac,))
c.execute('DELETE FROM client_traffic_daily WHERE UPPER(mac)=?', (mac,))
c.execute('DELETE FROM client_limits WHERE UPPER(mac)=?', (mac,))
c.execute('DELETE FROM client_vpn_routes WHERE UPPER(mac)=?', (mac,))
c.execute('DELETE FROM blocked_clients WHERE UPPER(mac)=?', (mac,))
c.execute('DELETE FROM connection_logs WHERE UPPER(mac)=?', (mac,))
c.commit(); c.close()
station_live_ips.pop(mac, None)
station_live_names.pop(mac, None)
_device_name_cache.pop(mac, None)
self.send_json({'ok': True, 'message': 'Appareil supprimé de l’historique'}); return
if self.path == '/api/advanced/capture/start':
target_iface = (data.get('interface') or '').strip() if isinstance(data, dict) else ''
ok, msg = start_capture(target_iface or None)
self.send_json({'ok': ok, 'message': msg}); return
if self.path == '/api/advanced/capture/stop':
ok, msg = stop_capture()
self.send_json({'ok': ok, 'message': msg}); return
if self.path == '/api/advanced/capture/clear':
ok, msg = clear_capture()
self.send_json({'ok': ok, 'message': msg}); return
if self.path == '/api/advanced/domains/clear':
with capture_lock:
captured_domains.clear()
self.send_json({'ok': True, 'message': 'Historique des domaines réinitialisé'}); return
if self.path == '/api/advanced/capture/test_packet':
generate_test_traffic()
self.send_json({'ok': True, 'message': 'Paquets de test DNS et ICMP générés'}); return
if self.path == '/api/ap/control':
action=str(data.get('action','')); name=connection_name()
if not name and not get_pref('ap_ssid', ''): raise ValueError('Aucune connexion AP configurée')
if is_bridge_mode():
b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
if action in ('start', 'restart'):
db_ssid = (get_pref('ap_ssid', '') or '').strip()
db_pass = get_pref('ap_password', '') or ''
db_sec = (get_pref('ap_security', 'wpa2') or 'wpa2').lower()
if not db_ssid or not db_pass:
raise RuntimeError('Paramètres Wi-Fi manquants en BDD : veuillez ré-enregistrer les réglages Wi-Fi')
if action == 'restart':
stop_hostapd(INTERFACE)
setup_bridge(b_name, b_eth)
start_bridge_hostapd(db_ssid, db_pass, sec=db_sec, bridge_name=b_name, iface=INTERFACE)
mark_ap_started()
elif action == 'stop':
stop_hostapd(INTERFACE)
teardown_bridge_dns_redirection(b_name, INTERFACE)
try: os.remove(UPTIME_FILE)
except OSError: pass
else:
if action in ('start', 'restart'):
ensure_nm_manages_wifi(INTERFACE)
nm_exists = bool(name) and (subprocess.run(['nmcli', 'connection', 'show', name], capture_output=True, text=True).returncode == 0)
if not nm_exists and get_pref('ap_ssid', ''):
if not restore_ap_from_db(force_start=True):
raise RuntimeError('Impossible de restaurer et démarrer la connexion Wi-Fi depuis la BDD')
else:
if action == 'restart':
subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True)
r = subprocess.run(['nmcli', 'connection', 'up', name], capture_output=True, text=True)
if r.returncode: raise RuntimeError(r.stderr.strip())
setup_ap_nat(INTERFACE)
mark_ap_started()
elif action == 'stop':
if name:
r = subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True)
if r.returncode and 'not an active connection' not in r.stderr.lower():
raise RuntimeError(r.stderr.strip())
teardown_ap_nat()
try: os.remove(UPTIME_FILE)
except OSError: pass
invalidate_status_cache()
log({'start':'démarrage','stop':'arrêt','restart':'redémarrage'}.get(action,'action'), 'Point d’accès Wi-Fi', ip=request_ip(self), mac='AP'); self.send_json({'ok':True}); return
if self.path == '/api/ap/mode':
target_mode = str(data.get('mode', '')).strip().lower()
if target_mode not in ('ap', 'bridge'):
raise ValueError("Mode invalide (attendu 'ap' ou 'bridge')")
cur_st = status(force_refresh=True)
ssid = (get_pref('ap_ssid', '') or cur_st.get('ssid') or '').strip()
password = get_pref('ap_password', '') or cur_st.get('password') or ''
sec = (get_pref('ap_security', '') or cur_st.get('security') or 'wpa2').lower()
auto_raw = get_pref('ap_autoconnect', None)
autoconnect = (str(auto_raw).lower() in ('1', 'true', 'yes', 'oui')) if auto_raw is not None else bool(cur_st.get('autoconnect', True))
b_name = str(data.get('bridge_name', '')).strip() or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
b_eth = str(data.get('bridge_eth', '')).strip() or get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
if not ssid or ssid == 'SSID inconnu' or not password:
raise RuntimeError('Configuration Wi-Fi incomplète en BDD : veuillez vérifier vos réglages Wi-Fi')
was_active = bool(cur_st.get('active'))
station_live_ips.clear()
configure_ap({
'ssid': ssid,
'password': password,
'security': sec,
'mode': target_mode,
'autoconnect': autoconnect,
'bridge_name': b_name,
'bridge_eth': b_eth
}, initial=False, caller_ip=request_ip(self), start_now=was_active)
new_st = status(force_refresh=True)
self.send_json({'ok': True, 'mode': target_mode, 'status': new_st}); return
if self.path == '/api/setup': self.send_json({'ok':True,'message':'Configuration enregistrée','connection':configure_ap(data,True,caller_ip=request_ip(self))}); return
if self.path == '/api/settings': self.send_json({'ok':True,'message':'Réglages enregistrés','connection':configure_ap(data,caller_ip=request_ip(self))}); return
if self.path == '/api/settings/proxy':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
enabled = '1' if data.get('enabled') else '0'
header = str(data.get('header', 'auto')).strip().lower()
valid_hdrs = {'auto', 'x-forwarded-for', 'x-real-ip', 'cf-connecting-ip', 'true-client-ip'}
if header not in valid_hdrs: header = 'auto'
trust_private = '1' if data.get('trust_all_private', True) else '0'
trusted_proxies = str(data.get('trusted_proxies', '')).strip()
c = db()
c.execute("INSERT INTO preferences(key, value) VALUES('reverse_proxy_enabled', ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (enabled,))
c.execute("INSERT INTO preferences(key, value) VALUES('reverse_proxy_header', ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (header,))
c.execute("INSERT INTO preferences(key, value) VALUES('reverse_proxy_trust_all_private', ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (trust_private,))
c.execute("INSERT INTO preferences(key, value) VALUES('reverse_proxy_trusted_proxies', ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (trusted_proxies,))
c.commit(); c.close()
log('configuration_proxy_inverse_modifiee', username(self) or 'Administrateur', request_ip(self), 'SETTINGS')
self.send_json({'ok': True, 'message': 'Réglages du proxy inversé enregistrés avec succès !'}); return
if self.path == '/api/vpn/profiles/delete':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
pid = int(data.get('id', 0))
delete_vpn_profile(pid)
self.send_json({'ok': True, 'message': 'Profil VPN supprimé avec succès'}); return
if self.path == '/api/vpn/connect':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
pid = int(data.get('id', 0))
ok, msg = connect_vpn_profile(pid, caller_ip=request_ip(self))
if not ok: self.send_json({'error': msg}, 400); return
self.send_json({'ok': True, 'message': msg}); return
if self.path == '/api/vpn/disconnect':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
pid = int(data.get('id', 0))
ok, msg = disconnect_vpn_profile(pid, caller_ip=request_ip(self))
self.send_json({'ok': True, 'message': msg}); return
if self.path in ('/api/vpn/check-ip', '/api/vpn/public-ip'):
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
pid = int(data.get('id', 0))
prof = get_vpn_profile(pid)
if not prof: self.send_json({'error':'Profil VPN introuvable'},404); return
iface = prof.get('iface') or (f"wg_ap{pid}" if prof['type'] == 'wireguard' else f"tun_ap{pid}")
if not is_iface_up(iface):
self.send_json({'ok': False, 'error': 'Le tunnel VPN est actuellement déconnecté'}); return
ip = get_vpn_public_ip(iface, force_refresh=True)
hs, hs_sec = get_wireguard_handshake_info(iface) if prof['type'] == 'wireguard' else (None, None)
if ip:
self.send_json({'ok': True, 'public_ip': ip, 'handshake': hs, 'handshake_age_seconds': hs_sec, 'iface': iface})
else:
err = 'Impossible de joindre Internet via ce tunnel VPN. '
if hs: err += f"({hs}). "
err += "Vérifiez que le serveur VPN distant est actif et que les clés/AllowedIPs sont correctes."
self.send_json({'ok': False, 'error': err, 'handshake': hs, 'handshake_age_seconds': hs_sec, 'iface': iface})
return
if self.path == '/api/vpn/clients/assign':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
mac = str(data.get('mac', '')).strip().upper()
pid = int(data.get('profile_id', 0))
ks = 1 if data.get('kill_switch') else 0
assign_client_vpn(mac, pid, ks)
self.send_json({'ok': True, 'message': 'Assignation VPN du client mise à jour avec succès'}); return
if self.path == '/api/notifications/stats-report/trigger':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
ok, msg = trigger_manual_stats_report()
self.send_json({'ok': ok, 'message': msg}); return
if self.path == '/api/stats/refresh':
update_background_metrics()
self.send_json(stats()); return
if self.path == '/api/logs/clear':
c=db(); c.execute('DELETE FROM connection_logs'); c.commit(); c.close()
log('suppression_journaux', username(self) or 'Administrateur', request_ip(self), 'SYSTEM')
update_background_metrics()
self.send_json({'ok':True,'message':'Journaux supprimés'}); return
if self.path == '/api/data/clear':
with _clear_data_lock:
if _clear_data_state.get('running'):
self.send_json({'ok': True, 'started': True, 'message': 'Réinitialisation déjà en cours', 'redirect': '/setup'}); return
_clear_data_state['running'] = True
_clear_data_state['step'] = 1
_clear_data_state['total_steps'] = 5
_clear_data_state['percent'] = 10
_clear_data_state['message'] = "Démarrage de la réinitialisation..."
_clear_data_state['done'] = False
_clear_data_state['error'] = None
t = threading.Thread(target=run_clear_all_data, args=(request_ip(self),), daemon=True)
t.start()
self.send_json({'ok': True, 'started': True, 'message': 'Réinitialisation en cours', 'redirect': '/setup'}); return
if self.path == '/api/backups/schedule':
sched = save_backup_schedule(data)
log('planification_sauvegarde_modifiee', f"{username(self) or 'Administrateur'} ({sched.get('cron_expr', '')})", request_ip(self), 'BACKUP')
self.send_json({'ok': True, 'message': 'Planification des sauvegardes enregistrée', 'schedule': sched}); return
if self.path == '/api/backups/create':
info = create_server_backup(trigger='manual')
log('creation_sauvegarde_serveur', f"{username(self) or 'Administrateur'} ({info['filename']})", request_ip(self), 'BACKUP')
items, total_size = list_server_backups()
self.send_json({
'ok': True,
'message': f"Sauvegarde créée : {info['filename']} ({info['size_str']})",
'backup': info,
'backups': items,
'total_count': len(items),
'total_size': total_size,
'total_size_str': format_bytes(total_size),
'schedule': get_backup_schedule()
}); return
if self.path == '/api/backups/delete':
fname = str(data.get('filename', '')).strip()
full_path, clean_name = safe_backup_filepath(fname)
if not os.path.isfile(full_path):
self.send_json({'error': 'Fichier de sauvegarde introuvable'}, 404); return
os.remove(full_path)
try:
rcfg = get_backup_remote_config()
up_files = rcfg.get('uploaded_files', {})
if isinstance(up_files, dict) and clean_name in up_files:
up_files.pop(clean_name, None)
rcfg['uploaded_files'] = up_files
set_pref('backup_remote_config', json.dumps(rcfg, ensure_ascii=False))
except Exception: pass
log('suppression_sauvegarde', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP')
items, total_size = list_server_backups()
self.send_json({
'ok': True,
'message': f'Sauvegarde supprimée : {clean_name}',
'backups': items,
'total_count': len(items),
'total_size': total_size,
'total_size_str': format_bytes(total_size)
}); return
if self.path == '/api/backups/inspect':
fname = str(data.get('filename', '')).strip()
full_path, clean_name = safe_backup_filepath(fname)
if not os.path.isfile(full_path):
self.send_json({'error': 'Fichier de sauvegarde introuvable'}, 404); return
raw_bytes = open(full_path, 'rb').read()
backup = inspect_backup_bytes(raw_bytes, clean_name)
self.send_json({'ok': True, 'filename': clean_name, 'backup': backup}); return
if self.path == '/api/backups/restore':
fname = str(data.get('filename', '')).strip()
full_path, clean_name = safe_backup_filepath(fname)
if not os.path.isfile(full_path):
_set_restore_progress(1, 5, 20, "Fichier introuvable", error="Fichier de sauvegarde introuvable", done=True)
self.send_json({'error': 'Fichier de sauvegarde introuvable'}, 404); return
try:
_set_restore_progress(1, 5, 20, "Analyse et vérification de la sauvegarde...", f"Chargement de {clean_name}...")
time.sleep(0.35)
raw_bytes = open(full_path, 'rb').read()
backup = inspect_backup_bytes(raw_bytes, clean_name)
stats = import_backup_data(backup, data.get('options', {}))
invalidate_status_cache()
log('import_configuration_complete', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP')
_set_restore_progress(5, 5, 100, "Sauvegarde restaurée avec succès !", "Redirection et synchronisation finale...", done=True)
self.send_json({
'ok': True,
'message': f"Sauvegarde « {clean_name} » restaurée avec succès ({stats.get('vpn_profiles',0)} profils VPN, {stats.get('client_names',0)} appareils, {stats.get('preferences',0)} réglages).",
'stats': stats
}); return
except Exception as e:
_set_restore_progress(5, 5, 100, f"Erreur : {e}", error=str(e), done=True)
self.send_json({'error': f'Erreur lors de la restauration: {e}'}, 400); return
if self.path == '/api/backups/remote':
rcfg = save_backup_remote_config(data)
log('configuration_stockage_distant', f"{username(self) or 'Administrateur'} ({rcfg.get('provider', '')})", request_ip(self), 'BACKUP')
self.send_json({'ok': True, 'message': 'Configuration du stockage distant enregistrée avec succès', 'remote': rcfg}); return
if self.path == '/api/backups/remote/upload':
fname = str(data.get('filename', '')).strip()
full_path, clean_name = safe_backup_filepath(fname)
if not os.path.isfile(full_path):
self.send_json({'error': 'Fichier de sauvegarde introuvable'}, 404); return
ok, msg = upload_backup_to_remote(full_path, remote_filename=clean_name)
# Vérification physique immédiate sur le stockage distant
try:
sync_remote_backups_presence(force=True)
except Exception as e_sync:
print(f"[ap-backup] Avertissement synchro post-upload : {e_sync}", flush=True)
log('televersement_distant_manuel', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP')
items, total_size = list_server_backups()
self.send_json({'ok': True, 'message': msg, 'remote': get_backup_remote_config(), 'backups': items}); return
if self.path == '/api/backups/remote/file/delete':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
fname = str(data.get('filename', '')).strip()
if not fname:
self.send_json({'error': 'Nom de fichier requis'}, 400); return
clean_name = os.path.basename(fname)
try:
ok, msg = delete_remote_file(clean_name)
if not ok:
raise RuntimeError(msg)
sync_remote_backups_presence(force=True)
log('suppression_sauvegarde_distante', f"{username(self) or 'Administrateur'} ({clean_name})", request_ip(self), 'BACKUP')
items, total_size = list_server_backups()
self.send_json({
'ok': True,
'message': f"Fichier « {clean_name} » supprimé du stockage distant.",
'backups': items
}); return
except Exception as e:
self.send_json({'error': f"Échec suppression sur le stockage distant : {e}"}, 500); return
if self.path == '/api/backups/remote/files/delete-all':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
rcfg = get_backup_remote_config()
if not rcfg.get('enabled'):
self.send_json({'error': "Le stockage distant n'est pas activé"}, 400); return
try:
items, err = list_remote_files_detailed(rcfg)
if items is None:
raise RuntimeError(err or "Impossible de lister les fichiers distants")
deleted_count = 0
errors = []
for item in items:
fname = item.get('name')
if fname:
clean_name = os.path.basename(fname)
ok, msg = delete_remote_file(clean_name)
if ok:
deleted_count += 1
else:
errors.append(f"{clean_name}: {msg}")
sync_remote_backups_presence(force=True)
log('suppression_sauvegardes_distantes_totale', f"{username(self) or 'Administrateur'} ({deleted_count} fichiers)", request_ip(self), 'BACKUP')
local_items, total_size = list_server_backups()
if errors and deleted_count == 0 and len(items) > 0:
self.send_json({'error': f"Échec de la suppression : {'; '.join(errors[:3])}"}, 500); return
msg = f"{deleted_count} fichier(s) supprimé(s) du stockage distant."
if errors:
msg += f" (Erreurs sur {len(errors)} fichier(s))"
self.send_json({
'ok': True,
'message': msg,
'deleted_count': deleted_count,
'backups': local_items
}); return
except Exception as e:
self.send_json({'error': f"Échec lors de la suppression sur le stockage distant : {e}"}, 500); return
if self.path == '/api/auth/2fa/status':
self.send_json({'enabled':auth_state()['two_factor'],'recovery_remaining':recovery_remaining()}); return
if self.path == '/api/auth/2fa/enable':
row=verify_user(username(self),str(data.get('password','')))
if not row: raise ValueError('Mot de passe incorrect')
secret=base64.b32encode(secrets.token_bytes(10)).decode('ascii').rstrip('=')
sessions[self.headers.get('X-Session-Token','')]['pending_2fa']=secret
log('generation_secret_2fa', username(self), request_ip(self), 'AUTH')
self.send_json({'ok':True,'message':'Secret généré. Ajoutez-le dans votre application TOTP puis confirmez avec le code affiché.','secret':secret}); return
if self.path == '/api/auth/2fa/confirm':
session=sessions.get(self.headers.get('X-Session-Token',''),{})
secret=session.get('pending_2fa')
if not secret or not totp_ok(secret,data.get('code')): raise ValueError('Code 2FA invalide')
row=verify_user(username(self),str(data.get('password','')))
if not row: raise ValueError('Mot de passe incorrect')
create_user(row[0],str(data.get('password','')),secret); session.pop('pending_2fa',None)
log('activation_2fa', username(self), request_ip(self), 'AUTH')
self.send_json({'ok':True,'message':'Double identification activée. Conservez vos codes de récupération.','recovery_codes':recovery_generate()}); return
if self.path == '/api/auth/2fa/disable':
row=verify_user(username(self),str(data.get('password','')))
if not row: raise ValueError('Mot de passe incorrect')
if row[2] and not second_factor_ok(row[2],data.get('code')): raise ValueError('Code 2FA invalide')
create_user(row[0],str(data.get('password','')),None); recovery_clear()
log('desactivation_2fa', username(self), request_ip(self), 'AUTH')
self.send_json({'ok':True,'message':'Double identification désactivée'}); return
if self.path == '/api/auth/2fa/recovery':
row=verify_user(username(self),str(data.get('password','')))
if not row: raise ValueError('Mot de passe incorrect')
if not row[2]: raise ValueError('La 2FA n’est pas activée')
if not second_factor_ok(row[2],data.get('code')): raise ValueError('Code 2FA invalide')
log('regeneration_codes_secours', username(self), request_ip(self), 'AUTH')
self.send_json({'ok':True,'message':'Nouveaux codes générés','recovery_codes':recovery_generate()}); return
if self.path == '/api/auth/password':
current=verify_user(username(self),str(data.get('current_password','')))
if not current: raise ValueError('Mot de passe actuel incorrect')
new_u = str(data.get('username',username(self)))
create_user(new_u,str(data.get('password','')),current[2])
log('modification_identifiants', new_u, request_ip(self), 'AUTH')
self.send_json({'ok':True,'message':'Identifiants modifiés'}); return
if self.path == '/api/preferences':
c=db()
if 'theme' in data:
theme=str(data.get('theme',''))
if theme not in ('dark','light','auto','winxp','futuristic','macos','hacker'): raise ValueError('Thème invalide')
c.execute("INSERT OR REPLACE INTO preferences(key,value) VALUES('theme',?)",(theme,))
if 'language' in data:
lang=str(data.get('language','fr')).strip().lower()
if lang not in ('fr','en-us','en-gb'): lang = 'fr'
c.execute("INSERT OR REPLACE INTO preferences(key,value) VALUES('language',?)",(lang,))
if 'app_name' in data:
if not valid_session(self): raise ValueError('Authentification requise')
app_name=str(data.get('app_name','')).strip()
if not app_name or len(app_name)>64: raise ValueError('Nom de l’application invalide')
c.execute("INSERT OR REPLACE INTO preferences(key,value) VALUES('app_name',?)",(app_name,))
if 'app_short_name' in data:
if not valid_session(self): raise ValueError('Authentification requise')
app_short_name=str(data.get('app_short_name','')).strip()
if not app_short_name or len(app_short_name)>32: raise ValueError('Nom court invalide')
c.execute("INSERT OR REPLACE INTO preferences(key,value) VALUES('app_short_name',?)",(app_short_name,))
c.commit(); c.close()
log('modification_preferences', username(self) or 'Administrateur', request_ip(self), 'CONFIG')
self.send_json({'ok':True,'message':'Préférences enregistrées'}); return
self.send_json({'error':'Route inconnue'},404)
except (ValueError, RuntimeError, sqlite3.Error) as e:
print(f"[ap-api] Requête POST {self.path} ({request_ip(self)}) refusée : {e}", flush=True)
self.send_json({'error':str(e)},400)
except Exception as e:
import traceback
print(f"[ap-error] Erreur interne sur POST {self.path} ({request_ip(self)}) : {e}\n{traceback.format_exc()}", flush=True)
self.send_json({'error':'Erreur interne'},500)
def log_message(self,*args): pass
connected_stations_order = []
def monitor():
global connected_stations_order
sync_vpn_counter = 0
sync_limits_counter = 0
while True:
try:
sync_vpn_counter += 1
if sync_vpn_counter >= 5:
sync_vpn_counter = 0
try:
ensure_ap_nat_active()
ensure_host_resolved_bridge_dns()
sync_vpn_client_rules()
except Exception:
pass
sync_limits_counter += 1
if sync_limits_counter >= 2:
sync_limits_counter = 0
try:
sync_client_bandwidth_and_quotas()
except Exception:
pass
items = clients()
max_c = get_max_clients()
# CORRECTION : éjecter en continu les appareils bloqués qui se reconnectent.
for x in items:
if x['blocked']: command('iw','dev',INTERFACE,'station','del',x['mac'])
active_items = [x for x in items if not x['blocked']]
if max_c > 0 and len(active_items) > max_c:
current_macs = [x['mac'] for x in active_items]
connected_stations_order = [m for m in connected_stations_order if m in current_macs]
for m in current_macs:
if m not in connected_stations_order:
connected_stations_order.append(m)
allowed_macs = set(connected_stations_order[:max_c])
for x in active_items:
if x['mac'] not in allowed_macs:
mac = x['mac']
command('iw','dev',INTERFACE,'station','del',mac)
log('rejet_limite', x['name'], x['ip'], mac)
if mac in connected_stations_order:
connected_stations_order.remove(mac)
else:
current_macs = [x['mac'] for x in active_items]
connected_stations_order = [m for m in connected_stations_order if m in current_macs]
for m in current_macs:
if m not in connected_stations_order:
connected_stations_order.append(m)
allowed_set = set(connected_stations_order[:max_c]) if max_c > 0 else None
update_logs([x for x in items if not x['blocked'] and (allowed_set is None or x['mac'] in allowed_set)])
# Analyse continue des métriques et statistiques en arrière-plan
try:
update_background_metrics(items)
except Exception as e_bg:
print(f"[ap-metrics] Erreur cycle analyse métriques : {e_bg}", flush=True)
# En mode pont, si des clients sont connectés sans IP résolue, solliciter l'ARP
if is_bridge_mode():
unresolved = [x for x in active_items if x['ip'] in ('', 'Non attribuée')]
if unresolved:
b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
ip_cidr, _, _ = get_iface_ip_info(b_name)
if ip_cidr:
try:
import ipaddress
net = ipaddress.IPv4Interface(ip_cidr).network
bcast = str(net.broadcast_address)
subprocess.run(['ping', '-c', '1', '-w', '1', '-b', '-I', b_name, bcast], capture_output=True)
except Exception: pass
except Exception as e:
print(f"[ap-monitor] Erreur surveillance clients : {e}", flush=True)
time.sleep(2)
class UnixServer(ThreadingHTTPServer):
address_family = socket.AF_UNIX
daemon_threads = True
def server_bind(self):
socketserver.TCPServer.server_bind(self)
self.server_name, self.server_port = 'localhost', 0
_update_loop_event = threading.Event()
def update_checker_loop():
"""Vérifie périodiquement si une mise à jour est disponible et déclenche une notification si configurée."""
if _update_loop_event.wait(timeout=30):
_update_loop_event.clear()
while True:
try:
enabled = get_pref('update_checker_enabled', '1') == '1'
if enabled:
check_gitea_update(force_refresh=True)
except Exception:
pass
try:
interval = int(get_pref('update_checker_interval', '7200'))
if interval < 60:
interval = 7200
except Exception:
interval = 7200
if _update_loop_event.wait(timeout=interval):
_update_loop_event.clear()
if __name__ == '__main__':
print(f"[ap-api] Initialisation de la base de données et surveillance sur {INTERFACE}...", flush=True)
sync_version_files()
db()
ensure_dnsmasq_dns()
try:
c = db()
c.execute('DELETE FROM auth_sessions WHERE expires < ?', (time.time(),))
c.execute("UPDATE vpn_profiles SET status='disconnected', last_error='' WHERE status IN ('connecting', 'connected')")
c.commit(); c.close()
except Exception as e_db:
print(f"[ap-vpn] Erreur réinitialisation statut VPN : {e_db}", flush=True)
# Restaurer le profil Wi-Fi (SSID, mot de passe, sécurité, mode, démarrage automatique) depuis la BDD SQLite
restore_ap_from_db()
apply_radio_defaults()
try: sync_client_bandwidth_and_quotas(force=True)
except Exception: pass
threading.Thread(target=arp_listener, daemon=True).start()
threading.Thread(target=monitor, daemon=True).start()
threading.Thread(target=auto_connect_vpn_profiles, daemon=True).start()
threading.Thread(target=vpn_healthcheck_loop, daemon=True).start()
threading.Thread(target=update_background_metrics, daemon=True).start()
threading.Thread(target=stats_report_scheduler_loop, daemon=True).start()
threading.Thread(target=backup_scheduler_loop, daemon=True).start()
threading.Thread(target=start_remote_backup_sync_daemon, daemon=True).start()
threading.Thread(target=update_checker_loop, daemon=True).start()
try: os.remove(SOCKET_PATH)
except OSError: pass
server = UnixServer(SOCKET_PATH, Handler)
os.chmod(SOCKET_PATH, 0o660)
try: shutil.chown(SOCKET_PATH, user='root', group='www-data')
except (LookupError, OSError): os.chmod(SOCKET_PATH, 0o666)
print(f"[ap-api] Serveur API opérationnel sur le socket UNIX {SOCKET_PATH}", flush=True)
server.serve_forever()