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 @@ -168,7 +168,8 @@ Renewal renew(long gateWaitSeconds, Runnable onWait) throws IOException {
Set<Long> seen = new HashSet<>();
boolean[] asked = {false};
try {
return new Renewal(gate, renewLocked(seen, asked));
String token = renewLocked(seen, asked);
return signInCheck(gate, token);
} catch (IOException | RuntimeException | Error ex) {
if (asked[0]) {
closeLateGames(gate, seen, LATE_GAME_SECONDS);
Expand Down Expand Up @@ -213,27 +214,37 @@ static void closeLateGames(ServerSocket gate, Set<Long> seen, long seconds) {
* tool's renewal could replace {@code EDITOR_TOKEN} before this client read it, leaving two clients one token.
*/
static final class Renewal implements AutoCloseable {
/** Whether the launched client has replaced the renewed {@code EDITOR_TOKEN} yet. */
@FunctionalInterface
interface SignedIn {
/** @throws IOException when that can no longer be told */
boolean check() throws IOException;
}

private final ServerSocket _gate;
private final @Nullable String _token;
private final SignedIn _signedIn;
private final Runnable _onClose;
private final long _pollMillis;

/** @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) {
Renewal(ServerSocket gate, SignedIn signedIn, Runnable onClose, long pollMillis) {
_gate = gate;
_token = token;
_signedIn = signedIn;
_onClose = onClose;
_pollMillis = pollMillis;
}

/**
* 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. 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.
* {@value #SIGN_IN_TIMEOUT_SECONDS} seconds. Does not block.
*
* @return the thread that waits, for tests
*/
void releaseWhenSignedIn() {
Thread releaseWhenSignedIn() {
Thread waiter = new Thread(() -> {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(SIGN_IN_TIMEOUT_SECONDS);
try {
while (System.nanoTime() < deadline && (_token == null
|| readBinary(GAME_KEY, "EDITOR_TOKEN").filter(_token::equals).isPresent())) {
Thread.sleep(500);
while (System.nanoTime() < deadline && !_signedIn.check()) {
Thread.sleep(_pollMillis);
}
} catch (IOException | InterruptedException | RuntimeException ex) {
WLogger.warning("Stopped waiting for the Warcraft III sign-in: " + ex.getMessage());
Expand All @@ -243,6 +254,7 @@ void releaseWhenSignedIn() {
}, "Battle.net sign-in lock");
waiter.setDaemon(true);
waiter.start();
return waiter;
}

@Override
Expand All @@ -252,7 +264,108 @@ public void close() {
} catch (IOException ex) {
WLogger.warning("Could not release the Battle.net lock: " + ex.getMessage());
}
_onClose.run();
}
}

/**
* {@link #SIGNIN_SCRIPT} running in the user's own registry view, where the client replaces {@code EDITOR_TOKEN}
* as it signs in. Read from Wurst's own view, the token may never change: a packaged app's private copy keeps the
* old one.
*/
static final class SignInWatcher {
private final @Nullable ProcessHandle _process;
private final Path _output;

SignInWatcher(@Nullable ProcessHandle process, Path output) {
_process = process;
_output = output;
}

private List<String> lines() {
return parseTokenScriptOutput(completeLines(readOutput(_output))).lines();
}

boolean ready() {
return lines().contains("ready");
}

/** True once the client has signed in; throws once the watcher has ended without seeing it. */
boolean signedIn() throws IOException {
boolean alive = _process != null && _process.isAlive();
// Read after the check, so a watcher that saw the sign-in and ended in between is not missed.
List<String> lines = lines();
if (lines.contains("signed-in")) return true;
if (lines.contains("timeout") || !alive) {
throw new IOException("the sign-in watcher ended (" + (lines.isEmpty() ? "no output" : lines.getLast()) + ")");
}
return false;
}

void stop() {
if (_process != null) {
_process.destroyForcibly();
try {
_process.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
}
}
try {
Files.deleteIfExists(_output);
} catch (IOException ex) {
_output.toFile().deleteOnExit();
}
}
}

/**
* The held lock, with how it tells that the launched client has signed in: from a {@link SignInWatcher} started
* outside Wurst's registry view, or, if that cannot start, by reading {@code EDITOR_TOKEN} from here. Called after
* the renewal and before the launch, so the token the watcher starts from is the renewed one.
*
* @param token the renewed {@code EDITOR_TOKEN} as Wurst reads it, for the fallback; null when unreadable
*/
private static Renewal signInCheck(ServerSocket gate, @Nullable String token) {
SignInWatcher watcher = null;
try {
Path output = tempDir().resolve("wurst-battlenet-signin-" + UUID.randomUUID() + ".log");
List<String> command = List.of("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy",
"Bypass", "-Command", "& " + powerShellQuote(scriptCopy(SIGNIN_SCRIPT, tempDir()).toString())
+ " -TimeoutSeconds " + (SIGN_IN_TIMEOUT_SECONDS + 10) + " *> " + powerShellQuote(output.toString()));
long pid = OutsideStart.startOrHere(command, null, OutsideStart.Show.HIDDEN);
watcher = new SignInWatcher(ProcessHandle.of(pid).orElse(null), output);
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(SIGNIN_READY_SECONDS);
while (!watcher.ready() && System.nanoTime() < deadline) pause(50);
if (watcher.ready()) {
SignInWatcher started = watcher;
watcher = null;
return new Renewal(gate, started::signedIn, started::stop, 250);
}
WLogger.warning("The Warcraft III sign-in watcher did not start; watching from Wurst instead.");
} catch (IOException ex) {
WLogger.warning("Watching the Warcraft III sign-in from Wurst instead: " + ex.getMessage());
} finally {
if (watcher != null) watcher.stop();
}
return new Renewal(gate, tokenReplaced(token, () -> readBinary(GAME_KEY, "EDITOR_TOKEN")), () -> { }, 500);
}

/** Reads {@code EDITOR_TOKEN}; empty when it is not set. */
@FunctionalInterface
interface TokenRead {
Optional<String> read() throws IOException;
}

/**
* The fallback sign-in check: whether the client has replaced the renewed token. If the renewed token could not
* be read, the sign-in cannot be told, and the lock is held until the timeout rather than released at once.
*/
static Renewal.SignedIn tokenReplaced(@Nullable String renewed, TokenRead current) {
if (renewed == null) return () -> false;
return () -> current.read().filter(renewed::equals).isEmpty();
}

/**
Expand Down Expand Up @@ -427,6 +540,10 @@ private static Path tempDir() {

/** The renewal script, run in the user's own registry view. */
static final String TOKEN_SCRIPT = "battlenet-token.ps1";
/** The sign-in watcher, run in the user's own registry view ({@link SignInWatcher}). */
static final String SIGNIN_SCRIPT = "battlenet-signin.ps1";
/** How long the sign-in watcher may take to start and read the renewed token before the game is launched. */
private static final long SIGNIN_READY_SECONDS = 15;
/** The watcher that keeps the app's window out of sight during the renewal. */
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. */
Expand Down
28 changes: 28 additions & 0 deletions de.peeeq.wurstscript/src/main/resources/battlenet-signin.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Waits, in the registry view it runs in, until the launched client replaces EDITOR_TOKEN, which it does as it signs in.
#
# Prints "ready" once it has read the token the renewal stored, then "signed-in" when that token changes, or "timeout".
# Never prints a token.
param(
[int]$TimeoutSeconds = 120,
[string]$Key = "HKCU:\Software\Blizzard Entertainment\Warcraft III"
)
$ErrorActionPreference = "Stop"

function Read-EditorToken {
$value = (Get-ItemProperty -Path $Key -Name EDITOR_TOKEN -ErrorAction SilentlyContinue).EDITOR_TOKEN
if ($value -is [byte[]]) { return [BitConverter]::ToString($value) }
return ""
}

$before = Read-EditorToken
"ready"
$watch = [Diagnostics.Stopwatch]::StartNew()
while ($watch.Elapsed.TotalSeconds -lt $TimeoutSeconds) {
if ((Read-EditorToken) -ne $before) {
"signed-in"
exit 0
}
Start-Sleep -Milliseconds 250
}
"timeout"
exit 1
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,94 @@ private static byte[] utf16WithBom(String text) {
return bytes;
}

private static ServerSocket loopbackGate() throws Exception {
ServerSocket gate = new ServerSocket();
gate.bind(new InetSocketAddress(InetAddress.getByAddress(new byte[]{127, 0, 0, 1}), 0));
return gate;
}

@Test
public void theLockIsReleasedOnceTheClientHasSignedInAndStopsTheWatcherWithIt() throws Exception {
ServerSocket gate = loopbackGate();
List<Boolean> reads = new java.util.ArrayList<>(List.of(false, false, true));
AtomicBoolean stopped = new AtomicBoolean();
Thread waiter = new BattleNetSignIn.Renewal(gate, () -> reads.removeFirst(), () -> stopped.set(true), 1)
.releaseWhenSignedIn();
waiter.join(10_000);
assertTrue(reads.isEmpty(), "polled until the client signed in");
assertTrue(gate.isClosed(), "the lock is released");
assertTrue(stopped.get(), "the sign-in watcher is stopped with the lock");
}

@Test
public void aSignInThatCanNoLongerBeWatchedReleasesTheLock() throws Exception {
ServerSocket gate = loopbackGate();
Thread waiter = new BattleNetSignIn.Renewal(gate, () -> {
throw new java.io.IOException("the sign-in watcher ended (timeout)");
}, () -> { }, 1).releaseWhenSignedIn();
waiter.join(10_000);
assertTrue(gate.isClosed());
}

@Test
public void theFallbackKeepsTheLockWhileTheRenewedTokenIsUnknownOrUnchanged() throws Exception {
assertFalse(BattleNetSignIn.tokenReplaced(null, Optional::empty).check(),
"an unreadable renewed token is no sign-in");
assertFalse(BattleNetSignIn.tokenReplaced(null, () -> Optional.of("new")).check(),
"an unreadable renewed token is no sign-in, whatever is read later");
assertFalse(BattleNetSignIn.tokenReplaced("renewed", () -> Optional.of("renewed")).check());
assertTrue(BattleNetSignIn.tokenReplaced("renewed", () -> Optional.of("new")).check());
assertTrue(BattleNetSignIn.tokenReplaced("renewed", Optional::empty).check(), "a spent token is a sign-in");
}

@Test
public void aSignInWatcherThatEndedWithoutTheSignInIsNotTakenForOne() throws Exception {
Path output = Files.createTempFile("wurst-signin", ".log");
Files.write(output, utf16WithBom("ready\r\ntimeout\r\n"));
BattleNetSignIn.SignInWatcher watcher = new BattleNetSignIn.SignInWatcher(null, output);
assertTrue(watcher.ready());
expectThrows(java.io.IOException.class, watcher::signedIn);
Files.write(output, utf16WithBom("ready\r\nsigned-in\r\n"));
assertTrue(watcher.signedIn(), "a watcher that saw the sign-in and ended still reports it");
watcher.stop();
assertFalse(Files.exists(output), "stop removes its output");
}

@Test
public void theSignInWatcherReportsWhenTheTokenItStartedWithIsReplaced() throws Exception {
if (!Orient.isWindowsSystem()) throw new SkipException("Windows registry");
String key = "HKCU\\Software\\WurstScriptTests\\SignIn-" + java.util.UUID.randomUUID();
reg("add", key, "/v", "EDITOR_TOKEN", "/t", "REG_BINARY", "/d", "0102", "/f");
Path dir = Files.createTempDirectory("wurst signin watcher");
Path output = dir.resolve("out.log");
Path script = BattleNetSignIn.scriptCopy(BattleNetSignIn.SIGNIN_SCRIPT, dir);
Process process = new ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
"-Command", "& " + BattleNetSignIn.powerShellQuote(script.toString()) + " -TimeoutSeconds 30 -Key "
+ BattleNetSignIn.powerShellQuote(key.replaceFirst("^HKCU\\\\", "HKCU:\\\\")) + " *> "
+ BattleNetSignIn.powerShellQuote(output.toString())).start();
BattleNetSignIn.SignInWatcher watcher = new BattleNetSignIn.SignInWatcher(process.toHandle(), output);
try {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
while (!watcher.ready() && System.nanoTime() < deadline) Thread.sleep(50);
assertTrue(watcher.ready());
assertFalse(watcher.signedIn(), "the token it started with is still there");
reg("add", key, "/v", "EDITOR_TOKEN", "/t", "REG_BINARY", "/d", "0304", "/f");
while (!watcher.signedIn() && System.nanoTime() < deadline) Thread.sleep(50);
assertTrue(watcher.signedIn());
} finally {
watcher.stop();
reg("delete", key, "/f");
}
assertTrue(Files.readString(script).chars().allMatch(c -> c < 128), "Windows PowerShell reads a .ps1 without BOM as ANSI");
}

private static void reg(String... args) throws Exception {
List<String> command = new java.util.ArrayList<>(List.of("reg.exe"));
command.addAll(List.of(args));
assertEquals(new ProcessBuilder(command).redirectErrorStream(true)
.redirectOutput(ProcessBuilder.Redirect.DISCARD).start().waitFor(), 0);
}

@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