diff --git a/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/BattleNetLaunchWindows.java b/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/BattleNetLaunchWindows.java index 7b3498cd7..c8f35d699 100644 --- a/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/BattleNetLaunchWindows.java +++ b/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/BattleNetLaunchWindows.java @@ -69,11 +69,11 @@ static List command(long gamePid) { "-EncodedCommand", encoded); } - static void handOff(Process game) { + static void handOff(long gamePid) { Thread.ofVirtual().name("Battle.net window handoff").start(() -> { - if (!game.isAlive()) return; + if (ProcessHandle.of(gamePid).filter(ProcessHandle::isAlive).isEmpty()) return; try { - Process helper = new ProcessBuilder(command(game.pid())) + Process helper = new ProcessBuilder(command(gamePid)) .redirectOutput(ProcessBuilder.Redirect.DISCARD) .redirectError(ProcessBuilder.Redirect.DISCARD) .start(); diff --git a/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignIn.java b/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignIn.java index fce3e1b23..471f4b88a 100644 --- a/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignIn.java +++ b/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignIn.java @@ -3,6 +3,7 @@ import de.peeeq.wurstscript.WLogger; import de.peeeq.wurstscript.utils.CompilationCancellation; import net.moonlightflower.wc3libs.port.Orient; +import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.net.BindException; @@ -24,9 +25,12 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -40,22 +44,30 @@ * *

Just before the app starts the game it writes a one-time {@code WEB_TOKEN} * ({@code ...\Battle.net\Launch Options\W3}). Stored as {@code EDITOR_TOKEN}, that token signs the next {@code -editor} - * client in. {@link #renew()} asks the app to start the game, closes that client before it spends the token, and - * stores the token. The map is then launched directly, as without the app. + * client in. {@link #renew()} runs {@value #TOKEN_SCRIPT}, which asks the app to start the game, closes that client + * before it spends the token, and stores the token. The map is then launched directly, as without the app. + * + *

The app, the script and the map's client hand the sign-in to each other through {@code HKCU}, so all three must + * see the same registry. A process started from a packaged (MSIX) app, such as the Claude desktop app or an editor + * started from inside one, reads and writes {@code HKCU} through the package's private copy, and so does everything it + * starts. The script and the client therefore start through WMI, in the user's own registry view + * ({@link OutsideStart}), whatever view Wurst has. A Battle.net that was itself started from inside such an app writes + * its token where nothing else reads it; the script then sees the app start the game but no new token, and the user is + * told to start Battle.net from the Start menu. * *

The wc3-e2e-harness does the same (docs/BattleNetSignIn.md there). Both hold the same localhost port as a lock * from the renewal until the launched client has signed in. */ @SuppressWarnings("StringConcatToTextBlock") // Error Prone 2.50 crashes on this source under javac 27. public final class BattleNetSignIn { - static final String LAUNCH_KEY = "HKCU\\Software\\Blizzard Entertainment\\Battle.net\\Launch Options\\W3"; static final String GAME_KEY = "HKCU\\Software\\Blizzard Entertainment\\Warcraft III"; private static final String LAUNCHER = "Battle.net.exe"; private static final String GAME = "Warcraft III.exe"; private static final long TIMEOUT_SECONDS = 90; - private static final long ASK_AGAIN_SECONDS = 25; - /** The app writes the token and then starts the game; wait this long for that game so it is closed. */ - private static final long GAME_AFTER_TOKEN_SECONDS = 10; + /** How long past its own timeout the renewal script may take to start and to write its result. */ + private static final long SCRIPT_EXIT_GRACE_SECONDS = 30; + /** How long the renewal script may take to exit, and close its output file, after writing its result. */ + private static final long OUTPUT_RELEASE_SECONDS = 5; /** How long the lock waits for the launched client to sign in; a client that takes longer has its own problems. */ static final long SIGN_IN_TIMEOUT_SECONDS = 120; /** How long a canceled renewal keeps closing the client it asked the app for, which may still be on its way. */ @@ -136,7 +148,8 @@ boolean isRunning() { /** * Stores a token from the app as {@code EDITOR_TOKEN}. Throws, with a message for the user, when the app cannot - * provide one: it is closed, signed out, updating, or running a client of its own. + * provide one: it is closed, signed out, updating, running a client of its own, or keeping its registry in a + * packaged app's private copy. * * @return the renewal, which holds the Battle.net lock; launch the map, then call * {@link Renewal#releaseWhenSignedIn()}, or {@link Renewal#close()} if the launch fails @@ -201,23 +214,25 @@ static void closeLateGames(ServerSocket gate, Set seen, long seconds) { */ static final class Renewal implements AutoCloseable { private final ServerSocket _gate; - private final String _token; + private final @Nullable String _token; - private Renewal(ServerSocket gate, String token) { + /** @param token the renewed {@code EDITOR_TOKEN} as Wurst reads it; null when it could not be read */ + private Renewal(ServerSocket gate, @Nullable String token) { _gate = gate; _token = token; } /** * Releases the lock once the client has replaced {@code EDITOR_TOKEN}, which it does as it signs in, or after - * {@value #SIGN_IN_TIMEOUT_SECONDS} seconds. Does not block. + * {@value #SIGN_IN_TIMEOUT_SECONDS} seconds. Does not block. Wurst may read a packaged app's private copy of the + * registry, where the client's new token never shows; the lock is then held until the timeout. */ void releaseWhenSignedIn() { Thread waiter = new Thread(() -> { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(SIGN_IN_TIMEOUT_SECONDS); try { - while (System.nanoTime() < deadline - && readBinary(GAME_KEY, "EDITOR_TOKEN").filter(_token::equals).isPresent()) { + while (System.nanoTime() < deadline && (_token == null + || readBinary(GAME_KEY, "EDITOR_TOKEN").filter(_token::equals).isPresent())) { Thread.sleep(500); } } catch (IOException | InterruptedException | RuntimeException ex) { @@ -243,59 +258,175 @@ public void close() { /** * @param seen collects every client that is not this renewal's to close: those running before it, and those * already handled - * @param asked set once the app has been asked for a client + * @param asked set once the app may have been asked for a client + * @return the renewed {@code EDITOR_TOKEN} as Wurst reads it, to see the client replace it; null if unreadable */ - private String renewLocked(Set seen, boolean[] asked) throws IOException { + private @Nullable String renewLocked(Set seen, boolean[] asked) throws IOException { if (!isRunning()) throw new IOException("Battle.net is not running."); for (ProcessHandle game : games()) { - if (startedByLauncher(game)) { - throw new IOException("Close the Warcraft III client started from Battle.net, then run the map again."); - } + if (startedByLauncher(game)) throw new IOException(APP_GAME_RUNNING); seen.add(game.pid()); } - Optional before = readBinary(LAUNCH_KEY, "WEB_TOKEN"); + Path script = scriptCopy(TOKEN_SCRIPT, tempDir()); // Asked to start the game, the app creates a window in front, and shows it again as the map's client signs // in; the watcher hides it as it is created. watchLauncherWindow(); long start = System.nanoTime(); - long askedAt = Long.MIN_VALUE; - String token = null; - long tokenAt = 0; - int closed = 0; - while (System.nanoTime() - start < TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS)) { - checkCancellation(); - if (token == null && (askedAt == Long.MIN_VALUE - || System.nanoTime() - askedAt >= TimeUnit.SECONDS.toNanos(ASK_AGAIN_SECONDS))) { - askedAt = System.nanoTime(); - asked[0] = true; - // An app that is still starting ignores the command, so it is repeated while waiting. - startLauncher("--exec=launch W3"); + asked[0] = true; + TokenScriptResult result = runTokenScript(script); + String problem = problem(result); + if (problem != null) { + // The script found a client the app started after the check above, and asked for nothing. That client is + // the user's, so no late client is closed. + if ("app-game-running".equals(result.outcome())) asked[0] = false; + WLogger.info("The Battle.net sign-in renewal ended with: " + String.join(" | ", result.lines())); + throw new IOException(problem); + } + WLogger.info("Renewed the Warcraft III sign-in from Battle.net in " + + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) + " ms"); + try { + return readBinary(GAME_KEY, "EDITOR_TOKEN").orElse(null); + } catch (IOException ex) { + WLogger.warning("Could not read the renewed Warcraft III sign-in: " + ex.getMessage()); + return null; + } + } + + static final String APP_GAME_RUNNING = "Close the Warcraft III client started from Battle.net, then run the map again."; + + /** What {@link #TOKEN_SCRIPT} printed: its outcome, null until its {@code result} line, and every line. */ + record TokenScriptResult(@Nullable String outcome, List lines) { + } + + private static final Pattern RESULT = Pattern.compile("result (\\S+)"); + + static TokenScriptResult parseTokenScriptOutput(String output) { + List lines = output.lines().map(String::strip).filter(line -> !line.isEmpty()).toList(); + String outcome = lines.stream().map(RESULT::matcher).filter(Matcher::matches) + .map(matcher -> matcher.group(1)).findFirst().orElse(null); + return new TokenScriptResult(outcome, lines); + } + + /** + * The complete lines of a script's redirected output: Windows PowerShell writes UTF-16 with a byte order mark, and + * a line still being written could read as a different result. + */ + static String completeLines(byte[] output) { + boolean utf16 = output.length >= 2 && (output[0] & 0xff) == 0xff && (output[1] & 0xff) == 0xfe; + String text = utf16 ? new String(output, 2, output.length - 2, StandardCharsets.UTF_16LE) + : new String(output, StandardCharsets.UTF_8); + return text.substring(0, text.lastIndexOf('\n') + 1); + } + + /** The message for the user when the renewal did not succeed; null when it did. */ + static @Nullable String problem(TokenScriptResult result) { + return switch (Objects.requireNonNullElse(result.outcome(), "")) { + case "refreshed" -> null; + case "no-token" -> "Battle.net did not start Warcraft III. Check that it is signed in and the game is ready to play."; + case "app-game-running" -> APP_GAME_RUNNING; + case "token-not-visible" -> "Battle.net started Warcraft III, but wrote its sign-in where other programs cannot" + + " read it, probably because Battle.net was started from a packaged app (such as the Claude desktop app)." + + " Quit Battle.net from its tray icon and start it from the Start menu."; + default -> { + List lines = result.lines(); + yield "The Battle.net sign-in renewal failed: " + (lines.isEmpty() ? "it printed nothing" + : String.join(" | ", lines.subList(Math.max(0, lines.size() - 3), lines.size()))) + "."; } - for (ProcessHandle game : games()) { - if (!seen.add(game.pid()) || !startedByLauncher(game)) continue; - game.destroyForcibly(); - closed++; + }; + } + + /** A PowerShell single-quoted string literal. PowerShell also reads the typographic single quotes as quotes. */ + static String powerShellQuote(String text) { + return "'" + text.replaceAll("['\\u2018\\u2019\\u201A\\u201B]", "$0$0") + "'"; + } + + /** + * The command that runs {@code script} and redirects everything it prints to {@code output}. Started outside, the + * script's output cannot come back through a pipe, so it goes to a file. + */ + static List tokenScriptCommand(Path script, Path launcher, long timeoutSeconds, Path output) { + return List.of("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", + "& " + powerShellQuote(script.toString()) + " -BattleNetExe " + powerShellQuote(launcher.toString()) + + " -TimeoutSeconds " + timeoutSeconds + " *> " + powerShellQuote(output.toString())); + } + + /** + * Runs {@link #TOKEN_SCRIPT} hidden in the user's own registry view, where the app writes {@code WEB_TOKEN} and the + * client reads {@code EDITOR_TOKEN}, whatever view Wurst has. Only if WMI cannot start it does it run from here. + */ + private TokenScriptResult runTokenScript(Path script) throws IOException { + Path output = tempDir().resolve("wurst-battlenet-renewal-" + UUID.randomUUID() + ".log"); + try { + long pid = OutsideStart.startOrHere(tokenScriptCommand(script, launcher, TIMEOUT_SECONDS, output), null, + OutsideStart.Show.HIDDEN); + @Nullable ProcessHandle handle = ProcessHandle.of(pid).orElse(null); + TokenScriptResult result = awaitTokenScript(handle, output, TIMEOUT_SECONDS + SCRIPT_EXIT_GRACE_SECONDS); + // The script ends right after its result line; let it close the output file before that is removed. + if (handle != null) { + try { + handle.onExit().get(OUTPUT_RELEASE_SECONDS, TimeUnit.SECONDS); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } catch (ExecutionException | TimeoutException ex) { + // still running: the delete below falls back to deleteOnExit + } } - if (token == null) { - Optional now = readBinary(LAUNCH_KEY, "WEB_TOKEN"); - if (now.isPresent() && !now.equals(before)) { - token = now.get(); - tokenAt = System.nanoTime(); + return result; + } finally { + try { + Files.deleteIfExists(output); + } catch (IOException ex) { + output.toFile().deleteOnExit(); + } + } + } + + /** + * Waits for the script's result line, or for the script to end. Ends the script if it outlives + * {@code timeoutSeconds} or the run is canceled; a canceled renewal then closes the client the script may still + * have coming ({@link #closeLateGames}). + * + * @param script null when it has ended already + */ + static TokenScriptResult awaitTokenScript(@Nullable ProcessHandle script, Path output, long timeoutSeconds) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds); + boolean done = false; + try { + while (true) { + // Read after the check, so a script that wrote its result and ended in between is not missed. + boolean running = script != null && script.isAlive(); + TokenScriptResult result = parseTokenScriptOutput(completeLines(readOutput(output))); + if (result.outcome() != null || !running) { + done = true; + return result; + } + if (System.nanoTime() >= deadline) { + List lines = new ArrayList<>(result.lines()); + lines.add("the renewal script did not finish"); + return new TokenScriptResult(null, lines); } + checkCancellation(); + pause(250); } - if (token != null && (closed > 0 - || System.nanoTime() - tokenAt >= TimeUnit.SECONDS.toNanos(GAME_AFTER_TOKEN_SECONDS))) break; - pause(50); + } finally { + if (!done && script != null) script.destroyForcibly(); } - if (token == null) { - throw new IOException("Battle.net did not start Warcraft III. Check that it is signed in and the game is ready to play."); + } + + private static byte[] readOutput(Path output) { + try { + return Files.readAllBytes(output); + } catch (IOException ex) { + return new byte[0]; // not created yet } - writeBinary(GAME_KEY, "EDITOR_TOKEN", token); - WLogger.info("Renewed the Warcraft III sign-in from Battle.net in " - + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) + " ms"); - return token; } + private static Path tempDir() { + return Path.of(System.getProperty("java.io.tmpdir")); + } + + /** A copy of the wc3-e2e-harness {@code node/src/runner/battlenet-token.ps1}; keep them equal. */ + static final String TOKEN_SCRIPT = "battlenet-token.ps1"; /** A copy of the wc3-e2e-harness {@code node/src/runner/battlenet-window.ps1}; keep them equal. */ static final String WINDOW_SCRIPT = "battlenet-window.ps1"; /** The watcher's limit without a client: every request the renewal may send, then a launch and a slow sign-in. */ @@ -303,22 +434,36 @@ private String renewLocked(Set seen, boolean[] asked) throws IOException { private static final long WINDOW_READY_SECONDS = 3; /** - * The command that runs {@link #WINDOW_SCRIPT} with {@code arguments}, from a copy in {@code dir} named by its - * content (a file, not -EncodedCommand: encoded, the script is close to Windows' 32,767-character command line - * limit). Null when the script cannot be provided. + * A copy of the resource {@code script} in {@code dir}, named by its content (a file, not -EncodedCommand: encoded, + * the window watcher is close to Windows' 32,767-character command line limit), so a Wurst update never runs an + * older copy. + */ + static Path scriptCopy(String script, Path dir) throws IOException { + try (var in = BattleNetSignIn.class.getClassLoader().getResourceAsStream(script)) { + if (in == null) throw new IOException(script + " is missing from Wurst"); + byte[] content = in.readAllBytes(); + String hash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(content), 0, 6); + String name = script.substring(0, script.length() - ".ps1".length()); + Path file = dir.resolve("wurst-" + name + "-" + hash + ".ps1"); + if (!Files.isRegularFile(file) || !Arrays.equals(Files.readAllBytes(file), content)) Files.write(file, content); + return file; + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException(ex); + } + } + + /** + * The command that runs {@link #WINDOW_SCRIPT} with {@code arguments}, from a copy in {@code dir} + * ({@link #scriptCopy}). Null when the script cannot be provided. */ static List windowWatcherCommand(List arguments, Path dir) { - try (var in = BattleNetSignIn.class.getClassLoader().getResourceAsStream(WINDOW_SCRIPT)) { - if (in == null) return null; - byte[] script = in.readAllBytes(); - String hash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(script), 0, 6); - Path file = dir.resolve("wurst-battlenet-window-" + hash + ".ps1"); - if (!Files.isRegularFile(file) || !Arrays.equals(Files.readAllBytes(file), script)) Files.write(file, script); + try { + Path file = scriptCopy(WINDOW_SCRIPT, dir); List command = new ArrayList<>(List.of("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file.toString())); command.addAll(arguments); return command; - } catch (IOException | NoSuchAlgorithmException ex) { + } catch (IOException ex) { WLogger.warning("Could not prepare the Battle.net window watcher: " + ex.getMessage()); return null; } @@ -395,29 +540,6 @@ private static Optional readBinary(String key, String value) throws IOEx return parseBinary(readCommand(new ProcessBuilder("reg.exe", "query", key, "/v", value)), value); } - private static void writeBinary(String key, String value, String hex) throws IOException { - Process process = new ProcessBuilder("reg.exe", "add", key, "/v", value, "/t", "REG_BINARY", "/d", hex, "/f") - .redirectOutput(ProcessBuilder.Redirect.DISCARD).redirectError(ProcessBuilder.Redirect.DISCARD).start(); - try { - if (!process.waitFor(8, TimeUnit.SECONDS) || process.exitValue() != 0) { - process.destroyForcibly(); - throw new IOException("Could not store the Warcraft III sign-in."); - } - } catch (InterruptedException ex) { - process.destroyForcibly(); - Thread.currentThread().interrupt(); - throw new CancellationException(); - } - } - - private void startLauncher(String... args) throws IOException { - List command = new ArrayList<>(); - command.add(launcher.toString()); - command.addAll(List.of(args)); - new ProcessBuilder(command).redirectOutput(ProcessBuilder.Redirect.DISCARD) - .redirectError(ProcessBuilder.Redirect.DISCARD).start(); - } - // The Node harness takes the same localhost port while it renews the sign-in. static int gatePort(Path config) { try { diff --git a/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/OutsideStart.java b/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/OutsideStart.java new file mode 100644 index 000000000..52a8678cb --- /dev/null +++ b/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/OutsideStart.java @@ -0,0 +1,143 @@ +package de.peeeq.wurstio.languageserver.requests; + +import de.peeeq.wurstscript.WLogger; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * Starts processes on Windows in the user's own registry view. + * + *

A child process sees the registry its parent sees. Under a packaged (MSIX) app, such as the Claude desktop app or a + * VS Code started from a terminal inside it, that is the package's private copy of {@code HKCU}: what such a process + * writes there no other process reads, and once it has written a value it no longer reads the user's. Battle.net, the + * sign-in renewal and the game pass the sign-in between them through {@code HKCU} ({@link BattleNetSignIn}), so each of + * them started from inside such an app would keep it where the rest of the machine never sees it. A process created + * through WMI ({@code Win32_Process.Create}) starts in the user's own context instead, in the same session and on the + * same desktop. + * + *

The wc3-e2e-harness does the same ({@code startOutside} in node/src/runner/win32.cjs there). + */ +final class OutsideStart { + /** The {@code SW_} value WMI passes to the new process's first window. */ + enum Show { + HIDDEN(0), NORMAL(1), MINIMIZED(7); + + final int value; + + Show(int value) { + this.value = value; + } + } + + private static final long WMI_TIMEOUT_SECONDS = 30; + private static final Pattern CREATED = Pattern.compile("^created (\\d+) (\\d+)\\s*$", Pattern.MULTILINE); + // The command line, window and directory travel in the environment, so nothing in them needs PowerShell quoting. + private static final String CREATE_SCRIPT = String.join("; ", + "$ErrorActionPreference = 'Stop'", + "[Console]::OutputEncoding = [Text.Encoding]::UTF8", + "$startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]$env:WURST_OUTSIDE_SHOW }", + "$arguments = @{ CommandLine = $env:WURST_OUTSIDE_COMMAND; ProcessStartupInformation = $startup }", + "if ($env:WURST_OUTSIDE_CWD) { $arguments.CurrentDirectory = $env:WURST_OUTSIDE_CWD }", + "$created = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments $arguments", + "'created {0} {1}' -f $created.ReturnValue, $created.ProcessId"); + + private OutsideStart() { + } + + /** One argument quoted for a Windows command line, as CommandLineToArgvW and the C runtime split it. */ + static String quoteWindowsArg(String arg) { + if (!arg.isEmpty() && arg.chars().noneMatch(c -> c == '"' || Character.isWhitespace(c))) return arg; + StringBuilder quoted = new StringBuilder("\""); + int backslashes = 0; + for (int i = 0; i < arg.length(); i++) { + char c = arg.charAt(i); + if (c == '\\') { + backslashes++; + continue; + } + quoted.append("\\".repeat(c == '"' ? backslashes * 2 + 1 : backslashes)).append(c); + backslashes = 0; + } + return quoted.append("\\".repeat(backslashes * 2)).append('"').toString(); + } + + static String commandLine(List command) { + return command.stream().map(OutsideStart::quoteWindowsArg).collect(Collectors.joining(" ")); + } + + /** + * Starts {@code command} through WMI, in the user's own registry view, and returns its pid. Throws when WMI cannot + * create it. + * + * @param directory the new process's working directory; null for WMI's default + */ + static long start(List command, @Nullable Path directory, Show show) throws IOException { + ProcessBuilder builder = new ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive", "-Command", + CREATE_SCRIPT).redirectErrorStream(true); + builder.environment().put("WURST_OUTSIDE_COMMAND", commandLine(command)); + builder.environment().put("WURST_OUTSIDE_SHOW", String.valueOf(show.value)); + builder.environment().put("WURST_OUTSIDE_CWD", directory == null ? "" : directory.toString()); + Process process = builder.start(); + String output; + try { + process.getOutputStream().close(); + // Read while it runs: an error record could fill the pipe and stall PowerShell until the timeout. + CompletableFuture read = CompletableFuture.supplyAsync(() -> { + try (var in = process.getInputStream()) { + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException ex) { + return ""; + } + }, runnable -> Thread.ofVirtual().name("WMI process start").start(runnable)); + if (!process.waitFor(WMI_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + throw new IOException("WMI did not answer within " + WMI_TIMEOUT_SECONDS + " s"); + } + output = read.get(5, TimeUnit.SECONDS); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new CancellationException(); + } catch (ExecutionException | TimeoutException ex) { + throw new IOException("WMI's answer could not be read", ex); + } finally { + process.destroyForcibly(); + } + String name = String.valueOf(Path.of(command.get(0)).getFileName()); + Matcher created = CREATED.matcher(output); + if (!created.find()) { + String first = output.strip().lines().findFirst().orElse("no answer"); + throw new IOException("WMI could not start " + name + ": " + first); + } + if (!created.group(1).equals("0")) { + throw new IOException("WMI could not start " + name + " (Win32_Process.Create returned " + created.group(1) + ")"); + } + return Long.parseLong(created.group(2)); + } + + /** + * {@link #start} if WMI can, else a direct start from this process (whose registry view the process then shares). + * Returns the pid. + */ + static long startOrHere(List command, @Nullable Path directory, Show show) throws IOException { + try { + return start(command, directory, show); + } catch (IOException ex) { + WLogger.warning("Starting " + Path.of(command.get(0)).getFileName() + " from Wurst instead: " + ex.getMessage()); + ProcessBuilder builder = new ProcessBuilder(command).redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD); + if (directory != null) builder.directory(directory.toFile()); + return builder.start().pid(); + } + } +} diff --git a/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/RunMap.java b/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/RunMap.java index 4527e7844..dd66795ff 100644 --- a/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/RunMap.java +++ b/de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/RunMap.java @@ -253,11 +253,11 @@ private void launchGame(WurstGui gui, W3InstallationData launchData, File cached List cmd = buildLaunchCommand(gameExe, path, detectedGameVersion, launchData.isVersionHeuristic()); BattleNetSignIn.Renewal renewal = renewBattleNetSignIn(gui, gameExe.toPath(), detectedGameVersion, cmd); - Process game; + long game; try { // Inside: a canceled run throws from the progress notification too, and must release the lock. gui.sendProgress("running " + cmd); - game = new ProcessBuilder(cmd).start(); + game = startGameProcess(cmd); } catch (IOException | RuntimeException e) { if (renewal != null) renewal.close(); throw e; @@ -268,6 +268,16 @@ private void launchGame(WurstGui gui, W3InstallationData launchData, File cached } } + /** + * Starts the client and returns its pid. On Windows it starts in the user's own registry view, where the sign-in + * is renewed, whatever view Wurst has ({@link OutsideStart}); if WMI cannot start it, it starts from here. + */ + private static long startGameProcess(List cmd) throws IOException { + if (!Orient.isWindowsSystem()) return new ProcessBuilder(cmd).start().pid(); + // The working directory Wurst would have given it, rather than WMI's (system32). + return OutsideStart.startOrHere(cmd, Path.of(System.getProperty("user.dir")), OutsideStart.Show.NORMAL); + } + /** * An {@code -editor} launch signs in with a stored token that lapses, after which the game asks for a login. * Renews it from the Battle.net app first ({@link BattleNetSignIn}). {@code wc3LaunchMode} "auto" (the default) diff --git a/de.peeeq.wurstscript/src/main/resources/battlenet-token.ps1 b/de.peeeq.wurstscript/src/main/resources/battlenet-token.ps1 new file mode 100644 index 000000000..cb9409394 --- /dev/null +++ b/de.peeeq.wurstscript/src/main/resources/battlenet-token.ps1 @@ -0,0 +1,90 @@ +# Renews the session that -editor launches sign in with, from the Battle.net desktop app. +# +# The app signs Warcraft III in with a one-time WEB_TOKEN it writes just before it starts the game. A client given +# -editor signs in with EDITOR_TOKEN instead, which only the client itself renews (on each sign-in), so once it has +# lapsed every -editor launch stops at the login panel. This asks the app to start the game, closes that game the +# moment it appears - before it can spend the token - and stores the token as EDITOR_TOKEN. +# +# Prints one line per step and ends with "result "; never prints a token. +param( + [Parameter(Mandatory = $true)][string]$BattleNetExe, + [int]$TimeoutSeconds = 90, + [int]$AskAgainSeconds = 25 +) +$ErrorActionPreference = "Stop" +$launchKey = "HKCU:\Software\Blizzard Entertainment\Battle.net\Launch Options\W3" +$gameKey = "HKCU:\Software\Blizzard Entertainment\Warcraft III" + +function Read-WebToken { + $value = (Get-ItemProperty -Path $launchKey -Name WEB_TOKEN -ErrorAction SilentlyContinue).WEB_TOKEN + if ($value -is [byte[]]) { return $value } + return $null +} + +function Test-AppGame([int]$id) { + # A client the app started: its parent is a Battle.net.exe process. Anything else is someone else's client. + $process = Get-CimInstance Win32_Process -Filter "ProcessId=$id" -ErrorAction SilentlyContinue + if (-not $process) { return $false } + $parent = Get-Process -Id $process.ParentProcessId -ErrorAction SilentlyContinue + return [bool]($parent -and $parent.ProcessName -eq "Battle.net") +} + +function Get-GamePids { + @(Get-Process -Name "Warcraft III" -ErrorAction SilentlyContinue | ForEach-Object { $_.Id }) +} + +$before = Read-WebToken +$beforeHex = if ($before) { [BitConverter]::ToString($before) } else { "" } +$existing = Get-GamePids +# The app does not start a second client while its own is running, so it would never write a token. +if (@($existing | Where-Object { Test-AppGame $_ }).Count -gt 0) { + "result app-game-running" + exit 3 +} + +$watch = [Diagnostics.Stopwatch]::StartNew() +$askedAt = -1e9 +$token = $null +$tokenAt = 0 +$closed = 0 +while ($watch.Elapsed.TotalSeconds -lt $TimeoutSeconds) { + if (-not $token -and $watch.Elapsed.TotalSeconds - $askedAt -ge $AskAgainSeconds) { + $askedAt = $watch.Elapsed.TotalSeconds + Start-Process -FilePath $BattleNetExe -ArgumentList '--exec="launch W3"' + "asked {0:N1}" -f $askedAt + } + foreach ($id in Get-GamePids) { + if ($existing -contains $id) { continue } + $existing += $id + if (Test-AppGame $id) { + Stop-Process -Id $id -Force -ErrorAction SilentlyContinue + $closed++ + "closed {0} {1:N1}" -f $id, $watch.Elapsed.TotalSeconds + } + } + if (-not $token) { + $now = Read-WebToken + if ($now -and [BitConverter]::ToString($now) -ne $beforeHex) { + $token = $now + $tokenAt = $watch.Elapsed.TotalSeconds + "token {0:N1}" -f $tokenAt + } + } + # The app writes the token, then starts the game: wait briefly for that game so it is closed, not left running. + if ($token -and ($closed -gt 0 -or $watch.Elapsed.TotalSeconds - $tokenAt -ge 10)) { break } + Start-Sleep -Milliseconds 50 +} +if (-not $token -and $closed -gt 0) { + # The app started the game, so it wrote a token, but not where this script reads: the app keeps a private copy of + # the registry, as one started from a packaged (MSIX) app does. + "result token-not-visible" + exit 4 +} +if (-not $token) { + "result no-token" + exit 2 +} +if (-not (Test-Path $gameKey)) { New-Item -Path $gameKey -Force | Out-Null } +Set-ItemProperty -Path $gameKey -Name EDITOR_TOKEN -Value ([byte[]]$token) -Type Binary +"result refreshed" +exit 0 diff --git a/de.peeeq.wurstscript/src/test/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignInTest.java b/de.peeeq.wurstscript/src/test/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignInTest.java index 511bb8438..2b06ef3e4 100644 --- a/de.peeeq.wurstscript/src/test/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignInTest.java +++ b/de.peeeq.wurstscript/src/test/java/de/peeeq/wurstio/languageserver/requests/BattleNetSignInTest.java @@ -11,8 +11,10 @@ import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Arrays; import java.util.HashSet; import java.util.concurrent.atomic.AtomicBoolean; import java.util.List; @@ -66,6 +68,96 @@ public void theWindowWatcherRunsFromACopyNamedByItsContent() throws Exception { assertEquals(BattleNetSignIn.windowWatcherCommand(List.of(), dir).get(6), command.get(6), "the copy is reused"); } + @Test + public void theRenewalScriptRunsFromACopyNamedByItsContent() throws Exception { + Path dir = Files.createTempDirectory("wurst-renewal-script"); + Path file = BattleNetSignIn.scriptCopy(BattleNetSignIn.TOKEN_SCRIPT, dir); + assertEquals(file.getParent(), dir); + assertTrue(file.getFileName().toString().matches("wurst-battlenet-token-[0-9a-f]{12}\\.ps1"), file.toString()); + String script = Files.readString(file); + assertTrue(script.contains("[Parameter(Mandatory = $true)][string]$BattleNetExe")); + for (String outcome : List.of("refreshed", "no-token", "app-game-running", "token-not-visible")) { + assertTrue(script.contains("\"result " + outcome + "\""), outcome); + } + assertTrue(script.chars().allMatch(c -> c < 128), "Windows PowerShell reads a .ps1 without BOM as ANSI"); + assertEquals(BattleNetSignIn.scriptCopy(BattleNetSignIn.TOKEN_SCRIPT, dir), file, "the copy is reused"); + } + + @Test + public void theRenewalScriptRedirectsEverythingItPrintsToTheOutputFile() { + List command = BattleNetSignIn.tokenScriptCommand(Path.of("C:\\Temp\\wurst-battlenet-token.ps1"), + Path.of("C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"), 90, Path.of("C:\\Users\\O'Neil\\renewal.log")); + assertEquals(command, List.of("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", + "-Command", "& 'C:\\Temp\\wurst-battlenet-token.ps1' -BattleNetExe 'C:\\Program Files (x86)\\Battle.net\\Battle.net.exe'" + + " -TimeoutSeconds 90 *> 'C:\\Users\\O''Neil\\renewal.log'")); + assertEquals(BattleNetSignIn.powerShellQuote("a\u2019b"), "'a\u2019\u2019b'"); + } + + @Test + public void readsOnlyCompleteLinesOfTheRedirectedUtf16Output() { + byte[] partial = utf16WithBom("asked 0.0\r\ntoken 0.5\r\nresult refre"); + assertEquals(BattleNetSignIn.completeLines(partial), "asked 0.0\r\ntoken 0.5\r\n"); + assertEquals(BattleNetSignIn.parseTokenScriptOutput(BattleNetSignIn.completeLines(partial)).outcome(), null, + "a result line still being written is no result"); + // Half a UTF-16 character at the end is part of an unfinished line. + byte[] odd = Arrays.copyOf(utf16WithBom("asked 0.0\r\nr"), utf16WithBom("asked 0.0\r\nr").length - 1); + assertEquals(BattleNetSignIn.completeLines(odd), "asked 0.0\r\n"); + + BattleNetSignIn.TokenScriptResult result = BattleNetSignIn.parseTokenScriptOutput(BattleNetSignIn.completeLines( + utf16WithBom("asked 0.0\r\ntoken 0.5\r\nclosed 1234 0.6\r\nresult refreshed\r\n"))); + assertEquals(result.outcome(), "refreshed"); + assertEquals(result.lines(), List.of("asked 0.0", "token 0.5", "closed 1234 0.6", "result refreshed")); + // Without a byte order mark the output is read as UTF-8. + assertEquals(BattleNetSignIn.completeLines("result no-token\n".getBytes(StandardCharsets.UTF_8)), "result no-token\n"); + assertEquals(BattleNetSignIn.completeLines(new byte[0]), ""); + } + + @Test + public void aRenewalScriptThatEndedIsReadOnceMore() throws Exception { + Path output = Files.createTempFile("wurst-renewal", ".log"); + Files.write(output, utf16WithBom("asked 0.0\r\nresult no-token\r\n")); + // null: the script has ended; its result line still counts. + assertEquals(BattleNetSignIn.awaitTokenScript(null, output, 5).outcome(), "no-token"); + Files.write(output, utf16WithBom("asked 0.0\r\n")); + BattleNetSignIn.TokenScriptResult ended = BattleNetSignIn.awaitTokenScript(null, output, 5); + assertEquals(ended.outcome(), null); + assertTrue(BattleNetSignIn.problem(ended).contains("asked 0.0"), BattleNetSignIn.problem(ended)); + // A running script's result line ends the wait at once. + Files.write(output, utf16WithBom("result refreshed\r\n")); + assertEquals(BattleNetSignIn.awaitTokenScript(ProcessHandle.current(), output, 5).outcome(), "refreshed"); + } + + @Test + public void eachRenewalOutcomeHasItsMessage() { + assertEquals(BattleNetSignIn.problem(outcome("refreshed")), null); + assertTrue(BattleNetSignIn.problem(outcome("no-token")).startsWith("Battle.net did not start Warcraft III.")); + assertEquals(BattleNetSignIn.problem(outcome("app-game-running")), + "Close the Warcraft III client started from Battle.net, then run the map again."); + String notVisible = BattleNetSignIn.problem(outcome("token-not-visible")); + assertTrue(notVisible.contains("wrote its sign-in where other programs cannot read it"), notVisible); + assertTrue(notVisible.contains("packaged app (such as the Claude desktop app)"), notVisible); + assertTrue(notVisible.contains("Quit Battle.net from its tray icon and start it from the Start menu."), notVisible); + String failed = BattleNetSignIn.problem(new BattleNetSignIn.TokenScriptResult(null, + List.of("one", "two", "three", "four"))); + assertEquals(failed, "The Battle.net sign-in renewal failed: two | three | four."); + assertEquals(BattleNetSignIn.problem(new BattleNetSignIn.TokenScriptResult(null, List.of())), + "The Battle.net sign-in renewal failed: it printed nothing."); + assertTrue(BattleNetSignIn.problem(outcome("something-new")).startsWith("The Battle.net sign-in renewal failed")); + } + + private static BattleNetSignIn.TokenScriptResult outcome(String outcome) { + return BattleNetSignIn.parseTokenScriptOutput("asked 0.0\nresult " + outcome + "\n"); + } + + private static byte[] utf16WithBom(String text) { + byte[] body = text.getBytes(StandardCharsets.UTF_16LE); + byte[] bytes = new byte[body.length + 2]; + bytes[0] = (byte) 0xff; + bytes[1] = (byte) 0xfe; + System.arraycopy(body, 0, bytes, 2, body.length); + return bytes; + } + @Test public void theWindowWatcherOutlivesEveryRequestOfASlowRenewal() { // The renewal asks the app again every 25 s for up to 90 s, and the app shows its window once more as the diff --git a/de.peeeq.wurstscript/src/test/java/de/peeeq/wurstio/languageserver/requests/OutsideStartTest.java b/de.peeeq.wurstscript/src/test/java/de/peeeq/wurstio/languageserver/requests/OutsideStartTest.java new file mode 100644 index 000000000..62f683621 --- /dev/null +++ b/de.peeeq.wurstscript/src/test/java/de/peeeq/wurstio/languageserver/requests/OutsideStartTest.java @@ -0,0 +1,77 @@ +package de.peeeq.wurstio.languageserver.requests; + +import net.moonlightflower.wc3libs.port.Orient; +import org.testng.SkipException; +import org.testng.annotations.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; + +public class OutsideStartTest { + @Test + public void quotesOnlyWhatACommandLineWouldSplit() { + assertEquals(OutsideStart.quoteWindowsArg("-editor"), "-editor"); + assertEquals(OutsideStart.quoteWindowsArg(""), "\"\""); + assertEquals(OutsideStart.quoteWindowsArg("C:\\Program Files\\Warcraft III\\Warcraft III.exe"), + "\"C:\\Program Files\\Warcraft III\\Warcraft III.exe\""); + // Backslashes before a quote, or before the closing one, are doubled; others are left alone. + assertEquals(OutsideStart.quoteWindowsArg("say \"hi\""), "\"say \\\"hi\\\"\""); + assertEquals(OutsideStart.quoteWindowsArg("C:\\dir with space\\"), "\"C:\\dir with space\\\\\""); + assertEquals(OutsideStart.quoteWindowsArg("C:\\dir\\"), "C:\\dir\\", "nothing to split, nothing to quote"); + assertEquals(OutsideStart.quoteWindowsArg("a\\\"b"), "\"a\\\\\\\"b\""); + assertEquals(OutsideStart.commandLine(List.of("game.exe", "-loadfile", "C:\\my map.w3x")), + "game.exe -loadfile \"C:\\my map.w3x\""); + } + + @Test + public void aProcessStartedThroughWmiGetsItsArgumentsAndDirectoryAsGiven() throws Exception { + if (!Orient.isWindowsSystem()) throw new SkipException("WMI is Windows only"); + Path dir = Files.createTempDirectory("wurst outside start"); + Path program = dir.resolve("PrintArguments.java"); + Path result = dir.resolve("arguments.txt"); + Files.writeString(program, """ + import java.nio.file.*; + import java.util.*; + public class PrintArguments { + public static void main(String[] args) throws Exception { + List lines = new ArrayList<>(List.of(System.getProperty("user.dir"))); + lines.addAll(Arrays.asList(args).subList(1, args.length)); + Path partial = Path.of(args[0] + ".tmp"); + Files.write(partial, lines); + Files.move(partial, Path.of(args[0])); + } + } + """); + Path java = Path.of(System.getProperty("java.home"), "bin", "java.exe"); + List arguments = List.of("with space", "quote\"inside", "trailing\\", "C:\\dir with space\\", "", + "both \\\"q\\\" and \\"); + List command = new ArrayList<>(List.of(java.toString(), program.toString(), result.toString())); + command.addAll(arguments); + + long pid = OutsideStart.start(command, dir, OutsideStart.Show.HIDDEN); + + assertTrue(pid > 0); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(60); + while (!Files.exists(result) && System.nanoTime() < deadline) Thread.sleep(100); + assertTrue(Files.exists(result), "the program started through WMI wrote " + result); + List lines = Files.readAllLines(result, StandardCharsets.UTF_8); + assertEquals(Path.of(lines.get(0)).toRealPath(), dir.toRealPath(), "the working directory"); + assertEquals(lines.subList(1, lines.size()), arguments); + } + + @Test + public void aProcessWmiCannotCreateIsAnError() { + if (!Orient.isWindowsSystem()) throw new SkipException("WMI is Windows only"); + Path missing = Path.of(System.getProperty("java.io.tmpdir"), "wurst-no-such-program-" + System.nanoTime() + ".exe"); + java.io.IOException failure = org.testng.Assert.expectThrows(java.io.IOException.class, + () -> OutsideStart.start(List.of(missing.toString()), null, OutsideStart.Show.HIDDEN)); + assertTrue(failure.getMessage().contains("WMI could not start " + missing.getFileName()), failure.getMessage()); + } +}