| 1 | """Bounded computer operations over the existing private VM transports.""" |
| 2 | import asyncio |
| 3 | import base64 |
| 4 | import contextlib |
| 5 | from contextvars import ContextVar |
| 6 | import hashlib |
| 7 | from importlib import import_module |
| 8 | import json |
| 9 | import os |
| 10 | from pathlib import Path |
| 11 | import shlex |
| 12 | import subprocess |
| 13 | import sys |
| 14 | import threading |
| 15 | import time |
| 16 | import uuid |
| 17 | import xml.etree.ElementTree as ET |
| 18 | |
| 19 | import vms |
| 20 | |
| 21 | rfb = import_module('vm-rfb') |
| 22 | SCREEN_SLOT = threading.BoundedSemaphore(1) |
| 23 | DEADLINE = ContextVar('computer_deadline', default=float('inf')) |
| 24 | |
| 25 | |
| 26 | def remaining(limit): |
| 27 | seconds = min(limit, DEADLINE.get() - time.monotonic()) |
| 28 | if seconds <= 0: |
| 29 | raise TimeoutError('The input batch timed out. Check the desktop before continuing.') |
| 30 | return seconds |
| 31 | |
| 32 | |
| 33 | def qga(name, operation, **arguments): |
| 34 | payload = json.dumps({'execute': operation, 'arguments': arguments}) |
| 35 | # Virsh reads stdin so guest scripts and file contents never enter host argv. |
| 36 | command = 'qemu-agent-command ' + shlex.quote(name) + ' --timeout 10 ' + shlex.quote(payload) + '\n' |
| 37 | result = subprocess.run(['virsh', '--quiet', '--connect', 'qemu:///system'], input=command, |
| 38 | capture_output=True, text=True, timeout=remaining(15)) |
| 39 | for line in result.stdout.splitlines(): |
| 40 | if line.startswith('{'): |
| 41 | value = json.loads(line) |
| 42 | if 'return' in value: |
| 43 | return value['return'] |
| 44 | if operation == 'guest-exec-status' and any(line.endswith(( |
| 45 | f"PID {arguments['pid']} does not exist", 'PID ld does not exist', 'PID lld does not exist', "Invalid parameter 'pid'")) |
| 46 | for line in result.stderr.splitlines()): |
| 47 | raise ProcessLookupError('The guest process result is unavailable. Check the VM before retrying.') |
| 48 | raise ValueError('The guest agent did not answer. Wait for the VM to finish starting, then retry.') |
| 49 | |
| 50 | |
| 51 | def guest_exec(name, path, args, data=None, timeout=20): |
| 52 | arguments = {'path': path, 'arg': args, 'capture-output': True} |
| 53 | if data is not None: |
| 54 | arguments['input-data'] = base64.b64encode(data).decode() |
| 55 | pid = qga(name, 'guest-exec', **arguments)['pid'] |
| 56 | deadline = time.monotonic() + remaining(timeout) |
| 57 | finished = None |
| 58 | while time.monotonic() < deadline: |
| 59 | try: |
| 60 | result = qga(name, 'guest-exec-status', pid=pid) |
| 61 | except ProcessLookupError: |
| 62 | if finished is None: |
| 63 | raise |
| 64 | if finished.get('exitcode') != 0: |
| 65 | raise ValueError('The guest worker could not run. Check the desktop session and installed computer tools.') |
| 66 | if finished.get('out-truncated') or finished.get('err-truncated'): |
| 67 | raise ValueError('The guest response was truncated. Narrow the request.') |
| 68 | return base64.b64decode(finished.get('out-data', ''), validate=True) |
| 69 | # QGA retains completed records across PID reuse and returns the oldest first. |
| 70 | if result.get('exited'): |
| 71 | finished = result |
| 72 | continue |
| 73 | finished = None |
| 74 | time.sleep(.15) |
| 75 | raise ValueError('The guest operation is still running. Check its status before retrying.') |
| 76 | |
| 77 | |
| 78 | def read_file(name, path, offset=0, length=65536): |
| 79 | handle = qga(name, 'guest-file-open', path=path, mode='rb') |
| 80 | try: |
| 81 | qga(name, 'guest-file-seek', handle=handle, offset=offset, whence=0) |
| 82 | value = qga(name, 'guest-file-read', handle=handle, count=length) |
| 83 | return base64.b64decode(value['buf-b64'], validate=True) |
| 84 | finally: |
| 85 | qga(name, 'guest-file-close', handle=handle) |
| 86 | |
| 87 | |
| 88 | def write_file(name, path, data, offset=0): |
| 89 | handle = qga(name, 'guest-file-open', path=path, mode='r+b' if offset else 'wb') |
| 90 | try: |
| 91 | if offset: |
| 92 | end = qga(name, 'guest-file-seek', handle=handle, offset=0, whence=2) |
| 93 | if end['position'] != offset: |
| 94 | raise ValueError('The transfer offset changed. Start a new upload.') |
| 95 | for start in range(0, len(data), 49152): |
| 96 | chunk = data[start:start + 49152] |
| 97 | result = qga(name, 'guest-file-write', handle=handle, **{'buf-b64': base64.b64encode(chunk).decode()}) |
| 98 | if result['count'] != len(chunk): |
| 99 | raise ValueError('The guest disk could not accept the file. Check free space.') |
| 100 | finally: |
| 101 | qga(name, 'guest-file-close', handle=handle) |
| 102 | |
| 103 | |
| 104 | def powershell(name, script, timeout=60): |
| 105 | """Win7 needs a hidden console; ARM64 QGA cannot capture WSH's console output.""" |
| 106 | stem = 'C:\\Windows\\Temp\\snowglobe-computer-' + uuid.uuid4().hex |
| 107 | command = 'cmd.exe /d /c powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + stem + '.ps1' |
| 108 | command += ' > ' + stem + '.out 2> ' + stem + '.err' |
| 109 | launcher = '''Set shell = CreateObject("WScript.Shell") |
| 110 | code = shell.Run("COMMAND", 0, True) |
| 111 | Set files = CreateObject("Scripting.FileSystemObject") |
| 112 | If code <> 0 Then files.DeleteFile "STEM.out" |
| 113 | files.DeleteFile "STEM.err" |
| 114 | files.DeleteFile "STEM.ps1" |
| 115 | files.DeleteFile WScript.ScriptFullName |
| 116 | WScript.Quit code |
| 117 | '''.replace('COMMAND', command).replace('STEM', stem) |
| 118 | write_file(name, stem + '.ps1', b'\xff\xfe' + script.encode('utf-16le')) |
| 119 | write_file(name, stem + '.vbs', launcher.encode('ascii')) |
| 120 | guest_exec(name, 'cscript.exe', ['//nologo', stem + '.vbs'], timeout=timeout) |
| 121 | try: |
| 122 | return read_file(name, stem + '.out', length=2*1024*1024) |
| 123 | finally: |
| 124 | guest_exec(name, 'cmd.exe', ['/d', '/c', 'del ' + stem + '.out']) |
| 125 | |
| 126 | |
| 127 | async def desktop(name, actions=None, platform=None, screenshot=True, native_text=True): |
| 128 | if not SCREEN_SLOT.acquire(blocking=False): |
| 129 | raise ValueError('Another screen capture is running. Retry in a moment.') |
| 130 | token = DEADLINE.set(min(DEADLINE.get(), time.monotonic() + 180)) |
| 131 | try: |
| 132 | return await asyncio.wait_for(capture(name, actions, platform, screenshot, native_text), remaining(180)) |
| 133 | finally: |
| 134 | DEADLINE.reset(token) |
| 135 | SCREEN_SLOT.release() |
| 136 | |
| 137 | |
| 138 | async def capture(name, actions, platform, screenshot=True, native_text=True): |
| 139 | target = vms.console_target(name, timeout=remaining(10)) |
| 140 | reader, writer = await asyncio.wait_for(asyncio.open_connection('127.0.0.1', target['port']), 10) |
| 141 | screen = rfb.Desktop(reader, writer, lambda _: None) |
| 142 | task = None |
| 143 | try: |
| 144 | await asyncio.wait_for(screen.start(), 10) |
| 145 | ready = asyncio.Event() |
| 146 | task = asyncio.create_task(screen.read(ready.set, ready.clear)) |
| 147 | await asyncio.wait_for(ready.wait(), 10) |
| 148 | if actions: |
| 149 | for action in actions: |
| 150 | kind = action['type'] |
| 151 | if kind in ('move', 'click', 'drag', 'scroll'): |
| 152 | x, y = action['x'], action['y'] |
| 153 | if not 0 <= x < screen.width or not 0 <= y < screen.height: |
| 154 | raise ValueError('Choose coordinates inside the latest screenshot.') |
| 155 | screen.input({'type': 'pointer', 'x': x, 'y': y, 'buttons': 0}) |
| 156 | button = {'left': 1, 'middle': 2, 'right': 4}.get(action.get('button', 'left')) |
| 157 | if kind == 'click': |
| 158 | for _ in range(action.get('count', 1)): |
| 159 | screen.input({'type': 'pointer', 'x': x, 'y': y, 'buttons': button}) |
| 160 | await asyncio.sleep(.04) |
| 161 | screen.input({'type': 'pointer', 'x': x, 'y': y, 'buttons': 0}) |
| 162 | await asyncio.sleep(.06) |
| 163 | elif kind == 'drag': |
| 164 | end_x, end_y = action['to_x'], action['to_y'] |
| 165 | if not 0 <= end_x < screen.width or not 0 <= end_y < screen.height: |
| 166 | raise ValueError('Choose drag coordinates inside the latest screenshot.') |
| 167 | screen.input({'type': 'pointer', 'x': x, 'y': y, 'buttons': button}) |
| 168 | for step in range(1, 21): |
| 169 | screen.input({'type': 'pointer', 'x': round(x+(end_x-x)*step/20), |
| 170 | 'y': round(y+(end_y-y)*step/20), 'buttons': button}) |
| 171 | await asyncio.sleep(action.get('duration_ms', 400)/20000) |
| 172 | screen.input({'type': 'release'}) |
| 173 | elif kind == 'scroll': |
| 174 | wheel = {'up': 8, 'down': 16, 'left': 32, 'right': 64}[action['direction']] |
| 175 | for _ in range(action.get('amount', 3)): |
| 176 | screen.input({'type': 'pointer', 'x': x, 'y': y, 'buttons': wheel}) |
| 177 | screen.input({'type': 'pointer', 'x': x, 'y': y, 'buttons': 0}) |
| 178 | await asyncio.sleep(.02) |
| 179 | elif kind == 'key': |
| 180 | keys = [keycode(key) for key in action['keys']] |
| 181 | for key in keys: |
| 182 | screen.input({'type': 'key', 'key': key, 'down': True}) |
| 183 | await asyncio.sleep(.04) |
| 184 | for key in reversed(keys): |
| 185 | screen.input({'type': 'key', 'key': key, 'down': False}) |
| 186 | elif kind == 'text': |
| 187 | if native_text: |
| 188 | pending = asyncio.create_task(asyncio.to_thread(worker,name,platform,{'action':'input','actions':[action],'screenshot':False})) |
| 189 | try: |
| 190 | await asyncio.shield(pending) |
| 191 | finally: |
| 192 | # Cancellation cannot release the VM lock while its worker still runs. |
| 193 | with contextlib.suppress(Exception): |
| 194 | await pending |
| 195 | else: |
| 196 | text = action['text'] |
| 197 | if any(not (32 <= ord(char) <= 126 or char in '\n\r\t') for char in text): |
| 198 | raise ValueError('This legacy guest supports ASCII text only. Use key actions for other keyboard input.') |
| 199 | shifted = dict(zip('~!@#$%^&*()_+{}|:"<>?', '`1234567890-=[]\\;\',./')) |
| 200 | for char in text.replace('\r\n', '\n'): |
| 201 | shift = char in shifted |
| 202 | base = shifted.get(char, char) |
| 203 | key = {'\n': 0xff0d, '\r': 0xff0d, '\t': 0xff09}.get(base, ord(base)) |
| 204 | if shift: |
| 205 | screen.input({'type': 'key', 'key': 0xffe1, 'down': True}) |
| 206 | screen.input({'type': 'key', 'key': key, 'down': True}) |
| 207 | await writer.drain() |
| 208 | await asyncio.sleep(.01) |
| 209 | screen.input({'type': 'key', 'key': key, 'down': False}) |
| 210 | if shift: |
| 211 | screen.input({'type': 'key', 'key': 0xffe1, 'down': False}) |
| 212 | await writer.drain() |
| 213 | await asyncio.sleep(.01) |
| 214 | elif kind == 'wait': |
| 215 | await asyncio.sleep(action['duration_ms']/1000) |
| 216 | await writer.drain() |
| 217 | screen.input({'type': 'release'}) |
| 218 | await asyncio.wait_for(writer.drain(), 5) |
| 219 | if not screenshot: |
| 220 | return {'completed': len(actions)} |
| 221 | await asyncio.sleep(.2) |
| 222 | # Force a full update even when the desktop has stopped painting. |
| 223 | ready.clear() |
| 224 | screen.request(False) |
| 225 | await writer.drain() |
| 226 | await asyncio.wait_for(ready.wait(), 10) |
| 227 | task.cancel() |
| 228 | with contextlib.suppress(asyncio.CancelledError): |
| 229 | await task |
| 230 | task = None |
| 231 | return {'width': screen.width, 'height': screen.height, 'bounds': [0,0,screen.width,screen.height], |
| 232 | 'scale': [1,1], 'png': rfb.png(screen.width, screen.height, screen.pixels, bgra=True).split(',',1)[1]} |
| 233 | finally: |
| 234 | with contextlib.suppress(Exception): |
| 235 | screen.input({'type': 'release'}) |
| 236 | await asyncio.wait_for(writer.drain(), 5) |
| 237 | if task: |
| 238 | task.cancel() |
| 239 | with contextlib.suppress(asyncio.CancelledError, Exception): |
| 240 | await task |
| 241 | writer.close() |
| 242 | await asyncio.wait_for(writer.wait_closed(), 5) |
| 243 | |
| 244 | |
| 245 | def keycode(key): |
| 246 | names = {'Enter': 0xff0d, 'Tab': 0xff09, 'Escape': 0xff1b, 'Backspace': 0xff08, |
| 247 | 'Delete': 0xffff, 'Insert': 0xff63, 'Home': 0xff50, 'End': 0xff57, |
| 248 | 'PageUp': 0xff55, 'PageDown': 0xff56, 'Left': 0xff51, 'Up': 0xff52, |
| 249 | 'Right': 0xff53, 'Down': 0xff54, 'Shift': 0xffe1, 'Control': 0xffe3, |
| 250 | 'Alt': 0xffe9, 'Meta': 0xffeb, 'Space': 0x20} |
| 251 | names.update({'F'+str(i): 0xffbd+i for i in range(1,25)}) |
| 252 | if key in names: |
| 253 | return names[key] |
| 254 | if len(key) == 1 and 32 <= ord(key) <= 126: |
| 255 | return ord(key) |
| 256 | raise ValueError('Use a named key or one ASCII character.') |
| 257 | |
| 258 | |
| 259 | def validate(request): |
| 260 | if not isinstance(request, dict): |
| 261 | raise ValueError('Send a computer operation.') |
| 262 | action = request.get('action') |
| 263 | fields = {'status': set(), 'shot': set(), 'ui': {'pid'}, 'ui_action': {'target','operation','value','screenshot'}, |
| 264 | 'exec': {'script','runtime','timeout_ms','screenshot'}, 'input': {'actions','screenshot'}, |
| 265 | 'spawn': {'script','runtime'}, 'process': {'id','operation'}, |
| 266 | 'file': {'operation','path','offset','data','length','destination','overwrite'}} |
| 267 | if not isinstance(action,str) or action not in fields or set(request)-{'action'}-fields[action]: |
| 268 | raise ValueError('Use the fields listed for this computer operation.') |
| 269 | if action in ('exec','spawn'): |
| 270 | if not isinstance(request.get('script'),str) or not 1 <= len(request['script'].encode()) <= 65536: |
| 271 | raise ValueError('Provide a script of at most 64 KiB.') |
| 272 | if request.get('runtime') not in (None,'default','bash','zsh','powershell','cmd','ahk'): |
| 273 | raise ValueError('Choose a runtime reported by computer_status.') |
| 274 | if action == 'exec' and (type(request.get('timeout_ms')) is not int or not 1 <= request['timeout_ms'] <= 180000): |
| 275 | raise ValueError('Choose a timeout between 1 and 180000 milliseconds.') |
| 276 | if 'screenshot' in request and type(request['screenshot']) is not bool: |
| 277 | raise ValueError('Choose whether to return a screenshot.') |
| 278 | if action == 'ui' and request.get('pid') is not None and (type(request['pid']) is not int or request['pid']<=0): |
| 279 | raise ValueError('Choose a positive application PID.') |
| 280 | if action == 'ui_action': |
| 281 | if not isinstance(request.get('target'),dict) or len(json.dumps(request['target']))>4096 or not isinstance(request.get('operation'),str) or len(request['operation'])>64: |
| 282 | raise ValueError('Use a target and action returned by computer_ui.') |
| 283 | if 'value' in request and (not isinstance(request['value'],str) or len(request['value'].encode())>16384): |
| 284 | raise ValueError('Set a value of at most 16 KiB.') |
| 285 | if action == 'file': |
| 286 | path=request.get('path') |
| 287 | if not isinstance(path,str) or not 1<=len(path)<=4096 or '\x00' in path: |
| 288 | raise ValueError('Use an absolute guest file path.') |
| 289 | operation=request.get('operation') |
| 290 | if operation not in ('stat','list','mkdir','remove','read','write','commit'): |
| 291 | raise ValueError('Choose a supported file operation.') |
| 292 | if operation in ('read','write'): |
| 293 | offset=request.get('offset',0) |
| 294 | if type(offset) is not int or not 0<=offset<=64*2**20: |
| 295 | raise ValueError('Choose a transfer offset within 64 MiB.') |
| 296 | if operation=='read': |
| 297 | length=request.get('length',65536) |
| 298 | if type(length) is not int or not 1<=length<=65536: raise ValueError('Read at most 64 KiB at a time.') |
| 299 | else: |
| 300 | if not isinstance(request.get('data'),str) or len(request['data'])>90000 or len(base64.b64decode(request['data'],validate=True))>65536: |
| 301 | raise ValueError('Write at most 64 KiB at a time.') |
| 302 | if operation=='commit' and (not isinstance(request.get('destination'),str) or not 1<=len(request['destination'])<=4096 or '\x00' in request['destination'] or type(request.get('overwrite',False)) is not bool): |
| 303 | raise ValueError('Choose an absolute guest destination and whether to replace it.') |
| 304 | if action == 'process' and (not isinstance(request.get('id'),str) or len(request['id'])>128 or request.get('operation') not in ('status','stop')): |
| 305 | raise ValueError('Use the process handle returned by computer_spawn.') |
| 306 | if action == 'input': |
| 307 | actions = request.get('actions') |
| 308 | if not isinstance(actions,list) or not 1 <= len(actions) <= 100: |
| 309 | raise ValueError('Send between 1 and 100 desktop actions.') |
| 310 | for item in actions: |
| 311 | if not isinstance(item,dict): |
| 312 | raise ValueError('Send a desktop action object.') |
| 313 | kind = item.get('type') |
| 314 | required = {'move': {'x','y'}, 'click': {'x','y'}, 'drag': {'x','y','to_x','to_y'}, |
| 315 | 'scroll': {'x','y','direction'}, 'key': {'keys'}, 'text': {'text'}, 'wait': {'duration_ms'}} |
| 316 | optional = {'click': {'button','count'}, 'drag': {'button','duration_ms'}, 'scroll': {'amount'}} |
| 317 | if not isinstance(kind,str) or kind not in required or not required[kind] <= item.keys() or set(item)-{'type'}-required[kind]-optional.get(kind,set()): |
| 318 | raise ValueError('Use the fields listed for this desktop action.') |
| 319 | for key in ('x','y','to_x','to_y'): |
| 320 | if key in item and (type(item[key]) is not int or not 0 <= item[key] <= 16384): |
| 321 | raise ValueError('Use nonnegative screenshot pixel coordinates.') |
| 322 | if 'button' in item and item['button'] not in ('left','right','middle'): |
| 323 | raise ValueError('Choose the left, right, or middle mouse button.') |
| 324 | for key,maximum in [('count',3),('amount',100),('duration_ms',5000)]: |
| 325 | if key in item and (type(item[key]) is not int or not 1 <= item[key] <= maximum): |
| 326 | raise ValueError('The desktop action exceeds its limit.') |
| 327 | if kind == 'scroll' and item['direction'] not in ('up','down','left','right'): |
| 328 | raise ValueError('Choose a scroll direction.') |
| 329 | if kind == 'key': |
| 330 | if not isinstance(item['keys'],list) or not 1 <= len(item['keys']) <= 8 or any(not isinstance(k,str) for k in item['keys']): |
| 331 | raise ValueError('Send between 1 and 8 key names.') |
| 332 | for key in item['keys']: keycode(key) |
| 333 | if kind == 'text' and (not isinstance(item['text'],str) or len(item['text'].encode()) > 16384): |
| 334 | raise ValueError('Type at most 16 KiB of text at a time.') |
| 335 | if sum(a.get('duration_ms',0) for a in actions) > 15000: |
| 336 | raise ValueError('Keep total waits and drags under 15 seconds.') |
| 337 | |
| 338 | |
| 339 | def record_operation(name, operation): |
| 340 | path = vms.DISKS / name / 'computer-operation.json' |
| 341 | temporary = path.with_suffix('.new') |
| 342 | with open(temporary, 'w', opener=lambda p, flags: os.open(p, flags | os.O_NOFOLLOW, 0o600)) as outgoing: |
| 343 | json.dump(operation, outgoing) |
| 344 | os.replace(temporary, path) |
| 345 | |
| 346 | |
| 347 | def finish_operation(name, operation): |
| 348 | token = DEADLINE.set(time.monotonic() + 60) |
| 349 | try: |
| 350 | if operation['platform'] == 'linux': |
| 351 | guest_exec(name, '/etc/qemu-ga/fsfreeze-hook.d/snowglobe-computer', [], |
| 352 | json.dumps({'_stop': operation['id']}).encode(), timeout=18) |
| 353 | else: |
| 354 | run = operation['id'] |
| 355 | directory = 'C:\\ProgramData\\SnowglobeComputer\\' + run |
| 356 | cleanup = "$ErrorActionPreference='Stop';$d='"+directory+"';" |
| 357 | cleanup += "if(Test-Path -LiteralPath ($d+'\\request.json')){Remove-Item -LiteralPath ($d+'\\request.json') -Force};" |
| 358 | cleanup += "$s=New-Object -ComObject Schedule.Service;$s.Connect();$f=$s.GetFolder('\\');" |
| 359 | cleanup += "$t=$f.GetTasks(1) | Where-Object {$_.Name -eq 'SnowglobeComputer-"+run+"'};if($t){" |
| 360 | if not operation.get('keep_spawn'): |
| 361 | cleanup += "$workers=@(Get-WmiObject Win32_Process | Where-Object {$_.CommandLine -like ('*'+$d+'\\request.json*')} | ForEach-Object {$p=Get-Process -Id $_.ProcessId -ErrorAction SilentlyContinue;if($p){$null=$p.Handle;$p}});" |
| 362 | cleanup += "[Reflection.Assembly]::LoadFrom($t.Definition.Actions.Item(1).Path)|Out-Null;[ComputerProcess]::Stop($d+'\\request.json');" |
| 363 | cleanup += "$t.Stop(0);while($t.State -eq 4){Start-Sleep -Milliseconds 100};" |
| 364 | cleanup += "foreach($p in $workers){if(!$p.WaitForExit(10000)){throw 'Process cleanup failed'};$p.Dispose()};" |
| 365 | cleanup += "$f.DeleteTask('SnowglobeComputer-"+run+"',0)};" |
| 366 | if not operation.get('keep_spawn'): |
| 367 | cleanup += "if(Test-Path -LiteralPath $d){Remove-Item -LiteralPath $d -Recurse -Force}" |
| 368 | powershell(name, cleanup, timeout=58) |
| 369 | (vms.DISKS / name / 'computer-operation.json').unlink() |
| 370 | except Exception as error: |
| 371 | raise BlockingIOError('The previous operation has not stopped. Check its screenshot, then retry when the guest agent reconnects.') from error |
| 372 | finally: |
| 373 | DEADLINE.reset(token) |
| 374 | |
| 375 | |
| 376 | def worker(name, platform, request): |
| 377 | if platform == 'macos': |
| 378 | source = Path(__file__).resolve().parent.parent / 'guest/computer-legacy-mac.py' |
| 379 | bootstrap = "import json,sys; request=json.load(sys.stdin); exec(compile(request.pop('_worker'),'<computer>','exec'))" |
| 380 | environment = dict(os.environ, SSH_ORIGINAL_COMMAND='/usr/bin/python -c ' + shlex.quote(bootstrap)) |
| 381 | result = subprocess.run([sys.executable, str(Path(__file__).with_name('vm-ssh.py')), name], |
| 382 | input=json.dumps({**request, '_worker':source.read_text()}).encode(), |
| 383 | capture_output=True, timeout=remaining(200), env=environment) |
| 384 | if result.returncode: |
| 385 | raise ValueError('The private guest connection failed. Wait for desktop setup to finish, then retry.') |
| 386 | reply = json.loads(result.stdout) |
| 387 | if 'error' in reply: raise ValueError(reply['error']) |
| 388 | return reply |
| 389 | if platform == 'linux': |
| 390 | source = Path(__file__).with_name('mac-computer.py').read_text() |
| 391 | unit = 'snowglobe-computer-request-' + uuid.uuid4().hex |
| 392 | guest_exec(name, '/etc/qemu-ga/fsfreeze-hook.d/snowglobe-computer', [], |
| 393 | json.dumps({'_prepare': unit}).encode()) |
| 394 | operation = {'platform': platform, 'id': unit} |
| 395 | record_operation(name, operation) |
| 396 | try: |
| 397 | raw = guest_exec(name, '/etc/qemu-ga/fsfreeze-hook.d/snowglobe-computer', [], |
| 398 | json.dumps({**request, '_worker': source, '_unit': unit, |
| 399 | '_timeout': max(1, int(remaining(200)) - 5)}).encode(), timeout=220) |
| 400 | except BaseException: |
| 401 | finish_operation(name, operation) |
| 402 | raise |
| 403 | (vms.DISKS / name / 'computer-operation.json').unlink() |
| 404 | result = json.loads(raw) |
| 405 | if 'error' in result: |
| 406 | if result.get('status') == 409: |
| 407 | raise BlockingIOError(result['error']) |
| 408 | raise ValueError(result['error']) |
| 409 | return result |
| 410 | if platform == 'windows': |
| 411 | run = uuid.uuid4().hex |
| 412 | directory = 'C:\\ProgramData\\SnowglobeComputer\\' + run |
| 413 | source = Path(__file__).resolve().parent.parent / 'guest/computer-windows.cs' |
| 414 | content = source.read_bytes() |
| 415 | digest = hashlib.sha256(content).hexdigest()[:16] |
| 416 | installed_worker = 'C:\\ProgramData\\SnowglobeComputer\\worker-' + digest + '.exe' |
| 417 | setup = "$d='" + directory + "'; New-Item -ItemType Directory -Force -Path $d | Out-Null; " |
| 418 | setup += "@((Test-Path C:\\ProgramData\\SnowglobeComputer\\AutoHotkey.exe),(Test-Path -LiteralPath '" + installed_worker + "')) | ConvertTo-Json -Compress" |
| 419 | installed, exists = json.loads(powershell(name,setup)) |
| 420 | ahk=os.environ.get('SNOWGLOBE_COMPUTER_AHK') |
| 421 | if not installed and ahk: |
| 422 | write_file(name,'C:\\ProgramData\\SnowglobeComputer\\AutoHotkey.exe',(Path(ahk)/'AutoHotkey32.exe').read_bytes()) |
| 423 | write_file(name,'C:\\ProgramData\\SnowglobeComputer\\AutoHotkey-license.txt',(Path(ahk)/'license.txt').read_bytes()) |
| 424 | write_file(name,directory+'\\request.json',json.dumps(request).encode()) |
| 425 | if not exists: |
| 426 | source_path = directory + '\\worker.cs' |
| 427 | write_file(name, source_path, content) |
| 428 | compile_script = r""" |
| 429 | $ErrorActionPreference='Stop' |
| 430 | $lock=New-Object Threading.Mutex($false,'Global\SnowglobeComputerCompile-HASH') |
| 431 | if(!$lock.WaitOne(0)){$lock.Dispose();Write-Output 'pending';return} |
| 432 | try { |
| 433 | if(Test-Path -LiteralPath 'WORKER'){return} |
| 434 | $references=@('System.dll','System.Core.dll') |
| 435 | foreach($assembly in @('System.Web.Extensions','UIAutomationClient','UIAutomationTypes','WindowsBase')) { |
| 436 | $references += [Reflection.Assembly]::LoadWithPartialName($assembly).Location |
| 437 | } |
| 438 | Remove-Item -LiteralPath 'WORKER.new.exe' -Force -ErrorAction SilentlyContinue |
| 439 | Add-Type -TypeDefinition ([IO.File]::ReadAllText('SOURCE')) -ReferencedAssemblies $references -OutputAssembly 'WORKER.new.exe' -OutputType WindowsApplication |
| 440 | Move-Item -LiteralPath 'WORKER.new.exe' -Destination 'WORKER' |
| 441 | } finally {$lock.ReleaseMutex();$lock.Dispose()} |
| 442 | """.replace('SOURCE', source_path).replace('WORKER', installed_worker).replace('HASH',digest) |
| 443 | if powershell(name, compile_script, timeout=60).strip() == b'pending': |
| 444 | raise ValueError('Computer tools are still installing. Retry in a moment.') |
| 445 | launch = """ |
| 446 | $ErrorActionPreference='Stop' |
| 447 | $d='DIRECTORY' |
| 448 | $user=(Get-WmiObject Win32_ComputerSystem).UserName |
| 449 | if(!$user){throw 'No interactive user'} |
| 450 | $service=New-Object -ComObject Schedule.Service |
| 451 | $service.Connect() |
| 452 | $task=$service.NewTask(0) |
| 453 | $task.Principal.UserId=$user |
| 454 | $task.Principal.LogonType=3 |
| 455 | $task.Principal.RunLevel=1 |
| 456 | $task.Settings.ExecutionTimeLimit='TASKLIMIT' |
| 457 | $task.Settings.Priority=4 |
| 458 | $task.Settings.DisallowStartIfOnBatteries=$false |
| 459 | $task.Settings.StopIfGoingOnBatteries=$false |
| 460 | $action=$task.Actions.Create(0) |
| 461 | $action.Path='WORKER' |
| 462 | $action.Arguments='"'+$d+'\\request.json" "'+$d+'\\response.json"' |
| 463 | $registered=$service.GetFolder('\\').RegisterTaskDefinition('SnowglobeComputer-RUN',$task,6,$user,$null,3) |
| 464 | $registered.Run($null) | Out-Null |
| 465 | """.replace('DIRECTORY',directory).replace('RUN',run).replace('WORKER',installed_worker).replace('TASKLIMIT','PT0S' if request['action'] == 'spawn' else 'PT210S') |
| 466 | operation = {'platform': platform, 'id': run} |
| 467 | record_operation(name, operation) |
| 468 | try: |
| 469 | powershell(name,launch) |
| 470 | deadline=time.monotonic()+remaining(200) |
| 471 | while time.monotonic()<deadline: |
| 472 | try: |
| 473 | raw=read_file(name,directory+'\\response.json',length=2*1024*1024) |
| 474 | result=json.loads(raw) |
| 475 | if 'error' in result: raise RuntimeError(result['error']) |
| 476 | if request['action'] == 'spawn': |
| 477 | record_operation(name, {**operation, 'keep_spawn': True}) |
| 478 | operation['keep_spawn'] = True |
| 479 | return result |
| 480 | except ValueError: |
| 481 | time.sleep(.2) |
| 482 | raise ValueError('The desktop worker timed out. Check the VM before retrying.') |
| 483 | except RuntimeError as error: |
| 484 | raise ValueError(str(error)) from None |
| 485 | finally: |
| 486 | try: |
| 487 | finish_operation(name, operation) |
| 488 | except BlockingIOError: |
| 489 | if not operation.get('keep_spawn'): |
| 490 | raise |
| 491 | raise ValueError('This guest needs its platform worker installed.') |
| 492 | |
| 493 | |
| 494 | |
| 495 | def handle(name, request): |
| 496 | validate(request) |
| 497 | vms.ensure_name(name) |
| 498 | if vms.mac_vms.CONFIG and name == vms.mac_vms.CONFIG['name']: |
| 499 | return vms.mac_vms.handle('computer', {'name':name,'request':request}) |
| 500 | token = DEADLINE.set(time.monotonic() + 210) |
| 501 | try: |
| 502 | with vms.computer_lock(name): |
| 503 | root = ET.fromstring(vms.virsh('dumpxml',name,timeout=remaining(15))) |
| 504 | if vms.virsh('domstate',name,timeout=remaining(15)).strip() != 'running': |
| 505 | raise ValueError('Start the VM before using its computer tools.') |
| 506 | platform = root.findtext(f'metadata/{vms.NS}vm/{vms.NS}platform','linux') |
| 507 | ai = import_module('vm-ai') |
| 508 | ai.lease(name, ai.LIMITS['idle_seconds']) |
| 509 | if request['action'] == 'shot': |
| 510 | return asyncio.run(desktop(name)) |
| 511 | try: |
| 512 | with os.fdopen(vms.open_regular(vms.DISKS / name / 'computer-operation.json')) as incoming: |
| 513 | unfinished = json.load(incoming) |
| 514 | except FileNotFoundError: |
| 515 | pass |
| 516 | else: |
| 517 | finish_operation(name, unfinished) |
| 518 | native_text = True |
| 519 | if platform == 'windows' and (request['action'] == 'status' or request['action'] == 'input' and any(a['type'] == 'text' for a in request['actions'])): |
| 520 | try: |
| 521 | info = qga(name, 'guest-info') |
| 522 | native_text = any(command['name'] == 'guest-exec' and command['enabled'] for command in info['supported_commands']) |
| 523 | except (ValueError, subprocess.TimeoutExpired): |
| 524 | native_text = False |
| 525 | if request['action'] == 'status': |
| 526 | result = {'platform':platform,'capabilities':['shot','input'],'coordinate_units':'screenshot_pixels'} |
| 527 | if not native_text: |
| 528 | return {**result, 'runtimes': [], 'text_encoding': 'ascii', 'worker_error': 'Desktop input is available. Commands, Unicode text and UI actions need a working guest agent with command support.'} |
| 529 | try: |
| 530 | result.update(worker(name,platform,request)) |
| 531 | except ValueError as error: |
| 532 | result['worker_error'] = str(error) |
| 533 | return result |
| 534 | if request['action'] == 'input': |
| 535 | return asyncio.run(desktop(name,request['actions'],platform,request.get('screenshot',True),native_text)) |
| 536 | if platform=='windows' and request['action']=='file' and request['operation'] in ('read','write'): |
| 537 | path=request['path'] |
| 538 | if len(path)<3 or path[1:3] not in (':\\',':/') or not path[0].isalpha(): raise ValueError('Use an absolute guest file path.') |
| 539 | if request['operation']=='read': |
| 540 | data=read_file(name,path,request.get('offset',0),request.get('length',65536)) |
| 541 | return {'data':base64.b64encode(data).decode(),'bytes':len(data)} |
| 542 | data=base64.b64decode(request['data'],validate=True) |
| 543 | write_file(name,path,data,offset=request.get('offset',0)) |
| 544 | return {'bytes':len(data)} |
| 545 | result = worker(name,platform,request) |
| 546 | if request.get('screenshot'): |
| 547 | try: result.update(asyncio.run(desktop(name))) |
| 548 | except (ValueError,OSError,TimeoutError): result['capture_error']='Screen capture failed. Retry computer_shot.' |
| 549 | return result |
| 550 | finally: |
| 551 | DEADLINE.reset(token) |