diff --git a/src/main/kotlin/config/WurstProjectConfig.kt b/src/main/kotlin/config/WurstProjectConfig.kt index 46cda17..012f15b 100644 --- a/src/main/kotlin/config/WurstProjectConfig.kt +++ b/src/main/kotlin/config/WurstProjectConfig.kt @@ -15,6 +15,7 @@ import logging.KotlinLogging import java.io.IOException import java.nio.file.Files import java.nio.file.Path +import java.nio.file.InvalidPathException import java.nio.file.Paths import java.nio.file.StandardOpenOption /** @@ -156,7 +157,20 @@ object WurstProjectConfig { /** The VS Code extension's `wurst.customMapDataPath`, which the language server's hot reload also uses. */ fun configuredCustomMapDataPath(projectRoot: Path): Path? = configuredPath(projectRoot, "wurst.customMapDataPath") + /** The VS Code extension's `wurst.wc3LaunchMode` (auto, battlenet or legacy), which Run Map also follows. */ + fun configuredLaunchMode(projectRoot: Path): String = configuredString(projectRoot, "wurst.wc3LaunchMode") ?: "auto" + + /** An optional setting: a path the system cannot represent counts as unset, so callers fall back as before. */ private fun configuredPath(projectRoot: Path, setting: String): Path? { + val value = configuredString(projectRoot, setting) ?: return null + return try { + Paths.get(value) + } catch (_: InvalidPathException) { + null + } + } + + private fun configuredString(projectRoot: Path, setting: String): String? { val settings = projectRoot.resolve(".vscode").resolve("settings.json") if (!Files.isRegularFile(settings)) { return null @@ -166,7 +180,6 @@ object WurstProjectConfig { ?.get(setting) ?.asText() ?.takeIf(String::isNotBlank) - ?.let(Paths::get) } catch (_: Exception) { null } diff --git a/src/main/kotlin/file/BattleNetSignIn.kt b/src/main/kotlin/file/BattleNetSignIn.kt new file mode 100644 index 0000000..4e21ca8 --- /dev/null +++ b/src/main/kotlin/file/BattleNetSignIn.kt @@ -0,0 +1,321 @@ +package file + +import java.io.IOException +import java.net.BindException +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.nio.ByteBuffer +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths +import java.security.MessageDigest +import java.util.Locale +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +/** + * Renews the sign-in that Warcraft III 3.x uses for `-editor` launches, from the Battle.net desktop app. + * + * A client started with `-editor` (every `grill run` of a Reforged client) signs in with `EDITOR_TOKEN` + * (`HKCU\Software\Blizzard Entertainment\Warcraft III`) and replaces it with a fresh one each time it signs in. Once + * that token lapses (overnight is enough) every launch stops at the in-game login panel. The app's own session does + * not reach it: a client the app starts with `-loadfile` shows the login panel too. + * + * Just before the app starts the game it writes a one-time `WEB_TOKEN` (`...\Battle.net\Launch Options\W3`). Stored + * as `EDITOR_TOKEN`, that token signs the next `-editor` client in. [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 as before. + * + * WurstScript's Run Map (`BattleNetSignIn`) and the wc3-e2e-harness (`docs/BattleNetSignIn.md`) do the same, and all + * hold the same localhost port as a lock from the renewal until the launched client has signed in. + */ +/** What [Wc3MapRunner] needs from the Battle.net app; replaced in tests. */ +internal interface BattleNetApp { + fun isRunning(): Boolean + + /** @param onWait called once if another launch holds the lock and this one has to wait for it */ + fun renew(onWait: () -> Unit = {}): BattleNetSignIn.Renewal +} + +internal class BattleNetSignIn private constructor(private val config: Path, private val launcher: Path) : BattleNetApp { + + /** + * Another tool holds the renewal lock for longer than a renewal and a sign-in take. Not a reason to launch + * without it: that launch could spend the token the other tool's client has not read yet. + */ + class LockBusyException(message: String) : IOException(message) + + /** The lock, held until the launched client has signed in; see [awaitSignIn]. */ + class Renewal internal constructor( + private val gate: ServerSocket, + private val token: String, + private val currentToken: () -> String? = { readBinary(GAME_KEY, "EDITOR_TOKEN") }, + private val pollMillis: Long = 500, + ) : AutoCloseable { + /** + * Blocks until the launched client replaces `EDITOR_TOKEN`, which it does as it signs in (about ten seconds after + * launch), or [SIGN_IN_TIMEOUT_SECONDS] pass, then releases the lock. Released earlier, another tool's renewal + * could replace the token before this client read it, leaving two clients one token. + */ + fun awaitSignIn(): Boolean { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(SIGN_IN_TIMEOUT_SECONDS) + try { + while (System.nanoTime() < deadline) { + if (currentToken() != token) return true + Thread.sleep(pollMillis) + } + return false + } finally { + close() + } + } + + override fun close() { + try { + gate.close() + } catch (_: IOException) { + } + } + } + + override fun isRunning(): Boolean = ProcessHandle.allProcesses().anyMatch { named(command(it), LAUNCHER) } + + override fun renew(onWait: () -> Unit): Renewal = renew(GATE_WAIT_SECONDS, onWait) + + /** + * Stores a token from the app as `EDITOR_TOKEN` and returns the held lock. 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. + */ + fun renew(gateWaitSeconds: Long, onWait: () -> Unit = {}): Renewal { + val gate = acquireGate(gateWaitSeconds, onWait) + try { + return Renewal(gate, renewLocked()) + } catch (e: Throwable) { + gate.close() + throw e + } + } + + private fun renewLocked(): String { + if (!isRunning()) throw IOException("Battle.net is not running.") + val seen = HashSet() + for (game in games()) { + if (startedByLauncher(game)) { + throw IOException("Close the Warcraft III client started from Battle.net, then run the map again.") + } + seen.add(game.pid()) + } + val before = readBinary(LAUNCH_KEY, "WEB_TOKEN") + // Asked to start the game, the app shows its window in front; the watcher minimizes it as soon as it appears + // and brings the map's client forward once that has a window. + watchLauncherWindow() + val start = System.nanoTime() + var askedAt = Long.MIN_VALUE + var token: String? = null + var tokenAt = 0L + var closed = 0 + while (System.nanoTime() - start < TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS)) { + if (token == null && (askedAt == Long.MIN_VALUE + || System.nanoTime() - askedAt >= TimeUnit.SECONDS.toNanos(ASK_AGAIN_SECONDS))) { + askedAt = System.nanoTime() + // An app that is still starting ignores the command, so it is repeated while waiting. + ProcessBuilder(launcher.toString(), "--exec=launch W3") + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start() + } + for (game in games()) { + if (!seen.add(game.pid()) || !startedByLauncher(game)) continue + game.destroyForcibly() + closed++ + } + if (token == null) { + val now = readBinary(LAUNCH_KEY, "WEB_TOKEN") + if (now != null && now != before) { + token = now + tokenAt = System.nanoTime() + } + } + // The app writes the token, then starts the game: wait briefly for that game so it is closed. + if (token != null && (closed > 0 + || System.nanoTime() - tokenAt >= TimeUnit.SECONDS.toNanos(GAME_AFTER_TOKEN_SECONDS))) break + Thread.sleep(50) + } + if (token == null) { + throw IOException("Battle.net did not start Warcraft III. Check that it is signed in and the game is ready to play.") + } + writeBinary(GAME_KEY, "EDITOR_TOKEN", token) + return token + } + + private fun acquireGate(waitSeconds: Long, onWait: () -> Unit): ServerSocket { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(waitSeconds) + var waiting = false + while (true) { + val socket = ServerSocket() + try { + // 127.0.0.1 exactly, as the harness binds it; the loopback name could resolve to ::1. + socket.bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), gatePort(config))) + return socket + } catch (e: BindException) { + socket.close() + if (!waiting) { + waiting = true + onWait() + } + if (System.nanoTime() >= deadline) { + throw LockBusyException("Another Warcraft III launch has held the Battle.net sign-in for over $waitSeconds s.") + } + Thread.sleep(250) + } catch (e: IOException) { + socket.close() + throw e + } + } + } + + companion object { + const val LAUNCH_KEY = "HKCU\\Software\\Blizzard Entertainment\\Battle.net\\Launch Options\\W3" + const val GAME_KEY = "HKCU\\Software\\Blizzard Entertainment\\Warcraft III" + private const val LAUNCHER = "Battle.net.exe" + private const val GAME = "Warcraft III.exe" + private const val TIMEOUT_SECONDS = 90L + private const val ASK_AGAIN_SECONDS = 25L + private const val GAME_AFTER_TOKEN_SECONDS = 10L + const val SIGN_IN_TIMEOUT_SECONDS = 120L + /** Another holder renews (up to [TIMEOUT_SECONDS]) and waits for its client's sign-in; outwait both. */ + const val GATE_WAIT_SECONDS = TIMEOUT_SECONDS + SIGN_IN_TIMEOUT_SECONDS + 30 + + /** A renewal for [config] whose launcher is never started; for tests that only touch the lock. */ + internal fun forTest(config: Path): BattleNetSignIn = BattleNetSignIn(config, Paths.get(LAUNCHER)) + private val REG_BINARY = Regex("""^\s*(\S+)\s+REG_BINARY\s+([0-9A-Fa-f]*)\s*$""", RegexOption.MULTILINE) + + /** A copy of the wc3-e2e-harness `node/src/runner/battlenet-window.ps1`; keep the two equal. */ + const val 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. */ + const val WINDOW_WATCH_SECONDS = TIMEOUT_SECONDS + 150 + private const val WINDOW_READY_SECONDS = 3L + + /** The PowerShell command that runs [WINDOW_SCRIPT] with [arguments]; null if the script is missing. */ + fun windowWatcherCommand(arguments: List, dir: Path = Paths.get(System.getProperty("java.io.tmpdir"))): List? { + val script = BattleNetSignIn::class.java.classLoader.getResourceAsStream(WINDOW_SCRIPT)?.use { it.readBytes() } + ?: return null + // A file, not -EncodedCommand: encoded, the script is close to Windows' 32,767-character command line limit. + // Named by content, so a grill of another version never runs this one's copy. + val hash = MessageDigest.getInstance("SHA-256").digest(script).take(6).joinToString("") { "%02x".format(it) } + val file = dir.resolve("grill-battlenet-window-$hash.ps1") + try { + if (!Files.isRegularFile(file) || !Files.readAllBytes(file).contentEquals(script)) Files.write(file, script) + } catch (_: IOException) { + return null + } + return listOf("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file.toString()) + arguments + } + + /** + * Starts the window watcher and waits until it has noted the windows already open (at most + * [WINDOW_READY_SECONDS]). It then runs on its own: the app shows its window again as the map's client signs in, + * so it ends a minute after that client appears, or after [WINDOW_WATCH_SECONDS]. Best effort: a watcher that does + * not start only means the app's window may show. + */ + private fun watchLauncherWindow() { + val command = windowWatcherCommand(listOf("-Seconds", WINDOW_WATCH_SECONDS.toString(), "-FocusGame")) ?: return + val process = try { + ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start() + } catch (_: IOException) { + return + } + val ready = CountDownLatch(1) + Thread { + try { + // The watcher prints nothing after "ready", so its output can be let go then. + process.inputReader().use { reader -> + while (true) { + val line = reader.readLine() ?: break + if (line.trim() == "ready") break + } + } + } catch (_: IOException) { + } finally { + ready.countDown() + } + }.apply { isDaemon = true }.start() + ready.await(WINDOW_READY_SECONDS, TimeUnit.SECONDS) + } + + fun find(): BattleNetSignIn? { + if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) return null + val appData = System.getenv("APPDATA") ?: return null + val launcher = launcherExecutable() ?: return null + return BattleNetSignIn(Paths.get(appData, "Battle.net", "Battle.net.config"), launcher) + } + + private fun launcherExecutable(): Path? { + ProcessHandle.allProcesses().map { command(it) }.filter { named(it, LAUNCHER) }.findFirst().orElse(null) + ?.let { return it } + return listOfNotNull(System.getenv("ProgramFiles(x86)"), System.getenv("ProgramFiles")) + .map { Paths.get(it, "Battle.net", LAUNCHER) } + .firstOrNull(Files::isRegularFile) + } + + /** Whether [executable] belongs to the install Battle.net manages; the token only works there. */ + fun isRegisteredGame(executable: Path): Boolean { + val key = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Warcraft III" + for (view in listOf("/reg:32", "/reg:64")) { + for (line in readCommand("reg.exe", "query", key, "/v", "InstallLocation", view)) { + val fields = line.trim().split(Regex("\\s{2,}"), 3) + if (fields.size == 3 && fields[0].equals("InstallLocation", ignoreCase = true) + && executable.toAbsolutePath().normalize().startsWith(Paths.get(fields[2]).toAbsolutePath().normalize())) { + return true + } + } + } + return false + } + + fun parseBinary(regQueryOutput: List, value: String): String? = + REG_BINARY.findAll(regQueryOutput.joinToString("\n")) + .firstOrNull { it.groupValues[1].equals(value, ignoreCase = true) } + ?.groupValues?.get(2)?.uppercase(Locale.ROOT) + + /** The lock port the wc3-e2e-harness and WurstScript use for the same Battle.net profile. */ + fun gatePort(config: Path): Int { + val key = config.toAbsolutePath().normalize().toString().lowercase(Locale.ROOT) + val hash = MessageDigest.getInstance("SHA-256").digest(key.toByteArray(Charsets.UTF_8)) + return 33000 + Integer.remainderUnsigned(ByteBuffer.wrap(hash).int, 10000) + } + + private fun games(): List = + ProcessHandle.allProcesses().filter { named(command(it), GAME) }.toList() + + /** A client the app started; anything else is someone else's game and is left alone. */ + private fun startedByLauncher(game: ProcessHandle): Boolean = + game.parent().map { named(command(it), LAUNCHER) }.orElse(false) + + private fun command(process: ProcessHandle): Path? = process.info().command().map { Paths.get(it) }.orElse(null) + + private fun named(executable: Path?, image: String): Boolean = + executable?.fileName?.toString()?.equals(image, ignoreCase = true) == true + + private fun readBinary(key: String, value: String): String? = + parseBinary(readCommand("reg.exe", "query", key, "/v", value), value) + + private fun writeBinary(key: String, value: String, hex: String) { + val process = ProcessBuilder("reg.exe", "add", key, "/v", value, "/t", "REG_BINARY", "/d", hex, "/f") + .redirectOutput(ProcessBuilder.Redirect.DISCARD).redirectError(ProcessBuilder.Redirect.DISCARD).start() + if (!process.waitFor(8, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly() + throw IOException("Could not store the Warcraft III sign-in.") + } + } + + private fun readCommand(vararg command: String): List { + val process = ProcessBuilder(*command).redirectError(ProcessBuilder.Redirect.DISCARD).start() + if (!process.waitFor(8, TimeUnit.SECONDS)) { + process.destroyForcibly() + throw IOException("Windows registry query timed out.") + } + return process.inputReader().use { it.readLines() } + } + } +} diff --git a/src/main/kotlin/file/SetupApp.kt b/src/main/kotlin/file/SetupApp.kt index 4625c0b..d2e520d 100644 --- a/src/main/kotlin/file/SetupApp.kt +++ b/src/main/kotlin/file/SetupApp.kt @@ -1202,7 +1202,9 @@ object SetupApp { private const val HOT_RELOAD_SESSION_CLASS = "de.peeeq.wurstio.languageserver.requests.LuaHotReloadSession" /** Starts Warcraft III with a built map; replaced in tests, which must never launch the game. */ - internal var launchMap: (Wc3ClientDetector.ClientInfo, Path) -> Unit = Wc3MapRunner::launch + internal var launchMap: (Wc3ClientDetector.ClientInfo, Path) -> Unit = { client, map -> + Wc3MapRunner.launch(client, map, WurstProjectConfig.configuredLaunchMode(setup.projectRoot), ::detail) + } /** What `run --hot` built with, so that `reload` builds the same script. */ private fun hotRunRecord(): Path = compilerOutputDir().resolve("hot-run.properties") diff --git a/src/main/kotlin/file/Wc3MapRunner.kt b/src/main/kotlin/file/Wc3MapRunner.kt index 77f95be..5774e42 100644 --- a/src/main/kotlin/file/Wc3MapRunner.kt +++ b/src/main/kotlin/file/Wc3MapRunner.kt @@ -2,6 +2,7 @@ package file import config.WurstProjectConfig import config.WurstProjectConfigData +import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths @@ -89,12 +90,87 @@ internal object Wc3MapRunner { } } - fun launch(client: Wc3ClientDetector.ClientInfo, map: Path) { + /** + * Starts Warcraft III on [map]. A Reforged client managed by Battle.net first has its sign-in renewed from the app + * (see [BattleNetSignIn]), and this returns once that client has signed in, so the shared lock covers it. + */ + fun launch(client: Wc3ClientDetector.ClientInfo, map: Path, launchMode: String = "auto", report: (String) -> Unit = {}) { val launchMap = stageMap(client, map) - ProcessBuilder(launchCommand(client, launchMap)) - .directory(client.root.toFile()) - .redirectOutput(ProcessBuilder.Redirect.DISCARD) - .redirectError(ProcessBuilder.Redirect.DISCARD) - .start() + val command = launchCommand(client, launchMap) + val renewal = renewSignIn(client, command, launchMode, report) + try { + ProcessBuilder(command) + .directory(client.root.toFile()) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start() + } catch (e: Exception) { + renewal?.close() + throw e + } + if (renewal != null) awaitSignIn(renewal, report) + } + + /** + * Holds the Battle.net lock until the launched client has signed in. The map is running by now, so nothing here + * may throw: callers treat an exception from a launch as a failed launch and roll back, as `grill run --hot` does + * with its session. A sign-in that cannot be watched is reported and the lock released. + */ + internal fun awaitSignIn(renewal: BattleNetSignIn.Renewal, report: (String) -> Unit) { + report("Waiting for Warcraft III to sign in...") + try { + if (!renewal.awaitSignIn()) { + report("Warcraft III did not sign in within ${BattleNetSignIn.SIGN_IN_TIMEOUT_SECONDS} s.") + } + } catch (e: InterruptedException) { + Thread.currentThread().interrupt() + } catch (e: Exception) { + report("Could not watch the Warcraft III sign-in (${e.message}); released the Battle.net lock.") + } finally { + renewal.close() + } + } + + /** + * `-editor` launches sign in with a stored token that lapses, after which the game asks for a login. + * [launchMode] is the VS Code setting `wurst.wc3LaunchMode`, as for the language server's Run Map: "auto" renews + * when Battle.net is open and otherwise launches on the stored token, "battlenet" fails the launch when it cannot + * renew, "legacy" never renews. + * + * @return the renewal holding the Battle.net lock, or null when there is none + */ + internal fun renewSignIn(client: Wc3ClientDetector.ClientInfo, command: List, launchMode: String, + report: (String) -> Unit, + find: () -> BattleNetApp? = BattleNetSignIn::find, + registered: (Path) -> Boolean = BattleNetSignIn::isRegisteredGame, + osName: String = System.getProperty("os.name")): BattleNetSignIn.Renewal? { + // The token lives in the Windows registry; other systems launch as before. + if (launchMode == "legacy" || "-editor" !in command || !osName.startsWith("Windows", ignoreCase = true)) return null + val battleNet = find() ?: return failOrNull(launchMode, "Battle.net was not found.", report) + val managed = try { + registered(client.executable) + } catch (e: IOException) { + false + } + if (!managed) return failOrNull(launchMode, "This Warcraft III install is not the one Battle.net manages.", report) + if (launchMode != "battlenet" && !battleNet.isRunning()) { + report("Battle.net is not running: launching with the stored sign-in, which may ask for a login.") + return null + } + report("Renewing the Warcraft III sign-in from Battle.net...") + return try { + battleNet.renew { report("Another Warcraft III launch is signing in; waiting until it has...") } + } catch (e: BattleNetSignIn.LockBusyException) { + // In every mode: launching without the lock could spend the other client's unread token. + throw IllegalStateException("${e.message} Run the map again once it has signed in.", e) + } catch (e: IOException) { + failOrNull(launchMode, "Could not renew the Warcraft III sign-in: ${e.message}", report) + } + } + + private fun failOrNull(launchMode: String, problem: String, report: (String) -> Unit): BattleNetSignIn.Renewal? { + if (launchMode == "battlenet") throw IllegalStateException("$problem (wurst.wc3LaunchMode is \"battlenet\")") + report("$problem Warcraft III may ask for a login.") + return null } } diff --git a/src/main/resources/battlenet-window.ps1 b/src/main/resources/battlenet-window.ps1 new file mode 100644 index 0000000..867886b --- /dev/null +++ b/src/main/resources/battlenet-window.ps1 @@ -0,0 +1,235 @@ +# Keeps the Battle.net app's window out of sight while a sign-in renewal asks it to start Warcraft III. +# +# Asked to start a game, the app creates its window and shows it in front, and depending on its "when I launch a game" +# setting leaves it there. Started just before the renewal, this hooks window creation: each new top-level app window +# is moved off-screen as it is created, so it is shown out of sight, and then minimized without being activated. Its +# restore position is set back to where the app put it, so the user's own next Restore opens it normally. An app window +# that was already open is minimized too if it takes the foreground, and left alone otherwise. With -FocusGame it brings +# the map's Warcraft III client to the front once that has a window: a client that started after this script and not +# from the app, so never the user's own game or the renewal's short-lived one. +# +# The app shows its window again as the map's client signs in, so the watcher ends $GameSeconds after that client +# (one that started after this script and not from the app) appears, or at $Seconds if none does. Until that client +# appears, a new crash reporter (BlizzardError.exe) of the renewal's closed client is closed; any other is left alone. +# +# Prints "ready" once it has noted the windows already open, so the caller can ask the app only then; with -Log also +# one line per action. WurstSetup embeds a copy; keep it self-contained. +param([int]$Seconds = 20, [int]$GameSeconds = 60, [switch]$FocusGame, [switch]$Log) +$ErrorActionPreference = "Stop" +Add-Type @" +using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; +public static class BattleNetWindow { + delegate bool EnumProc(IntPtr h, IntPtr p); + delegate void WinEventProc(IntPtr hook, uint ev, IntPtr hwnd, int idObject, int idChild, uint thread, uint time); + [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc f, IntPtr p); + [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); + [DllImport("user32.dll")] static extern bool IsWindow(IntPtr h); + [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); + [DllImport("user32.dll")] static extern bool IsIconic(IntPtr h); + [DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr h, uint cmd); + [DllImport("user32.dll")] static extern IntPtr GetAncestor(IntPtr h, uint flags); + [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr h, int cmd); + [DllImport("user32.dll")] static extern bool ShowWindowAsync(IntPtr h, int cmd); + [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags); + [DllImport("user32.dll")] static extern bool GetWindowPlacement(IntPtr h, ref WINDOWPLACEMENT p); + [DllImport("user32.dll")] static extern bool SetWindowPlacement(IntPtr h, ref WINDOWPLACEMENT p); + [DllImport("user32.dll")] static extern IntPtr SetWinEventHook(uint min, uint max, IntPtr mod, WinEventProc proc, uint pid, uint tid, uint flags); + [DllImport("user32.dll")] static extern bool UnhookWinEvent(IntPtr hook); + [DllImport("user32.dll")] static extern uint MsgWaitForMultipleObjects(uint n, IntPtr[] h, bool all, uint ms, uint mask); + [DllImport("user32.dll")] static extern bool PeekMessage(out MSG m, IntPtr h, uint min, uint max, uint remove); + [DllImport("user32.dll")] static extern bool TranslateMessage(ref MSG m); + [DllImport("user32.dll")] static extern IntPtr DispatchMessage(ref MSG m); + [DllImport("kernel32.dll")] static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint pid); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern bool Process32FirstW(IntPtr snap, ref PROCESSENTRY32 e); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern bool Process32NextW(IntPtr snap, ref PROCESSENTRY32 e); + [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h); + [StructLayout(LayoutKind.Sequential)] struct RECT { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] struct POINT { public int X, Y; } + [StructLayout(LayoutKind.Sequential)] struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam, lParam; public uint time; public POINT pt; } + [StructLayout(LayoutKind.Sequential)] struct WINDOWPLACEMENT { public int length, flags, showCmd; public POINT min, max; public RECT normal; } + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct PROCESSENTRY32 { + public uint dwSize, cntUsage, th32ProcessID; public IntPtr th32DefaultHeapID; public uint th32ModuleID, cntThreads, + th32ParentProcessID; public int pcPriClassBase; public uint dwFlags; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szExeFile; } + + const uint EVENT_CREATE = 0x8000, EVENT_SHOW = 0x8002, EVENT_LOCATION = 0x800B; + const uint SWP_MOVE_ONLY = 0x0001 | 0x0004 | 0x0010; // NOSIZE | NOZORDER | NOACTIVATE + const int OFF_SCREEN = -32000; + static readonly Stopwatch watch = new Stopwatch(); + static readonly Dictionary moved = new Dictionary(); + static readonly HashSet handled = new HashSet(); + static HashSet background = new HashSet(); + static HashSet appPids = new HashSet(); + static readonly HashSet notOurGame = new HashSet(); + static readonly HashSet oldReporters = new HashSet(); + static readonly HashSet earlierGames = new HashSet(); + static readonly HashSet renewalClients = new HashSet(); + static bool log; + static WinEventProc callback; + + static void Note(string s) { if (log) Console.WriteLine("{0} {1:N2}", s, watch.Elapsed.TotalSeconds); } + + static Dictionary Processes() { + var all = new Dictionary(); + IntPtr snap = CreateToolhelp32Snapshot(2, 0); + if (snap == new IntPtr(-1)) return all; + try { + var e = new PROCESSENTRY32(); e.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32)); + for (bool ok = Process32FirstW(snap, ref e); ok; ok = Process32NextW(snap, ref e)) all[e.th32ProcessID] = e; + } finally { CloseHandle(snap); } + return all; + } + + static HashSet Pids(Dictionary all, string exe) { + var pids = new HashSet(); + foreach (var e in all.Values) if (string.Equals(e.szExeFile, exe, StringComparison.OrdinalIgnoreCase)) pids.Add(e.th32ProcessID); + return pids; + } + + // Visible, not minimized, unowned top-level windows of the given processes. + static List Shown(HashSet pids) { + var found = new List(); + EnumWindows((h, p) => { + uint pid; GetWindowThreadProcessId(h, out pid); + if (pids.Contains(pid) && IsWindowVisible(h) && !IsIconic(h) && GetWindow(h, 4) == IntPtr.Zero) found.Add(h); + return true; + }, IntPtr.Zero); + return found; + } + + static bool AppWindow(IntPtr h) { + uint pid; GetWindowThreadProcessId(h, out pid); + return appPids.Contains(pid) && GetAncestor(h, 2) == h && GetWindow(h, 4) == IntPtr.Zero; + } + + // Minimizes without activating; the window holding the foreground is minimized normally, which hands it on. + static void Minimize(IntPtr h, string why) { + bool foreground = GetForegroundWindow() == h; + ShowWindow(h, foreground ? 6 : 7); + handled.Add(h); + RECT original; + if (moved.TryGetValue(h, out original) && original.Right > original.Left) { + var p = new WINDOWPLACEMENT(); p.length = Marshal.SizeOf(p); + if (GetWindowPlacement(h, ref p)) { p.normal = original; p.showCmd = 7; SetWindowPlacement(h, ref p); } + } + Note("minimized " + why); + } + + static void OnEvent(IntPtr hook, uint ev, IntPtr h, int idObject, int idChild, uint thread, uint time) { + if (idObject != 0 || idChild != 0 || h == IntPtr.Zero || !AppWindow(h)) return; + RECT r; GetWindowRect(h, out r); + bool onScreen = r.Left > OFF_SCREEN / 2; + if (ev == EVENT_CREATE) { + if (!moved.ContainsKey(h)) { + moved[h] = r; + SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); + } + return; + } + if (!IsWindowVisible(h)) { + // Not shown yet: the app may put it back where it last was; keep it off-screen and remember that as its place. + if (ev == EVENT_LOCATION && moved.ContainsKey(h) && !handled.Contains(h) && onScreen) { + moved[h] = r; + SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); + } + return; + } + if (IsIconic(h)) return; + // Shown, or restored, in the open: unless it is a window the user had open in the background, move it out of + // sight at once and minimize it. Its restore position stays the one the app first gave it. + if (background.Contains(h) && GetForegroundWindow() != h) return; + if (onScreen) { + if (!moved.ContainsKey(h)) moved[h] = r; + SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); + } + Minimize(h, ev == EVENT_SHOW ? "shown window" : "restored window"); + } + + public static void Prepare(bool logActions) { + log = logActions; + var all = Processes(); + appPids = Pids(all, "Battle.net.exe"); + foreach (uint pid in Pids(all, "Warcraft III.exe")) { notOurGame.Add(pid); earlierGames.Add(pid); } + foreach (uint pid in Pids(all, "BlizzardError.exe")) oldReporters.Add(pid); + IntPtr foreground = GetForegroundWindow(); + background = new HashSet(Shown(appPids)); + background.Remove(foreground); + } + + public static void Run(int seconds, int gameSeconds, bool focusGame) { + watch.Start(); + callback = OnEvent; + IntPtr hook = SetWinEventHook(EVENT_CREATE, EVENT_LOCATION, IntPtr.Zero, callback, 0, 0, 0); + bool focused = !focusGame; + long lastScan = -1000; + double gameSeenAt = -1; + try { + // The app shows its window again as the map's client signs in, so watch until that client has run a while. + while (watch.Elapsed.TotalSeconds < seconds && (gameSeenAt < 0 || watch.Elapsed.TotalSeconds - gameSeenAt < gameSeconds)) { + MsgWaitForMultipleObjects(0, null, false, 25, 0x04FF); + MSG m; + while (PeekMessage(out m, IntPtr.Zero, 0, 0, 1)) { TranslateMessage(ref m); DispatchMessage(ref m); } + if (watch.ElapsedMilliseconds - lastScan < 50) continue; + lastScan = watch.ElapsedMilliseconds; + var all = Processes(); + appPids = Pids(all, "Battle.net.exe"); + IntPtr foreground = GetForegroundWindow(); + // An app window that was open already, or one the hook missed: minimize it if it is in the way. + foreach (IntPtr h in Shown(appPids)) { + if (background.Contains(h) && h != foreground) continue; + Minimize(h, "shown window"); + } + var ours = new HashSet(); + foreach (uint pid in Pids(all, "Warcraft III.exe")) { + if (notOurGame.Contains(pid)) continue; + PROCESSENTRY32 e; PROCESSENTRY32 parent; + if (all.TryGetValue(pid, out e) && all.TryGetValue(e.th32ParentProcessID, out parent) + && string.Equals(parent.szExeFile, "Battle.net.exe", StringComparison.OrdinalIgnoreCase)) { + notOurGame.Add(pid); + renewalClients.Add(pid); + continue; + } + ours.Add(pid); + } + if (ours.Count > 0 && gameSeenAt < 0) gameSeenAt = watch.Elapsed.TotalSeconds; + if (gameSeenAt < 0) { + // A new crash reporter for the renewal's closed client: its parent is that client, or (seen too briefly to be + // noted) a process already gone that was not one of the games running before. Any other reporter is left alone. + foreach (uint pid in Pids(all, "BlizzardError.exe")) { + if (oldReporters.Contains(pid)) continue; + oldReporters.Add(pid); + PROCESSENTRY32 reporter; + if (!all.TryGetValue(pid, out reporter)) continue; + uint parentPid = reporter.th32ParentProcessID; + bool renewals = renewalClients.Contains(parentPid) || (!all.ContainsKey(parentPid) && !earlierGames.Contains(parentPid)); + if (!renewals) continue; + try { Process.GetProcessById((int)pid).Kill(); Note("closed crash reporter"); } catch (Exception) { } + } + } + if (!focused) { + var game = Shown(ours); + if (game.Count > 0) { + if (!game.Contains(foreground)) SetForegroundWindow(game[0]); + focused = true; + Note("focused"); + } + } + } + } finally { + UnhookWinEvent(hook); + // Windows the app created but never showed go back where it put them. + foreach (var entry in moved) { + if (!handled.Contains(entry.Key) && IsWindow(entry.Key)) { + SetWindowPos(entry.Key, IntPtr.Zero, entry.Value.Left, entry.Value.Top, 0, 0, SWP_MOVE_ONLY); + } + } + } + } +} +"@ +[BattleNetWindow]::Prepare([bool]$Log) +"ready" +[BattleNetWindow]::Run($Seconds, $GameSeconds, [bool]$FocusGame) diff --git a/src/test/kotlin/BattleNetSignInTests.kt b/src/test/kotlin/BattleNetSignInTests.kt new file mode 100644 index 0000000..151dab5 --- /dev/null +++ b/src/test/kotlin/BattleNetSignInTests.kt @@ -0,0 +1,159 @@ +import config.WurstProjectConfig +import file.BattleNetApp +import file.BattleNetSignIn +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import file.Wc3ClientDetector +import file.Wc3MapRunner +import org.testng.Assert +import org.testng.SkipException +import org.testng.annotations.Test +import java.nio.file.Files +import java.nio.file.Paths + +class BattleNetSignInTests { + private fun reforgedClient(): Wc3ClientDetector.ClientInfo { + val root = Files.createTempDirectory("grill-battlenet-client") + Files.writeString(Files.createDirectories(root.resolve("_retail_/x86_64")).resolve("Warcraft III.exe"), "") + return Wc3ClientDetector.inspectGameRoot(root)!! + } + + private val editorLaunch = listOf("Warcraft III.exe", "-launch", "-editor", "-windowmode", "windowed", "-loadfile", "map.w3x") + + @Test + fun readsOnlyTheRequestedBinaryValueFromRegQuery() { + val output = listOf( + "", + "HKEY_CURRENT_USER\\Software\\Blizzard Entertainment\\Battle.net\\Launch Options\\W3", + " WEB_TOKEN REG_BINARY 01000000d08c9ddf", + " LOCALE REG_SZ enUS", + "") + Assert.assertEquals(BattleNetSignIn.parseBinary(output, "WEB_TOKEN"), "01000000D08C9DDF") + Assert.assertEquals(BattleNetSignIn.parseBinary(output, "web_token"), "01000000D08C9DDF") + Assert.assertNull(BattleNetSignIn.parseBinary(output, "LOCALE")) + Assert.assertNull(BattleNetSignIn.parseBinary( + listOf("ERROR: The system was unable to find the specified registry key or value."), "WEB_TOKEN")) + } + + @Test + fun takesTheSameLockAsTheE2eHarnessAndWurstScript() { + if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) throw SkipException("Windows paths") + // wc3-e2e-harness node/src/runner/battlenet.cjs: 33000 + sha256(lower-cased path) as uint32 BE % 10000 + Assert.assertEquals(BattleNetSignIn.gatePort(Paths.get("C:\\Users\\tester\\AppData\\Roaming\\Battle.net\\Battle.net.config")), 36941) + } + + @Test + fun theWindowWatcherShipsAndRunsFromAFileNamedByItsContent() { + val dir = Files.createTempDirectory("grill-window-watcher") + val command = BattleNetSignIn.windowWatcherCommand(listOf("-Seconds", "30", "-FocusGame"), dir)!! + Assert.assertEquals(command.subList(0, 6), + listOf("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File")) + Assert.assertEquals(command.subList(7, command.size), listOf("-Seconds", "30", "-FocusGame")) + val file = Paths.get(command[6]) + Assert.assertEquals(file.parent, dir) + val script = Files.readString(file) + Assert.assertTrue(script.contains("param([int]\$Seconds = 20, [int]\$GameSeconds = 60, [switch]\$FocusGame, [switch]\$Log)")) + Assert.assertTrue(script.contains("\"ready\""), "the caller waits for this line") + Assert.assertTrue(script.all { it.code < 128 }, "Windows PowerShell reads a .ps1 without BOM as ANSI") + // A second call reuses the same file. + Assert.assertEquals(BattleNetSignIn.windowWatcherCommand(listOf(), dir)!![6], command[6]) + } + + @Test + fun legacyModeAndOtherSystemsNeverAskBattleNet() { + val client = reforgedClient() + val reports = mutableListOf() + val find: () -> BattleNetSignIn? = { throw AssertionError("Battle.net must not be asked") } + Assert.assertNull(Wc3MapRunner.renewSignIn(client, editorLaunch, "legacy", reports::add, find, { true }, "Windows 11")) + Assert.assertNull(Wc3MapRunner.renewSignIn(client, editorLaunch, "auto", reports::add, find, { true }, "Mac OS X")) + Assert.assertNull(Wc3MapRunner.renewSignIn(client, editorLaunch, "battlenet", reports::add, find, { true }, "Linux")) + Assert.assertNull(Wc3MapRunner.renewSignIn(client, listOf("war3.exe", "-window", "-loadfile", "map.w3x"), "auto", + reports::add, find, { true }, "Windows 11"), "a classic launch has no -editor sign-in to renew") + Assert.assertEquals(reports, emptyList()) + } + + @Test + fun autoModeLaunchesOnTheStoredSignInWhenBattleNetIsMissing() { + val reports = mutableListOf() + Assert.assertNull(Wc3MapRunner.renewSignIn(reforgedClient(), editorLaunch, "auto", reports::add, { null }, { true }, "Windows 11")) + Assert.assertEquals(reports.size, 1) + Assert.assertTrue(reports[0].contains("may ask for a login"), reports[0]) + } + + @Test + fun aRenewalLockHeldElsewhereIsReportedAsBusy() { + if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) throw SkipException("Windows only") + val config = Files.createTempDirectory("grill-battlenet-lock").resolve("Battle.net.config") + ServerSocket().use { holder -> + holder.bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), BattleNetSignIn.gatePort(config))) + var waited = false + try { + BattleNetSignIn.forTest(config).renew(gateWaitSeconds = 1, onWait = { waited = true }) + Assert.fail("the lock is held elsewhere") + } catch (e: BattleNetSignIn.LockBusyException) { + Assert.assertTrue(waited, "the user is told why the launch waits") + } + } + } + + @Test(expectedExceptions = [IllegalStateException::class]) + fun aBusyRenewalLockStopsTheLaunchEvenInAutoMode() { + // Launching without the lock could spend the token another tool's client has not read yet. + val busy = object : BattleNetApp { + override fun isRunning() = true + override fun renew(onWait: () -> Unit): BattleNetSignIn.Renewal = + throw BattleNetSignIn.LockBusyException("another launch is signing in") + } + Wc3MapRunner.renewSignIn(reforgedClient(), editorLaunch, "auto", {}, { busy }, { true }, "Windows 11") + } + + @Test + fun aSignInThatCannotBeWatchedNeitherFailsTheLaunchNorKeepsTheLock() { + // The map runs by now: an exception would make `grill run --hot` roll back a session the new map uses. + val gate = ServerSocket().apply { bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), 0)) } + val renewal = BattleNetSignIn.Renewal(gate, "TOKEN", { throw java.io.IOException("registry query timed out") }, 1) + val reports = mutableListOf() + + Wc3MapRunner.awaitSignIn(renewal, reports::add) + + Assert.assertTrue(gate.isClosed, "the lock is released") + Assert.assertTrue(reports.last().contains("registry query timed out"), reports.toString()) + } + + @Test + fun theLauncherWindowWatcherOutlivesASlowRenewalAndTheSignInAfterIt() { + // The renewal asks the app again every 25 s for up to 90 s, and the app shows its window once more as the + // launched client signs in (up to 120 s); each can bring its window back. + Assert.assertTrue(BattleNetSignIn.WINDOW_WATCH_SECONDS >= 90 + BattleNetSignIn.SIGN_IN_TIMEOUT_SECONDS, + "${BattleNetSignIn.WINDOW_WATCH_SECONDS} s") + } + + @Test + fun aSignInIsAwaitedUntilTheClientReplacesTheToken() { + val gate = ServerSocket().apply { bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), 0)) } + val reads = mutableListOf("TOKEN", "TOKEN", "NEW") + val renewal = BattleNetSignIn.Renewal(gate, "TOKEN", { reads.removeAt(0) }, 1) + val reports = mutableListOf() + + Wc3MapRunner.awaitSignIn(renewal, reports::add) + + Assert.assertTrue(reads.isEmpty(), "polled until the token changed") + Assert.assertTrue(gate.isClosed) + Assert.assertEquals(reports, listOf("Waiting for Warcraft III to sign in...")) + } + + @Test + fun anInvalidConfiguredPathFallsBackToDetection() { + if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) throw SkipException("Windows path rules") + val project = Files.createTempDirectory("grill-bad-setting") + Files.writeString(Files.createDirectories(project.resolve(".vscode")).resolve("settings.json"), + """{ "wurst.wc3path": "C:\\Games\\War