diff --git a/dashboard/src/host.rs b/dashboard/src/host.rs index a521b4b19440ef0d3166b5438f81d6f445770d80..892cce35b63f989cc7b83be95621c8a88498aecc 100644 --- a/dashboard/src/host.rs +++ b/dashboard/src/host.rs @@ -34,7 +34,9 @@ pub async fn open(request: Value) -> Result<(Value, tokio::net::UnixStream)> { Some("vm.create" | "vm.media" | "vm.preset" | "vm.ai") ) { 910 - } else if matches!(request["operation"].as_str(), Some("vm.act" | "vm.computer")) { + } else if request["operation"] == "vm.computer" { + 300 + } else if request["operation"] == "vm.act" { 240 } else if request["operation"] == "copyparty.manage" { 310 diff --git a/guest/computer-windows.cs b/guest/computer-windows.cs index dcf2b2e344d560a8a6fabd713d4b36eacae24219..77b4f4e8a2883754a796af02467a440fab1005d7 100644 --- a/guest/computer-windows.cs +++ b/guest/computer-windows.cs @@ -210,7 +210,8 @@ public static class ComputerWorker { string runtime=Text(request,"runtime","default"),directory=System.IO.Path.GetDirectoryName(requestPath),file,exe,arguments,script=Text(request,"script"); if(runtime=="default")runtime="powershell"; switch(runtime) { - case "powershell": file=System.IO.Path.Combine(directory,"script.ps1");exe="powershell.exe";arguments="-NoProfile -NonInteractive -ExecutionPolicy Bypass -File \""+file+"\"";script="[Console]::OutputEncoding=New-Object Text.UTF8Encoding($false)\n"+script;break; + // PowerShell 3 caches pipeline encoding before the script runs. + case "powershell": file=System.IO.Path.Combine(directory,"script.ps1");exe="cmd.exe";arguments="/d /s /c \"chcp 65001 >nul & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \""+file+"\"\"";break; case "cmd": file=System.IO.Path.Combine(directory,"script.cmd");exe="cmd.exe";arguments="/d /s /c \"\""+file+"\"\"";script="@chcp 65001 >nul\r\n"+script;break; case "ahk": file=System.IO.Path.Combine(directory,"script.ahk");exe=System.IO.Path.Combine(root,"AutoHotkey.exe");arguments="/ErrorStdOut \""+file+"\"";script="#Requires AutoHotkey v2.0\n#SingleInstance Off\n#NoTrayIcon\nFileEncoding 'UTF-8-RAW'\nSendMode 'Input'\nCoordMode 'Mouse', 'Screen'\nCoordMode 'Pixel', 'Screen'\nCoordMode 'ToolTip', 'Screen'\nSetTitleMatchMode 2\nDetectHiddenWindows true\n"+script;break; default:throw new Exception("Choose a runtime reported by computer_status."); diff --git a/tools/computer-test.py b/tools/computer-test.py index 2f96176092806460b2ddd6e1175e13c6201de77d..0ead726c36b4318790332bf26326f73e673f126c 100644 --- a/tools/computer-test.py +++ b/tools/computer-test.py @@ -75,6 +75,16 @@ class GuestCancellation(unittest.TestCase): patcher.start() self.addCleanup(patcher.stop) + def test_windows_powershell_reads_redirected_output_without_console_capture(self): + with patch.object(computer, 'write_file'), patch.object(computer, 'guest_exec', return_value=b''), patch.object(computer, 'read_file', return_value=b'file output'): + self.assertEqual(computer.powershell('fixture', "Write-Output 'file output'"), b'file output') + + def test_windows_powershell_rejects_failed_execution_before_reading_output(self): + with patch.object(computer, 'write_file'), patch.object(computer, 'guest_exec', side_effect=ValueError('Failed')), patch.object(computer, 'read_file') as read: + with self.assertRaises(ValueError): + computer.powershell('fixture', 'exit 7') + read.assert_not_called() + def test_reused_guest_pid_waits_for_current_process(self): replies = [{'pid': 2596}, {'exited': True, 'exitcode': 1}, {'exited': False}, {'exited': True, 'exitcode': 0, 'out-data': base64.b64encode(b'current').decode()}, @@ -113,7 +123,7 @@ class GuestCancellation(unittest.TestCase): self.assertGreater(computer.remaining(20), 0) running.clear() return b'' - return b'True' + return b'[true,true]' token = computer.DEADLINE.set(time.monotonic() + 30) try: with patch.object(computer, 'powershell', execute), patch.object(computer, 'write_file'): @@ -160,7 +170,7 @@ class GuestCancellation(unittest.TestCase): def execute(name, script, **kwargs): if 'DeleteTask' in script: raise TimeoutError() - return b'True' + return b'[true,true]' with patch.object(computer, 'powershell', execute), patch.object(computer, 'write_file'), patch.object(computer, 'read_file', return_value=json.dumps(result).encode()): self.assertEqual(computer.worker('fixture', 'windows', {'action': 'spawn'}), result) pending = computer.vms.DISKS / 'fixture' / 'computer-operation.json' @@ -177,7 +187,7 @@ class GuestCancellation(unittest.TestCase): if operation.get('keep_spawn'): raise OSError('Disk full') record(name, operation) - with patch.object(computer, 'record_operation', persist), patch.object(computer, 'powershell', return_value=b'True') as execute, patch.object(computer, 'write_file'), patch.object(computer, 'read_file', return_value=b'{"id":"123:456"}'): + with patch.object(computer, 'record_operation', persist), patch.object(computer, 'powershell', return_value=b'[true,true]') as execute, patch.object(computer, 'write_file'), patch.object(computer, 'read_file', return_value=b'{"id":"123:456"}'): with self.assertRaises(OSError): computer.worker('fixture', 'windows', {'action': 'spawn'}) self.assertIn('$t.Stop(0)', execute.call_args.args[1]) diff --git a/tools/vm-computer.py b/tools/vm-computer.py index 37df08f13a8998d782ff8c37544babd1303784ae..f7f00a1348c5674b44f30cc969f356a007ab094d 100644 --- a/tools/vm-computer.py +++ b/tools/vm-computer.py @@ -101,25 +101,15 @@ def write_file(name, path, data, offset=0): qga(name, 'guest-file-close', handle=handle) -def powershell(name, script, timeout=20): - """Windows 7 PowerShell needs a hidden console when launched by QGA.""" +def powershell(name, script, timeout=60): + """Win7 needs a hidden console; ARM64 QGA cannot capture WSH's console output.""" stem = 'C:\\Windows\\Temp\\snowglobe-computer-' + uuid.uuid4().hex command = 'cmd.exe /d /c powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + stem + '.ps1' command += ' > ' + stem + '.out 2> ' + stem + '.err' launcher = '''Set shell = CreateObject("WScript.Shell") code = shell.Run("COMMAND", 0, True) -Set stream = CreateObject("ADODB.Stream") -stream.Type = 1 -stream.Open -stream.LoadFromFile "STEM.out" -Set xml = CreateObject("Msxml2.DOMDocument.6.0") -Set node = xml.createElement("output") -node.DataType = "bin.base64" -node.nodeTypedValue = stream.Read -WScript.StdOut.Write Replace(Replace(node.Text, vbCr, ""), vbLf, "") -stream.Close Set files = CreateObject("Scripting.FileSystemObject") -files.DeleteFile "STEM.out" +If code <> 0 Then files.DeleteFile "STEM.out" files.DeleteFile "STEM.err" files.DeleteFile "STEM.ps1" files.DeleteFile WScript.ScriptFullName @@ -127,7 +117,11 @@ WScript.Quit code '''.replace('COMMAND', command).replace('STEM', stem) write_file(name, stem + '.ps1', b'\xff\xfe' + script.encode('utf-16le')) write_file(name, stem + '.vbs', launcher.encode('ascii')) - return base64.b64decode(guest_exec(name, 'cscript.exe', ['//nologo', stem + '.vbs'], timeout=timeout), validate=True) + guest_exec(name, 'cscript.exe', ['//nologo', stem + '.vbs'], timeout=timeout) + try: + return read_file(name, stem + '.out', length=2*1024*1024) + finally: + guest_exec(name, 'cmd.exe', ['/d', '/c', 'del ' + stem + '.out']) async def desktop(name, actions=None, platform=None, screenshot=True, native_text=True): @@ -351,7 +345,7 @@ def record_operation(name, operation): def finish_operation(name, operation): - token = DEADLINE.set(time.monotonic() + 20) + token = DEADLINE.set(time.monotonic() + 60) try: if operation['platform'] == 'linux': guest_exec(name, '/etc/qemu-ga/fsfreeze-hook.d/snowglobe-computer', [], @@ -372,7 +366,7 @@ def finish_operation(name, operation): cleanup += "$f.DeleteTask('SnowglobeComputer-"+run+"',0)};" if not operation.get('keep_spawn'): cleanup += "if(Test-Path -LiteralPath $d){Remove-Item -LiteralPath $d -Recurse -Force}" - powershell(name, cleanup, timeout=18) + powershell(name, cleanup, timeout=58) (vms.DISKS / name / 'computer-operation.json').unlink() except Exception as error: raise BlockingIOError('The previous operation has not stopped. Check its screenshot, then retry when the guest agent reconnects.') from error @@ -417,18 +411,18 @@ def worker(name, platform, request): if platform == 'windows': run = uuid.uuid4().hex directory = 'C:\\ProgramData\\SnowglobeComputer\\' + run - setup = "$d='" + directory + "'; New-Item -ItemType Directory -Force -Path $d | Out-Null; Test-Path C:\\ProgramData\\SnowglobeComputer\\AutoHotkey.exe" - installed=powershell(name,setup).strip()==b'True' + source = Path(__file__).resolve().parent.parent / 'guest/computer-windows.cs' + content = source.read_bytes() + digest = hashlib.sha256(content).hexdigest()[:16] + installed_worker = 'C:\\ProgramData\\SnowglobeComputer\\worker-' + digest + '.exe' + setup = "$d='" + directory + "'; New-Item -ItemType Directory -Force -Path $d | Out-Null; " + setup += "@((Test-Path C:\\ProgramData\\SnowglobeComputer\\AutoHotkey.exe),(Test-Path -LiteralPath '" + installed_worker + "')) | ConvertTo-Json -Compress" + installed, exists = json.loads(powershell(name,setup)) ahk=os.environ.get('SNOWGLOBE_COMPUTER_AHK') if not installed and ahk: write_file(name,'C:\\ProgramData\\SnowglobeComputer\\AutoHotkey.exe',(Path(ahk)/'AutoHotkey32.exe').read_bytes()) write_file(name,'C:\\ProgramData\\SnowglobeComputer\\AutoHotkey-license.txt',(Path(ahk)/'license.txt').read_bytes()) write_file(name,directory+'\\request.json',json.dumps(request).encode()) - source = Path(__file__).resolve().parent.parent / 'guest/computer-windows.cs' - content = source.read_bytes() - digest = hashlib.sha256(content).hexdigest()[:16] - installed_worker = 'C:\\ProgramData\\SnowglobeComputer\\worker-' + digest + '.exe' - exists = powershell(name, "Test-Path -LiteralPath '" + installed_worker + "'").strip() == b'True' if not exists: source_path = directory + '\\worker.cs' write_file(name, source_path, content)