mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 22:05:59 +00:00
feat(stores): add Rockstar store and classic GTA launches
This commit is contained in:
1 parent
9cc37d0a12
commit
b841b232b4
42 files changed
+2708
-22
No files matched your search
@@ -433,6 +433,13 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then
|
||||
CARGO_TARGET_DIR="${cache_dir}/ubisoft-target" bash tools/ubisoft-launcher/build.sh "${upc_out}"
|
||||
save_step ubisoft "${upc_key}" "${upc_out}"
|
||||
fi
|
||||
rockstar_out="${repo_root}/app/src/main/resources/rockstar/helpers"
|
||||
rockstar_key=$(inputs_hash "windows-gnu" tools/rockstar-launcher/src tools/rockstar-launcher/Cargo.toml tools/rockstar-launcher/Cargo.lock tools/rockstar-launcher/build.sh)
|
||||
if ! restore_step rockstar "${rockstar_key}" "${rockstar_out}"; then
|
||||
command -v i686-w64-mingw32-gcc >/dev/null 2>&1 || { echo "i686-w64-mingw32-gcc is required for the Rockstar launcher service." >&2; exit 1; }
|
||||
CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}"
|
||||
save_step rockstar "${rockstar_key}" "${rockstar_out}"
|
||||
fi
|
||||
fi
|
||||
python3 tools/powervr/fetch.py
|
||||
bash tools/packs/build.sh app/build/packs
|
||||
|
||||
@@ -286,6 +286,12 @@ def cloud_on(sidecar):
|
||||
def exited(argv, code=0):
|
||||
found = find_store_game(argv)
|
||||
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
|
||||
if found is not None and launch_dir and str(found[1].get("store")) == "rockstar":
|
||||
ask(Path(launch_dir) / "stores", {"op": "rockstar-exited", "store": "rockstar", "id": str(found[1].get("id"))}, timeout=1.0)
|
||||
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH")
|
||||
if compat_data:
|
||||
(Path(compat_data) / "pfx" / ROCKSTAR_FOLDER / "launch.json").unlink(missing_ok=True)
|
||||
return 0
|
||||
if found is not None and str(found[1].get("store")) == "epic" and os.environ.get(EPIC_HANDLED) != "1" \
|
||||
and os.access(EPIC_CLIENT, os.X_OK):
|
||||
try:
|
||||
@@ -307,6 +313,104 @@ def exited(argv, code=0):
|
||||
UBISOFT_DIR = "drive_c/Program Files (x86)/Ubisoft/Ubisoft Game Launcher"
|
||||
UBISOFT_WINDOWS_DIR = "C:\\Program Files (x86)\\Ubisoft\\Ubisoft Game Launcher\\"
|
||||
UBISOFT_INSTALLER_URL = "https://static3.cdn.ubi.com/orbit/launcher_installer/UbisoftConnectInstaller.exe"
|
||||
ROCKSTAR_SERVICE = Path("/usr/local/lib/droiddeck-rockstar")
|
||||
ROCKSTAR_FOLDER = "drive_c/Program Files/Rockstar Games/Launcher"
|
||||
ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: Vice City", "gtasa": "GTA: San Andreas"}
|
||||
|
||||
|
||||
def rockstar_registry(folder, title, compat_data, proton):
|
||||
pfx = Path(compat_data) / "pfx"
|
||||
launcher = r"C:\Program Files\Rockstar Games\Launcher"
|
||||
values = [(r"Rockstar Games\Launcher", launcher), ("Rockstar Games\\" + title, windows_path(str(folder)))]
|
||||
entries = [("Software\\" + view + key, value) for view in ("", "Wow6432Node\\") for key, value in values]
|
||||
reg = pfx / "system.reg"
|
||||
if all(has_value(reg, "[" + key.replace("\\", "\\\\") + "]", "InstallFolder", value) for key, value in entries):
|
||||
return True
|
||||
if wait_for_server(pfx, 2):
|
||||
return all(set_value(reg, "[" + key.replace("\\", "\\\\") + "]", "InstallFolder", value) for key, value in entries)
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-rockstar-") as temp:
|
||||
path = Path(temp) / "install.reg"
|
||||
text = "Windows Registry Editor Version 5.00\r\n\r\n"
|
||||
text += "\r\n".join('[HKEY_LOCAL_MACHINE\\%s]\r\n"InstallFolder"="%s"\r\n' % (key, reg_escape(value)) for key, value in entries)
|
||||
path.write_text(text, encoding="utf-16")
|
||||
result = subprocess.run([proton, "run", "reg.exe", "import", windows_path(str(path))],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=45)
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def prepare_rockstar(folder, sidecar, compat_data, launch_dir, proton="", ask_app=None):
|
||||
if not compat_data:
|
||||
return "no-prefix"
|
||||
target = Path(compat_data) / "pfx" / ROCKSTAR_FOLDER
|
||||
config = target / "launch.json"
|
||||
config.unlink(missing_ok=True)
|
||||
title = ROCKSTAR_TITLES.get(str(sidecar.get("id")))
|
||||
if not title:
|
||||
return "unsupported-title"
|
||||
if not launch_dir:
|
||||
return "no-channel"
|
||||
root = folder.resolve()
|
||||
exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve()
|
||||
if not exe.is_relative_to(root):
|
||||
return "invalid-game-path"
|
||||
workdir = (folder / str(sidecar["workdir"])).resolve() if sidecar.get("workdir") is not None else exe.parent
|
||||
if not workdir.is_relative_to(root) or not exe.is_file() or not (folder / "MTLX.dll").is_file():
|
||||
return "invalid-game-path"
|
||||
args = sidecar.get("args") or []
|
||||
if not isinstance(args, list) or any(not isinstance(arg, str) or "\0" in arg for arg in args):
|
||||
return "invalid-game-arguments"
|
||||
with exe.open("rb") as source:
|
||||
if source.read(2) != b"MZ":
|
||||
return "invalid-game-exe"
|
||||
source.seek(0x3c)
|
||||
raw = source.read(4)
|
||||
if len(raw) != 4:
|
||||
return "invalid-game-exe"
|
||||
source.seek(int.from_bytes(raw, "little"))
|
||||
signature = source.read(6)
|
||||
if len(signature) != 6 or signature[:4] != b"PE\0\0" or signature[4:] not in (b"\x4c\x01", b"\x64\x86"):
|
||||
return "invalid-game-exe"
|
||||
service = ROCKSTAR_SERVICE / ("Launcher32.exe" if signature[4:] == b"\x4c\x01" else "Launcher64.exe")
|
||||
if not service.is_file():
|
||||
return "no-service"
|
||||
made = "present" if (Path(compat_data) / "pfx/user.reg").is_file() else create_prefix(compat_data, proton)
|
||||
if made not in ("created", "present"):
|
||||
return "prefix-" + made
|
||||
if not rockstar_registry(folder, title, compat_data, proton):
|
||||
return "registry-unavailable"
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.NamedTemporaryFile(prefix="Launcher-", suffix=".exe", dir=target, delete=False) as temporary:
|
||||
temporary_path = Path(temporary.name)
|
||||
try:
|
||||
with service.open("rb") as source:
|
||||
shutil.copyfileobj(source, temporary)
|
||||
except BaseException:
|
||||
temporary_path.unlink(missing_ok=True)
|
||||
raise
|
||||
os.replace(temporary_path, target / "Launcher.exe")
|
||||
answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "rockstar-launch", "store": "rockstar", "id": str(sidecar.get("id"))}, timeout=120.0)
|
||||
if not isinstance(answer, dict) or not answer.get("ok"):
|
||||
return "session-" + (str(answer.get("reason") or "refused") if isinstance(answer, dict) else "timeout")
|
||||
if not isinstance(answer.get("material"), str) or not re.fullmatch(r"[0-9A-Fa-f]{640}", answer["material"]):
|
||||
return "invalid-material"
|
||||
expires = answer.get("expiresAt")
|
||||
if not isinstance(expires, int) or not time.time() * 1000 < expires <= time.time() * 1000 + 120_000:
|
||||
return "invalid-expiry"
|
||||
launch = {"folder": windows_path(str(root)), "exe": windows_path(str(exe)), "workdir": windows_path(str(workdir)),
|
||||
"args": args, "pipe": answer.get("pipe"), "material": answer["material"], "expiresAt": expires}
|
||||
if len(json.dumps(launch).encode("utf-8")) > 16384:
|
||||
return "handoff-too-large"
|
||||
with tempfile.NamedTemporaryFile(mode="w", prefix="launch-", suffix=".json", dir=target, delete=False) as temporary:
|
||||
temporary_path = Path(temporary.name)
|
||||
try:
|
||||
json.dump(launch, temporary)
|
||||
except BaseException:
|
||||
temporary_path.unlink(missing_ok=True)
|
||||
raise
|
||||
os.replace(temporary_path, config)
|
||||
return "ready"
|
||||
|
||||
|
||||
UBISOFT_CACHE = Path("/root/.cache/droiddeck/ubisoft")
|
||||
UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
|
||||
UBISOFT_SERVICE = Path("/usr/local/lib/droiddeck-ubisoft/droiddeck-upc.exe")
|
||||
@@ -1341,6 +1445,15 @@ def main(argv):
|
||||
prepare_gog(sidecar, compat_data, launch_dir)
|
||||
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("BL_STORE_PROTON", "")))
|
||||
log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("BL_STORE_PROTON", "")))
|
||||
if store == "rockstar":
|
||||
try:
|
||||
state = prepare_rockstar(folder, sidecar, compat_data, launch_dir, os.environ.get("BL_STORE_PROTON", ""))
|
||||
except (OSError, ValueError, subprocess.TimeoutExpired):
|
||||
state = "preparation-failed"
|
||||
log("rockstar %s: %s" % (game, state))
|
||||
if state != "ready" and launch_dir:
|
||||
ask(Path(launch_dir) / "stores", {"op": "rockstar-exited", "store": "rockstar", "id": game}, timeout=1.0)
|
||||
return STORE_GAME if state == "ready" else RAN_FAILED
|
||||
if store == "ubisoft":
|
||||
try:
|
||||
log("ubisoft %s: %s" % (game, prepare_ubisoft(folder, sidecar, compat_data, launch_dir, os.environ.get("BL_STORE_PROTON", ""))))
|
||||
|
||||
@@ -23,11 +23,11 @@ PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'po
|
||||
SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst',
|
||||
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio', 'tools/packs',
|
||||
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
|
||||
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh',
|
||||
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh',
|
||||
'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi',
|
||||
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
|
||||
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
|
||||
'tools/gpuload',
|
||||
'tools/gpuload', 'app/src/main/resources/rockstar/legacy-cipher.bin',
|
||||
'app/src/main/cpp/waylandcomp/src/headpose_shm.h',
|
||||
'app/src/main/cpp/venc/venc_proto.h',
|
||||
'app/src/main/cpp/waylandcomp/src/spatialpose_shm.h',
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
/target/
|
||||
Generated
+105
@@ -0,0 +1,105 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "droiddeck-rockstar-launcher"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.26"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "droiddeck-rockstar-launcher"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-only"
|
||||
publish = false
|
||||
|
||||
[[bin]]
|
||||
name = "Launcher"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1"
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -0,0 +1,30 @@
|
||||
# Rockstar launcher service
|
||||
|
||||
`Launcher.exe` starts the selected installed game and serves its launcher pipe. The Android app checks ownership and retrieves the launch response from Rockstar. Account credentials and ROS tickets stay in the app.
|
||||
|
||||
The handoff is deleted before starting the game. It expires after 90 seconds. The pipe accepts the child process's greeting and returns the server-issued launch material. No game files are patched.
|
||||
|
||||
GTA III defaults to full x87 precision for FEX before Wine starts, because reduced precision crashed new-game initialization on the test device. San Andreas defaults to WineD3D, because DXVK intermittently corrupted its textures; full precision and conservative memory ordering did not prevent that corruption. These defaults use DroidDeck's per-game settings and preserve explicit per-game overrides.
|
||||
|
||||
`build.sh` builds 32-bit and 64-bit executables with the GNU Windows targets and stages them as APK resources. `legacy-cipher.bin` contains the fixed client protocol tables, not account credentials or APK signing keys.
|
||||
|
||||
Run the protocol tests with:
|
||||
|
||||
```sh
|
||||
cargo test --locked --manifest-path tools/rockstar-launcher/Cargo.toml
|
||||
```
|
||||
|
||||
The optional `capture` example records a first-party launcher reply to a new local file. Run it on Windows or Wine while launching the corresponding game in Rockstar's launcher:
|
||||
|
||||
```powershell
|
||||
cargo run --release --example capture --manifest-path tools/rockstar-launcher/Cargo.toml -- --pipe GTA-VC_Pipe --output 'C:\captures\reply.bin'
|
||||
```
|
||||
|
||||
On Linux, cross-compile the example and run it in the same Wine prefix as Rockstar's launcher:
|
||||
|
||||
```sh
|
||||
cargo build --release --locked --example capture --target x86_64-pc-windows-gnu --manifest-path tools/rockstar-launcher/Cargo.toml
|
||||
WINEPREFIX=/path/to/launcher-prefix wine tools/rockstar-launcher/target/x86_64-pc-windows-gnu/release/examples/capture.exe --pipe GTA-VC_Pipe --output 'Z:\tmp\reply.bin'
|
||||
```
|
||||
|
||||
Captures contain live launch material. Keep them outside source control; the tool prints only the message tag and payload length.
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
out=${1:-"$here/../../app/src/main/resources/rockstar/helpers"}
|
||||
mkdir -p "$out"
|
||||
for target in i686-pc-windows-gnu x86_64-pc-windows-gnu; do
|
||||
rustup target add "$target" >/dev/null 2>&1 || true
|
||||
cargo build --manifest-path "$here/Cargo.toml" --release --locked --target "$target"
|
||||
name=Launcher64.exe
|
||||
[[ "$target" == i686-* ]] && name=Launcher32.exe
|
||||
install -m644 "${CARGO_TARGET_DIR:-$here/target}/$target/release/Launcher.exe" "$out/$name"
|
||||
done
|
||||
@@ -0,0 +1,65 @@
|
||||
#[cfg(windows)]
|
||||
fn main() -> std::io::Result<()> {
|
||||
use droiddeck_rockstar_launcher::{pipe::Pipe, Frame, Length};
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::time::Duration;
|
||||
|
||||
struct Recording<'a> {
|
||||
source: &'a mut Pipe,
|
||||
output: &'a mut std::fs::File,
|
||||
}
|
||||
|
||||
impl Read for Recording<'_> {
|
||||
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
||||
let size = self.source.read(buffer)?;
|
||||
self.output.write_all(&buffer[..size])?;
|
||||
Ok(size)
|
||||
}
|
||||
}
|
||||
|
||||
let args: Vec<_> = std::env::args_os().collect();
|
||||
let output = args
|
||||
.windows(2)
|
||||
.find(|pair| pair[0] == "--output")
|
||||
.map(|pair| pair[1].clone())
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or(std::env::current_exe()?.with_file_name("reference-reply.bin"));
|
||||
let mut file = OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.open(output)?;
|
||||
let pipe_name = args
|
||||
.windows(2)
|
||||
.find(|pair| pair[0] == "--pipe")
|
||||
.map(|pair| pair[1].to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| "GTA-VC_Pipe".to_owned());
|
||||
let mut pipe = Pipe::connect(&pipe_name, Duration::from_secs(90))?;
|
||||
Frame {
|
||||
tag: *b"COLE",
|
||||
payload: Vec::new(),
|
||||
nul_terminated: true,
|
||||
}
|
||||
.write(&mut pipe, Length::Total)?;
|
||||
let reply = Frame::read(
|
||||
&mut Recording {
|
||||
source: &mut pipe,
|
||||
output: &mut file,
|
||||
},
|
||||
Length::Body,
|
||||
);
|
||||
file.sync_all()?;
|
||||
let reply = reply?;
|
||||
println!(
|
||||
"Received {} ({} payload bytes)",
|
||||
String::from_utf8_lossy(&reply.tag),
|
||||
reply.payload.len()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn main() {
|
||||
eprintln!("The reference pipe client runs on Windows or Wine.");
|
||||
std::process::exit(1);
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
use std::io::{self, Read, Write};
|
||||
|
||||
#[cfg(windows)]
|
||||
pub mod pipe;
|
||||
|
||||
pub const MAX_FRAME_BYTES: usize = 64 * 1024;
|
||||
const OVERHEAD: usize = 4 + 4 + 1;
|
||||
|
||||
pub fn wait_for_game(
|
||||
child: &mut std::process::Child,
|
||||
handshake: std::sync::mpsc::Receiver<io::Result<()>>,
|
||||
) -> io::Result<std::process::ExitStatus> {
|
||||
use std::sync::mpsc::RecvTimeoutError;
|
||||
loop {
|
||||
match handshake.recv_timeout(std::time::Duration::from_millis(10)) {
|
||||
Ok(Ok(())) => return child.wait(),
|
||||
result @ (Ok(Err(_)) | Err(RecvTimeoutError::Disconnected)) => {
|
||||
let error = match result {
|
||||
Ok(Err(error)) => error,
|
||||
_ => io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
"Rockstar handshake worker stopped",
|
||||
),
|
||||
};
|
||||
let _ = child.kill();
|
||||
child.wait()?;
|
||||
return Err(error);
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(status);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Length {
|
||||
Total,
|
||||
Body,
|
||||
}
|
||||
|
||||
impl Length {
|
||||
fn header_bytes(self) -> usize {
|
||||
match self {
|
||||
Self::Total => 0,
|
||||
Self::Body => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Frame {
|
||||
pub tag: [u8; 4],
|
||||
pub payload: Vec<u8>,
|
||||
pub nul_terminated: bool,
|
||||
}
|
||||
|
||||
fn invalid(message: &'static str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, message)
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
pub fn read(reader: &mut impl Read, length: Length) -> io::Result<Self> {
|
||||
let mut header = [0; 4];
|
||||
reader.read_exact(&mut header)?;
|
||||
let size = (u32::from_le_bytes(header) as usize)
|
||||
.checked_add(length.header_bytes())
|
||||
.ok_or_else(|| invalid("invalid Rockstar pipe frame length"))?;
|
||||
if !(OVERHEAD..=MAX_FRAME_BYTES).contains(&size) {
|
||||
return Err(invalid("invalid Rockstar pipe frame length"));
|
||||
}
|
||||
let mut body = vec![0; size - header.len()];
|
||||
reader.read_exact(&mut body)?;
|
||||
let nul_terminated = body.last() == Some(&0);
|
||||
let end = body.len() - usize::from(nul_terminated);
|
||||
if body[4] != b':' || body[..4].contains(&b':') || body[..end].contains(&0) {
|
||||
return Err(invalid("invalid Rockstar pipe frame envelope"));
|
||||
}
|
||||
Ok(Self {
|
||||
tag: body[..4].try_into().unwrap(),
|
||||
payload: body[5..end].to_vec(),
|
||||
nul_terminated,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write(&self, writer: &mut impl Write, length: Length) -> io::Result<()> {
|
||||
let size = self
|
||||
.payload
|
||||
.len()
|
||||
.checked_add(OVERHEAD + usize::from(self.nul_terminated))
|
||||
.filter(|size| *size <= MAX_FRAME_BYTES)
|
||||
.ok_or_else(|| invalid("Rockstar pipe frame exceeds size limit"))?;
|
||||
if self.tag.contains(&0) || self.tag.contains(&b':') || self.payload.contains(&0) {
|
||||
return Err(invalid("Rockstar pipe frame contains a delimiter"));
|
||||
}
|
||||
let mut encoded = Vec::with_capacity(size);
|
||||
encoded.extend_from_slice(&((size - length.header_bytes()) as u32).to_le_bytes());
|
||||
encoded.extend_from_slice(&self.tag);
|
||||
encoded.push(b':');
|
||||
encoded.extend_from_slice(&self.payload);
|
||||
if self.nul_terminated {
|
||||
encoded.push(0);
|
||||
}
|
||||
writer.write_all(&encoded)?;
|
||||
writer.flush()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Cursor;
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn sleeping_game() {
|
||||
std::thread::sleep(std::time::Duration::from_secs(30));
|
||||
}
|
||||
|
||||
fn sleeping_child() -> std::process::Child {
|
||||
std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "tests::sleeping_game", "--ignored"])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_handshake_terminates_and_reaps_the_game() {
|
||||
let mut child = sleeping_child();
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
sender
|
||||
.send(Err(io::Error::new(io::ErrorKind::TimedOut, "test timeout")))
|
||||
.unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
assert_eq!(
|
||||
wait_for_game(&mut child, receiver).unwrap_err().kind(),
|
||||
io::ErrorKind::TimedOut
|
||||
);
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(3));
|
||||
assert!(child.try_wait().unwrap().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopped_handshake_worker_terminates_and_reaps_the_game() {
|
||||
let mut child = sleeping_child();
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
drop(sender);
|
||||
assert_eq!(
|
||||
wait_for_game(&mut child, receiver).unwrap_err().kind(),
|
||||
io::ErrorKind::BrokenPipe
|
||||
);
|
||||
assert!(child.try_wait().unwrap().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exited_game_does_not_wait_for_its_handshake() {
|
||||
let mut child = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "no_test_with_this_name"])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let (_sender, receiver) = std::sync::mpsc::channel();
|
||||
assert!(wait_for_game(&mut child, receiver).unwrap().success());
|
||||
}
|
||||
|
||||
struct Fragmented<T>(T);
|
||||
|
||||
impl<T: Read> Read for Fragmented<T> {
|
||||
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
||||
let size = buffer.len().min(1);
|
||||
self.0.read(&mut buffer[..size])
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Write> Write for Fragmented<T> {
|
||||
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
|
||||
self.0.write(&buffer[..buffer.len().min(1)])
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.0.flush()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_observed_greeting_across_partial_reads() {
|
||||
let bytes = b"\x0a\0\0\0COLE:\0";
|
||||
assert_eq!(
|
||||
Frame::read(&mut Fragmented(&bytes[..]), Length::Total).unwrap(),
|
||||
Frame {
|
||||
tag: *b"COLE",
|
||||
payload: Vec::new(),
|
||||
nul_terminated: true,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_the_observed_total_length_even_with_partial_writes() {
|
||||
let mut bytes = Fragmented(Vec::new());
|
||||
Frame {
|
||||
tag: *b"COLE",
|
||||
payload: Vec::new(),
|
||||
nul_terminated: true,
|
||||
}
|
||||
.write(&mut bytes, Length::Total)
|
||||
.unwrap();
|
||||
assert_eq!(bytes.0, b"\x0a\0\0\0COLE:\0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_colons_in_payload_and_leaves_the_next_frame_unread() {
|
||||
let frame = Frame {
|
||||
tag: *b"DUNN",
|
||||
payload: b"one:two".to_vec(),
|
||||
nul_terminated: false,
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
frame.write(&mut bytes, Length::Total).unwrap();
|
||||
bytes.extend_from_slice(b"\x0a\0\0\0COLE:\0");
|
||||
let mut reader = Cursor::new(bytes);
|
||||
assert_eq!(Frame::read(&mut reader, Length::Total).unwrap(), frame);
|
||||
assert_eq!(
|
||||
Frame::read(&mut reader, Length::Total).unwrap().tag,
|
||||
*b"COLE"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_lengths_before_reading_a_body() {
|
||||
for size in [0u32, 4, 8, MAX_FRAME_BYTES as u32 + 1, u32::MAX] {
|
||||
let mut reader = Cursor::new(size.to_le_bytes());
|
||||
assert_eq!(
|
||||
Frame::read(&mut reader, Length::Total).unwrap_err().kind(),
|
||||
io::ErrorKind::InvalidData
|
||||
);
|
||||
assert_eq!(reader.position(), 4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncated_or_malformed_frames() {
|
||||
for bytes in [&b"\x0a\0\0"[..], &b"\x0a\0\0\0COLE:"[..]] {
|
||||
assert_eq!(
|
||||
Frame::read(&mut &bytes[..], Length::Total)
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
io::ErrorKind::UnexpectedEof
|
||||
);
|
||||
}
|
||||
for bytes in [
|
||||
b"\x0a\0\0\0COLE=\0",
|
||||
b"\x0a\0\0\0CO:E:x",
|
||||
b"\x0a\0\0\0CO\0E:\0",
|
||||
] {
|
||||
assert_eq!(
|
||||
Frame::read(&mut &bytes[..], Length::Total)
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
io::ErrorKind::InvalidData
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_output_before_writing_any_bytes() {
|
||||
let mut bytes = Vec::new();
|
||||
for frame in [
|
||||
Frame {
|
||||
tag: *b"DUNN",
|
||||
payload: vec![b'x'; MAX_FRAME_BYTES],
|
||||
nul_terminated: false,
|
||||
},
|
||||
Frame {
|
||||
tag: *b"DUNN",
|
||||
payload: b"one\0two".to_vec(),
|
||||
nul_terminated: false,
|
||||
},
|
||||
Frame {
|
||||
tag: *b"CO:E",
|
||||
payload: Vec::new(),
|
||||
nul_terminated: false,
|
||||
},
|
||||
] {
|
||||
assert!(frame.write(&mut bytes, Length::Total).is_err());
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_the_observed_unterminated_launch_reply_shape() {
|
||||
let payload = vec![b'A'; 640];
|
||||
let mut bytes = 645u32.to_le_bytes().to_vec();
|
||||
bytes.extend_from_slice(b"DUNN:");
|
||||
bytes.extend_from_slice(&payload);
|
||||
let frame = Frame::read(&mut Fragmented(&bytes[..]), Length::Body).unwrap();
|
||||
assert_eq!(bytes.len(), 649);
|
||||
assert_eq!(frame.tag, *b"DUNN");
|
||||
assert_eq!(frame.payload, payload);
|
||||
assert!(!frame.nul_terminated);
|
||||
let mut encoded = Vec::new();
|
||||
frame.write(&mut encoded, Length::Body).unwrap();
|
||||
assert_eq!(encoded, bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presents_a_complete_reply_to_the_pipe_in_one_write() {
|
||||
struct Writes(Vec<usize>);
|
||||
impl Write for Writes {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
self.0.push(bytes.len());
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
let mut writer = Writes(Vec::new());
|
||||
Frame {
|
||||
tag: *b"DUNN",
|
||||
payload: vec![b'A'; 640],
|
||||
nul_terminated: false,
|
||||
}
|
||||
.write(&mut writer, Length::Body)
|
||||
.unwrap();
|
||||
assert_eq!(writer.0, vec![649]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
#![cfg_attr(windows, windows_subsystem = "windows")]
|
||||
|
||||
#[cfg(windows)]
|
||||
fn log(message: &str) {
|
||||
use std::io::Write;
|
||||
let Ok(exe) = std::env::current_exe() else {
|
||||
return;
|
||||
};
|
||||
let path = exe.with_file_name("launcher.log");
|
||||
if let Ok(metadata) = std::fs::symlink_metadata(&path) {
|
||||
if !metadata.is_file() || metadata.len() > 65536 {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if let Ok(mut file) = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(path)
|
||||
{
|
||||
let _ = writeln!(file, "{message}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn run() -> Result<i32, Box<dyn std::error::Error>> {
|
||||
use droiddeck_rockstar_launcher::{pipe::Listener, wait_for_game, Frame, Length};
|
||||
use std::io::Read;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
let config_path = std::env::current_exe()?.with_file_name("launch.json");
|
||||
let mut data = Vec::new();
|
||||
std::fs::File::open(&config_path)?
|
||||
.take(16385)
|
||||
.read_to_end(&mut data)?;
|
||||
std::fs::remove_file(&config_path)?;
|
||||
if data.len() > 16384 {
|
||||
return Err("launch handoff exceeds size limit".into());
|
||||
}
|
||||
let config: serde_json::Value = serde_json::from_slice(&data)?;
|
||||
let text = |key| {
|
||||
config
|
||||
.get(key)
|
||||
.and_then(|value| value.as_str())
|
||||
.ok_or("missing launch field")
|
||||
};
|
||||
let expires = config
|
||||
.get("expiresAt")
|
||||
.and_then(|value| value.as_u64())
|
||||
.ok_or("missing launch expiry")?;
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64;
|
||||
if expires <= now || expires - now > 120_000 {
|
||||
return Err("launch handoff expired".into());
|
||||
}
|
||||
let material = text("material")?.as_bytes().to_vec();
|
||||
if material.len() != 640 || !material.iter().all(u8::is_ascii_hexdigit) {
|
||||
return Err("invalid launch material".into());
|
||||
}
|
||||
let pipe_name = text("pipe")?.to_owned();
|
||||
if !matches!(
|
||||
pipe_name.as_str(),
|
||||
"GTA3_Pipe" | "GTA-VC_Pipe" | "GTA_SA_Pipe"
|
||||
) {
|
||||
return Err("unsupported Rockstar launch pipe".into());
|
||||
}
|
||||
let root = std::fs::canonicalize(text("folder")?)?;
|
||||
let exe = std::fs::canonicalize(text("exe")?)?;
|
||||
let workdir = std::fs::canonicalize(text("workdir")?)?;
|
||||
if !exe.is_file()
|
||||
|| !exe.starts_with(&root)
|
||||
|| !workdir.starts_with(&root)
|
||||
|| !root.join("MTLX.dll").is_file()
|
||||
{
|
||||
return Err("invalid Rockstar game path".into());
|
||||
}
|
||||
if let Some(index) =
|
||||
std::env::args().position(|arg| arg.eq_ignore_ascii_case("-launchTitleInFolder"))
|
||||
{
|
||||
let folder = std::env::args()
|
||||
.nth(index + 1)
|
||||
.ok_or("missing game folder")?;
|
||||
if std::fs::canonicalize(folder)? != root {
|
||||
return Err("Rockstar launch folder mismatch".into());
|
||||
}
|
||||
}
|
||||
let args = config
|
||||
.get("args")
|
||||
.and_then(|value| value.as_array())
|
||||
.ok_or("missing game arguments")?;
|
||||
let args: Result<Vec<&str>, _> = args
|
||||
.iter()
|
||||
.map(|value| value.as_str().ok_or("invalid game argument"))
|
||||
.collect();
|
||||
log("launch handoff accepted");
|
||||
let listener = Listener::new(&pipe_name, Duration::from_secs(30))?;
|
||||
log("launcher pipe created");
|
||||
let mut child = std::process::Command::new(exe)
|
||||
.current_dir(workdir)
|
||||
.args(args?)
|
||||
.spawn()?;
|
||||
let pid = child.id();
|
||||
log("game process started");
|
||||
let (result, handshake) = std::sync::mpsc::sync_channel(1);
|
||||
std::thread::spawn(move || {
|
||||
let serve = || -> std::io::Result<()> {
|
||||
let mut pipe = listener.accept()?;
|
||||
log("launcher pipe connected");
|
||||
if pipe.client_pid()? != pid {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
"unexpected Rockstar pipe client",
|
||||
));
|
||||
}
|
||||
let request = Frame::read(&mut pipe, Length::Total)?;
|
||||
log("game greeting received");
|
||||
if request.tag != *b"COLE" || !request.payload.is_empty() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"unexpected Rockstar greeting",
|
||||
));
|
||||
}
|
||||
Frame {
|
||||
tag: *b"DUNN",
|
||||
payload: material,
|
||||
nul_terminated: false,
|
||||
}
|
||||
.write(&mut pipe, Length::Body)?;
|
||||
log("launcher handshake complete");
|
||||
Ok(())
|
||||
};
|
||||
let outcome = serve();
|
||||
if let Err(error) = &outcome {
|
||||
log(&format!("launcher handshake failed: {error}"));
|
||||
}
|
||||
let _ = result.send(outcome);
|
||||
});
|
||||
Ok(wait_for_game(&mut child, handshake)?.code().unwrap_or(1))
|
||||
}
|
||||
|
||||
fn main() {
|
||||
#[cfg(windows)]
|
||||
let code = match run() {
|
||||
Ok(code) => code,
|
||||
Err(error) => {
|
||||
log(&format!("launch failed: {error}"));
|
||||
eprintln!("Rockstar launch failed: {error}");
|
||||
1
|
||||
}
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let code = 1;
|
||||
std::process::exit(code);
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
use std::ffi::c_void;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::ptr::{null, null_mut};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
type Handle = *mut c_void;
|
||||
const INVALID_HANDLE: Handle = -1isize as Handle;
|
||||
const ERROR_IO_PENDING: i32 = 997;
|
||||
const ERROR_MORE_DATA: i32 = 234;
|
||||
|
||||
#[repr(C)]
|
||||
struct Overlapped {
|
||||
internal: usize,
|
||||
internal_high: usize,
|
||||
offset: u32,
|
||||
offset_high: u32,
|
||||
event: Handle,
|
||||
}
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
extern "system" {
|
||||
fn CreateNamedPipeW(
|
||||
name: *const u16,
|
||||
open: u32,
|
||||
mode: u32,
|
||||
max: u32,
|
||||
output: u32,
|
||||
input: u32,
|
||||
timeout: u32,
|
||||
security: *const c_void,
|
||||
) -> Handle;
|
||||
fn ConnectNamedPipe(handle: Handle, overlapped: *mut Overlapped) -> i32;
|
||||
fn GetNamedPipeClientProcessId(handle: Handle, pid: *mut u32) -> i32;
|
||||
fn CreateFileW(
|
||||
name: *const u16,
|
||||
access: u32,
|
||||
share: u32,
|
||||
security: *const c_void,
|
||||
creation: u32,
|
||||
flags: u32,
|
||||
template: Handle,
|
||||
) -> Handle;
|
||||
fn WaitNamedPipeW(name: *const u16, timeout: u32) -> i32;
|
||||
fn CreateEventW(security: *const c_void, manual: i32, initial: i32, name: *const u16)
|
||||
-> Handle;
|
||||
fn CloseHandle(handle: Handle) -> i32;
|
||||
fn ReadFile(
|
||||
handle: Handle,
|
||||
buffer: *mut u8,
|
||||
size: u32,
|
||||
read: *mut u32,
|
||||
overlapped: *mut Overlapped,
|
||||
) -> i32;
|
||||
fn WriteFile(
|
||||
handle: Handle,
|
||||
buffer: *const u8,
|
||||
size: u32,
|
||||
written: *mut u32,
|
||||
overlapped: *mut Overlapped,
|
||||
) -> i32;
|
||||
fn WaitForSingleObject(handle: Handle, timeout: u32) -> u32;
|
||||
fn CancelIoEx(handle: Handle, overlapped: *mut Overlapped) -> i32;
|
||||
fn GetOverlappedResult(
|
||||
handle: Handle,
|
||||
overlapped: *mut Overlapped,
|
||||
transferred: *mut u32,
|
||||
wait: i32,
|
||||
) -> i32;
|
||||
}
|
||||
|
||||
struct OwnedHandle(Handle);
|
||||
|
||||
unsafe impl Send for OwnedHandle {}
|
||||
|
||||
impl Drop for OwnedHandle {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
CloseHandle(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Pipe {
|
||||
handle: OwnedHandle,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
pub struct Listener(Pipe);
|
||||
|
||||
impl Listener {
|
||||
pub fn new(name: &str, timeout: Duration) -> io::Result<Self> {
|
||||
if name.is_empty() || name.contains(['\\', '/', '\0']) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"invalid pipe name",
|
||||
));
|
||||
}
|
||||
let path = format!(r"\\.\pipe\{name}");
|
||||
let wide: Vec<_> = std::ffi::OsStr::new(&path)
|
||||
.encode_wide()
|
||||
.chain(Some(0))
|
||||
.collect();
|
||||
let handle = unsafe {
|
||||
CreateNamedPipeW(
|
||||
wide.as_ptr(),
|
||||
3 | 0x4000_0000 | 0x0008_0000,
|
||||
8,
|
||||
1,
|
||||
65536,
|
||||
65536,
|
||||
0,
|
||||
null(),
|
||||
)
|
||||
};
|
||||
if handle == INVALID_HANDLE {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(Self(Pipe {
|
||||
handle: OwnedHandle(handle),
|
||||
timeout,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn accept(self) -> io::Result<Pipe> {
|
||||
let event = unsafe { CreateEventW(null(), 1, 0, null()) };
|
||||
if event.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let event = OwnedHandle(event);
|
||||
let mut overlapped = Overlapped {
|
||||
internal: 0,
|
||||
internal_high: 0,
|
||||
offset: 0,
|
||||
offset_high: 0,
|
||||
event: event.0,
|
||||
};
|
||||
if unsafe { ConnectNamedPipe(self.0.handle.0, &mut overlapped) } != 0 {
|
||||
return Ok(self.0);
|
||||
}
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(535) {
|
||||
return Ok(self.0);
|
||||
}
|
||||
if error.raw_os_error() != Some(ERROR_IO_PENDING) {
|
||||
return Err(error);
|
||||
}
|
||||
let wait = unsafe {
|
||||
WaitForSingleObject(
|
||||
event.0,
|
||||
self.0.timeout.as_millis().min(u32::MAX as u128 - 1) as u32,
|
||||
)
|
||||
};
|
||||
let mut transferred = 0;
|
||||
if wait != 0 {
|
||||
let error = if wait == 258 {
|
||||
io::Error::new(io::ErrorKind::TimedOut, "waiting for Rockstar game")
|
||||
} else {
|
||||
io::Error::last_os_error()
|
||||
};
|
||||
unsafe {
|
||||
CancelIoEx(self.0.handle.0, &mut overlapped);
|
||||
GetOverlappedResult(self.0.handle.0, &mut overlapped, &mut transferred, 1);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
if unsafe { GetOverlappedResult(self.0.handle.0, &mut overlapped, &mut transferred, 0) }
|
||||
== 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Pipe {
|
||||
pub fn client_pid(&self) -> io::Result<u32> {
|
||||
let mut pid = 0;
|
||||
if unsafe { GetNamedPipeClientProcessId(self.handle.0, &mut pid) } == 0 || pid == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(pid)
|
||||
}
|
||||
pub fn connect(name: &str, timeout: Duration) -> io::Result<Self> {
|
||||
if name.is_empty() || name.contains(['\\', '/', '\0']) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"invalid pipe name",
|
||||
));
|
||||
}
|
||||
let path = format!(r"\\.\pipe\{name}");
|
||||
let wide: Vec<_> = std::ffi::OsStr::new(&path)
|
||||
.encode_wide()
|
||||
.chain(Some(0))
|
||||
.collect();
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
let handle = unsafe {
|
||||
CreateFileW(
|
||||
wide.as_ptr(),
|
||||
0xc000_0000,
|
||||
0,
|
||||
null(),
|
||||
3,
|
||||
0x4000_0000,
|
||||
null_mut(),
|
||||
)
|
||||
};
|
||||
if handle != INVALID_HANDLE {
|
||||
return Ok(Self {
|
||||
handle: OwnedHandle(handle),
|
||||
timeout,
|
||||
});
|
||||
}
|
||||
let error = io::Error::last_os_error();
|
||||
if !matches!(error.raw_os_error(), Some(2 | 231)) {
|
||||
return Err(error);
|
||||
}
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"waiting for Rockstar pipe",
|
||||
));
|
||||
}
|
||||
unsafe {
|
||||
WaitNamedPipeW(wide.as_ptr(), remaining.as_millis().min(50) as u32);
|
||||
}
|
||||
std::thread::sleep(remaining.min(Duration::from_millis(2)));
|
||||
}
|
||||
}
|
||||
|
||||
fn transfer(&self, buffer: *mut u8, size: usize, writing: bool) -> io::Result<usize> {
|
||||
if size == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let event = unsafe { CreateEventW(null(), 1, 0, null()) };
|
||||
if event.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let event = OwnedHandle(event);
|
||||
let mut overlapped = Overlapped {
|
||||
internal: 0,
|
||||
internal_high: 0,
|
||||
offset: 0,
|
||||
offset_high: 0,
|
||||
event: event.0,
|
||||
};
|
||||
let mut transferred = 0;
|
||||
let size = size.min(u32::MAX as usize) as u32;
|
||||
let ok = unsafe {
|
||||
if writing {
|
||||
WriteFile(
|
||||
self.handle.0,
|
||||
buffer,
|
||||
size,
|
||||
&mut transferred,
|
||||
&mut overlapped,
|
||||
)
|
||||
} else {
|
||||
ReadFile(
|
||||
self.handle.0,
|
||||
buffer,
|
||||
size,
|
||||
&mut transferred,
|
||||
&mut overlapped,
|
||||
)
|
||||
}
|
||||
};
|
||||
if ok != 0 {
|
||||
return Ok(transferred as usize);
|
||||
}
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(ERROR_MORE_DATA) && !writing && transferred > 0 {
|
||||
return Ok(transferred as usize);
|
||||
}
|
||||
if error.raw_os_error() != Some(ERROR_IO_PENDING) {
|
||||
return Err(error);
|
||||
}
|
||||
let wait = unsafe {
|
||||
WaitForSingleObject(
|
||||
event.0,
|
||||
self.timeout.as_millis().min(u32::MAX as u128 - 1) as u32,
|
||||
)
|
||||
};
|
||||
if wait != 0 {
|
||||
let error = if wait == 258 {
|
||||
io::Error::new(io::ErrorKind::TimedOut, "Rockstar pipe operation timed out")
|
||||
} else {
|
||||
io::Error::last_os_error()
|
||||
};
|
||||
unsafe {
|
||||
CancelIoEx(self.handle.0, &mut overlapped);
|
||||
GetOverlappedResult(self.handle.0, &mut overlapped, &mut transferred, 1);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
let ok =
|
||||
unsafe { GetOverlappedResult(self.handle.0, &mut overlapped, &mut transferred, 0) };
|
||||
if ok != 0 {
|
||||
return Ok(transferred as usize);
|
||||
}
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(ERROR_MORE_DATA) && !writing && transferred > 0 {
|
||||
return Ok(transferred as usize);
|
||||
}
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for Pipe {
|
||||
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
||||
self.transfer(buffer.as_mut_ptr(), buffer.len(), false)
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for Pipe {
|
||||
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
|
||||
self.transfer(buffer.as_ptr() as *mut u8, buffer.len(), true)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Frame, Length};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn name() -> String {
|
||||
format!(
|
||||
"dd-rockstar-test-{}-{}",
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_pipe_exchanges_both_framing_modes_and_identifies_the_client() {
|
||||
let name = name();
|
||||
let listener = Listener::new(&name, Duration::from_secs(2)).unwrap();
|
||||
let worker = std::thread::spawn(move || {
|
||||
let mut server = listener.accept().unwrap();
|
||||
assert_eq!(server.client_pid().unwrap(), std::process::id());
|
||||
assert_eq!(
|
||||
Frame::read(&mut server, Length::Total).unwrap().tag,
|
||||
*b"COLE"
|
||||
);
|
||||
Frame {
|
||||
tag: *b"DUNN",
|
||||
payload: vec![b'A'; 640],
|
||||
nul_terminated: false,
|
||||
}
|
||||
.write(&mut server, Length::Body)
|
||||
.unwrap();
|
||||
});
|
||||
let mut client = Pipe::connect(&name, Duration::from_secs(2)).unwrap();
|
||||
Frame {
|
||||
tag: *b"COLE",
|
||||
payload: Vec::new(),
|
||||
nul_terminated: true,
|
||||
}
|
||||
.write(&mut client, Length::Total)
|
||||
.unwrap();
|
||||
let response = Frame::read(&mut client, Length::Body).unwrap();
|
||||
assert_eq!(response.payload.len(), 640);
|
||||
assert!(!response.nul_terminated);
|
||||
worker.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timed_out_accept_releases_the_first_pipe_instance() {
|
||||
let name = name();
|
||||
let listener = Listener::new(&name, Duration::from_millis(20)).unwrap();
|
||||
assert!(matches!(listener.accept(), Err(error) if error.kind() == io::ErrorKind::TimedOut));
|
||||
assert!(Listener::new(&name, Duration::from_millis(20)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timed_out_read_cancels_the_pending_operation() {
|
||||
let name = name();
|
||||
let listener = Listener::new(&name, Duration::from_secs(2)).unwrap();
|
||||
let (done, wait) = mpsc::channel();
|
||||
let worker = std::thread::spawn(move || {
|
||||
let _server = listener.accept().unwrap();
|
||||
wait.recv_timeout(Duration::from_secs(2)).unwrap();
|
||||
});
|
||||
let mut client = Pipe::connect(&name, Duration::from_millis(30)).unwrap();
|
||||
assert_eq!(
|
||||
client.read(&mut [0u8; 4]).unwrap_err().kind(),
|
||||
io::ErrorKind::TimedOut
|
||||
);
|
||||
done.send(()).unwrap();
|
||||
worker.join().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from test_store_launch import store
|
||||
|
||||
|
||||
class RockstarLaunch(unittest.TestCase):
|
||||
def setup_game(self, root):
|
||||
folder = Path(root) / 'game'
|
||||
folder.mkdir()
|
||||
exe = bytearray(128)
|
||||
exe[:2] = b'MZ'
|
||||
exe[0x3c:0x40] = (64).to_bytes(4, 'little')
|
||||
exe[64:70] = b'PE\0\0\x4c\x01'
|
||||
(folder / 'gta-vc.exe').write_bytes(exe)
|
||||
(folder / 'MTLX.dll').write_bytes(b'vendor')
|
||||
prefix = Path(root) / 'prefix'
|
||||
(prefix / 'pfx').mkdir(parents=True)
|
||||
(prefix / 'pfx/user.reg').write_text('WINE REGISTRY Version 2\n')
|
||||
(prefix / 'pfx/system.reg').write_text('WINE REGISTRY Version 2\n')
|
||||
service = Path(root) / 'service'
|
||||
service.mkdir()
|
||||
(service / 'Launcher32.exe').write_bytes(b'compiled-helper')
|
||||
sidecar = {'store': 'rockstar', 'id': 'gtavc', 'exe': 'gta-vc.exe', 'args': ['one argument', '&literal']}
|
||||
answer = {'ok': True, 'pipe': 'GTA-VC_Pipe', 'material': 'A' * 640,
|
||||
'expiresAt': int(time.time() * 1000) + 90000, 'ticket': 'must-not-be-exported'}
|
||||
return folder, sidecar, prefix, service, answer
|
||||
|
||||
def prepare(self, root, modify=lambda values: None):
|
||||
values = self.setup_game(root)
|
||||
modify(values)
|
||||
folder, sidecar, prefix, service, answer = values
|
||||
config = prefix / 'pfx' / store.ROCKSTAR_FOLDER / 'launch.json'
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text('stale')
|
||||
requests = []
|
||||
|
||||
def ask(channel, request, timeout):
|
||||
requests.append(request)
|
||||
return answer
|
||||
|
||||
with patch.object(store, 'ROCKSTAR_SERVICE', service), patch.object(store, 'rockstar_registry', return_value=True):
|
||||
result = store.prepare_rockstar(folder, sidecar, str(prefix), str(Path(root) / 'channel'), ask_app=ask)
|
||||
return result, config, requests
|
||||
|
||||
def test_handoff_contains_only_launch_fields_and_preserves_argument_boundaries(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
result, path, requests = self.prepare(root)
|
||||
self.assertEqual('ready', result)
|
||||
data = json.loads(path.read_text())
|
||||
self.assertEqual({'folder', 'exe', 'workdir', 'args', 'pipe', 'material', 'expiresAt'}, set(data))
|
||||
self.assertEqual(['one argument', '&literal'], data['args'])
|
||||
self.assertNotIn('must-not-be-exported', path.read_text())
|
||||
self.assertEqual('rockstar-launch', requests[0]['op'])
|
||||
self.assertEqual(b'compiled-helper', path.with_name('Launcher.exe').read_bytes())
|
||||
|
||||
def test_rejected_or_expired_sessions_cannot_reuse_stale_material(self):
|
||||
for update in ({'ok': False, 'reason': 'not-owned'}, {'material': 'A' * 641}, {'expiresAt': 1}):
|
||||
with self.subTest(update=update), tempfile.TemporaryDirectory() as root:
|
||||
result, config, _ = self.prepare(root, lambda values: values[4].update(update))
|
||||
self.assertNotEqual('ready', result)
|
||||
self.assertFalse(config.exists())
|
||||
|
||||
def test_path_escape_does_not_request_account_data(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
def change(values):
|
||||
(Path(root) / 'outside.exe').write_bytes(b'MZ')
|
||||
values[1]['exe'] = '../outside.exe'
|
||||
result, config, requests = self.prepare(root, change)
|
||||
self.assertEqual('invalid-game-path', result)
|
||||
self.assertEqual([], requests)
|
||||
self.assertFalse(config.exists())
|
||||
|
||||
def test_writes_both_registry_views_and_escapes_values(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder, _, prefix, _, _ = self.setup_game(root)
|
||||
with patch.object(store, 'wait_for_server', return_value=True):
|
||||
self.assertTrue(store.rockstar_registry(folder, 'Grand Theft Auto: Vice City', prefix, ''))
|
||||
text = (prefix / 'pfx/system.reg').read_text()
|
||||
self.assertIn(r'[Software\\Rockstar Games\\Launcher]', text)
|
||||
self.assertIn(r'[Software\\Wow6432Node\\Rockstar Games\\Launcher]', text)
|
||||
self.assertIn('Grand Theft Auto: Vice City', text)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user