mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 14:26:00 +00:00
feat(ea, ubisoft): cloud saves and a kept Ubisoft Denuvo token (#2824)
* feat(ubisoft): keep Denuvo game tokens per account and product until the game invalidates them * feat(ubisoft): sync cloud saves through Ubisoft's cloud save service * fix(xbox): turning cloud saves off passes the offline mode the game save runtime reads * fix(ubisoft): Ubisoft games list their shared prefix, so they get a saves and cloud tab * feat(ea): sync cloud saves through EA's cloud sync service * fix(ea): sync at EA launch and exit, keep one rule snapshot, and check the cloud copy under the write lock * fix(ubisoft): exact slot versions, scoped save export, and a Denuvo cache bound to its account * fix(ea): fresh rules per sync, checksums required, backup before restore, and sign-in shown on the saves tab * fix(ubisoft): launch-time sync on the shared prefix, saves scoped to the game, and Denuvo bound to each launch's account * fix(ea): back up only the saves a restore replaces, refuse truncated manifests, and need a master title id * fix(ubisoft): treat a slot whose bytes changed since the last sync as a conflict before uploading over it * fix(ea): one resolved save folder per sync, refuse case collisions, and walk each folder once * fix(ubisoft): sync only identified slots, keep live saves and backups safe, and tie a pending eviction to its account * fix(cloud): a forced download fetches every saved conflict and keeps the ones it could not write * test(ea): keep the cloud save cases in EaTest * fix(ubisoft): report only written slots, keep drift conflicts, read whole headers, and never rename a named eviction * fix(ea): keep real save folders in the inventory, back up any restored file, refuse duplicate or malformed cloud listings * fix(cloud): commit Ubisoft slots one at a time and stop on a newer cloud write, name skipped and blocked slots, keep unsent conflicts * fix(ubisoft): acknowledge an invalidation only once its marker is published and never serve a kept token after it * fix(cloud): a cloud request the launcher cannot write still starts the game and keeps the exit upload * fix(cloud): scope Ubisoft sync state to the account and product, compare alike slots, keep committed progress, and name partial slots * fix(ea): ask for sign-in after a rejected refresh, upload saves reached through folder aliases * fix(cloud): a launch that stops waiting for the cloud download claims it back, so no save is written once the game starts * fix(ubisoft): name the account in an invalidation marker and never hold the token lock across a pipe write * fix(ea): only invalid_grant asks for sign-in again, and case collisions count only among synced saves * test(epic): let the launcher's ask doubles take the claim flag * fix(ea): apply save rules in their order, match bare patterns inside the save folder, and resolve LocalLow and install folders * fix(ubisoft): stamp a fresh identifier into a new save that has none, so it can sync * fix(ubisoft): answer a burn ticket request as unavailable instead of leaving the game waiting * fix(cloud): read EA manifests with the XML parser, clear conflicts whose sides match, and bound the claim and stall tests
This commit is contained in:
1 parent
6ed281f78d
commit
123c431b8e
31 files changed
+1999
-132
No files matched your search
@@ -116,7 +116,7 @@ def through_client(folder, sidecar, timeout=CLIENT_TIMEOUT):
|
||||
return str(answer.get("reason") or "failed")
|
||||
|
||||
|
||||
def ask(channel, request, timeout=TIMEOUT):
|
||||
def ask(channel, request, timeout=TIMEOUT, claim=False):
|
||||
req_dir, resp_dir = channel / "req", channel / "resp"
|
||||
req_dir.mkdir(parents=True, exist_ok=True)
|
||||
resp_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -125,19 +125,33 @@ def ask(channel, request, timeout=TIMEOUT):
|
||||
tmp.write_text(json.dumps(request))
|
||||
os.rename(tmp, req_dir / (rid + ".json"))
|
||||
answer = resp_dir / (rid + ".json")
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
|
||||
def wait(seconds):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = json.loads(answer.read_text())
|
||||
answer.unlink()
|
||||
return value
|
||||
except (OSError, ValueError):
|
||||
time.sleep(0.05)
|
||||
return None
|
||||
|
||||
value = wait(timeout)
|
||||
if value is not None:
|
||||
return value
|
||||
for pending in (req_dir / (rid + ".json"), resp_dir / (rid + ".taken")):
|
||||
abandoned = pending.with_name(rid + ".abandoned")
|
||||
try:
|
||||
value = json.loads(answer.read_text())
|
||||
answer.unlink()
|
||||
return value
|
||||
except (OSError, ValueError):
|
||||
time.sleep(0.05)
|
||||
try:
|
||||
(req_dir / (rid + ".json")).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
os.rename(pending, abandoned)
|
||||
except OSError:
|
||||
continue
|
||||
try:
|
||||
abandoned.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
return wait(CLAIMED_TIMEOUT) if claim else None
|
||||
|
||||
|
||||
def windows_path(unix):
|
||||
@@ -255,7 +269,8 @@ def create_prefix(compat_data, proton, timeout=120):
|
||||
|
||||
|
||||
CLOUD_TIMEOUT = 15.0
|
||||
CLOUD_STORES = ("gog", "epic")
|
||||
CLAIMED_TIMEOUT = 120.0
|
||||
CLOUD_STORES = ("gog", "epic", "ea", "ubisoft")
|
||||
STORE_GAME = 10
|
||||
RAN = 11
|
||||
RAN_FAILED = 12
|
||||
@@ -304,11 +319,14 @@ def exited(argv, code=0):
|
||||
if found is not None and launch_dir and str(found[1].get("store")) == "ea":
|
||||
ask(Path(launch_dir) / "stores", {"op": "ea-exited", "store": "ea", "id": str(found[1].get("id"))}, timeout=1.0)
|
||||
log("ea %s exited" % found[1].get("id"))
|
||||
return 0
|
||||
if found is None or not launch_dir or not cloud_on(found[1]):
|
||||
return 0
|
||||
store, game = str(found[1].get("store")), str(found[1].get("id"))
|
||||
ask(Path(launch_dir) / "stores", {"op": "cloud-up", "store": store, "id": game}, timeout=1.0)
|
||||
try:
|
||||
ask(Path(launch_dir) / "stores", {"op": "cloud-up", "store": store, "id": game}, timeout=1.0)
|
||||
except OSError as error:
|
||||
log("cloud %s %s up not requested (%s)" % (store, game, type(error).__name__))
|
||||
return 0
|
||||
log("cloud %s %s up requested" % (store, game))
|
||||
return 0
|
||||
|
||||
@@ -1601,7 +1619,7 @@ def main(argv):
|
||||
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
|
||||
prefix_id = os.path.basename(compat_data) if compat_data else ""
|
||||
launch_dir = os.environ.get("DD_LAUNCH_DIR", "")
|
||||
if launch_dir and cloud_on(sidecar):
|
||||
if launch_dir and cloud_on(sidecar) and store != "ea":
|
||||
made = create_prefix(compat_data, os.environ.get("DD_STORE_PROTON", ""))
|
||||
if made != "present":
|
||||
log("cloud %s %s prefix=%s" % (store, game, made))
|
||||
@@ -1670,13 +1688,16 @@ def main(argv):
|
||||
log("epic prefix=%s %s" % (prefix_id or "?", provision_prefix(compat_data)))
|
||||
if store == "ea":
|
||||
prepare_ea(folder, sidecar, compat_data, launch_dir)
|
||||
return STORE_GAME
|
||||
if not cloud_on(sidecar):
|
||||
if store in CLOUD_STORES:
|
||||
log("cloud %s %s down result=skipped reason=off" % (store, game))
|
||||
return 0
|
||||
return STORE_GAME if store == "ea" else 0
|
||||
if launch_dir:
|
||||
answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT)
|
||||
try:
|
||||
answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT, claim=True)
|
||||
except OSError as error:
|
||||
log("cloud %s %s down result=failed reason=%s" % (store, game, type(error).__name__))
|
||||
return STORE_GAME
|
||||
if answer is None:
|
||||
log("cloud %s %s down result=timeout" % (store, game))
|
||||
else:
|
||||
|
||||
@@ -518,7 +518,7 @@ def launch(command, env):
|
||||
context.chmod(0o600)
|
||||
owned_env = dict(env, DROIDDECK_XBOX_ACTIVE='1', DROIDDECK_XBOX_COMMAND_FILE=str(context),
|
||||
XODUS_SOCKET=reply['socket'], XODUS_BRIDGE_PORT=str(port), XODUS_BRIDGE_KEY=key,
|
||||
XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'off')
|
||||
XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'none')
|
||||
for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'):
|
||||
owned_env.pop(name, None)
|
||||
if reply.get('playfab'):
|
||||
|
||||
@@ -1318,7 +1318,7 @@ class StoreLaunchClientTest(unittest.TestCase):
|
||||
(self.folder / ".droiddeck-store.json").write_text(json.dumps(sidecar))
|
||||
with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.tmp / "launch"), "STEAM_COMPAT_DATA_PATH": ""}), \
|
||||
mock.patch.dict(S, {"client_wanted": lambda: calls.append("wanted") or True,
|
||||
"ask": lambda channel, request, timeout=0: calls.append(request["op"]) or {"ok": True}}):
|
||||
"ask": lambda channel, request, timeout=0, claim=False: calls.append(request["op"]) or {"ok": True}}):
|
||||
S["main"]([str(self.folder / ".droiddeck-launch.bat")])
|
||||
self.assertNotIn("wanted", calls)
|
||||
self.assertNotIn("epic-code", calls)
|
||||
@@ -1341,7 +1341,7 @@ class StoreLaunchClientTest(unittest.TestCase):
|
||||
with mock.patch.dict(os.environ, env), \
|
||||
mock.patch.dict(S, {"client_wanted": lambda: True,
|
||||
"through_client": lambda folder, sidecar, timeout=0: calls.append("client") or "timeout",
|
||||
"ask": lambda channel, request, timeout=0: calls.append(request["op"]) or {"ok": True, "code": True}}):
|
||||
"ask": lambda channel, request, timeout=0, claim=False: calls.append(request["op"]) or {"ok": True, "code": True}}):
|
||||
S["main"]([str(self.folder / ".droiddeck-launch.bat")])
|
||||
self.assertEqual(["client", "epic-code", "cloud-down"], calls)
|
||||
|
||||
@@ -1356,7 +1356,7 @@ class StoreLaunchClientTest(unittest.TestCase):
|
||||
(self.folder / ".droiddeck-epic-code").write_text("stale")
|
||||
with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.tmp / "launch"), "STEAM_COMPAT_DATA_PATH": ""}), \
|
||||
mock.patch.dict(S, {"client_wanted": lambda: True, "through_client": through,
|
||||
"ask": lambda channel, request, timeout=0: calls.append(request["op"]) or {"ok": True}}):
|
||||
"ask": lambda channel, request, timeout=0, claim=False: calls.append(request["op"]) or {"ok": True}}):
|
||||
S["main"]([str(self.folder / ".droiddeck-launch.bat")])
|
||||
self.assertEqual(["client", "cloud-down"], calls)
|
||||
self.assertFalse((self.folder / ".droiddeck-epic-code").exists())
|
||||
@@ -1368,7 +1368,7 @@ class StoreLaunchClientTest(unittest.TestCase):
|
||||
with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.tmp / "launch"), "DROIDDECK_EPIC_HANDLED": "1",
|
||||
"STEAM_COMPAT_DATA_PATH": ""}), \
|
||||
mock.patch.dict(S, {"client_wanted": lambda: calls.append("wanted") or True,
|
||||
"ask": lambda channel, request, timeout=0: calls.append(request["op"]) or {"ok": True}}):
|
||||
"ask": lambda channel, request, timeout=0, claim=False: calls.append(request["op"]) or {"ok": True}}):
|
||||
S["main"]([str(self.folder / ".droiddeck-launch.bat")])
|
||||
self.assertEqual(["cloud-down"], calls)
|
||||
self.assertTrue((self.folder / ".droiddeck-epic-args").exists())
|
||||
|
||||
@@ -106,6 +106,62 @@ class Asking(unittest.TestCase):
|
||||
self.assertIsNone(store.ask(channel, {'op': 'epic-code'}, timeout=0.2))
|
||||
self.assertEqual([], list((channel / 'req').iterdir()))
|
||||
|
||||
def test_a_cloud_download_the_launcher_stops_waiting_for_loses_its_claim(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
channel = Path(root) / 'stores'
|
||||
taken = []
|
||||
handed = threading.Event()
|
||||
|
||||
def app():
|
||||
deadline = time.monotonic() + 5
|
||||
while not taken and time.monotonic() < deadline:
|
||||
for request in (channel / 'req').glob('*.json') if (channel / 'req').is_dir() else []:
|
||||
target = channel / 'resp' / (request.stem + '.taken')
|
||||
os.rename(request, target)
|
||||
taken.append(target)
|
||||
handed.set()
|
||||
time.sleep(0.02)
|
||||
|
||||
t = threading.Thread(target=app, daemon=True)
|
||||
t.start()
|
||||
try:
|
||||
self.assertIsNone(store.ask(channel, {'op': 'cloud-down'}, timeout=2.0, claim=True))
|
||||
finally:
|
||||
t.join(5)
|
||||
self.assertTrue(handed.is_set(), 'the app never took the request')
|
||||
with self.assertRaises(OSError):
|
||||
os.rename(taken[0], taken[0].with_suffix('.writing'))
|
||||
|
||||
def test_a_claimed_cloud_download_is_waited_for(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
channel = Path(root) / 'stores'
|
||||
handed = threading.Event()
|
||||
|
||||
def app():
|
||||
deadline = time.monotonic() + 5
|
||||
while time.monotonic() < deadline:
|
||||
names = list((channel / 'req').glob('*.json')) if (channel / 'req').is_dir() else []
|
||||
if names:
|
||||
handed.set()
|
||||
writing = channel / 'resp' / (names[0].stem + '.writing')
|
||||
os.rename(names[0], writing)
|
||||
time.sleep(0.6)
|
||||
tmp = channel / 'resp' / (names[0].name + '.tmp')
|
||||
tmp.write_text(json.dumps({'ok': True, 'result': 'ok'}))
|
||||
os.rename(tmp, channel / 'resp' / names[0].name)
|
||||
writing.unlink()
|
||||
return
|
||||
time.sleep(0.02)
|
||||
|
||||
t = threading.Thread(target=app, daemon=True)
|
||||
t.start()
|
||||
try:
|
||||
answer = store.ask(channel, {'op': 'cloud-down'}, timeout=0.2, claim=True)
|
||||
finally:
|
||||
t.join(5)
|
||||
self.assertTrue(handed.is_set(), 'the app never took the request')
|
||||
self.assertEqual({'ok': True, 'result': 'ok'}, answer)
|
||||
|
||||
def test_a_stale_code_is_dropped_before_asking(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root)
|
||||
@@ -214,7 +270,7 @@ class CloudHooks(unittest.TestCase):
|
||||
try:
|
||||
original = store.ask
|
||||
asked = []
|
||||
store.ask = lambda channel, request, timeout=5.0: asked.append((request, timeout)) or {'ok': True, 'files': 2, 'reason': 'ok'}
|
||||
store.ask = lambda channel, request, timeout=5.0, claim=False: asked.append((request, timeout)) or {'ok': True, 'files': 2, 'reason': 'ok'}
|
||||
self.assertEqual(store.STORE_GAME, store.main([bat]))
|
||||
self.assertEqual(0, store.main(['--exited', bat]))
|
||||
finally:
|
||||
@@ -225,6 +281,55 @@ class CloudHooks(unittest.TestCase):
|
||||
self.assertEqual(store.CLOUD_TIMEOUT, asked[1][1])
|
||||
self.assertEqual('cloud-up', asked[2][0]['op'])
|
||||
|
||||
def test_a_cloud_request_that_cannot_be_written_still_starts_the_game_and_uploads_on_exit(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='ubisoft', ident='space-1')
|
||||
sc = json.loads((folder / '.droiddeck-store.json').read_text()); sc['extra'] = {'productId': '109'}
|
||||
(folder / '.droiddeck-store.json').write_text(json.dumps(sc))
|
||||
bat = str(folder / '.droiddeck-launch.bat')
|
||||
asked = []
|
||||
|
||||
def ask(channel, request, timeout=5.0, claim=False):
|
||||
asked.append(request['op'])
|
||||
if request['op'] in ('cloud-down', 'cloud-up'):
|
||||
raise PermissionError(13, 'read-only')
|
||||
return {'ok': True}
|
||||
|
||||
lines = []
|
||||
with patch.dict(os.environ, {'DD_LAUNCH_DIR': str(Path(root) / 'session')}), patch.object(store, 'ask', side_effect=ask), patch.object(store, 'prepare_ubisoft', return_value='ready'), patch.object(store, 'create_prefix', return_value='present'), patch.object(store, 'log', side_effect=lines.append):
|
||||
self.assertEqual(store.STORE_GAME, store.main([bat]))
|
||||
self.assertEqual(0, store.main(['--exited', bat]))
|
||||
self.assertEqual(['cloud-down', 'cloud-up'], [op for op in asked if op.startswith('cloud-')])
|
||||
self.assertIn('cloud ubisoft space-1 down result=failed reason=PermissionError', lines)
|
||||
self.assertIn('cloud ubisoft space-1 up not requested (PermissionError)', lines)
|
||||
def test_an_ea_game_with_cloud_saves_asks_after_its_preparation_and_exit(self):
|
||||
ident = 'Origin.OFR.50.0002694'
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='ea', ident=ident)
|
||||
bat = str(folder / '.droiddeck-launch.bat')
|
||||
asked = []
|
||||
env = {'DD_LAUNCH_DIR': str(Path(root) / 'session')}
|
||||
record = lambda channel, request, timeout=5.0, claim=False: asked.append(request) or {'result': 'ok'}
|
||||
with patch.dict(os.environ, env), \
|
||||
patch.object(store, 'prepare_ea', side_effect=lambda *a: asked.append({'op': 'prepared'})), \
|
||||
patch.object(store, 'create_prefix', side_effect=AssertionError('EA prepares its own prefix')), \
|
||||
patch.object(store, 'ask', side_effect=record):
|
||||
self.assertEqual(store.STORE_GAME, store.main([bat]))
|
||||
self.assertEqual(['prepared', 'cloud-down'], [r['op'] for r in asked])
|
||||
self.assertEqual({'op': 'cloud-down', 'store': 'ea', 'id': ident}, asked[1])
|
||||
self.assertEqual(0, store.main(['--exited', bat]))
|
||||
self.assertEqual(['ea-exited', 'cloud-up'], [r['op'] for r in asked[2:]])
|
||||
self.assertEqual({'op': 'cloud-up', 'store': 'ea', 'id': ident}, asked[3])
|
||||
sidecar = json.loads((folder / store.SIDECAR).read_text())
|
||||
sidecar['cloud'] = False
|
||||
(folder / store.SIDECAR).write_text(json.dumps(sidecar))
|
||||
asked.clear()
|
||||
with patch.dict(os.environ, env), patch.object(store, 'prepare_ea'), patch.object(store, 'ask', side_effect=record):
|
||||
self.assertEqual(store.STORE_GAME, store.main([bat]))
|
||||
self.assertEqual([], asked)
|
||||
self.assertEqual(0, store.main(['--exited', bat]))
|
||||
self.assertEqual(['ea-exited'], [r['op'] for r in asked])
|
||||
|
||||
def test_a_first_launch_creates_the_prefix_before_the_cloud_download(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='epic', ident='fa4240e5')
|
||||
@@ -244,7 +349,7 @@ class CloudHooks(unittest.TestCase):
|
||||
|
||||
env = {'DD_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': str(compat), 'DD_STORE_PROTON': str(proton)}
|
||||
with patch.dict(os.environ, env), patch.object(store.subprocess, 'run', side_effect=run), \
|
||||
patch.object(store, 'ask', side_effect=lambda channel, request, timeout=5.0: order.append(request) or {'result': 'ok'}):
|
||||
patch.object(store, 'ask', side_effect=lambda channel, request, timeout=5.0, claim=False: order.append(request) or {'result': 'ok'}):
|
||||
self.assertEqual(store.STORE_GAME, store.main([str(folder / store.LAUNCHER)]))
|
||||
self.assertEqual([str(proton), 'run', 'cmd.exe', '/d', '/c', 'exit'], order[0])
|
||||
self.assertEqual({'op': 'cloud-down', 'store': 'epic', 'id': 'fa4240e5'}, order[-1])
|
||||
|
||||
@@ -147,7 +147,7 @@ class EaHook(unittest.TestCase):
|
||||
folder.mkdir()
|
||||
asked = {}
|
||||
|
||||
def fake_ask(channel, request, timeout=5.0):
|
||||
def fake_ask(channel, request, timeout=5.0, claim=False):
|
||||
asked.update(request)
|
||||
return {'ok': True, 'lsx': True, 'license': 'ok v4', 'licenses': [{'path': 'ProgramData/L/x.dlf', 'data': base64.b64encode(b'z').decode()}]}
|
||||
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
//! The file bridge DroidDeck answers Denuvo activations through.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::{Condvar, Mutex};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
pub const INVALIDATE: &str = "denuvo-invalidate";
|
||||
|
||||
pub fn publish_invalidation(dir: &Path, account: &str, tries: u32, pause: Duration) -> bool {
|
||||
let marker = dir.join(INVALIDATE);
|
||||
let part = dir.join(format!("{INVALIDATE}.upc"));
|
||||
for attempt in 0..tries {
|
||||
if marker.is_file() {
|
||||
return true;
|
||||
}
|
||||
if std::fs::write(&part, account.as_bytes()).is_ok() && std::fs::rename(&part, &marker).is_ok() {
|
||||
return true;
|
||||
}
|
||||
let _ = std::fs::remove_file(&part);
|
||||
if attempt + 1 < tries {
|
||||
thread::sleep(pause);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Generation {
|
||||
state: Mutex<(u64, usize)>,
|
||||
idle: Condvar,
|
||||
}
|
||||
|
||||
impl Generation {
|
||||
pub fn current(&self) -> u64 {
|
||||
self.state.lock().unwrap().0
|
||||
}
|
||||
|
||||
pub fn invalidate<T>(&self, wait: Duration, acknowledge: impl FnOnce() -> T) -> T {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
state.0 += 1;
|
||||
let _ = self.idle.wait_timeout_while(state, wait, |s| s.1 > 0).unwrap();
|
||||
acknowledge()
|
||||
}
|
||||
|
||||
pub fn serve<T>(&self, seen: u64, reply: impl FnOnce() -> T) -> Option<T> {
|
||||
{
|
||||
let mut state = self.state.lock().unwrap();
|
||||
if state.0 != seen {
|
||||
return None;
|
||||
}
|
||||
state.1 += 1;
|
||||
}
|
||||
let out = reply();
|
||||
self.state.lock().unwrap().1 -= 1;
|
||||
self.idle.notify_all();
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
fn dir(name: &str) -> std::path::PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("upc-bridge-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalidation_is_published_as_the_marker() {
|
||||
let d = dir("publish");
|
||||
assert!(publish_invalidation(&d, "user-a", 1, Duration::ZERO));
|
||||
assert_eq!(std::fs::read(d.join(INVALIDATE)).unwrap(), b"user-a");
|
||||
assert!(!d.join("denuvo-invalidate.upc").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marker_naming_its_account_is_kept() {
|
||||
let d = dir("named");
|
||||
std::fs::write(d.join(INVALIDATE), b"user-a").unwrap();
|
||||
assert!(publish_invalidation(&d, "user-b", 1, Duration::ZERO));
|
||||
assert_eq!(std::fs::read(d.join(INVALIDATE)).unwrap(), b"user-a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marker_that_cannot_be_written_is_reported_after_every_try() {
|
||||
let d = dir("missing").join("gone");
|
||||
let started = Instant::now();
|
||||
assert!(!publish_invalidation(&d, "user-a", 3, Duration::from_millis(20)));
|
||||
assert!(started.elapsed() >= Duration::from_millis(40));
|
||||
assert!(!d.join(INVALIDATE).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marker_written_while_retrying_counts() {
|
||||
let d = dir("late").join("bridge");
|
||||
let later = d.clone();
|
||||
let maker = thread::spawn(move || {
|
||||
thread::sleep(Duration::from_millis(30));
|
||||
std::fs::create_dir_all(later).unwrap();
|
||||
});
|
||||
assert!(publish_invalidation(&d, "user-a", 50, Duration::from_millis(10)));
|
||||
maker.join().unwrap();
|
||||
assert!(d.join(INVALIDATE).is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_token_asked_for_before_an_invalidation_is_not_served_after_it() {
|
||||
let g = Generation::default();
|
||||
let seen = g.current();
|
||||
assert_eq!(g.invalidate(Duration::from_secs(1), || "acknowledged"), "acknowledged");
|
||||
assert_eq!(g.serve(seen, || "token"), None);
|
||||
assert_eq!(g.serve(g.current(), || "token"), Some("token"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reply_being_served_holds_the_acknowledgement_back() {
|
||||
let g = Arc::new(Generation::default());
|
||||
let order = Arc::new(Mutex::new(Vec::new()));
|
||||
let seen = g.current();
|
||||
let (g2, o2) = (g.clone(), order.clone());
|
||||
let served = g.serve(seen, || {
|
||||
let ack = thread::spawn(move || g2.invalidate(Duration::from_secs(5), || o2.lock().unwrap().push("acknowledged")));
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
order.lock().unwrap().push("token");
|
||||
ack
|
||||
});
|
||||
served.unwrap().join().unwrap();
|
||||
assert_eq!(*order.lock().unwrap(), vec!["token", "acknowledged"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reply_that_stalls_never_blocks_other_connections_or_the_acknowledgement_for_long() {
|
||||
let g = Arc::new(Generation::default());
|
||||
let seen = g.current();
|
||||
let (entered, inside) = std::sync::mpsc::channel();
|
||||
let (release, held) = std::sync::mpsc::channel::<()>();
|
||||
let stalled = {
|
||||
let g = g.clone();
|
||||
thread::spawn(move || g.serve(seen, move || {
|
||||
entered.send(()).unwrap();
|
||||
let _ = held.recv();
|
||||
}))
|
||||
};
|
||||
inside.recv().unwrap();
|
||||
let started = Instant::now();
|
||||
assert_eq!(g.current(), seen);
|
||||
assert_eq!(g.serve(seen, || "other"), Some("other"));
|
||||
assert!(started.elapsed() < Duration::from_millis(200));
|
||||
assert_eq!(g.invalidate(Duration::from_millis(100), || "acknowledged"), "acknowledged");
|
||||
assert!(started.elapsed() < Duration::from_millis(450));
|
||||
assert_eq!(g.serve(seen, || "late"), None);
|
||||
release.send(()).unwrap();
|
||||
assert!(stalled.join().unwrap().is_some());
|
||||
}
|
||||
}
|
||||
@@ -338,6 +338,8 @@ pub fn announced(body: &[u8]) -> Option<(Option<u32>, Option<u32>)> {
|
||||
pub enum AuxReq<'a> {
|
||||
Init(u64),
|
||||
Activate(u64, &'a [u8]),
|
||||
Invalidate(u64),
|
||||
BurnTicket(u64),
|
||||
Other(u64),
|
||||
}
|
||||
|
||||
@@ -348,8 +350,14 @@ pub fn aux_request(body: &[u8]) -> AuxReq<'_> {
|
||||
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))
|
||||
let Some(a) = pb::fields(activate) else { return AuxReq::Other(rid) };
|
||||
if pb::has(&a, 1) && !pb::has(&a, 2) {
|
||||
return AuxReq::Invalidate(rid);
|
||||
}
|
||||
if pb::has(&a, 3) && !pb::has(&a, 2) {
|
||||
return AuxReq::BurnTicket(rid);
|
||||
}
|
||||
let token = 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),
|
||||
@@ -365,6 +373,15 @@ pub fn aux_init(rid: u64, pid: u32) -> Vec<u8> {
|
||||
Msg::new().uint(1, rid).msg(2, init).0
|
||||
}
|
||||
|
||||
pub fn aux_invalidated(rid: u64) -> Vec<u8> {
|
||||
Msg::new().uint(1, rid).msg(3, Msg::new()).0
|
||||
}
|
||||
|
||||
pub fn aux_no_burn_ticket(rid: u64) -> Vec<u8> {
|
||||
let answer = Msg::new().uint(2, 3).uint(3, 3);
|
||||
Msg::new().uint(1, rid).msg(3, Msg::new().msg(3, answer)).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
|
||||
@@ -476,6 +493,30 @@ mod tests {
|
||||
assert!(matches!(aux_request(&Msg::new().uint(1, 1).msg(2, Msg::new().uint(1, 109)).0), AuxReq::Init(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalidation_is_recognised_and_acknowledged_with_an_empty_activation() {
|
||||
let req = Msg::new().uint(1, 5).msg(3, Msg::new().msg(1, Msg::new()));
|
||||
assert!(matches!(aux_request(&req.0), AuxReq::Invalidate(5)));
|
||||
let rsp = pb::fields(&aux_invalidated(5)).unwrap().into_iter().map(|(n, _)| n).collect::<Vec<_>>();
|
||||
assert_eq!(rsp, vec![1, 3]);
|
||||
assert_eq!(pb::sub(&pb::fields(&aux_invalidated(5)).unwrap(), 3), Some(&b""[..]));
|
||||
let burn = Msg::new().uint(1, 6).msg(3, Msg::new().msg(3, Msg::new().bytes(2, b"t")));
|
||||
assert!(matches!(aux_request(&burn.0), AuxReq::BurnTicket(6)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burn_ticket_request_is_answered_with_a_connection_error() {
|
||||
let rsp = aux_no_burn_ticket(6);
|
||||
let top = pb::fields(&rsp).unwrap();
|
||||
assert_eq!(pb::num(&top, 1), Some(6));
|
||||
let activate = pb::fields(pb::sub(&top, 3).unwrap()).unwrap();
|
||||
assert!(!pb::has(&activate, 2));
|
||||
let burn = pb::fields(pb::sub(&activate, 3).unwrap()).unwrap();
|
||||
assert_eq!(pb::num(&burn, 2), Some(3));
|
||||
assert_eq!(pb::num(&burn, 3), Some(3));
|
||||
assert!(!pb::has(&burn, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orbit_init_answers_with_the_save_folder() {
|
||||
let (rsp, what) = config().orbit(&[0x08, 0x01, 0x62, 0x03, 0x08, 0xcd, 0x01]).unwrap();
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
#![cfg_attr(windows, windows_subsystem = "windows")]
|
||||
|
||||
mod bridge;
|
||||
mod launcher;
|
||||
mod pb;
|
||||
#[cfg(windows)]
|
||||
@@ -22,12 +23,13 @@ fn main() {
|
||||
|
||||
#[cfg(windows)]
|
||||
mod service {
|
||||
use crate::bridge::{self, Generation};
|
||||
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::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -36,6 +38,9 @@ mod service {
|
||||
const ANNOUNCE_WAIT: Duration = Duration::from_secs(120);
|
||||
const RESTART_WAIT: Duration = Duration::from_secs(15);
|
||||
const DENUVO_WAIT: Duration = Duration::from_secs(90);
|
||||
const SERVE_WAIT: Duration = Duration::from_secs(10);
|
||||
const MARKER_TRIES: u32 = 25;
|
||||
const MARKER_PAUSE: Duration = Duration::from_millis(200);
|
||||
|
||||
struct State {
|
||||
cfg: Config,
|
||||
@@ -43,6 +48,8 @@ mod service {
|
||||
log: Mutex<Option<std::fs::File>>,
|
||||
event: Handle,
|
||||
game: AtomicU32,
|
||||
stale_token: AtomicBool,
|
||||
generation: Generation,
|
||||
started: Instant,
|
||||
}
|
||||
|
||||
@@ -175,7 +182,8 @@ mod service {
|
||||
state.say("session: closed");
|
||||
}
|
||||
|
||||
fn denuvo(state: &State, rid: u64, challenge: &[u8]) -> Option<Vec<u8>> {
|
||||
/// The game token for an activation, with the invalidation count it was asked under when it may be a kept one.
|
||||
fn denuvo(state: &State, rid: u64, challenge: &[u8], fresh: bool) -> Option<(Vec<u8>, Option<u64>)> {
|
||||
if state.cfg.bridge.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -185,12 +193,20 @@ mod service {
|
||||
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 seen = state.generation.current();
|
||||
let stale = state.stale_token.swap(false, Ordering::SeqCst) || fresh;
|
||||
let kind = if stale { "req" } else { "cache.req" };
|
||||
if std::fs::rename(&part, dir.join(format!("denuvo-{rid}.{kind}"))).is_err() {
|
||||
if stale {
|
||||
state.stale_token.store(true, Ordering::SeqCst);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
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);
|
||||
return (!token.is_empty()).then_some((token, (!stale).then_some(seen)));
|
||||
}
|
||||
thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
@@ -207,14 +223,48 @@ mod service {
|
||||
}
|
||||
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));
|
||||
let mut fresh = false;
|
||||
loop {
|
||||
let Some((token, seen)) = denuvo(state, rid, challenge, fresh) else {
|
||||
state.say(&format!("aux: no game token for activation {rid}"));
|
||||
break;
|
||||
};
|
||||
let answer = || send(&pipe, &launcher::aux_token(rid, &token));
|
||||
let served = match seen {
|
||||
Some(g) => state.generation.serve(g, answer).is_some(),
|
||||
None => {
|
||||
answer();
|
||||
true
|
||||
}
|
||||
};
|
||||
if served {
|
||||
state.say(&format!("aux: activation {rid} answered ({} B)", token.len()));
|
||||
break;
|
||||
}
|
||||
None => state.say(&format!("aux: no game token for activation {rid}")),
|
||||
state.say(&format!("aux: kept token for activation {rid} came back after an invalidation; asking afresh"));
|
||||
fresh = true;
|
||||
}
|
||||
}
|
||||
AuxReq::Invalidate(rid) => {
|
||||
state.stale_token.store(true, Ordering::SeqCst);
|
||||
let published = state.generation.invalidate(SERVE_WAIT, || {
|
||||
let published = state.cfg.bridge.is_empty()
|
||||
|| bridge::publish_invalidation(Path::new(&state.cfg.bridge), &state.cfg.user_id, MARKER_TRIES, MARKER_PAUSE);
|
||||
if published {
|
||||
send(&pipe, &launcher::aux_invalidated(rid));
|
||||
}
|
||||
published
|
||||
});
|
||||
if published {
|
||||
state.say(&format!("aux: token invalidated by request {rid}"));
|
||||
} else {
|
||||
state.say(&format!("aux: invalidation {rid} not acknowledged; the kept token could not be marked stale"));
|
||||
}
|
||||
}
|
||||
AuxReq::BurnTicket(rid) => {
|
||||
send(&pipe, &launcher::aux_no_burn_ticket(rid));
|
||||
state.say(&format!("aux: burn ticket {rid} answered as unavailable"));
|
||||
}
|
||||
AuxReq::Other(rid) => state.say(&format!("aux: request {rid} not handled ({} B)", req.len())),
|
||||
}
|
||||
}
|
||||
@@ -304,6 +354,8 @@ mod service {
|
||||
log: Mutex::new(log),
|
||||
event: win::inheritable_event(),
|
||||
game: AtomicU32::new(0),
|
||||
stale_token: AtomicBool::new(false),
|
||||
generation: Generation::default(),
|
||||
started: Instant::now(),
|
||||
});
|
||||
state.say(&format!("product {} on {}*", state.cfg.product, state.prefix));
|
||||
|
||||
Reference in new issue
Block a user