Play Windows games on Apple Silicon Macs. Free, open-source app that installs the official Battle.net, Steam, Epic and GOG launchers and lists your games in one library.
HTML apple-siliconbattle-netcrossover-alternatived3dmetaldiablo-ii-resurrecteddxmtea-appepic-gamesgame-porting-toolkitgogmac-gamingmacosmacos-gamingrockstar-gamessteamubisoft-connectwhisky-alternativewindows-gameswinewine-wrapper
Finish a stalled Battle.net setup through the agent (#61)
Mikek7d821c89379a
diff --git a/scripts/bnet-agent-install.js b/scripts/bnet-agent-install.jsnew file mode 100644index 00000000000..590bacfdd3c--- /dev/null+++ b/scripts/bnet-agent-install.js@@ -0,0 +1,46 @@+// Ask the Battle.net Agent to install the Battle.net app, the way Blizzard's+// setup does. create-bottle.sh runs this under Wine's cscript when the setup+// stalls at 45% (issue #60).+// Usage: cscript //nologo bnet-agent-install.js <agent port> <install dir>+//+// The agent only answers clients running inside the bottle (curl from macOS+// gets 401), hence JScript + WinHttp instead of curl.+var args = WScript.Arguments, port = args(0), dir = args(1).replace(/\\/g, "/"), token = "";++function call(method, path, body) {+ var r = new ActiveXObject("WinHttp.WinHttpRequest.5.1");+ r.SetTimeouts(5000, 5000, 30000, 30000); // resolve, connect, send, receive (ms)+ r.Open(method, "http://127.0.0.1:" + port + path, false);+ r.SetRequestHeader("User-Agent", "phoenix-agent/1.0");+ if (token) r.SetRequestHeader("Authorization", token);+ r.Send(body || "");+ if (r.Status < 200 || r.Status > 299) throw new Error(method + " " + path + ": HTTP " + r.Status + " " + r.ResponseText);+ return r.ResponseText;+}++function main() {+ var auth = /"authorization"\s*:\s*"([^"]+)"/.exec(call("GET", "/agent"));+ if (!auth) throw new Error("the agent returned no authorization token");+ token = auth[1];+ call("POST", "/install", '{"instructions_patch_url":"http://us.patch.battle.net:1119/bna",' ++ '"instructions_product":"NGDP","monitor_pid":12345,' ++ '"priority":{"insert_at_head":true,"value":900},"uid":"battle.net"}');+ call("POST", "/install/battle.net", '{"account_country":"USA","finalized":true,"game_dir":"' + dir + '",' ++ '"geo_ip_country":"US","language":["enus"],"selected_asset_locale":"enus",' ++ '"selected_locale":"enus","shortcut":"all","tome_torrent":""}');+ for (var i = 0; i < 450; i++) { // 15 minutes+ var state = call("GET", "/install/battle.net");+ if (/"download_complete"\s*:\s*true/.test(state)) return 0;+ var progress = /"progress"\s*:\s*([0-9.]+)/.exec(state);+ if (progress && parseFloat(progress[1]) >= 1) return 0;+ WScript.Sleep(2000);+ }+ throw new Error("the install did not finish in 15 minutes");+}++try {+ WScript.Quit(main());+} catch (e) {+ WScript.Echo(" Agent install: " + e.message);+ WScript.Quit(1);+}diff --git a/scripts/create-bottle.sh b/scripts/create-bottle.shindex 20513465f23..037781c1810 100755--- a/scripts/create-bottle.sh+++ b/scripts/create-bottle.sh@@ -14,6 +14,7 @@ export DYLD_FALLBACK_LIBRARY_PATH="$ENGINE/lib:/usr/lib"[ -x "$ENGINE/bin/wine" ] || { echo "Engine not found, run build-engine.sh first"; exit 1; }[ -f "$CX_APPLEGPTK_LIBD3DSHARED_PATH" ] || { echo "libd3dshared not found, run get-gptk.sh first"; exit 1; }+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"WORK="${WORK:-$HOME/.battlenet-macos/build}"; mkdir -p "$WORK"echo "==> Initializing the prefix: $WINEPREFIX"@@ -36,7 +37,7 @@ doneBN="$WINEPREFIX/drive_c/Program Files (x86)/Battle.net"PROGRAMDATA="$WINEPREFIX/drive_c/ProgramData"SETUP="$WORK/Battle.net-Setup.exe"-SETUP_TIMEOUT="${SETUP_TIMEOUT:-600}"+SETUP_TIMEOUT="${SETUP_TIMEOUT:-300}"download_setup() {[ -f "$SETUP" ] || { curl -fL "https://downloader.battle.net/download/getInstaller?os=win&installer=Battle.net-Setup.exe" -o "$SETUP.part" && mv -f "$SETUP.part" "$SETUP"; }@@ -74,6 +75,50 @@ run_setup() {wait "$pid" 2>/dev/null || true}+# The Battle.net Agent's local HTTP port. Only the agent listens inside the+# bottle at this point; the bottle's wineserver (found by its working directory,+# named after the prefix's device and inode) holds the socket.+agent_port() {+ local dir pid real+ # Wine names the directory after the resolved prefix (see soju-reaper.sh)+ real=$(cd "$WINEPREFIX" && pwd -P)+ dir=$(printf 'server-%x-%x' $(stat -L -f '%d %i' "$real"))+ for pid in $(pgrep -x wineserver); do+ lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | grep -q "/$dir\$" || continue+ lsof -nP -a -p "$pid" -iTCP -sTCP:LISTEN -Fn 2>/dev/null | sed -n 's/^n.*://p' | head -1+ return+ done+}++# Agent 2.41 (Oct 2026) never queues the app install when the setup drives it+# under Wine: the setup sits at 45% forever (issue #60). The agent it unpacked+# installs the app when asked directly through its local API, the same calls+# the setup makes (scripts/bnet-agent-install.js).+install_via_agent() {+ local agents agent port i+ agents="$PROGRAMDATA/Battle.net/Agent"+ agent=$(cd "$agents" 2>/dev/null && ls -d Agent.[0-9]* 2>/dev/null | sort -t. -k2 -n | tail -1)+ [ -n "$agent" ] && [ -f "$agents/$agent/Agent.exe" ] || return 1+ echo " Finishing the install through the Battle.net Agent ($agent)"+ "$ENGINE/bin/wine" "C:\\ProgramData\\Battle.net\\Agent\\$agent\\Agent.exe" --internalclienttools >/dev/null 2>&1 &+ port=""+ for i in $(seq 1 60); do+ sleep 1; port=$(agent_port)+ [ -z "$port" ] || break+ done+ [ -n "$port" ] || { echo " The agent did not open its port"; "$ENGINE/bin/wineserver" -k 2>/dev/null || true; return 1; }+ local js="$SCRIPT_DIR/bnet-agent-install.js"+ # Battle.net.exe can land a moment after the agent reports the download done+ if "$ENGINE/bin/wine" cscript //nologo "Z:${js//\//\\}" "$port" "C:\\Program Files (x86)\\Battle.net"; then+ for i in $(seq 1 30); do+ [ ! -f "$BN/Battle.net.exe" ] || break+ sleep 2+ done+ fi+ "$ENGINE/bin/wineserver" -k 2>/dev/null || true+ [ -f "$BN/Battle.net.exe" ]+}+echo "==> Downloading the Battle.net installer (official Blizzard)"download_setupset_aside_setup_state@@ -81,11 +126,13 @@ set_aside_setup_stateecho "==> Running the installer (a few minutes, fully automatic)"if ! run_setup; thenecho "==> The installer did not finish in $(( (SETUP_TIMEOUT + 59) / 60 )) minutes (Battle.net setup can stall at 45%)."- echo " Retrying once from a clean state with a fresh installer download"- set_aside_setup_state- rm -f "$SETUP"- download_setup- run_setup || { echo "The installer stalled again, logs: $PROGRAMDATA/Battle.net/Setup"; exit 1; }+ if ! install_via_agent; then+ echo " Retrying once from a clean state with a fresh installer download"+ set_aside_setup_state+ rm -f "$SETUP"+ download_setup+ run_setup || install_via_agent || { echo "The installer stalled again, logs: $PROGRAMDATA/Battle.net/Setup"; exit 1; }+ fifi# Wait for the install to finish (up to 10 minutes)diff --git a/tests/test_installation.py b/tests/test_installation.pyindex 633978f640e..14a8a049273 100644--- a/tests/test_installation.py+++ b/tests/test_installation.py@@ -152,7 +152,7 @@ class RecoveryTests(unittest.TestCase):self.assertEqual((system/"d3d11.dll").read_text(),"changed")class BattleNetSetupTests(unittest.TestCase):- def install(self, stalls):+ def install(self, stalls, agent_works=True):temp = tempfile.TemporaryDirectory()self.addCleanup(temp.cleanup)d = Path(temp.name); engine = d/"engine"; work = d/"work"; prefix = d/"bottle"; bin_ = d/"bin"@@ -162,40 +162,66 @@ class BattleNetSetupTests(unittest.TestCase):(work/"Battle.net-Setup.exe").write_text("cached installer")stale = prefix/"drive_c/ProgramData/Battle.net/Agent"stale.mkdir(parents=True); (stale/"state").write_text("unfinished")+ bn = '"$WINEPREFIX/drive_c/Program Files (x86)/Battle.net"'tools = {engine/"bin/wineserver": "exit 0\n",- engine/"bin/wine": f"""case "$1" in wineboot|reg) exit 0;; esac+ engine/"bin/wine": f"""echo "$*" >> "{d}/wine.log"+case "$1" in+ wineboot|reg) exit 0;;+ *Agent.exe) exit 0;;+ cscript) {"mkdir -p " + bn + " && touch " + bn + "/Battle.net.exe" if agent_works else "exit 1"}; exit 0;;+esacn=$(( $(cat "{d}/attempts" 2>/dev/null || echo 0) + 1 )); echo $n > "{d}/attempts"-mkdir -p "$WINEPREFIX/drive_c/ProgramData/Battle.net/Setup"+mkdir -p "$WINEPREFIX/drive_c/ProgramData/Battle.net/Setup" "$WINEPREFIX/drive_c/ProgramData/Battle.net/Agent/Agent.9824"+touch "$WINEPREFIX/drive_c/ProgramData/Battle.net/Agent/Agent.9824/Agent.exe"[ $n -le {stalls} ] && exec sleep 30-mkdir -p "$WINEPREFIX/drive_c/Program Files (x86)/Battle.net"-touch "$WINEPREFIX/drive_c/Program Files (x86)/Battle.net/Battle.net.exe"+mkdir -p {bn}+touch {bn}/Battle.net.exe""",bin_/"curl": f"""while [ $# -gt 0 ]; do [ "$1" = -o ] && out="$2"; shift; doneecho fresh > "$out"; echo x >> "{d}/downloads"+""",+ bin_/"stat": "echo 16777234 245634352\n",+ bin_/"pgrep": "echo 4242\n",+ bin_/"lsof": """case "$*" in+ *cwd*) echo p4242; echo n/tmp/.wine-501/server-1000012-ea41530;;+ *LISTEN*) echo p4242; echo n127.0.0.1:55475;;+esac""",}for path, body in tools.items():path.write_text("#!/bin/bash\n" + body); path.chmod(0o755)result = subprocess.run(["/bin/bash", str(ROOT/"scripts/create-bottle.sh")], capture_output=True, text=True,env={**os.environ, "ENGINE": str(engine), "WORK": str(work), "WINEPREFIX": str(prefix),- "SETUP_TIMEOUT": "1", "PATH": f"{bin_}:{os.environ['PATH']}"}, timeout=60)+ "SETUP_TIMEOUT": "1", "PATH": f"{bin_}:{os.environ['PATH']}"}, timeout=120)attempts = int((d/"attempts").read_text()) if (d/"attempts").exists() else 0downloads = len((d/"downloads").read_text().split()) if (d/"downloads").exists() else 0+ self.wine_log = (d/"wine.log").read_text() if (d/"wine.log").exists() else ""return result, prefix, work, attempts, downloads- def test_stalled_installer_retries_once_from_clean_state(self):+ def test_stalled_installer_is_finished_through_the_agent(self):result, prefix, work, attempts, downloads = self.install(stalls=1)self.assertEqual(result.returncode, 0, result.stdout + result.stderr)self.assertTrue((prefix/"drive_c/Program Files (x86)/Battle.net/Battle.net.exe").exists())+ self.assertEqual((attempts, downloads), (1, 0))+ self.assertIn("through the Battle.net Agent (Agent.9824)", result.stdout)+ self.assertNotIn("Retrying", result.stdout)+ self.assertIn("C:\\ProgramData\\Battle.net\\Agent\\Agent.9824\\Agent.exe --internalclienttools", self.wine_log)+ js = "Z:" + str(ROOT/"scripts/bnet-agent-install.js").replace("/", "\\")+ self.assertIn(f"cscript //nologo {js} 55475 C:\\Program Files (x86)\\Battle.net", self.wine_log)++ def test_stalled_installer_retries_once_from_clean_state_when_the_agent_fails(self):+ result, prefix, work, attempts, downloads = self.install(stalls=1, agent_works=False)+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertTrue((prefix/"drive_c/Program Files (x86)/Battle.net/Battle.net.exe").exists())self.assertEqual((attempts, downloads), (2, 1))self.assertIn("Retrying once", result.stdout)- kept = list(work.glob("previous-setup-*/Battle.net/Agent/state"))- self.assertEqual([p.read_text() for p in kept], ["unfinished"])+ kept = sorted(p.read_text() for p in work.glob("previous-setup-*/Battle.net/Agent/state"))+ self.assertEqual(kept, ["unfinished"])self.assertEqual((work/"Battle.net-Setup.exe").read_text().strip(), "fresh")def test_installer_that_stalls_twice_fails_instead_of_hanging(self):- result, prefix, work, attempts, downloads = self.install(stalls=2)+ result, prefix, work, attempts, downloads = self.install(stalls=2, agent_works=False)self.assertNotEqual(result.returncode, 0)self.assertIn("stalled again", result.stdout)self.assertEqual(attempts, 2)@@ -206,6 +232,13 @@ echo fresh > "$out"; echo x >> "{d}/downloads"self.assertEqual(result.returncode, 0, result.stdout + result.stderr)self.assertEqual((attempts, downloads), (1, 0))self.assertNotIn("Retrying", result.stdout)+ self.assertNotIn("Agent", result.stdout)++ def test_agent_install_script_makes_the_setup_calls(self):+ js = (ROOT/"scripts/bnet-agent-install.js").read_text()+ for needle in ('"phoenix-agent/1.0"', '"/agent"', '"/install"', '"/install/battle.net"',+ '"finalized":true', 'WinHttp.WinHttpRequest.5.1'):+ self.assertIn(needle, js)class SupportManifestTests(unittest.TestCase):def test_published_manifest_names_one_release(self):