feat(ubisoft): Ubisoft Connect store with native sign-in, library, downloads and launch (#2322)

* feat(ubisoft): sign in to Ubisoft Connect and list the owned library

* feat(ubisoft): download games natively through Demux and Ubisoft's CDN

* fix(ubisoft): show the owned games on the store page

* fix(ctl): reach the agent bridge by broadcast when the shell has no content command

* feat(ubisoft): run Ubisoft games in one prefix with Ubisoft Connect installed and the game registered

* feat(ubisoft): launch games through a native stand-in for Ubisoft Connect's local service

* feat(ubisoft): document the launcher pipes, log why owned games have no download, drop the installer after extraction

* feat(ubisoft): Steam-owned Ubisoft games install through Steam, and the launch session carries the game's application id

* feat(ubisoft): answer Denuvo activations through Ubisoft's activation service and log unanswered pipe traffic

* feat(ubisoft): report installed chunks to the game and skip add-ons the account does not own

* fix(ubisoft): the overlay stays off, Ubisoft's install steps pick Windows components, and shared-prefix games keep their own settings

* fix(ubisoft): write the manifest's registry values, and pick the game's exe over Ubisoft's installer stubs

* fix(ubisoft): stream download slices, guard the launch hook, and keep per-game components in the shared prefix

* fix(ubisoft): direct launches in the shared prefix keep their own game id

* ci(ubisoft): build the launcher service after the prepared components are verified

* fix(ubisoft): verify reused files, drop syncs from a signed-out account, and clear activation requests before launch

* fix(ubisoft): fetch again a reused file whose slices cannot be checked
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-10 15:08:37 -05:00
1 parent d8ed02f2cf
commit 3c96df4ab1
49 files changed
+3960 -24

No files matched your search

+9
View File
@@ -424,6 +424,15 @@ if ! restore_step comet "${comet_key}" "${comet_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh
save_step comet "${comet_key}" "${comet_out}"
fi
if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then
upc_out="${linuxfs_dir}/usr/local/lib/droiddeck-ubisoft"
upc_key=$(inputs_hash "x86_64-pc-windows-gnu" tools/ubisoft-launcher/src tools/ubisoft-launcher/Cargo.toml tools/ubisoft-launcher/Cargo.lock tools/ubisoft-launcher/build.sh)
if ! restore_step ubisoft "${upc_key}" "${upc_out}"; then
command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1 || { echo "x86_64-w64-mingw32-gcc is required for the Ubisoft launcher service (droiddeck-upc.exe)." >&2; exit 1; }
CARGO_TARGET_DIR="${cache_dir}/ubisoft-target" bash tools/ubisoft-launcher/build.sh "${upc_out}"
save_step ubisoft "${upc_key}" "${upc_out}"
fi
fi
python3 tools/powervr/fetch.py
bash tools/packs/build.sh app/build/packs
python3 tools/release/runtime_inputs.py record
@@ -17,12 +17,12 @@ SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
def game_id(env):
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
if not prefix:
return None
value = prefix.rsplit("/", 1)[-1]
if not re.fullmatch(r"-?[0-9]+", value):
# Prefixes several games share; the game itself is the Steam app being launched.
SHARED_PREFIXES = {"2929927072"}
def app_number(value):
if not re.fullmatch(r"-?[0-9]+", value or ""):
return None
number = int(value)
if not -(2**31) <= number < 2**32 or number == 0:
@@ -30,6 +30,26 @@ def game_id(env):
return str(number % 2**32)
def game_id(env):
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
if not prefix:
return None
found = app_number(prefix.rsplit("/", 1)[-1])
if found in SHARED_PREFIXES:
return app_number(env.get("SteamAppId", "")) or shortcut_number(env.get("SteamGameId", "")) or found
return found
def shortcut_number(value):
"""The shortcut appid inside Steam's 64-bit shortcut game id `(appid << 32) | 0x02000000`."""
if not re.fullmatch(r"[0-9]{1,20}", value or ""):
return None
number = int(value)
if number >= 2**64 or number & 0xFFFFFFFF != 0x02000000:
return None
return app_number(str(number >> 32))
DOTNET_FEX = {
"FEX_TSOENABLED": "1",
"FEX_VECTORTSOENABLED": "1",
@@ -289,6 +289,218 @@ def exited(argv, code=0):
return 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"
UBISOFT_CACHE = Path("/root/.cache/droiddeck/ubisoft")
UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
UBISOFT_SERVICE = Path("/usr/local/lib/droiddeck-ubisoft/droiddeck-upc.exe")
UBISOFT_ASK_WAIT = 45.0
UBISOFT_EXTRACT_WAIT = 300
# Ubisoft's own game-side runtime from the Connect installer, unmodified: the API and aux DLLs the
# game's loader opens from InstallDir, the starter it re-executes into and its imports, and the overlay
# DLLs uplay_r1.dll loads even with the overlay off (its startup fails without them).
UBISOFT_RUNTIME = ("uplay_r1.dll", "uplay_r164.dll", "uplay_aux_r1.dll", "uplay_aux_r164.dll",
"uplay_r2.dll", "uplay_r264.dll", "ubiorbitapi_r2.dll", "ubiorbitapi_r264.dll",
"UbisoftGameLauncher.exe", "UbisoftGameLauncher64.exe", "discord-rpc.x86.dll",
"discord-rpc.x64.dll", "steam_api.dll", "steam_api64.dll", "overlay.dll", "overlay64.dll")
UBISOFT_VIEWS = ("[Software\\\\Ubisoft\\\\Launcher%s]", "[Software\\\\Wow6432Node\\\\Ubisoft\\\\Launcher%s]")
MIN_INSTALLER = 1 << 20
def ubisoft_runtime_dir(compat_data):
return Path(compat_data) / "pfx" / UBISOFT_DIR
def ubisoft_runtime_ready(compat_data):
folder = ubisoft_runtime_dir(compat_data)
return all((folder / name).is_file() for name in UBISOFT_RUNTIME)
def fetch_installer(url=UBISOFT_INSTALLER_URL, folder=UBISOFT_CACHE):
target = folder / "UbisoftConnectInstaller.exe"
if target.is_file() and target.stat().st_size >= MIN_INSTALLER:
return target
import urllib.request
folder.mkdir(parents=True, exist_ok=True)
part = target.with_name(target.name + ".part")
request = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(request, timeout=60) as reply, open(part, "wb") as out:
shutil.copyfileobj(reply, out)
if part.stat().st_size < MIN_INSTALLER:
part.unlink()
raise OSError("installer too small")
os.replace(part, target)
return target
def install_runtime(compat_data, wait=UBISOFT_EXTRACT_WAIT):
if ubisoft_runtime_ready(compat_data):
return "present"
if not (Path(compat_data) / "pfx").is_dir():
return "no-prefix"
try:
installer = fetch_installer()
except OSError as error:
return "download-failed-" + type(error).__name__
target = ubisoft_runtime_dir(compat_data)
target.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="droiddeck-ubisoft-", dir=str(UBISOFT_CACHE)) as tmp:
try:
subprocess.run(["7z", "e", "-y", "-o" + tmp, str(installer)] + list(UBISOFT_RUNTIME), stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=wait)
except subprocess.TimeoutExpired:
return "extract-timeout"
except OSError:
return "no-7z"
missing = [name for name in UBISOFT_RUNTIME if not (Path(tmp) / name).is_file()]
if missing:
return "extract-missing-" + ",".join(missing)
for name in UBISOFT_RUNTIME:
shutil.copyfile(Path(tmp) / name, target / name)
if not ubisoft_runtime_ready(compat_data):
return "copy-failed"
try:
installer.unlink()
except OSError:
pass
return "installed"
def ubisoft_product(sidecar):
extra = sidecar.get("extra") if isinstance(sidecar.get("extra"), dict) else {}
try:
return int(str(extra.get("productId") or ""))
except ValueError:
return None
def ubisoft_install_dir(folder):
return windows_path(str(folder)).replace("\\", "/").rstrip("/") + "/"
def register_ubisoft(folder, product, compat_data):
reg = Path(compat_data) / "pfx" / "system.reg"
if not reg.is_file():
return "no-registry"
if not wait_for_server(reg.parent):
return "server-running"
for view in UBISOFT_VIEWS:
set_value(reg, view % "", "InstallDir", UBISOFT_WINDOWS_DIR)
set_value(reg, view % ("\\\\Installs\\\\%d" % product), "InstallDir", ubisoft_install_dir(folder))
return "registered %d" % product
UBISOFT_HIVES = {"HKEY_LOCAL_MACHINE": "system.reg", "HKEY_CURRENT_USER": "user.reg"}
def manifest_value(values, folder, language):
"""The value Connect writes for a manifest registry entry: the install folder, the entry for the
language being played, or the only entry there is."""
entries = [v for v in values if isinstance(v, dict)]
if not entries:
return None
names = [str(v.get("name") or "") for v in entries]
if "$INSTALL_DIR" in names:
return windows_path(str(folder)).rstrip("\\") + "\\"
for v in entries:
if str(v.get("value") or "").lower() == language.lower():
return str(v.get("value"))
prefix = language.split("-")[0].lower()
for v in entries:
if str(v.get("value") or "").lower().split("-")[0] == prefix:
return str(v.get("value"))
return str(entries[0].get("value") or entries[0].get("name") or "")
def apply_manifest_registry(compat_data, registry, folder, language):
written = 0
for item in registry or []:
if not isinstance(item, dict):
continue
path = str(item.get("key") or "").replace("/", "\\")
hive, _, rest = path.partition("\\")
target = UBISOFT_HIVES.get(hive.upper())
if not target or "\\" not in rest:
continue
subkey, _, name = rest.rpartition("\\")
value = manifest_value(item.get("values"), folder, language)
if value is None or not name:
continue
reg = Path(compat_data) / "pfx" / target
parts = subkey.split("\\")
views = [parts]
if target == "system.reg" and len(parts) > 1 and parts[0].lower() == "software" and parts[1].lower() != "wow6432node":
views.append(parts[:1] + ["Wow6432Node"] + parts[1:])
for view in views:
key = "[" + "\\\\".join(view) + "]"
if set_value(reg, key, name, value):
written += 1
return written
def ubisoft_launch(folder, sidecar, product, compat_data, answer):
"""The launch file droiddeck-upc.exe reads: the game, the account and this launch's ticket."""
account = answer.get("account") if isinstance(answer.get("account"), dict) else {}
user = str(account.get("userId") or "user")
saves = Path(compat_data) / "pfx" / "drive_c/users/steamuser/Saved Games/Ubisoft" / user / str(product)
saves.mkdir(parents=True, exist_ok=True)
exe = str(sidecar.get("exe") or "").replace("\\", "/")
workdir = folder / str(sidecar.get("workdir")) if sidecar.get("workdir") else folder
UBISOFT_CACHE.mkdir(parents=True, exist_ok=True)
return {
"productId": product,
"exe": windows_path(str(folder / exe)),
"args": " ".join(str(a) for a in sidecar.get("args") or []),
"workdir": windows_path(str(workdir)),
"account": account,
"ticket": str(answer.get("ticket") or ""),
"owned": [int(i) for i in answer.get("owned") or [] if str(i).isdigit()],
"products": [p for p in answer.get("products") or [] if isinstance(p, dict) and isinstance(p.get("id"), int)],
"appId": str(answer.get("appId") or ""),
"chunks": [c for c in answer.get("chunks") or [] if isinstance(c, dict) and isinstance(c.get("id"), int)],
"saves": "C:/users/steamuser/Saved Games/Ubisoft/%s/%d/" % (user, product),
"language": str(answer.get("language") or "en-US"),
"bridge": windows_path(str(UBISOFT_CACHE / ("bridge-%d" % product))),
"log": windows_path(str(UBISOFT_CACHE / ("upc-%d.log" % product))),
}
def prepare_ubisoft(folder, sidecar, compat_data, launch_dir, proton="", ask_app=None):
launch = folder / UBISOFT_LAUNCH
try:
launch.unlink()
except OSError:
pass
if not compat_data:
return "no-prefix"
product = ubisoft_product(sidecar)
if product is None:
return "no-product"
if not UBISOFT_SERVICE.is_file():
return "no-service"
made = create_prefix(compat_data, proton) if not (Path(compat_data) / "pfx/user.reg").is_file() else "present"
if made not in ("present", "created"):
return "prefix " + made
runtime = install_runtime(compat_data)
if not ubisoft_runtime_ready(compat_data):
return "runtime " + runtime
registry = register_ubisoft(folder, product, compat_data)
if not launch_dir:
return "runtime %s, %s, no-channel" % (runtime, registry)
answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "ubisoft-launch", "store": "ubisoft", "id": str(sidecar.get("id"))},
timeout=UBISOFT_ASK_WAIT)
if not isinstance(answer, dict) or not answer.get("ok") or not answer.get("ticket"):
reason = "timeout" if answer is None else str(answer.get("reason") or "refused")
return "runtime %s, %s, session %s" % (runtime, registry, reason)
written = 0
if answer.get("registry") and wait_for_server(Path(compat_data) / "pfx"):
written = apply_manifest_registry(compat_data, answer.get("registry"), folder, str(answer.get("language") or "en-US"))
tmp = launch.with_name(launch.name + ".tmp")
tmp.write_text(json.dumps(ubisoft_launch(folder, sidecar, product, compat_data, answer)))
os.replace(tmp, launch)
return "runtime %s, %s, %d manifest value(s), session ready" % (runtime, registry, written)
COMET_DIR = Path("/usr/local/lib/droiddeck-comet")
@@ -1114,6 +1326,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 == "ubisoft":
try:
log("ubisoft %s: %s" % (game, prepare_ubisoft(folder, sidecar, compat_data, launch_dir, os.environ.get("BL_STORE_PROTON", ""))))
except OSError as e:
try:
(folder / UBISOFT_LAUNCH).unlink()
except OSError:
pass
log("ubisoft %s: not prepared (%s), starting directly" % (game, e))
if store == "epic":
handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file()
if not handled:
@@ -152,6 +152,13 @@ bl_components() {
else
cm_app=""
fi
if [ "$cm_app" = 2929927072 ] && [[ "${SteamAppId:-}" =~ ^[0-9]{1,10}$ ]] && (( 10#$SteamAppId > 0 && 10#$SteamAppId <= 4294967295 )); then
cm_app=$((10#$SteamAppId))
elif [ "$cm_app" = 2929927072 ] && [[ "${SteamGameId:-}" =~ ^[1-9][0-9]{9,19}$ ]] &&
{ [ ${#SteamGameId} -lt 20 ] || [[ ! "$SteamGameId" > 18446744073709551615 ]]; } &&
(( (10#$SteamGameId & 0xFFFFFFFF) == 0x02000000 && ((10#$SteamGameId >> 32) & 0xFFFFFFFF) != 0 )); then
cm_app=$(( (10#$SteamGameId >> 32) & 0xFFFFFFFF ))
fi
if [ -z "$cm_app" ]; then
echo "droiddeck-proton: components: invalid game prefix, left as it is" >&2
return 0
+21
View File
@@ -1124,6 +1124,23 @@ class GameEnvironmentTest(unittest.TestCase):
scope = MODULE["game_id"](env)
expected = "untouched" if scope is None else scope if scope in {"42", "4294967295", "2147483648"} else "*"
self.assertEqual(target.read_text(), expected)
for app, expected in (("42", "42"), ("4294967295", "4294967295"), ("43", "*"), ("", "*"), ("x", "*")):
with self.subTest(shared=app):
env = dict(os.environ, HOME=str(root), STEAM_COMPAT_DATA_PATH="/steam/compatdata/2929927072", SteamAppId=app)
target.write_text("untouched")
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True, capture_output=True)
self.assertEqual(MODULE["game_id"](env), app if app in {"42", "4294967295", "43"} else "2929927072")
self.assertEqual(target.read_text(), expected)
for game, expected in (
(str(42 << 32 | 0x02000000), "42"), (str(4294967295 << 32 | 0x02000000), "4294967295"),
(str(42 << 32 | 0x02000001), "*"), (str(42 << 32 | 0x02000000 | 1 << 64), "*"), ("33554432", "*"), ("x", "*"),
):
with self.subTest(direct=game):
env = dict(os.environ, HOME=str(root), STEAM_COMPAT_DATA_PATH="/steam/compatdata/2929927072", SteamAppId="0", SteamGameId=game)
target.write_text("untouched")
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True, capture_output=True)
self.assertEqual(MODULE["game_id"](env), expected if expected != "*" else "2929927072")
self.assertEqual(target.read_text(), expected)
def test_engine_fixes_follow_the_games_files(self):
with tempfile.TemporaryDirectory() as tmp:
@@ -1628,6 +1645,10 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertIsNone(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": prefix}))
self.assertEqual(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": "/a/compatdata/42/"}), "42")
self.assertEqual(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": "/a/compatdata/-1"}), "4294967295")
shared = {"STEAM_COMPAT_DATA_PATH": "/a/compatdata/2929927072", "SteamAppId": "2424921676"}
self.assertEqual(MODULE["game_id"](shared), "2424921676")
self.assertEqual(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": "/a/compatdata/2929927072"}), "2929927072")
self.assertEqual(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": "/a/compatdata/42", "SteamAppId": "7"}), "42")
def test_launch_reads_updates_preserves_argv_and_does_not_execute_values(self):
with tempfile.TemporaryDirectory() as tmp:
+99
View File
@@ -797,3 +797,102 @@ class GogRegistry(unittest.TestCase):
store.main([str(folder / store.LAUNCHER)])
apply.assert_called_once_with(folder, root + '/compat', '/chosen/proton')
support.assert_called_once_with(folder, root + '/compat', '/chosen/proton')
class Ubisoft(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.root = Path(self.tmp.name)
self.compat_data = self.root / 'compatdata/2929927072'
(self.compat_data / 'pfx').mkdir(parents=True)
(self.compat_data / 'pfx/system.reg').write_text('WINE REGISTRY Version 2\n')
(self.compat_data / 'pfx/user.reg').write_text('WINE REGISTRY Version 2\n')
self.folder = self.root / 'Games/Stores/Ubisoft/Splinter Cell'
(self.folder / 'system').mkdir(parents=True)
self.sidecar = {'store': 'ubisoft', 'id': 'space-1', 'exe': 'system/SplinterCell.exe', 'extra': {'productId': '109'}}
service = self.root / 'droiddeck-upc.exe'
service.write_bytes(b'MZ')
for patcher in (patch.object(store, 'UBISOFT_SERVICE', service), patch.object(store, 'UBISOFT_CACHE', self.root / 'cache'),
patch.object(store, 'wait_for_server', return_value=True)):
patcher.start()
self.addCleanup(patcher.stop)
def tearDown(self):
self.tmp.cleanup()
def runtime(self):
folder = store.ubisoft_runtime_dir(self.compat_data)
folder.mkdir(parents=True, exist_ok=True)
for name in store.UBISOFT_RUNTIME:
(folder / name).write_bytes(b'MZ')
def answer(self, *_args, **_kwargs):
return {'ok': True, 'ticket': 'PC', 'owned': [82, 109], 'appId': 'app',
'account': {'userId': 'u1', 'username': 'name', 'nameOnPlatform': 'name', 'email': 'e@x', 'country': 'US'}}
def prepare(self, ask_app):
return store.prepare_ubisoft(self.folder, self.sidecar, str(self.compat_data), str(self.root / 'launch'), '/proton', ask_app=ask_app)
def test_an_extracted_runtime_is_not_extracted_again(self):
self.runtime()
with patch.object(store.subprocess, 'run') as run:
self.assertEqual('present', store.install_runtime(str(self.compat_data)))
run.assert_not_called()
def test_the_runtime_comes_from_the_installer_through_7z(self):
installer = self.root / 'UbisoftConnectInstaller.exe'
def run(command, **_kwargs):
self.assertEqual(['7z', 'e', '-y'], command[:3])
self.assertEqual(str(installer), command[4])
out = Path(command[3][2:])
for name in command[5:]:
(out / name).write_bytes(b'MZ')
(self.root / 'cache').mkdir()
with patch.object(store, 'fetch_installer', return_value=installer), patch.object(store.subprocess, 'run', side_effect=run):
self.assertEqual('installed', store.install_runtime(str(self.compat_data)))
self.assertTrue(store.ubisoft_runtime_ready(str(self.compat_data)))
def test_a_launch_registers_the_game_and_writes_the_session_for_the_service(self):
self.runtime()
result = self.prepare(self.answer)
self.assertEqual('runtime present, registered 109, 0 manifest value(s), session ready', result)
reg = (self.compat_data / 'pfx/system.reg').read_text()
for view in ('[Software\\\\Ubisoft\\\\Launcher]', '[Software\\\\Wow6432Node\\\\Ubisoft\\\\Launcher]'):
self.assertIn(view, reg)
self.assertIn('[Software\\\\Wow6432Node\\\\Ubisoft\\\\Launcher\\\\Installs\\\\109]', reg)
self.assertIn('"InstallDir"="C:\\\\Program Files (x86)\\\\Ubisoft\\\\Ubisoft Game Launcher\\\\"', reg)
launch = json.loads((self.folder / store.UBISOFT_LAUNCH).read_text())
self.assertEqual(109, launch['productId'])
self.assertEqual('PC', launch['ticket'])
self.assertEqual([82, 109], launch['owned'])
self.assertEqual(store.windows_path(str(self.folder / 'system/SplinterCell.exe')), launch['exe'])
self.assertEqual('C:/users/steamuser/Saved Games/Ubisoft/u1/109/', launch['saves'])
self.assertTrue((self.compat_data / 'pfx/drive_c/users/steamuser/Saved Games/Ubisoft/u1/109').is_dir())
def test_without_a_session_the_launch_file_is_removed_and_the_game_starts_as_is(self):
self.runtime()
(self.folder / store.UBISOFT_LAUNCH).write_text('{}')
result = self.prepare(lambda *_a, **_k: {'ok': False, 'reason': 'signed-out'})
self.assertEqual('runtime present, registered 109, session signed-out', result)
self.assertFalse((self.folder / store.UBISOFT_LAUNCH).exists())
def test_a_game_without_a_product_is_left_alone(self):
self.sidecar['extra'] = {}
self.assertEqual('no-product', self.prepare(self.answer))
def test_the_manifest_registry_lands_in_both_views_with_the_install_folder_and_language(self):
self.runtime()
registry = [{'key': r'HKEY_LOCAL_MACHINE\SOFTWARE\Ubisoft\Launcher\Installs\109\Language',
'values': [{'name': 'French', 'value': 'fr-FR'}, {'name': 'English', 'value': 'en-US'}]},
{'key': r'HKEY_LOCAL_MACHINE\SOFTWARE\Ubisoft\Splinter Cell\GamePath', 'values': [{'name': '$INSTALL_DIR', 'value': ''}]}]
answer = dict(self.answer(), registry=registry, language='en-US')
result = self.prepare(lambda *_a, **_k: answer)
self.assertEqual('runtime present, registered 109, 4 manifest value(s), session ready', result)
reg = (self.compat_data / 'pfx/system.reg').read_text()
self.assertIn(r'[SOFTWARE\\Wow6432Node\\Ubisoft\\Launcher\\Installs\\109]', reg)
self.assertIn(r'[SOFTWARE\\Ubisoft\\Launcher\\Installs\\109]', reg)
self.assertIn('"Language"="en-US"', reg)
folder = store.windows_path(str(self.folder)).replace('\\', '\\\\')
self.assertIn('"GamePath"="%s\\\\"' % folder, reg)
+2
View File
@@ -0,0 +1,2 @@
target/
out/
+105
View File
@@ -0,0 +1,105 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "droiddeck-ubisoft-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.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "droiddeck-ubisoft-launcher"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0-only"
publish = false
[[bin]]
name = "droiddeck-upc"
path = "src/main.rs"
[dependencies]
serde_json = "1"
[profile.release]
opt-level = "s"
lto = true
panic = "abort"
strip = true
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
# Builds droiddeck-upc.exe for Wine and stages it with the guest scripts.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
out=${1:-"$here/../../app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft"}
target=x86_64-pc-windows-gnu
rustup target add "$target" >/dev/null 2>&1 || true
cargo build --manifest-path "$here/Cargo.toml" --release --locked --target "$target"
mkdir -p "$out"
install -m644 "${CARGO_TARGET_DIR:-$here/target}/$target/release/droiddeck-upc.exe" "$out/droiddeck-upc.exe"
+358
View File
@@ -0,0 +1,358 @@
//! What Ubisoft Connect answers on its local pipes, built from the launch configuration.
//!
//! Field numbers follow `mg.protocol.uplaydll` and `game_starter` as embedded in Ubisoft's own
//! `uplay_r1.dll`; see docs/development/ubisoft-launch.md.
use crate::pb::{self, Msg, Value};
use serde_json::Value as Json;
pub const GAME_START: &str = "game_start_ipc_pipe_";
pub const API_PROCESS: &str = "uplay_api_process_ipc_pipe_";
pub const SESSION: &str = "uplay_ipc_pipe_";
pub const AUX: &str = "uplay_aux_ipc_pipe_";
pub const SERVICE: &str = "uplay_service_ipc_pipe_";
/// Pipes Connect creates that the game may open; they are held open without answers.
pub const QUIET: &[&str] = &[
"upc_api_process_ipc_pipe_standard",
"uplay_protocol_ipc_pipe_",
"uplay_overlay_ipc_pipe_",
"orbit_ipc_pipe_",
"uplay_crash_reporter_ipc_pipe_",
];
/// The add-on list Connect returns from the aux init; the game echoes it back.
const AUX_ADDONS: [u64; 3] = [3367, 3368, 3962];
/// `OverlayInjectionMethod_None`.
const OVERLAY_NONE: u64 = 1;
const HWSCORE: &str = "C:/ProgramData/Ubisoft/Ubisoft Game Launcher/cache//statistics/hwscore";
pub struct Config {
pub product: u32,
pub exe: String,
pub args: String,
pub workdir: String,
pub user_id: String,
pub username: String,
pub name_on_platform: String,
pub email: String,
pub country: String,
pub ticket: String,
pub owned: Vec<u32>,
pub app_id: String,
pub saves: String,
pub language: String,
pub bridge: String,
pub log: String,
/// Installed chunks of the game's manifest: id and tags.
pub chunks: Vec<(u32, String)>,
/// Owned products and their ownership type (0 game, 1 add-on).
pub products: Vec<(u32, u32)>,
}
fn s(j: &Json, k: &str) -> String {
j.get(k).and_then(|v| v.as_str()).unwrap_or_default().to_string()
}
impl Config {
pub fn parse(text: &str) -> Result<Config, String> {
let j: Json = serde_json::from_str(text).map_err(|e| format!("config: {e}"))?;
let product = j.get("productId").and_then(|v| v.as_u64()).ok_or("config: no productId")? as u32;
let account = j.get("account").cloned().unwrap_or(Json::Null);
let mut owned: Vec<u32> = j.get("owned").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|v| v.as_u64()).map(|v| v as u32).collect()).unwrap_or_default();
if !owned.contains(&product) {
owned.push(product);
}
let mut saves = s(&j, "saves").replace('\\', "/");
if !saves.ends_with('/') {
saves.push('/');
}
let c = Config {
product,
exe: s(&j, "exe"),
args: s(&j, "args"),
workdir: s(&j, "workdir"),
user_id: s(&account, "userId"),
username: s(&account, "username"),
name_on_platform: s(&account, "nameOnPlatform"),
email: s(&account, "email"),
country: s(&account, "country"),
ticket: s(&j, "ticket"),
owned,
app_id: s(&j, "appId"),
saves,
language: Some(s(&j, "language")).filter(|l| !l.is_empty()).unwrap_or_else(|| "en-US".into()),
bridge: s(&j, "bridge"),
log: s(&j, "log"),
chunks: j.get("chunks").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|c| {
Some((c.get("id")?.as_u64()? as u32, c.get("tags").and_then(|t| t.as_str()).unwrap_or("").to_string()))
}).collect()).unwrap_or_default(),
products: j.get("products").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|p| {
Some((p.get("id")?.as_u64()? as u32, p.get("type").and_then(|t| t.as_u64()).unwrap_or(0) as u32))
}).collect()).unwrap_or_default(),
};
if c.exe.is_empty() || c.ticket.is_empty() {
return Err("config: exe and ticket are required".into());
}
Ok(c)
}
fn root(&self) -> String {
let mut r = self.workdir.replace('\\', "/");
if !r.ends_with('/') {
r.push('/');
}
r
}
/// The executable the way Connect hands it back: the install root, a slash, then the path under it.
pub fn reply_exe(&self, requested: &str) -> String {
let root = self.root();
let base = root.trim_end_matches('/');
let exe = requested.replace('\\', "/");
let rel = if !base.is_empty() && exe.to_lowercase().starts_with(&(base.to_lowercase() + "/")) { &exe[base.len() + 1..] } else { &exe[..] };
format!("{root}/{rel}")
}
/// `game_starter.Downstream` granting the start the starter asked for.
pub fn game_start(&self, request: &[u8]) -> Vec<u8> {
let requested = pb::find(request, 10, 4).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_else(|| self.exe.clone());
let progress = Msg::new()
.msg(1, Msg::new().uint(1, 1).uint(2, 113).uint(3, 0).uint(4, 1).uint(5, 0))
.msg(1, Msg::new().uint(1, 3).uint(2, 123).uint(3, 0).uint(4, 0).uint(5, 0));
let granted = Msg::new()
.uint(1, 0)
.uint(2, 0)
.text(3, &self.reply_exe(&requested))
.text(4, &self.root())
.uint(8, 3)
.msg(9, progress);
Msg::new().msg(2, Msg::new().msg(1, granted)).0
}
/// `Chunks`: every installed chunk, marked downloaded.
fn chunks(&self) -> Msg {
let mut m = Msg::new();
for (id, tags) in &self.chunks {
m = m.msg(1, Msg::new().uint(1, *id as u64).uint(2, 1).text(3, tags));
}
m
}
/// `Rsp.initProcessRsp` for the game announcing its process. The overlay is reported off
/// everywhere: with it on, `uplay_r1.dll` loads `overlay.dll` and fails its startup without it.
pub fn init_process(&self) -> Vec<u8> {
Msg::new().msg(13, Msg::new().uint(1, 1).uint(3, 0).uint(4, OVERLAY_NONE).uint(6, 0)).0
}
/// `Rsp.initRsp`: the account, its products and the PC ticket.
pub fn session(&self) -> Vec<u8> {
let account = Msg::new()
.text(1, &self.user_id)
.text(2, &self.username)
.text(3, &self.name_on_platform)
.text(4, &self.email)
.text(5, "")
.text(6, &self.country);
let mut body = Msg::new().uint(1, 1).msg(2, account).uint(3, 1).uint(4, self.product as u64);
for id in &self.owned {
body = body.uint(5, *id as u64);
}
body = body
.msg(6, Msg::new().uint(1, self.product as u64).text(2, ""))
.uint(7, 0)
.text(8, &self.ticket)
.msg(14, Msg::new().uint(1, 1).msg(2, self.chunks()).text(3, &self.language))
.msg(11, Msg::new().uint(1, 0))
.uint(12, 0)
.msg(15, Msg::new().uint(1, 0).uint(2, OVERLAY_NONE))
.msg(16, Msg::new().uint(1, 6211).uint(2, 22395).float(3, 1.0))
.msg(17, Msg::new().text(1, &self.saves))
.bytes(18, b"")
.msg(19, Msg::new().uint(1, 1).uint(2, 1))
.msg(21, Msg::new().uint(2, 1));
if !self.app_id.is_empty() {
body = body.msg(22, Msg::new().text(1, &self.app_id));
}
Msg::new().msg(1, body.bytes(23, b"")).0
}
/// `Rsp.installerRsp.initInstallerRsp`.
pub fn installer(&self) -> Vec<u8> {
Msg::new().msg(10, Msg::new().msg(1, Msg::new().uint(1, 1).msg(2, self.chunks()).text(3, &self.language))).0
}
/// `Rsp.productRsp.getProductListRsp`: every owned product as owned, playable and purchased.
pub fn product_list(&self, request_id: u64) -> Vec<u8> {
let mut list = Msg::new().uint(1, request_id).uint(2, 1);
let products: Vec<(u32, u32)> = if self.products.is_empty() { self.owned.iter().map(|id| (*id, 0)).collect() } else { self.products.clone() };
for (id, kind) in products {
list = list.msg(3, Msg::new().uint(1, id as u64).uint(2, if kind == 1 { 2 } else { 1 }).uint(3, 1).uint(4, 3).uint(6, 1));
}
Msg::new().msg(15, Msg::new().msg(1, list)).0
}
pub fn service_hello(&self) -> Vec<u8> {
Msg::new().msg(3, Msg::new().uint(1, 1).msg(3, Msg::new().text(1, HWSCORE))).0
}
}
/// Requests answered with only their id and a result: (`Req` field, its request) to (`Rsp` field, its
/// response, `OperationResult`). 1 is ok and 4 not found.
const ACKNOWLEDGED: &[(u32, u32, u32, u32, u64)] = &[
(8, 1, 5, 1, 1), // achievements: list (none)
(8, 2, 5, 2, 4), // achievements: image
(8, 3, 5, 3, 1), // achievements: earn
(9, 1, 6, 1, 1), // overlay: show
(9, 2, 6, 2, 1), // overlay: shop url
(9, 4, 6, 3, 1), // overlay: browser url
(9, 5, 6, 4, 1), // overlay: notification
(9, 6, 6, 5, 1), // overlay: friend invitation
(9, 7, 6, 6, 1), // overlay: friend selection
(9, 8, 6, 8, 1), // overlay: micro app
(10, 1, 7, 1, 4), // avatar
(20, 1, 14, 1, 1), // store products (none)
(23, 3, 15, 5, 1), // track add-on
(25, 1, 17, 1, 4), // user lookup
(25, 3, 17, 3, 1), // rich presence
(25, 4, 17, 4, 1), // played with
];
/// The id-and-result answer to a request in [ACKNOWLEDGED], with a name for the log.
pub fn acknowledge(body: &[u8]) -> Option<(Vec<u8>, String)> {
let f = pb::fields(body)?;
for &(req, sub, rsp, rsp_sub, result) in ACKNOWLEDGED {
let Some(inner) = pb::sub(&f, req).and_then(pb::fields) else { continue };
let Some(leaf) = pb::sub(&inner, sub).and_then(pb::fields) else { continue };
let id = pb::num(&leaf, 1).unwrap_or(0);
let answer = Msg::new().msg(rsp, Msg::new().msg(rsp_sub, Msg::new().uint(1, id).uint(2, result))).0;
return Some((answer, format!("{req}.{sub} id {id} -> {result}")));
}
None
}
pub enum SessionReq {
Init,
Installer,
ProductList(u64),
Other,
}
pub fn session_request(body: &[u8]) -> SessionReq {
match pb::fields(body) {
Some(f) if pb::sub(&f, 13).and_then(pb::fields).is_some_and(|i| pb::has(&i, 1)) => SessionReq::Installer,
Some(f) if pb::has(&f, 1) => SessionReq::Init,
Some(f) => match pb::sub(&f, 23).and_then(pb::fields).and_then(|p| pb::sub(&p, 1).and_then(pb::fields)) {
Some(list) => SessionReq::ProductList(pb::num(&list, 1).unwrap_or(0)),
None => SessionReq::Other,
},
_ => SessionReq::Other,
}
}
/// The product and game process the game announces on the api-process pipe.
pub fn announced(body: &[u8]) -> Option<(u32, u32)> {
let f = pb::fields(body)?;
let r = pb::fields(pb::sub(&f, 2)?)?;
Some((pb::num(&r, 1)? as u32, pb::num(&r, 2)? as u32))
}
pub enum AuxReq<'a> {
Init(u64),
Activate(u64, &'a [u8]),
Other(u64),
}
/// `UplayAuxDll.Req`: an init, or an activation carrying the game's Denuvo request token.
pub fn aux_request(body: &[u8]) -> AuxReq<'_> {
let Some(f) = pb::fields(body) else { return AuxReq::Other(0) };
let rid = pb::num(&f, 1).unwrap_or(0);
let Some(activate) = pb::sub(&f, 3) else {
return if pb::has(&f, 2) { AuxReq::Init(rid) } else { AuxReq::Other(rid) };
};
let token = pb::fields(activate)
.and_then(|a| pb::sub(&a, 2).and_then(pb::fields))
.and_then(|t| t.iter().find_map(|(n, v)| match v { Value::Bytes(b) if *n == 2 => Some(*b), _ => None }));
match token {
Some(t) => AuxReq::Activate(rid, t),
None => AuxReq::Other(rid),
}
}
pub fn aux_init(rid: u64, pid: u32) -> Vec<u8> {
let mut init = Msg::new().uint(1, 1).uint(2, pid as u64);
for a in AUX_ADDONS {
init = init.uint(3, a);
}
Msg::new().uint(1, rid).msg(2, init).0
}
pub fn aux_token(rid: u64, game_token: &[u8]) -> Vec<u8> {
let answer = Msg::new().uint(2, 1).uint(3, 0).bytes(4, game_token).bytes(5, b"");
Msg::new().uint(1, rid).msg(3, Msg::new().msg(2, answer)).0
}
#[cfg(test)]
mod tests {
use super::*;
fn config() -> Config {
Config::parse(r#"{"productId":109,"exe":"Z:/games/sc/system/splintercell.exe","workdir":"Z:/games/sc","ticket":"T",
"account":{"userId":"u1","username":"name","nameOnPlatform":"name","email":"e@x","country":"US"},
"owned":[82],"appId":"a-b","saves":"Z:/saves/u1/109","chunks":[{"id":0,"tags":""},{"id":64,"tags":"custo05"}]}"#).unwrap()
}
#[test]
fn the_owned_list_always_holds_the_game_and_saves_end_with_a_slash() {
let c = config();
assert_eq!(c.owned, vec![82, 109]);
assert_eq!(c.saves, "Z:/saves/u1/109/");
}
#[test]
fn the_start_reply_names_the_exe_under_the_root_with_connects_double_slash() {
let c = config();
assert_eq!(c.reply_exe("Z:\\games\\sc\\system\\splintercell.exe"), "Z:/games/sc//system/splintercell.exe");
let req = Msg::new().msg(1, Msg::new().msg(1, Msg::new().uint(1, 13389).uint(2, 109).text(10, "Z:/games/sc/system/splintercell.exe")));
let rsp = c.game_start(&req.0);
let granted = pb::fields(pb::sub(&pb::fields(pb::sub(&pb::fields(&rsp).unwrap(), 2).unwrap()).unwrap(), 1).unwrap()).unwrap();
assert_eq!(pb::num(&granted, 1), Some(0));
assert_eq!(pb::sub(&granted, 3), Some(&b"Z:/games/sc//system/splintercell.exe"[..]));
assert_eq!(pb::sub(&granted, 4), Some(&b"Z:/games/sc/"[..]));
assert_eq!(pb::num(&granted, 8), Some(3));
}
#[test]
fn the_session_carries_the_ticket_products_and_save_root() {
let rsp = config().session();
let init = pb::fields(pb::sub(&pb::fields(&rsp).unwrap(), 1).unwrap()).unwrap();
assert_eq!(pb::num(&init, 1), Some(1));
assert_eq!(pb::num(&init, 4), Some(109));
let owned: Vec<u64> = init.iter().filter_map(|(n, v)| match v { Value::Int(x) if *n == 5 => Some(*x), _ => None }).collect();
assert_eq!(owned, vec![82, 109]);
assert_eq!(pb::sub(&init, 8), Some(&b"T"[..]));
let saves = pb::fields(pb::sub(&init, 17).unwrap()).unwrap();
assert_eq!(pb::sub(&saves, 1), Some(&b"Z:/saves/u1/109/"[..]));
let account = pb::fields(pb::sub(&init, 2).unwrap()).unwrap();
assert_eq!(pb::sub(&account, 1), Some(&b"u1"[..]));
assert_eq!(pb::sub(&account, 5), Some(&b""[..]));
let install = pb::fields(pb::sub(&init, 14).unwrap()).unwrap();
assert_eq!(pb::num(&install, 1), Some(1));
let chunks = pb::fields(pb::sub(&install, 2).unwrap()).unwrap();
let second = pb::fields(match &chunks[1].1 { Value::Bytes(b) => b, _ => panic!() }).unwrap();
assert_eq!((pb::num(&second, 1), pb::num(&second, 2), pb::sub(&second, 3)), (Some(64), Some(1), Some(&b"custo05"[..])));
}
#[test]
fn requests_are_told_apart() {
assert!(matches!(session_request(&Msg::new().msg(1, Msg::new().uint(1, 109)).0), SessionReq::Init));
assert!(matches!(session_request(&Msg::new().msg(13, Msg::new().bytes(1, b"")).0), SessionReq::Installer));
assert!(matches!(session_request(&[0xba, 0x01, 0x06, 0x0a, 0x04, 0x08, 0x80, 0x80, 0x04]), SessionReq::ProductList(65536)));
let (answer, _) = acknowledge(&[0x42, 0x08, 0x0a, 0x06, 0x08, 0x80, 0x80, 0x08, 0x10, 0x00]).unwrap();
let rsp = pb::fields(pb::sub(&pb::fields(pb::sub(&pb::fields(&answer).unwrap(), 5).unwrap()).unwrap(), 1).unwrap()).unwrap();
assert_eq!((pb::num(&rsp, 1), pb::num(&rsp, 2)), (Some(0x20000), Some(1)));
assert!(acknowledge(&Msg::new().msg(1, Msg::new().uint(1, 1)).0).is_none());
assert_eq!(announced(&Msg::new().msg(2, Msg::new().uint(1, 109).uint(2, 4242).uint(5, 1)).0), Some((109, 4242)));
let activate = Msg::new().uint(1, 2).msg(3, Msg::new().msg(2, Msg::new().bytes(2, b"challenge").uint(3, 0)));
assert!(matches!(aux_request(&activate.0), AuxReq::Activate(2, b"challenge")));
assert!(matches!(aux_request(&Msg::new().uint(1, 1).msg(2, Msg::new().uint(1, 109)).0), AuxReq::Init(1)));
}
}
+331
View File
@@ -0,0 +1,331 @@
//! Stands in for Ubisoft Connect on the local pipes a Ubisoft game talks to, and starts the game.
//!
//! Usage: droiddeck-upc.exe <launch.json>
#![cfg_attr(windows, windows_subsystem = "windows")]
mod launcher;
mod pb;
#[cfg(windows)]
mod win;
#[cfg(not(windows))]
fn main() {
eprintln!("droiddeck-upc runs inside Wine");
std::process::exit(2);
}
#[cfg(windows)]
fn main() {
std::process::exit(service::run());
}
#[cfg(windows)]
mod service {
use crate::launcher::{self, AuxReq, Config, SessionReq};
use crate::win::{self, Handle};
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
const MAX_FRAME: usize = 16 << 20;
const ANNOUNCE_WAIT: Duration = Duration::from_secs(120);
const RESTART_WAIT: Duration = Duration::from_secs(15);
const DENUVO_WAIT: Duration = Duration::from_secs(90);
struct State {
cfg: Config,
prefix: String,
log: Mutex<Option<std::fs::File>>,
event: Handle,
game: AtomicU32,
started: Instant,
}
impl State {
fn say(&self, line: &str) {
let text = format!("[{:7.2}] {line}\n", self.started.elapsed().as_secs_f32());
eprint!("droiddeck-upc: {text}");
if let Some(f) = self.log.lock().unwrap().as_mut() {
let _ = f.write_all(text.as_bytes());
}
}
}
struct Frames<'a> {
pipe: &'a Handle,
buf: Vec<u8>,
}
impl<'a> Frames<'a> {
fn new(pipe: &'a Handle) -> Self {
Frames { pipe, buf: Vec::new() }
}
fn fill(&mut self) -> bool {
let mut chunk = vec![0u8; 65536];
match self.pipe.read(&mut chunk) {
Some(n) => {
self.buf.extend_from_slice(&chunk[..n]);
true
}
None => false,
}
}
/// The next message without its 4-byte big-endian length.
fn next(&mut self) -> Option<Vec<u8>> {
while self.buf.len() < 4 {
if !self.fill() {
return None;
}
}
let n = u32::from_be_bytes(self.buf[..4].try_into().unwrap()) as usize;
if n > MAX_FRAME {
return None;
}
while self.buf.len() < 4 + n {
if !self.fill() {
return None;
}
}
let body = self.buf[4..4 + n].to_vec();
self.buf.drain(..4 + n);
Some(body)
}
}
fn send(pipe: &Handle, body: &[u8]) -> bool {
let mut framed = (body.len() as u32).to_be_bytes().to_vec();
framed.extend_from_slice(body);
pipe.write_all(&framed)
}
fn hold(state: &State, name: &str, frames: &mut Frames) {
while let Some(body) = frames.next() {
state.say(&format!("{name}: {} B left unanswered", body.len()));
}
}
fn game_start(state: &State, pipe: Handle) {
let mut frames = Frames::new(&pipe);
let Some(req) = frames.next() else { return };
send(&pipe, &state.cfg.game_start(&req));
state.say("game_start: start granted");
hold(state, "game_start", &mut frames);
}
fn api_process(state: &State, pipe: Handle) {
let mut frames = Frames::new(&pipe);
let Some(req) = frames.next() else { return };
match launcher::announced(&req) {
Some((product, pid)) => {
state.say(&format!("api_process: product {product} is process {pid}"));
if pid != 0 {
state.game.store(pid, Ordering::SeqCst);
}
}
None => state.say(&format!("api_process: {} B announcement not understood", req.len())),
}
send(&pipe, &state.cfg.init_process());
state.event.set();
hold(state, "api_process", &mut frames);
}
fn session(state: &State, pipe: Handle) {
let mut frames = Frames::new(&pipe);
let mut pushes = 0;
while let Some(req) = frames.next() {
match launcher::session_request(&req) {
SessionReq::Init => {
pushes += 1;
send(&pipe, &state.cfg.session());
state.say(&format!("session: init answered ({pushes})"));
}
SessionReq::Installer => {
send(&pipe, &state.cfg.installer());
state.say("session: installer init answered");
}
SessionReq::ProductList(id) => {
send(&pipe, &state.cfg.product_list(id));
state.say(&format!("session: product list {id} answered"));
}
SessionReq::Other => match launcher::acknowledge(&req) {
Some((answer, what)) => {
send(&pipe, &answer);
state.say(&format!("session: {what}"));
}
None => state.say(&format!("session: {} B request {} not handled", req.len(), hex(&req, 24))),
},
}
}
state.say("session: closed");
}
fn denuvo(state: &State, rid: u64, challenge: &[u8]) -> Option<Vec<u8>> {
if state.cfg.bridge.is_empty() {
return None;
}
let dir = PathBuf::from(&state.cfg.bridge);
let _ = std::fs::create_dir_all(&dir);
let rsp = dir.join(format!("denuvo-{rid}.rsp"));
let _ = std::fs::remove_file(&rsp);
let part = dir.join(format!("denuvo-{rid}.req.part"));
std::fs::write(&part, challenge).ok()?;
std::fs::rename(&part, dir.join(format!("denuvo-{rid}.req"))).ok()?;
let deadline = Instant::now() + DENUVO_WAIT;
while Instant::now() < deadline {
if let Ok(token) = std::fs::read(&rsp) {
let _ = std::fs::remove_file(&rsp);
return (!token.is_empty()).then_some(token);
}
thread::sleep(Duration::from_millis(200));
}
None
}
fn aux(state: &State, pipe: Handle) {
let mut frames = Frames::new(&pipe);
while let Some(req) = frames.next() {
match launcher::aux_request(&req) {
AuxReq::Init(rid) => {
send(&pipe, &launcher::aux_init(rid, win::pid()));
state.say("aux: init answered");
}
AuxReq::Activate(rid, challenge) => {
state.say(&format!("aux: activation {rid} with a {} B challenge", challenge.len()));
match denuvo(state, rid, challenge) {
Some(token) => {
send(&pipe, &launcher::aux_token(rid, &token));
state.say(&format!("aux: activation {rid} answered ({} B)", token.len()));
}
None => state.say(&format!("aux: no game token for activation {rid}")),
}
}
AuxReq::Other(rid) => state.say(&format!("aux: request {rid} not handled ({} B)", req.len())),
}
}
}
fn service(state: &State, pipe: Handle) {
send(&pipe, &state.cfg.service_hello());
let mut chunk = vec![0u8; 65536];
while pipe.read(&mut chunk).is_some() {}
}
fn quiet(state: &State, name: &str, pipe: Handle) {
state.say(&format!("{name}: connected"));
let mut chunk = vec![0u8; 65536];
while let Some(n) = pipe.read(&mut chunk) {
state.say(&format!("{name}: {n} B unanswered {}", hex(&chunk[..n], 64)));
}
}
fn serve(state: Arc<State>, name: &'static str) {
thread::spawn(move || {
let full = format!("{}{name}", state.prefix);
loop {
let Some(pipe) = win::accept(&full) else {
state.say(&format!("{name}: cannot serve the pipe (error {})", win::last_error()));
return;
};
let s = state.clone();
thread::spawn(move || match name {
launcher::GAME_START => game_start(&s, pipe),
launcher::API_PROCESS => api_process(&s, pipe),
launcher::SESSION => session(&s, pipe),
launcher::AUX => aux(&s, pipe),
launcher::SERVICE => service(&s, pipe),
_ => quiet(&s, name, pipe),
});
}
});
}
fn hex(b: &[u8], n: usize) -> String {
b.iter().take(n).map(|x| format!("{x:02x}")).collect()
}
fn command_line(cfg: &Config) -> String {
let mut c = format!("\"{}\"", cfg.exe);
if !cfg.args.trim().is_empty() {
c.push(' ');
c.push_str(cfg.args.trim());
}
c
}
pub fn run() -> i32 {
let Some(path) = std::env::args().nth(1) else {
eprintln!("usage: droiddeck-upc <launch.json>");
return 2;
};
let parsed = std::fs::read_to_string(&path).map_err(|e| e.to_string()).and_then(|t| Config::parse(&t));
let _ = std::fs::remove_file(&path);
let cfg = match parsed {
Ok(c) => c,
Err(e) => {
eprintln!("droiddeck-upc: {e}");
return 2;
}
};
let log = (!cfg.log.is_empty()).then(|| OpenOptions::new().create(true).append(true).open(&cfg.log).ok()).flatten();
let state = Arc::new(State {
prefix: format!(r"\\.\pipe\terminal_{}_", win::session_id()),
cfg,
log: Mutex::new(log),
event: win::inheritable_event(),
game: AtomicU32::new(0),
started: Instant::now(),
});
state.say(&format!("product {} on {}*", state.cfg.product, state.prefix));
for name in [launcher::GAME_START, launcher::API_PROCESS, launcher::SESSION, launcher::AUX, launcher::SERVICE]
.into_iter()
.chain(launcher::QUIET.iter().copied())
{
serve(state.clone(), name);
}
thread::sleep(Duration::from_millis(300));
let (child, pid) = match win::spawn(&command_line(&state.cfg), &state.cfg.workdir) {
Ok(c) => c,
Err(e) => {
state.say(&format!("cannot start {} (error {e})", state.cfg.exe));
return 1;
}
};
state.say(&format!("started {} as process {pid}", state.cfg.exe));
while !child.wait(1000) {}
let mut code = child.exit_code();
state.say(&format!("process {pid} exited with 0x{code:08x}"));
let mut waiting = Instant::now();
let mut limit = ANNOUNCE_WAIT;
loop {
let game = state.game.swap(0, Ordering::SeqCst);
if game != 0 {
match win::open_process(game) {
Some(h) => {
while !h.wait(1000) {}
code = h.exit_code();
state.say(&format!("game process {game} exited with 0x{code:08x}"));
}
None => state.say(&format!("game process {game} is already gone")),
}
waiting = Instant::now();
limit = RESTART_WAIT;
continue;
}
if waiting.elapsed() >= limit {
break;
}
thread::sleep(Duration::from_millis(500));
}
state.say("done");
code as i32
}
}
+168
View File
@@ -0,0 +1,168 @@
//! The protobuf wire format, enough to build and read the launcher messages by field number.
pub fn varint(mut n: u64, out: &mut Vec<u8>) {
loop {
let b = (n & 0x7f) as u8;
n >>= 7;
if n == 0 {
out.push(b);
return;
}
out.push(b | 0x80);
}
}
#[derive(Default, Clone)]
pub struct Msg(pub Vec<u8>);
impl Msg {
pub fn new() -> Self {
Msg(Vec::new())
}
fn key(mut self, field: u32, wire: u8) -> Self {
varint(((field as u64) << 3) | wire as u64, &mut self.0);
self
}
pub fn uint(self, field: u32, value: u64) -> Self {
let mut m = self.key(field, 0);
varint(value, &mut m.0);
m
}
pub fn bytes(self, field: u32, value: &[u8]) -> Self {
let mut m = self.key(field, 2);
varint(value.len() as u64, &mut m.0);
m.0.extend_from_slice(value);
m
}
pub fn text(self, field: u32, value: &str) -> Self {
self.bytes(field, value.as_bytes())
}
pub fn msg(self, field: u32, value: Msg) -> Self {
self.bytes(field, &value.0)
}
pub fn float(self, field: u32, value: f32) -> Self {
let mut m = self.key(field, 5);
m.0.extend_from_slice(&value.to_le_bytes());
m
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Value<'a> {
Int(u64),
Bytes(&'a [u8]),
}
fn read_varint(b: &[u8], i: &mut usize) -> Option<u64> {
let mut r = 0u64;
let mut shift = 0;
loop {
let c = *b.get(*i)?;
*i += 1;
if shift >= 64 {
return None;
}
r |= ((c & 0x7f) as u64) << shift;
if c & 0x80 == 0 {
return Some(r);
}
shift += 7;
}
}
/// The top-level fields of a message, or `None` when it does not parse.
pub fn fields(b: &[u8]) -> Option<Vec<(u32, Value<'_>)>> {
let mut out = Vec::new();
let mut i = 0;
while i < b.len() {
let key = read_varint(b, &mut i)?;
let field = (key >> 3) as u32;
match key & 7 {
0 => out.push((field, Value::Int(read_varint(b, &mut i)?))),
1 => {
let v = b.get(i..i + 8)?;
i += 8;
out.push((field, Value::Int(u64::from_le_bytes(v.try_into().ok()?))));
}
2 => {
let n = read_varint(b, &mut i)? as usize;
let v = b.get(i..i.checked_add(n)?)?;
i += n;
out.push((field, Value::Bytes(v)));
}
5 => {
let v = b.get(i..i + 4)?;
i += 4;
out.push((field, Value::Int(u32::from_le_bytes(v.try_into().ok()?) as u64)));
}
_ => return None,
}
}
Some(out)
}
pub fn sub<'a>(f: &[(u32, Value<'a>)], field: u32) -> Option<&'a [u8]> {
f.iter().find_map(|(n, v)| match v {
Value::Bytes(b) if *n == field => Some(*b),
_ => None,
})
}
pub fn num(f: &[(u32, Value<'_>)], field: u32) -> Option<u64> {
f.iter().find_map(|(n, v)| match v {
Value::Int(x) if *n == field => Some(*x),
_ => None,
})
}
pub fn has(f: &[(u32, Value<'_>)], field: u32) -> bool {
f.iter().any(|(n, _)| *n == field)
}
/// The first length-delimited `field` at any depth up to `depth`, searching breadth first.
pub fn find(b: &[u8], field: u32, depth: u32) -> Option<&[u8]> {
let f = fields(b)?;
if let Some(v) = sub(&f, field) {
return Some(v);
}
if depth == 0 {
return None;
}
f.iter().find_map(|(_, v)| match v {
Value::Bytes(inner) => find(inner, field, depth - 1),
_ => None,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trip() {
let m = Msg::new().uint(1, 300).text(2, "hi").msg(3, Msg::new().uint(4, 1)).float(5, 1.0);
let f = fields(&m.0).unwrap();
assert_eq!(num(&f, 1), Some(300));
assert_eq!(sub(&f, 2), Some(&b"hi"[..]));
assert_eq!(num(&fields(sub(&f, 3).unwrap()).unwrap(), 4), Some(1));
assert_eq!(num(&f, 5), Some(0x3f80_0000));
}
#[test]
fn finds_nested_fields() {
let m = Msg::new().msg(1, Msg::new().msg(1, Msg::new().uint(2, 109).text(10, "C:/game.exe")));
assert_eq!(find(&m.0, 10, 4), Some(&b"C:/game.exe"[..]));
assert_eq!(find(&m.0, 11, 4), None);
}
#[test]
fn rejects_truncated_input() {
assert!(fields(&[0x0a, 0x05, 1, 2]).is_none());
}
}
+183
View File
@@ -0,0 +1,183 @@
//! The handful of kernel32 calls the launcher needs.
#![allow(non_snake_case, clippy::upper_case_acronyms)]
use std::ffi::c_void;
use std::os::windows::ffi::OsStrExt;
pub type HANDLE = *mut c_void;
pub const INVALID: HANDLE = -1isize as HANDLE;
const PIPE_ACCESS_DUPLEX: u32 = 3;
const PIPE_TYPE_BYTE: u32 = 0;
const PIPE_READMODE_BYTE: u32 = 0;
const PIPE_WAIT: u32 = 0;
const PIPE_UNLIMITED_INSTANCES: u32 = 255;
const ERROR_PIPE_CONNECTED: u32 = 535;
const HANDLE_FLAG_INHERIT: u32 = 1;
const SYNCHRONIZE: u32 = 0x0010_0000;
const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;
pub const WAIT_OBJECT_0: u32 = 0;
const BUFFER: u32 = 65536;
#[repr(C)]
struct STARTUPINFOW {
cb: u32,
lpReserved: *mut u16,
lpDesktop: *mut u16,
lpTitle: *mut u16,
dwX: u32,
dwY: u32,
dwXSize: u32,
dwYSize: u32,
dwXCountChars: u32,
dwYCountChars: u32,
dwFillAttribute: u32,
dwFlags: u32,
wShowWindow: u16,
cbReserved2: u16,
lpReserved2: *mut u8,
hStdInput: HANDLE,
hStdOutput: HANDLE,
hStdError: HANDLE,
}
#[repr(C)]
struct PROCESS_INFORMATION {
hProcess: HANDLE,
hThread: HANDLE,
dwProcessId: u32,
dwThreadId: u32,
}
#[link(name = "kernel32")]
extern "system" {
fn CreateNamedPipeW(name: *const u16, open: u32, mode: u32, max: u32, out: u32, inp: u32, timeout: u32, sa: *mut c_void) -> HANDLE;
fn ConnectNamedPipe(h: HANDLE, ov: *mut c_void) -> i32;
fn ReadFile(h: HANDLE, buf: *mut u8, n: u32, read: *mut u32, ov: *mut c_void) -> i32;
fn WriteFile(h: HANDLE, buf: *const u8, n: u32, written: *mut u32, ov: *mut c_void) -> i32;
fn FlushFileBuffers(h: HANDLE) -> i32;
fn CloseHandle(h: HANDLE) -> i32;
fn GetLastError() -> u32;
fn CreateEventW(sa: *mut c_void, manual: i32, initial: i32, name: *const u16) -> HANDLE;
fn SetEvent(h: HANDLE) -> i32;
fn SetHandleInformation(h: HANDLE, mask: u32, flags: u32) -> i32;
fn CreateProcessW(app: *const u16, cmd: *mut u16, pa: *mut c_void, ta: *mut c_void, inherit: i32, flags: u32,
env: *mut c_void, cwd: *const u16, si: *mut STARTUPINFOW, pi: *mut PROCESS_INFORMATION) -> i32;
fn WaitForSingleObject(h: HANDLE, ms: u32) -> u32;
fn GetExitCodeProcess(h: HANDLE, code: *mut u32) -> i32;
fn OpenProcess(access: u32, inherit: i32, pid: u32) -> HANDLE;
fn ProcessIdToSessionId(pid: u32, session: *mut u32) -> i32;
fn GetCurrentProcessId() -> u32;
}
pub fn wide(s: &str) -> Vec<u16> {
std::ffi::OsStr::new(s).encode_wide().chain(Some(0)).collect()
}
pub fn last_error() -> u32 {
unsafe { GetLastError() }
}
pub fn pid() -> u32 {
unsafe { GetCurrentProcessId() }
}
pub fn session_id() -> u32 {
let mut s = 0;
if unsafe { ProcessIdToSessionId(GetCurrentProcessId(), &mut s) } == 0 {
return 1;
}
s
}
pub struct Handle(pub HANDLE);
unsafe impl Send for Handle {}
unsafe impl Sync for Handle {}
impl Drop for Handle {
fn drop(&mut self) {
if !self.0.is_null() && self.0 != INVALID {
unsafe { CloseHandle(self.0) };
}
}
}
impl Handle {
pub fn read(&self, buf: &mut [u8]) -> Option<usize> {
let mut n = 0u32;
let ok = unsafe { ReadFile(self.0, buf.as_mut_ptr(), buf.len() as u32, &mut n, std::ptr::null_mut()) };
(ok != 0 && n > 0).then_some(n as usize)
}
pub fn write_all(&self, mut data: &[u8]) -> bool {
while !data.is_empty() {
let mut n = 0u32;
if unsafe { WriteFile(self.0, data.as_ptr(), data.len() as u32, &mut n, std::ptr::null_mut()) } == 0 || n == 0 {
return false;
}
data = &data[n as usize..];
}
unsafe { FlushFileBuffers(self.0) };
true
}
pub fn wait(&self, ms: u32) -> bool {
unsafe { WaitForSingleObject(self.0, ms) == WAIT_OBJECT_0 }
}
pub fn exit_code(&self) -> u32 {
let mut c = 0;
unsafe { GetExitCodeProcess(self.0, &mut c) };
c
}
pub fn set(&self) {
unsafe { SetEvent(self.0) };
}
}
/// A new instance of the named pipe, waiting for its client; `None` when it cannot be created.
pub fn accept(name: &str) -> Option<Handle> {
let w = wide(name);
let h = unsafe {
CreateNamedPipeW(w.as_ptr(), PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES, BUFFER, BUFFER, 0, std::ptr::null_mut())
};
if h == INVALID {
return None;
}
let pipe = Handle(h);
if unsafe { ConnectNamedPipe(h, std::ptr::null_mut()) } == 0 && last_error() != ERROR_PIPE_CONNECTED {
return None;
}
Some(pipe)
}
/// An auto-reset event the started process inherits.
pub fn inheritable_event() -> Handle {
let h = unsafe { CreateEventW(std::ptr::null_mut(), 0, 0, std::ptr::null()) };
unsafe { SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) };
Handle(h)
}
pub fn spawn(command_line: &str, cwd: &str) -> Result<(Handle, u32), u32> {
let mut cmd = wide(command_line);
let dir = wide(cwd);
let mut si: STARTUPINFOW = unsafe { std::mem::zeroed() };
si.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
let ok = unsafe {
CreateProcessW(std::ptr::null(), cmd.as_mut_ptr(), std::ptr::null_mut(), std::ptr::null_mut(), 1, 0,
std::ptr::null_mut(), if cwd.is_empty() { std::ptr::null() } else { dir.as_ptr() }, &mut si, &mut pi)
};
if ok == 0 {
return Err(last_error());
}
drop(Handle(pi.hThread));
Ok((Handle(pi.hProcess), pi.dwProcessId))
}
pub fn open_process(pid: u32) -> Option<Handle> {
let h = unsafe { OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
(!h.is_null()).then(|| Handle(h))
}