APmanageur Wi-Fi V1.0
This commit is contained in:
1 parent
c46d60d262
commit
ed08f9c8d4
8 files changed
+915
-26
No files matched your search
@@ -7853,6 +7853,252 @@ def inspect_backup_bytes(raw_bytes, filename=''):
|
||||
raise ValueError(f"Fichier de sauvegarde non reconnu (ni ZIP, ni SQLite, ni JSON) : {e}")
|
||||
|
||||
|
||||
BACKUP_DIR = os.environ.get('AP_BACKUP_DIR', '/backups').strip() or '/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))
|
||||
|
||||
st = os.stat(full_path)
|
||||
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 list_server_backups():
|
||||
ensure_backup_dir()
|
||||
items = []
|
||||
total_size = 0
|
||||
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'
|
||||
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
|
||||
})
|
||||
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', 'Cron', '127.0.0.1', info['filename'])
|
||||
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'},
|
||||
@@ -8169,6 +8415,40 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return
|
||||
except Exception as e:
|
||||
self.send_json({'error': f'Erreur génération archive ZIP: {e}'}, 500); return
|
||||
if self.path == '/api/backups/list':
|
||||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||||
items, total_size = list_server_backups()
|
||||
self.send_json({
|
||||
'ok': True,
|
||||
'backup_dir': BACKUP_DIR,
|
||||
'schedule': get_backup_schedule(),
|
||||
'backups': items,
|
||||
'total_count': len(items),
|
||||
'total_size': total_size,
|
||||
'total_size_str': format_bytes(total_size)
|
||||
}); return
|
||||
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', username(self) or 'Administrateur', request_ip(self), clean_name)
|
||||
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()
|
||||
@@ -8997,6 +9277,63 @@ class Handler(BaseHTTPRequestHandler):
|
||||
with traffic_lock: station_traffic.clear()
|
||||
log('reinitialisation_donnees', 'Système', request_ip(self), 'SYSTEM')
|
||||
self.send_json({'ok':True,'message':'Toutes les données et le point d’accès ont été réinitialisés et supprimés','redirect':'/setup'}); return
|
||||
if self.path == '/api/backups/schedule':
|
||||
sched = save_backup_schedule(data)
|
||||
log('planification_sauvegarde_modifiee', username(self) or 'Administrateur', request_ip(self), sched.get('cron_expr', ''))
|
||||
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', username(self) or 'Administrateur', request_ip(self), info['filename'])
|
||||
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)
|
||||
log('suppression_sauvegarde', username(self) or 'Administrateur', request_ip(self), clean_name)
|
||||
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):
|
||||
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)
|
||||
stats = import_backup_data(backup, data.get('options', {}))
|
||||
invalidate_status_cache()
|
||||
log('import_configuration_complete', username(self) or 'Administrateur', request_ip(self), clean_name)
|
||||
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
|
||||
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':
|
||||
@@ -9179,6 +9516,7 @@ if __name__ == '__main__':
|
||||
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()
|
||||
try: os.remove(SOCKET_PATH)
|
||||
except OSError: pass
|
||||
server = UnixServer(SOCKET_PATH, Handler)
|
||||
|
||||
Reference in new issue
Block a user