"""Verify and recover media into a NEW host directory; never overwrite live data. Requires the running Deck container with maintenance/backup_stream.py. """ import argparse,json,os,shutil,subprocess,tarfile,tempfile,threading from pathlib import Path from scheduled_backup import command,KEY def feed(process,archive,secret,errors): try: process.stdin.write(secret) with archive.open('rb') as f:shutil.copyfileobj(f,process.stdin,1024*1024) except BaseException as e:errors.append(e) finally:process.stdin.close() def restore(archive,target,keyfile): if target.exists() or target.is_symlink():raise ValueError('Ziel muss neu und leer sein; bestehende Daten werden nicht überschrieben') secret=keyfile.read_bytes().strip()+b'\n' check=subprocess.Popen(command('backup_stream.py','verify'),stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) errors=[];thread=threading.Thread(target=feed,args=(check,archive,secret,errors));thread.start();out,err=check.stdout.read(),check.stderr.read();thread.join() if check.wait() or errors:raise ValueError('Archiv oder Schlüssel ungültig; nichts wiederhergestellt') target.parent.mkdir(parents=True,exist_ok=True) with tempfile.TemporaryDirectory(prefix='.userdata-restore-',dir=target.parent) as temporary: stage=Path(temporary)/'data';stage.mkdir(mode=0o700) process=subprocess.Popen(command('backup_stream.py','decrypt'),stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) errors=[];thread=threading.Thread(target=feed,args=(process,archive,secret,errors));thread.start() try: with tarfile.open(fileobj=process.stdout,mode='r|gz') as tar: for member in tar: if not member.isfile() or member.name.startswith('/') or '..' in member.name.split('/'):raise ValueError('Unsicherer Archivpfad') dest=stage/member.name if dest.exists():raise ValueError('Doppelter Archivpfad') dest.parent.mkdir(parents=True,exist_ok=True) with dest.open('xb') as f:shutil.copyfileobj(tar.extractfile(member),f,1024*1024) dest.chmod(0o600) # Drain the decrypted stream so AES-GCM final authentication runs. while process.stdout.read(1024*1024):pass thread.join();err=process.stderr.read() if process.wait() or errors:raise ValueError('Wiederherstellung unvollständig') stage.rename(target) finally: if process.poll() is None:process.kill();process.wait() thread.join() return json.loads(out) if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('archive',type=Path);p.add_argument('target',type=Path);p.add_argument('--key',type=Path,default=KEY);a=p.parse_args();print(json.dumps(restore(a.archive,a.target,a.key)))