Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,11 @@ static List<String> 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();
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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.
*
* <p>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<String> 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<String> 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<String> 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<String> 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();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -253,11 +253,11 @@ private void launchGame(WurstGui gui, W3InstallationData launchData, File cached
List<String> 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;
Expand All @@ -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<String> 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)
Expand Down
90 changes: 90 additions & 0 deletions de.peeeq.wurstscript/src/main/resources/battlenet-token.ps1
Original file line number Diff line number Diff line change
@@ -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 <outcome>"; 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
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String> 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
Expand Down
Loading
Loading