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