1#!/usr/bin/env python3
2import json
3import fcntl
4import os
5from pathlib import Path
6import pwd
7import re
8import subprocess
9import sys
10import tempfile
11
12request = json.load(sys.stdin)
13prepare = request.pop('_prepare', None)
14stop = request.pop('_stop', None)
15unit = prepare or stop or request.pop('_unit')
16if not re.fullmatch(r'snowglobe-computer-request-[0-9a-f]{32}', unit):
17 raise ValueError('Invalid computer task.')
18lease = '/run/snowglobe-computer-request'
19if prepare or stop:
20 with os.fdopen(os.open(lease, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600), 'r+') as current:
21 fcntl.flock(current, fcntl.LOCK_EX)
22 if prepare or current.read() == unit:
23 current.seek(0)
24 current.truncate()
25 current.write(unit if prepare else '')
26 current.flush()
27 if prepare:
28 print(json.dumps({'prepared': True}))
29 sys.exit(0)
30if stop:
31 subprocess.run(['systemctl', 'stop', unit], timeout=12, capture_output=True)
32 state = subprocess.check_output(['systemctl', 'show', unit, '-p', 'ActiveState', '--value'], text=True, timeout=3).strip()
33 if state not in ('inactive', 'failed'):
34 raise RuntimeError('The computer task did not stop.')
35 print(json.dumps({'stopped': True}))
36 sys.exit(0)
37timeout = max(1, min(200, int(request.pop('_timeout'))))
38sessions = subprocess.check_output(['loginctl', 'list-sessions', '--no-legend'], text=True).splitlines()
39for line in sessions:
40 props = dict(item.split('=', 1) for item in subprocess.check_output([
41 'loginctl', 'show-session', line.split()[0], '-p', 'Active', '-p', 'Remote', '-p', 'Type', '-p', 'User',
42 ], text=True).splitlines())
43 if props.get('Active') == 'yes' and props.get('Remote') == 'no' and props.get('Type') in ('x11', 'wayland'):
44 account = pwd.getpwuid(int(props['User']))
45 break
46else:
47 print(json.dumps({'error': 'Sign in to the VM desktop before using this tool.'}))
48 sys.exit(0)
49env = dict(os.environ, HOME=account.pw_dir, USER=account.pw_name, LOGNAME=account.pw_name,
50 XDG_RUNTIME_DIR='/run/user/' + str(account.pw_uid),
51 DBUS_SESSION_BUS_ADDRESS='unix:path=/run/user/' + str(account.pw_uid) + '/bus')
52for path in Path('/proc').glob('[0-9]*/environ'):
53 try:
54 if path.stat().st_uid != account.pw_uid:
55 continue
56 entries = dict(p.split(b'=', 1) for p in path.read_bytes().split(b'\0') if b'=' in p)
57 if b'WAYLAND_DISPLAY' in entries or b'DISPLAY' in entries:
58 for key in ('DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'XDG_SESSION_TYPE', 'GI_TYPELIB_PATH'):
59 if key.encode() in entries:
60 env[key] = entries[key.encode()].decode()
61 break
62 except (OSError, ValueError):
63 pass
64source = request.pop('_worker')
65requests = Path('/var/lib/snowglobe/computer-requests')
66requests.mkdir(mode=0o700, parents=True, exist_ok=True)
67with tempfile.TemporaryDirectory(dir=requests) as directory:
68 root = Path(directory)
69 (root / 'request').write_text(json.dumps(request))
70 args = ['systemd-run', '--quiet', '--wait', '--collect', '--service-type=exec', '--unit=' + unit,
71 '-p', 'RuntimeMaxSec=' + str(timeout), '-p', 'TimeoutStopSec=5', '-p', 'WorkingDirectory=' + account.pw_dir,
72 '-p', 'StandardInput=file:' + str(root / 'request'),
73 '-p', 'StandardOutput=file:' + str(root / 'response'),
74 '-p', 'StandardError=file:' + str(root / 'error')]
75 for key in ('HOME', 'USER', 'LOGNAME', 'PATH', 'XDG_RUNTIME_DIR', 'DBUS_SESSION_BUS_ADDRESS',
76 'DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'XDG_SESSION_TYPE', 'GI_TYPELIB_PATH'):
77 if key in env:
78 args.append('--setenv=' + key + '=' + env[key])
79 identity = f'''import os, fcntl
80with open({lease!r}) as current:
81 fcntl.flock(current, fcntl.LOCK_SH)
82 if current.read() != {unit!r}: raise SystemExit(125)
83os.setgroups({os.getgrouplist(account.pw_name, account.pw_gid)!r}); os.setgid({account.pw_gid}); os.setuid({account.pw_uid})
84'''
85 python = '/var/lib/snowglobe/computer/bin/snowglobe-python'
86 args += [python if Path(python).exists() else sys.executable, '-c', identity + source]
87 result = subprocess.run(args, capture_output=True, timeout=210)
88 if result.returncode:
89 print(json.dumps({'error': 'The desktop worker could not start. Check the guest computer installation.'}))
90 else:
91 sys.stdout.buffer.write((root / 'response').read_bytes())