"""Temporary LAN browser desktop. Run from its private working directory.""" import os import pathlib import secrets import signal import subprocess import time from urllib.parse import quote root = pathlib.Path.cwd() os.umask(0o077) lan_ip = os.environ['LAN_IP'] token = secrets.token_urlsafe(24) (root / 'access.tokens').write_text(f'{token}: 127.0.0.1:5901\n') path = quote('websockify?token=' + token, safe='') (root / 'connection.txt').write_text( f'https://{lan_ip}:6080/vnc.html?autoconnect=1&resize=scale&path={path}\n' ) commands = [ [str(root / 'lan-remote')], [str(root / 'venv/bin/python'), '-m', 'websockify', '--web', str(root / 'noVNC'), '--token-plugin', 'TokenFile', '--token-source', str(root / 'access.tokens'), '--cert', str(root / 'lan.crt'), '--key', str(root / 'lan.key'), '--ssl-only', f'{lan_ip}:6080'], ] children = [] logs = [] def stop(*_): for child in children: if child.poll() is None: child.terminate() for child in children: try: child.wait(timeout=3) except subprocess.TimeoutExpired: child.kill() child.wait() for log in logs: log.close() for name in ['access.tokens', 'connection.txt', 'manager.pid']: (root / name).unlink(missing_ok=True) print('Temporary remote desktop stopped.', flush=True) raise SystemExit() signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) try: for index, command in enumerate(commands): log = open(root / f'server-{index}.log', 'w') logs.append(log) children.append(subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)) (root / 'manager.pid').write_text(str(os.getpid())) print('Temporary LAN desktop started; expires in 30 minutes.', flush=True) deadline = time.monotonic() + 1800 while time.monotonic() < deadline: if any(child.poll() is not None for child in children): print('A component exited; stopping all components.', flush=True) break time.sleep(1) finally: stop()