1#!/usr/bin/python
2"""Bounded console and files over the legacy guest's pinned private SSH connection."""
3import base64
4import ctypes
5import json
6import os
7import select
8import signal
9import stat
10import subprocess
11import sys
12import tempfile
13import time
14
15
16def identity(pid):
17 value = subprocess.Popen(['ps', '-p', str(pid), '-o', 'lstart='], stdout=subprocess.PIPE).communicate()[0]
18 return value.decode().strip().replace(':', '-')
19
20
21def run(request):
22 action = request['action']
23 if action == 'status':
24 return {'platform': 'macos', 'runtimes': ['bash', 'zsh'],
25 'capabilities': ['shot', 'input', 'exec', 'spawn', 'process', 'file'],
26 'max_timeout_ms': 180000, 'coordinate_units': 'screenshot_pixels'}
27 if action == 'input':
28 quartz = ctypes.CDLL('/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices')
29 core = ctypes.CDLL('/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation')
30 quartz.CGEventCreateKeyboardEvent.argtypes = [ctypes.c_void_p, ctypes.c_ushort, ctypes.c_bool]
31 quartz.CGEventCreateKeyboardEvent.restype = ctypes.c_void_p
32 quartz.CGEventKeyboardSetUnicodeString.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p]
33 quartz.CGEventPost.argtypes = [ctypes.c_uint, ctypes.c_void_p]
34 core.CFRelease.argtypes = [ctypes.c_void_p]
35 for item in request['actions']:
36 if item['type'] != 'text':
37 raise ValueError('Use the VM console for pointer and key actions.')
38 text = item['text']
39 for start in range(0, len(text), 8):
40 data = text[start:start + 8].encode('utf-16-le')
41 buffer = ctypes.create_string_buffer(data)
42 for down in (True, False):
43 event = quartz.CGEventCreateKeyboardEvent(None, 0, down)
44 if not event:
45 raise ValueError('The desktop refused keyboard input. Sign in and retry.')
46 try:
47 quartz.CGEventKeyboardSetUnicodeString(event, len(data) // 2, buffer)
48 quartz.CGEventPost(0, event)
49 finally:
50 core.CFRelease(event)
51 time.sleep(.015)
52 return {'completed': len(request['actions'])}
53 if action == 'process':
54 pid, separator, started = request['id'].partition(':')
55 if not separator or not pid.isdigit() or int(pid) <= 1:
56 raise ValueError('Use the process handle returned by computer_spawn.')
57 pid = int(pid)
58 if identity(pid) != started:
59 return {'running': False}
60 if request['operation'] == 'stop':
61 if os.getpgid(pid) != pid:
62 raise ValueError('The process is not an isolated computer task.')
63 os.killpg(pid, signal.SIGTERM)
64 return {'stopping': True}
65 return {'running': True, 'pid': pid}
66 if action == 'file':
67 path = request['path']
68 if not path.startswith('/') or '\x00' in path:
69 raise ValueError('Use an absolute guest file path.')
70 operation = request['operation']
71 if operation in ('stat', 'list'):
72 info = os.stat(path)
73 result = {'path': path, 'size': info.st_size, 'directory': stat.S_ISDIR(info.st_mode), 'modified': info.st_mtime}
74 if operation == 'list':
75 names = os.listdir(path)
76 result['entries'] = [{'name': name, 'directory': stat.S_ISDIR(os.lstat(os.path.join(path, name)).st_mode)} for name in names[:1000]]
77 result['truncated'] = len(names) > 1000
78 return result
79 if operation == 'mkdir':
80 if not os.path.isdir(path):
81 os.makedirs(path)
82 return {'path': path}
83 if operation == 'remove':
84 os.unlink(path)
85 return {'removed': True}
86 if operation == 'read':
87 with open(path, 'rb') as incoming:
88 if not stat.S_ISREG(os.fstat(incoming.fileno()).st_mode):
89 raise ValueError('Choose a regular guest file.')
90 incoming.seek(request.get('offset', 0))
91 data = incoming.read(request.get('length', 65536))
92 return {'data': base64.b64encode(data).decode(), 'bytes': len(data)}
93 if operation == 'write':
94 offset = request.get('offset', 0)
95 flags = os.O_WRONLY | os.O_NOFOLLOW | (os.O_CREAT | os.O_EXCL if offset == 0 else 0)
96 with os.fdopen(os.open(path, flags, 0o600), 'wb') as outgoing:
97 info = os.fstat(outgoing.fileno())
98 if not stat.S_ISREG(info.st_mode) or info.st_size != offset:
99 raise ValueError('The transfer offset changed. Start a new upload.')
100 outgoing.seek(offset)
101 data = base64.b64decode(request['data'])
102 outgoing.write(data)
103 return {'bytes': len(data)}
104 if operation == 'commit':
105 destination = request['destination']
106 if not destination.startswith('/') or '\x00' in destination:
107 raise ValueError('Use an absolute guest destination path.')
108 if request.get('overwrite', False):
109 os.rename(path, destination)
110 else:
111 os.link(path, destination)
112 os.unlink(path)
113 return {'path': destination}
114 if action not in ('exec', 'spawn'):
115 raise ValueError('This legacy guest supports screenshot, keyboard, mouse, console, and file tools.')
116 runtime = request.get('runtime', 'default')
117 if runtime == 'default':
118 runtime = 'bash'
119 if runtime not in ('bash', 'zsh'):
120 raise ValueError('Choose bash or zsh for this guest.')
121 descriptor, path = tempfile.mkstemp(prefix='snowglobe-computer-')
122 try:
123 with os.fdopen(descriptor, 'wb') as outgoing:
124 outgoing.write(request['script'].encode('utf-8'))
125 with open('/dev/null', 'rb') as incoming:
126 with open('/dev/null', 'wb') as quiet:
127 process = subprocess.Popen(['/bin/' + runtime, path], stdin=incoming,
128 stdout=quiet if action == 'spawn' else subprocess.PIPE,
129 stderr=quiet if action == 'spawn' else subprocess.PIPE, preexec_fn=os.setsid)
130 if action == 'spawn':
131 return {'id': str(process.pid) + ':' + identity(process.pid), 'pid': process.pid}
132 streams = {process.stdout: 'stdout', process.stderr: 'stderr'}
133 output = {'stdout': b'', 'stderr': b''}
134 truncated = set()
135 deadline = time.time() + request['timeout_ms'] / 1000.0
136 timed_out = False
137 try:
138 while streams or process.poll() is None:
139 if time.time() >= deadline:
140 timed_out = True
141 break
142 ready = select.select(list(streams), [], [], min(.1, max(0, deadline - time.time())))[0]
143 for stream in ready:
144 name = streams[stream]
145 data = os.read(stream.fileno(), 8192)
146 if not data:
147 del streams[stream]
148 continue
149 available = 65536 - len(output[name])
150 output[name] += data[:available]
151 if len(data) > available:
152 truncated.add(name)
153 finally:
154 try:
155 os.killpg(process.pid, signal.SIGKILL)
156 except OSError:
157 pass
158 process.wait()
159 return {'exit': process.returncode, 'stdout': output['stdout'].decode('utf-8', 'replace'),
160 'stderr': output['stderr'].decode('utf-8', 'replace'), 'timed_out': timed_out,
161 'stdout_truncated': 'stdout' in truncated, 'stderr_truncated': 'stderr' in truncated}
162 finally:
163 if action != 'spawn':
164 os.unlink(path)
165
166
167try:
168 print(json.dumps(run(request)))
169except (ValueError, OSError, KeyError) as error:
170 print(json.dumps({'error': str(error)}))