mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-23 06:46:02 +00:00
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:
1 parent
d8ed02f2cf
commit
3c96df4ab1
49 files changed
+3960
-24
No files matched your search
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
Reference in new issue
Block a user