mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 22:36:00 +00:00
feat: add GOG maintenance
This commit is contained in:
1 parent
52fa41767c
commit
198f667bf0
54 files changed
+11840
-26
No files matched your search
Generated
+3
@@ -1,3 +1,5 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
@@ -186,6 +188,7 @@ dependencies = [
|
||||
name = "droiddeckstores"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"flate2",
|
||||
"futures-util",
|
||||
"jni",
|
||||
|
||||
@@ -21,6 +21,9 @@ serde_json = { version = "1", features = ["preserve_order"] }
|
||||
sha1 = "0.10"
|
||||
sha2 = "0.10"
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1"
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
lto = "thin"
|
||||
|
||||
@@ -77,14 +77,14 @@ after it (marker files, exe resolution, DLC markers, redist orchestration).
|
||||
| `nativeCancel(handle: Long)` | `(J)V` | `Java_com_droiddeck_launcher_stores_gog_GogNative_nativeCancel` |
|
||||
| `nativeRelease(handle: Long)` | `(J)V` | `Java_com_droiddeck_launcher_stores_gog_GogNative_nativeRelease` |
|
||||
|
||||
`nativeProbe()` always returns `1`; it exists so `isAvailable()` can catch `UnsatisfiedLinkError`
|
||||
`nativeProbe()` returns `2`; it exists so `isAvailable()` can catch `UnsatisfiedLinkError`
|
||||
once at startup instead of mid-download.
|
||||
|
||||
`nativeStart` parameters, in order:
|
||||
|
||||
| # | Parameter | Meaning |
|
||||
|---|---|---|
|
||||
| 1 | `kind: Int` | `0` = `KIND_GEN2_CHUNKS`, `1` = `KIND_GEN1_RANGES` (anything else → gen2) |
|
||||
| 1 | `kind: Int` | `0` = `KIND_GEN2_CHUNKS`, `1` = `KIND_GEN1_RANGES`, `2` = GOG maintenance (anything else → gen2) |
|
||||
| 2 | `depotManifests: Array<String>` | gen2: the inflated depot-manifest JSON strings, in fetch order, already filtered by product + language; gen1: the inflated build manifest (one element) |
|
||||
| 3 | `cdnBases: Array<String>` | gen2: **every** CDN base of the secure-link answer — one per `urls[]` entry, each resolved the way `parseCdnUrl` resolves `urls[0]` today (query string intact), in GOG's order — or the one unauthenticated dependency store base (an array of one); gen1: `emptyArray()` (file URLs are in the manifest). Blank entries are ignored and a base whose host already appeared is dropped (the first wins). The fetch core spreads the window across the distinct hosts with a per-host cap of `max(6, ceil(maxWorkers / hosts))`, rotating a failed chunk to another CDN; one base behaves exactly like the old single `cdnBase`. The start log line lists them as `hosts=a,b,c`. |
|
||||
| 4 | `installDir: String` | absolute install directory |
|
||||
@@ -113,6 +113,15 @@ On-disk protocol (what a resumed run, by either engine, relies on): a file is as
|
||||
`<file>.bhtmp`, then renamed over `<file>` once its size and MD5 match the manifest; an existing
|
||||
`<file>` whose size+MD5 match is skipped. The engine writes nothing else.
|
||||
|
||||
Maintenance (`kind=2`) instead takes a single normalized plan in `depotManifests[0]`:
|
||||
`files`, `oldFiles`, optional exact-build `patches`, per-product `links` and `patchLinks`,
|
||||
and estimated `downloadBytes`. Credentials and these temporary links stay in memory.
|
||||
It stages replacements under `.droiddeck-gog/stage`, revalidates completed chunks on
|
||||
every run, and verifies each file before atomic replacement. `onBytes` counts actual
|
||||
network bytes, including failed attempts. `onMaintenance(networkBytes, reusedBytes,
|
||||
appliedBytes)` (`(JJJ)V`) reports the three separate cumulative counters. Existing
|
||||
gen1/gen2 first-install progress semantics are unchanged.
|
||||
|
||||
## `com.droiddeck.launcher.stores.epic.EpicNative`
|
||||
|
||||
Everything Epic runs in the Rust `epic` module: the web-service calls (sign-in, refresh, exchange
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
fn main() {
|
||||
cc::Build::new()
|
||||
.include("vendor/xdelta3")
|
||||
.file("vendor/xdelta3/xdelta3.c")
|
||||
.file("src/gog/delta.c")
|
||||
.define("SIZEOF_SIZE_T", "8")
|
||||
.define("SIZEOF_UNSIGNED_INT", "4")
|
||||
.define("SIZEOF_UNSIGNED_LONG", "8")
|
||||
.define("SIZEOF_UNSIGNED_LONG_LONG", "8")
|
||||
.define("XD3_USE_LARGEFILE64", "1")
|
||||
.define("XD3_ENCODER", "0")
|
||||
.define("SECONDARY_DJW", "0")
|
||||
.define("SECONDARY_FGK", "0")
|
||||
.define("SECONDARY_LZMA", "0")
|
||||
.define("SHELL_TESTS", "0")
|
||||
.define("XD3_MAIN", "0")
|
||||
.warnings(false)
|
||||
.compile("gogdelta");
|
||||
println!("cargo:rerun-if-changed=vendor/xdelta3");
|
||||
println!("cargo:rerun-if-changed=src/gog/delta.c");
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
pub mod engine;
|
||||
pub mod jni;
|
||||
pub mod plan;
|
||||
pub mod maintenance;
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
#include "xdelta3.h"
|
||||
|
||||
typedef struct { size_t used; } dd_budget;
|
||||
typedef struct { size_t size; } dd_allocation;
|
||||
|
||||
static void *dd_alloc(void *opaque, size_t count, usize_t size) {
|
||||
dd_budget *budget = opaque;
|
||||
if (size && count > (62u * 1024u * 1024u) / size) return NULL;
|
||||
size_t n = count * size;
|
||||
if (n > 62u * 1024u * 1024u - budget->used) return NULL;
|
||||
dd_allocation *allocation = malloc(sizeof(*allocation) + n);
|
||||
if (!allocation) return NULL;
|
||||
allocation->size = n;
|
||||
budget->used += n;
|
||||
return allocation + 1;
|
||||
}
|
||||
|
||||
static void dd_free(void *opaque, void *ptr) {
|
||||
if (!ptr) return;
|
||||
dd_allocation *allocation = (dd_allocation *)ptr - 1;
|
||||
((dd_budget *)opaque)->used -= allocation->size;
|
||||
free(allocation);
|
||||
}
|
||||
|
||||
int dd_gog_delta(const char *source, const char *patch, const char *target,
|
||||
int (*cancel)(void *), void *opaque) {
|
||||
FILE *old = NULL, *delta = NULL, *out = NULL;
|
||||
xd3_stream stream = {0};
|
||||
xd3_source src = {0};
|
||||
xd3_config config = {0};
|
||||
dd_budget budget = {0};
|
||||
unsigned char *input = NULL, *block = NULL;
|
||||
int result = -1, configured = 0;
|
||||
old = fopen(source, "rb"); delta = fopen(patch, "rb"); out = fopen(target, "wb");
|
||||
if (!old || !delta || !out) goto done;
|
||||
input = malloc(64 * 1024); block = malloc(1024 * 1024);
|
||||
if (!input || !block) goto done;
|
||||
config.winsize = 64 * 1024;
|
||||
config.alloc = dd_alloc; config.freef = dd_free; config.opaque = &budget;
|
||||
if (xd3_config_stream(&stream, &config)) goto done;
|
||||
configured = 1;
|
||||
src.blksize = 1024 * 1024; src.curblk = block; src.curblkno = 0;
|
||||
src.onblk = fread(block, 1, src.blksize, old);
|
||||
if (xd3_set_source(&stream, &src)) goto done;
|
||||
for (;;) {
|
||||
size_t n = fread(input, 1, 64 * 1024, delta);
|
||||
if (ferror(delta)) goto done;
|
||||
if (feof(delta)) xd3_set_flags(&stream, XD3_FLUSH);
|
||||
xd3_avail_input(&stream, input, n);
|
||||
int code;
|
||||
while ((code = xd3_decode_input(&stream)) != XD3_INPUT) {
|
||||
if (cancel && cancel(opaque)) { result = 130; goto done; }
|
||||
switch (code) {
|
||||
case XD3_OUTPUT:
|
||||
if (fwrite(stream.next_out, 1, stream.avail_out, out) != stream.avail_out) goto done;
|
||||
xd3_consume_output(&stream); break;
|
||||
case XD3_GETSRCBLK:
|
||||
if (fseeko(old, (off_t)(src.getblkno * src.blksize), SEEK_SET)) goto done;
|
||||
src.curblkno = src.getblkno;
|
||||
src.onblk = fread(block, 1, src.blksize, old);
|
||||
if (ferror(old)) goto done;
|
||||
break;
|
||||
case XD3_GOTHEADER: case XD3_WINSTART: case XD3_WINFINISH: break;
|
||||
default: goto done;
|
||||
}
|
||||
}
|
||||
if (feof(delta)) break;
|
||||
}
|
||||
if (xd3_close_stream(&stream) || fflush(out)) goto done;
|
||||
result = 0;
|
||||
done:
|
||||
if (configured) xd3_free_stream(&stream);
|
||||
if (old) fclose(old);
|
||||
if (delta) fclose(delta);
|
||||
if (out && fclose(out)) result = -1;
|
||||
free(input); free(block);
|
||||
return result;
|
||||
}
|
||||
@@ -32,11 +32,14 @@ pub enum PlanKind {
|
||||
#[default]
|
||||
Gen2Chunks,
|
||||
Gen1Ranges,
|
||||
Maintenance,
|
||||
}
|
||||
|
||||
impl PlanKind {
|
||||
pub fn from_i32(v: i32) -> Self {
|
||||
if v == 1 {
|
||||
if v == 2 {
|
||||
PlanKind::Maintenance
|
||||
} else if v == 1 {
|
||||
PlanKind::Gen1Ranges
|
||||
} else {
|
||||
PlanKind::Gen2Chunks
|
||||
@@ -72,6 +75,7 @@ pub trait GogEvents: Sync {
|
||||
);
|
||||
fn on_log(&self, line: &str);
|
||||
fn on_bytes(&self, _bytes_done: u64, _bytes_total: u64) {}
|
||||
fn on_maintenance(&self, _network_bytes: u64, _reused_bytes: u64, _applied_bytes: u64) {}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
@@ -672,6 +676,7 @@ pub fn run(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Gog
|
||||
match req.kind {
|
||||
PlanKind::Gen2Chunks => run_gen2(req, cancel, events),
|
||||
PlanKind::Gen1Ranges => run_gen1(req, cancel, events),
|
||||
PlanKind::Maintenance => super::maintenance::run(req, cancel, events),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
@@ -153,6 +153,15 @@ impl GogEvents for JniEvents {
|
||||
let _ = env.delete_local_ref(text);
|
||||
});
|
||||
}
|
||||
|
||||
fn on_maintenance(&self, network_bytes: u64, reused_bytes: u64, applied_bytes: u64) {
|
||||
self.with_env(|env| {
|
||||
let _ = env.call_method(self.listener.as_obj(), "onMaintenance", "(JJJ)V", &[
|
||||
JValue::Long(network_bytes as jlong), JValue::Long(reused_bytes as jlong), JValue::Long(applied_bytes as jlong),
|
||||
]);
|
||||
Self::clear_exception(env);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn jstring_to_string(env: &mut JNIEnv, value: &JString) -> Option<String> {
|
||||
@@ -197,7 +206,7 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_gog_GogNative_nativePr
|
||||
_env: JNIEnv,
|
||||
_class: JClass,
|
||||
) -> jint {
|
||||
1
|
||||
2
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
|
||||
@@ -0,0 +1,523 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ffi::CString;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use serde_json::Value;
|
||||
use super::engine::{GogEvents, GogRequest, GogRunResult, http_status_in, is_link_expiry_status};
|
||||
use super::{md5_hex, md5_hex_file};
|
||||
|
||||
static DELTA_LOCK: Mutex<()> = Mutex::new(());
|
||||
unsafe extern "C" {
|
||||
fn dd_gog_delta(source: *const libc::c_char, patch: *const libc::c_char, target: *const libc::c_char,
|
||||
cancel: extern "C" fn(*mut libc::c_void) -> libc::c_int, opaque: *mut libc::c_void) -> libc::c_int;
|
||||
}
|
||||
extern "C" fn cancelled(opaque: *mut libc::c_void) -> libc::c_int {
|
||||
unsafe { (*(opaque as *const AtomicBool)).load(Ordering::Relaxed) as libc::c_int }
|
||||
}
|
||||
|
||||
fn http_client(read_timeout: std::time::Duration) -> Result<reqwest::Client, String> {
|
||||
reqwest::Client::builder()
|
||||
.connect_timeout(std::time::Duration::from_secs(20))
|
||||
.read_timeout(read_timeout)
|
||||
.build().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn inside(root: &Path, relative: &str) -> Result<PathBuf, String> {
|
||||
if relative.is_empty() || relative.contains(['\\', ':', '\0']) || relative.split('/').any(|p| p.is_empty() || p == "." || p == "..") { return Err("invalid GOG path".into()); }
|
||||
let mut out = root.to_path_buf();
|
||||
for component in Path::new(relative).components() {
|
||||
let Component::Normal(part) = component else { return Err("GOG path leaves installation".into()) };
|
||||
out.push(part);
|
||||
if fs::symlink_metadata(&out).map(|m| m.file_type().is_symlink()).unwrap_or(false) {
|
||||
return Err("GOG path is a symbolic link".into());
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn text<'a>(v: &'a Value, key: &str) -> &'a str { v.get(key).and_then(Value::as_str).unwrap_or("") }
|
||||
fn num(v: &Value, key: &str) -> u64 { v.get(key).and_then(Value::as_u64).unwrap_or(0) }
|
||||
fn array<'a>(v: &'a Value, key: &str) -> &'a [Value] { v.get(key).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) }
|
||||
fn valid_md5(s: &str) -> bool { s.len() == 32 && s.bytes().all(|c| c.is_ascii_hexdigit()) }
|
||||
|
||||
fn matches(path: &Path, file: &Value) -> bool {
|
||||
if !fs::metadata(path).map(|m| m.is_file() && m.len() == num(file, "size")).unwrap_or(false) { return false; }
|
||||
let md5 = text(file, "md5");
|
||||
if valid_md5(md5) { return md5_hex_file(path).map(|h| h.eq_ignore_ascii_case(md5)).unwrap_or(false); }
|
||||
let sha = text(file, "sha256");
|
||||
if sha.len() == 64 {
|
||||
use sha2::{Digest, Sha256};
|
||||
let Ok(mut input) = File::open(path) else { return false; };
|
||||
let mut digest = Sha256::new(); let mut buffer = [0u8; 64 * 1024];
|
||||
loop { let Ok(n) = input.read(&mut buffer) else { return false; }; if n == 0 { break; } digest.update(&buffer[..n]); }
|
||||
return super::to_hex(&digest.finalize()).eq_ignore_ascii_case(sha);
|
||||
}
|
||||
let chunks = array(file, "chunks");
|
||||
if chunks.is_empty() { return num(file, "size") == 0; }
|
||||
let Ok(mut input) = File::open(path) else { return false; };
|
||||
chunks.iter().all(|chunk| {
|
||||
let size = num(chunk, "size");
|
||||
valid_md5(text(chunk, "md5")) && hash_range(&mut input, size).as_deref() == Some(text(chunk, "md5"))
|
||||
})
|
||||
}
|
||||
|
||||
fn hash_range(input: &mut File, size: u64) -> Option<String> {
|
||||
let mut digest = crate::md5_small::Md5::new();
|
||||
let mut remaining = size;
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
while remaining > 0 {
|
||||
let want = remaining.min(buffer.len() as u64) as usize;
|
||||
input.read_exact(&mut buffer[..want]).ok()?;
|
||||
digest.update(&buffer[..want]); remaining -= want as u64;
|
||||
}
|
||||
Some(super::to_hex(&digest.finalize()))
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Reuse { path: PathBuf, offset: u64, size: u64 }
|
||||
type ReuseMap = HashMap<(String, u64), Vec<Reuse>>;
|
||||
|
||||
fn reuse_map(root: &Path, files: &[Value]) -> Result<ReuseMap, String> {
|
||||
let mut result: ReuseMap = HashMap::new();
|
||||
for file in files {
|
||||
if text(file, "path").to_lowercase().starts_with(".droiddeck-") { return Err("GOG content overlaps launcher metadata".into()); }
|
||||
let path = inside(root, text(file, "path"))?;
|
||||
let mut offset: u64 = 0;
|
||||
for chunk in array(file, "chunks") {
|
||||
let size = num(chunk, "size");
|
||||
if valid_md5(text(chunk, "md5")) {
|
||||
result.entry((text(chunk, "md5").to_ascii_lowercase(), size)).or_default()
|
||||
.push(Reuse { path: path.clone(), offset, size });
|
||||
}
|
||||
offset = offset.checked_add(size).ok_or("GOG file size overflow")?;
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn reusable(chunk: &Value, map: &ReuseMap) -> Option<Reuse> {
|
||||
let key = (text(chunk, "md5").to_ascii_lowercase(), num(chunk, "size"));
|
||||
map.get(&key)?.iter().find(|old| {
|
||||
let Ok(mut file) = File::open(&old.path) else { return false; };
|
||||
file.seek(SeekFrom::Start(old.offset)).is_ok() && hash_range(&mut file, old.size).map(|h| h.eq_ignore_ascii_case(&key.0)).unwrap_or(false)
|
||||
}).cloned()
|
||||
}
|
||||
|
||||
struct Transfer<'a> {
|
||||
runtime: tokio::runtime::Runtime,
|
||||
client: reqwest::Client,
|
||||
cancel: &'a AtomicBool,
|
||||
events: &'a dyn GogEvents,
|
||||
wire: u64,
|
||||
total: u64,
|
||||
}
|
||||
|
||||
impl Transfer<'_> {
|
||||
fn fetch(&mut self, urls: &[String], range: Option<(u64, u64)>, dest: &Path, limit: u64) -> Result<(), String> {
|
||||
let mut failure = "GOG download has no URLs".to_string();
|
||||
for _ in 0..3 {
|
||||
for url in urls {
|
||||
if self.cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
let result = self.runtime.block_on(async {
|
||||
let mut request = self.client.get(url).header("User-Agent", "GOG Galaxy");
|
||||
if let Some((start, end)) = range { request = request.header("Range", format!("bytes={start}-{end}")); }
|
||||
let mut response = request.send().await.map_err(|_| "GOG connection failed".to_string())?;
|
||||
let status = response.status().as_u16();
|
||||
if status != if range.is_some() { 206 } else { 200 } { return Err(format!("HTTP {status}")); }
|
||||
let mut output = File::create(dest).map_err(|e| e.to_string())?;
|
||||
let mut size = 0u64;
|
||||
while let Some(bytes) = response.chunk().await.map_err(|_| "GOG connection interrupted".to_string())? {
|
||||
if self.cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
size += bytes.len() as u64;
|
||||
if limit > 0 && size > limit { return Err("GOG response exceeds expected size".into()); }
|
||||
self.wire += bytes.len() as u64;
|
||||
self.events.on_bytes(self.wire, self.total.max(self.wire));
|
||||
output.write_all(&bytes).map_err(|e| e.to_string())?;
|
||||
}
|
||||
if limit > 0 && size != limit { return Err("GOG download is incomplete".into()); }
|
||||
output.sync_all().map_err(|e| e.to_string())
|
||||
});
|
||||
match result { Ok(()) => return Ok(()), Err(e) => failure = e }
|
||||
if http_status_in(&failure).map(is_link_expiry_status).unwrap_or(false) { return Err(failure); }
|
||||
}
|
||||
}
|
||||
Err(failure)
|
||||
}
|
||||
}
|
||||
|
||||
fn urls(links: &Value, product: &str, suffix: &str) -> Vec<String> {
|
||||
links.get(product).and_then(Value::as_array).map(|bases| bases.iter().filter_map(Value::as_str).map(|base| {
|
||||
if base.contains("{GALAXY_PATH}") { base.replace("{GALAXY_PATH}", suffix) }
|
||||
else if let Some((path, query)) = base.split_once('?') { format!("{}{suffix}?{query}", path.trim_end_matches('/').to_string() + "/") }
|
||||
else { format!("{}{suffix}", base.trim_end_matches('/').to_string() + "/") }
|
||||
}).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn chunk_path(chunk: &Value) -> Result<String, String> {
|
||||
let hash = text(chunk, "compressedMd5");
|
||||
if !valid_md5(hash) { return Err("GOG chunk has no valid compressed hash".into()); }
|
||||
Ok(super::plan::build_cdn_path(hash))
|
||||
}
|
||||
|
||||
fn download_chunk(transfer: &mut Transfer, links: &Value, product: &str, chunk: &Value, scratch: &Path, output: &mut File) -> Result<(), String> {
|
||||
transfer.fetch(&urls(links, product, &chunk_path(chunk)?), None, scratch, num(chunk, "compressedSize"))?;
|
||||
if !md5_hex_file(scratch).map(|h| h.eq_ignore_ascii_case(text(chunk, "compressedMd5"))).unwrap_or(false) { return Err("GOG compressed chunk checksum mismatch".into()); }
|
||||
let mut raw = File::open(scratch).map_err(|e| e.to_string())?;
|
||||
let mut head = [0u8; 1]; raw.read_exact(&mut head).map_err(|e| e.to_string())?;
|
||||
raw.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
|
||||
let stored = num(chunk, "size") == num(chunk, "compressedSize") && text(chunk, "md5").eq_ignore_ascii_case(text(chunk, "compressedMd5"));
|
||||
let input: Box<dyn Read> = if !stored && head[0] == 0x78 { Box::new(flate2::read::ZlibDecoder::new(raw)) } else { Box::new(raw) };
|
||||
let mut input = input.take(num(chunk, "size") + 1);
|
||||
let mut digest = crate::md5_small::Md5::new();
|
||||
let mut size = 0u64;
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
loop {
|
||||
let n = input.read(&mut buffer).map_err(|_| "GOG chunk decompression failed")?;
|
||||
if n == 0 { break; }
|
||||
if transfer.cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
digest.update(&buffer[..n]); size += n as u64;
|
||||
output.write_all(&buffer[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
if size != num(chunk, "size") || !super::to_hex(&digest.finalize()).eq_ignore_ascii_case(text(chunk, "md5")) { return Err("GOG chunk checksum mismatch".into()); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_delta(root: &Path, file: &Value, patch: &Value, plan: &Value, stage: &Path, transfer: &mut Transfer) -> Result<(), String> {
|
||||
let _guard = DELTA_LOCK.lock().map_err(|_| "GOG delta lock poisoned")?;
|
||||
let source = inside(root, &text(patch, "path_source").replace('\\', "/"))?;
|
||||
if !md5_hex_file(&source).map(|h| h.eq_ignore_ascii_case(text(patch, "md5_source"))).unwrap_or(false) { return Err("GOG delta source changed".into()); }
|
||||
let payload = stage.with_extension("delta");
|
||||
let packed = stage.with_extension("packed");
|
||||
let mut output = File::create(&payload).map_err(|e| e.to_string())?;
|
||||
for chunk in array(patch, "chunks") { download_chunk(transfer, &plan["patchLinks"], text(patch, "product"), chunk, &packed, &mut output)?; }
|
||||
drop(output);
|
||||
if !md5_hex_file(&payload).map(|h| h.eq_ignore_ascii_case(text(patch, "md5"))).unwrap_or(false) { return Err("GOG delta checksum mismatch".into()); }
|
||||
let cpath = |p: &Path| CString::new(p.as_os_str().as_encoded_bytes()).map_err(|_| "invalid path");
|
||||
let (s, p, t) = (cpath(&source)?, cpath(&payload)?, cpath(stage)?);
|
||||
let code = unsafe { dd_gog_delta(s.as_ptr(), p.as_ptr(), t.as_ptr(), cancelled, transfer.cancel as *const AtomicBool as *mut libc::c_void) };
|
||||
let _ = fs::remove_file(payload); let _ = fs::remove_file(packed);
|
||||
if code != 0 || !matches(stage, file) || !md5_hex_file(stage).map(|h| h.eq_ignore_ascii_case(text(patch, "md5_target"))).unwrap_or(false) { return Err("GOG delta reconstruction failed".into()); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn run(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> GogRunResult {
|
||||
let mut result = GogRunResult::default();
|
||||
let work = || -> Result<(u64, u32), String> {
|
||||
let plan: Value = serde_json::from_str(req.depot_manifests.first().ok_or("missing GOG maintenance plan")?).map_err(|_| "invalid GOG maintenance plan")?;
|
||||
let root = fs::canonicalize(&req.install_dir).map_err(|e| e.to_string())?;
|
||||
let files = array(&plan, "files");
|
||||
let mut seen = HashSet::new();
|
||||
let mut components = HashMap::new();
|
||||
for file in files {
|
||||
let name = text(file, "path"); inside(&root, name)?;
|
||||
if name.to_lowercase().starts_with(".droiddeck-") || !seen.insert(name.to_lowercase()) { return Err("ambiguous GOG path".into()); }
|
||||
let mut parent = root.clone();
|
||||
let mut relative = PathBuf::new();
|
||||
for part in name.split('/') {
|
||||
relative.push(part);
|
||||
let key = relative.to_string_lossy().to_lowercase();
|
||||
if let Some(previous) = components.insert(key, relative.clone()) {
|
||||
if previous != relative { return Err("ambiguous GOG directory".into()); }
|
||||
}
|
||||
if let Ok(entries) = fs::read_dir(&parent) {
|
||||
for entry in entries.flatten() {
|
||||
let actual = entry.file_name().to_string_lossy().into_owned();
|
||||
if actual != part && actual.to_lowercase() == part.to_lowercase() { return Err("existing path differs only by case".into()); }
|
||||
}
|
||||
}
|
||||
parent.push(part);
|
||||
}
|
||||
}
|
||||
let map = reuse_map(&root, array(&plan, "oldFiles"))?;
|
||||
let stages = inside(&root, ".droiddeck-gog/stage")?;
|
||||
fs::create_dir_all(&stages).map_err(|e| e.to_string())?;
|
||||
let mut transfer = Transfer {
|
||||
runtime: tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| e.to_string())?,
|
||||
client: http_client(std::time::Duration::from_secs(60))?,
|
||||
cancel, events, wire: 0, total: num(&plan, "downloadBytes"),
|
||||
};
|
||||
let mut done = 0u32; let mut reused = 0u64; let mut applied = 0u64;
|
||||
for file in files {
|
||||
if cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
let path = inside(&root, text(file, "path"))?;
|
||||
if file.get("directory").and_then(Value::as_bool).unwrap_or(false) {
|
||||
fs::create_dir_all(&path).map_err(|e| e.to_string())?; done += 1; continue;
|
||||
}
|
||||
if matches(&path, file) { done += 1; events.on_file_done(text(file, "path"), num(file, "size"), true, done, files.len() as u32, transfer.wire, transfer.total); continue; }
|
||||
let stage = stages.join(md5_hex(text(file, "path").as_bytes()));
|
||||
if !matches(&stage, file) {
|
||||
let mut start = 0;
|
||||
let missing_bytes: u64 = array(file, "chunks").iter().map(|chunk| {
|
||||
let valid = File::open(&stage).ok().map(|mut input| input.seek(SeekFrom::Start(start)).is_ok() &&
|
||||
hash_range(&mut input, num(chunk, "size")).map(|h| h.eq_ignore_ascii_case(text(chunk, "md5"))).unwrap_or(false)).unwrap_or(false);
|
||||
start += num(chunk, "size");
|
||||
if valid || reusable(chunk, &map).is_some() { 0 } else { num(chunk, "compressedSize") }
|
||||
}).sum();
|
||||
let patch = array(&plan, "patches").iter().find(|p| text(p, "path_target").replace('\\', "/") == text(file, "path") &&
|
||||
array(p, "chunks").iter().map(|c| num(c, "compressedSize")).sum::<u64>() < missing_bytes);
|
||||
let delta_ok = if let Some(patch) = patch {
|
||||
match apply_delta(&root, file, patch, &plan, &stage, &mut transfer) {
|
||||
Ok(()) => true,
|
||||
Err(e) => { if cancel.load(Ordering::Relaxed) || http_status_in(&e).map(is_link_expiry_status).unwrap_or(false) { return Err(e); } events.on_log(&format!("gog: delta fallback file={} reason={e}", text(file, "path"))); false }
|
||||
}
|
||||
} else { false };
|
||||
if !delta_ok {
|
||||
let chunks = array(file, "chunks");
|
||||
if chunks.is_empty() && num(file, "size") > 0 {
|
||||
let offset = num(file, "offset");
|
||||
let remote = text(file, "remotePath");
|
||||
let endpoints = if remote.starts_with("https://") { vec![remote.to_string()] } else { urls(&plan["links"], text(file, "product"), remote.trim_start_matches('/')) };
|
||||
transfer.fetch(&endpoints, Some((offset, offset + num(file, "size") - 1)), &stage, num(file, "size"))?;
|
||||
} else {
|
||||
let mut output = OpenOptions::new().create(true).truncate(false).read(true).write(true).open(&stage).map_err(|e| e.to_string())?;
|
||||
let mut offset = 0u64;
|
||||
for chunk in chunks {
|
||||
if cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
output.seek(SeekFrom::Start(offset)).map_err(|e| e.to_string())?;
|
||||
let valid_stage = hash_range(&mut output, num(chunk, "size")).map(|h| h.eq_ignore_ascii_case(text(chunk, "md5"))).unwrap_or(false);
|
||||
output.seek(SeekFrom::Start(offset)).map_err(|e| e.to_string())?;
|
||||
if valid_stage { reused += num(chunk, "size"); }
|
||||
else if let Some(old) = reusable(chunk, &map) {
|
||||
let mut source = File::open(old.path).map_err(|e| e.to_string())?;
|
||||
source.seek(SeekFrom::Start(old.offset)).map_err(|e| e.to_string())?;
|
||||
std::io::copy(&mut source.take(old.size), &mut output).map_err(|e| e.to_string())?;
|
||||
reused += old.size;
|
||||
} else {
|
||||
download_chunk(&mut transfer, &plan["links"], text(file, "product"), chunk, &stage.with_extension("packed"), &mut output)?;
|
||||
}
|
||||
offset += num(chunk, "size");
|
||||
}
|
||||
output.set_len(num(file, "size")).map_err(|e| e.to_string())?;
|
||||
output.sync_all().map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let unhashed_range = array(file, "chunks").is_empty() && !valid_md5(text(file, "md5")) && text(file, "sha256").is_empty();
|
||||
if !matches(&stage, file) && !(unhashed_range && fs::metadata(&stage).map(|m| m.len() == num(file, "size")).unwrap_or(false)) { return Err(format!("GOG target verification failed: {}", text(file, "path"))); }
|
||||
if cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
inside(&root, text(file, "path"))?;
|
||||
fs::create_dir_all(path.parent().ok_or("GOG file has no parent")?).map_err(|e| e.to_string())?;
|
||||
File::open(&stage).and_then(|f| f.sync_all()).map_err(|e| e.to_string())?;
|
||||
fs::rename(&stage, &path).map_err(|e| e.to_string())?;
|
||||
applied += num(file, "size"); done += 1;
|
||||
events.on_file_done(text(file, "path"), num(file, "size"), false, done, files.len() as u32, transfer.wire, transfer.total);
|
||||
events.on_maintenance(transfer.wire, reused, applied);
|
||||
events.on_log(&format!("gog: maintenance wire={} reused={reused} applied={applied} files={done}", transfer.wire));
|
||||
}
|
||||
for old in array(&plan, "oldFiles") {
|
||||
if cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
if !seen.contains(&text(old, "path").to_lowercase()) {
|
||||
let path = inside(&root, text(old, "path"))?;
|
||||
if matches(&path, old) { fs::remove_file(path).map_err(|e| e.to_string())?; }
|
||||
}
|
||||
}
|
||||
events.on_log(&format!("gog: maintenance complete wire={} reused={reused} applied={applied}", transfer.wire));
|
||||
Ok((transfer.wire, done))
|
||||
};
|
||||
match work() {
|
||||
Ok((bytes, files)) => { result.success = true; result.bytes_written = bytes; result.files_done = files; }
|
||||
Err(error) => { result.cancelled = cancel.load(Ordering::Relaxed); result.link_expiry = http_status_in(&error).map(is_link_expiry_status).unwrap_or(false); result.error = error; }
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use flate2::{write::ZlibEncoder, Compression};
|
||||
use serde_json::json;
|
||||
use std::net::TcpListener;
|
||||
use std::sync::{Arc, atomic::AtomicU64};
|
||||
|
||||
struct Events;
|
||||
impl GogEvents for Events {
|
||||
fn on_file_done(&self, _: &str, _: u64, _: bool, _: u32, _: u32, _: u64, _: u64) {}
|
||||
fn on_log(&self, _: &str) {}
|
||||
}
|
||||
struct Temp(PathBuf);
|
||||
impl Temp {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!("gog-maintenance-{}-{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
|
||||
fs::create_dir_all(&path).unwrap(); Self(path)
|
||||
}
|
||||
}
|
||||
impl Drop for Temp { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); } }
|
||||
|
||||
struct Server { base: String, bytes: Arc<AtomicU64>, stop: Arc<AtomicBool>, thread: Option<std::thread::JoinHandle<()>> }
|
||||
impl Server {
|
||||
fn new(payloads: HashMap<String, Vec<u8>>, range: bool) -> Self {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let stop = Arc::new(AtomicBool::new(false)); let bytes = Arc::new(AtomicU64::new(0));
|
||||
let (stopped, count) = (stop.clone(), bytes.clone());
|
||||
let thread = std::thread::spawn(move || {
|
||||
while !stopped.load(Ordering::Relaxed) {
|
||||
if let Ok((mut stream, _)) = listener.accept() {
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap();
|
||||
let mut request = Vec::new(); let mut one = [0u8];
|
||||
while stream.read(&mut one).unwrap_or(0) > 0 { request.push(one[0]); if request.ends_with(b"\r\n\r\n") { break; } }
|
||||
let request = String::from_utf8_lossy(&request);
|
||||
let path = request.split_whitespace().nth(1).unwrap_or("");
|
||||
if let Some(body) = payloads.get(path) {
|
||||
let status = if range { "206 Partial Content" } else { "200 OK" };
|
||||
let _ = write!(stream, "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
|
||||
if stream.write_all(body).is_ok() { count.fetch_add(body.len() as u64, Ordering::Relaxed); }
|
||||
} else { let _ = stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); }
|
||||
} else { std::thread::sleep(std::time::Duration::from_millis(2)); }
|
||||
}
|
||||
});
|
||||
Self { base, bytes, stop, thread: Some(thread) }
|
||||
}
|
||||
}
|
||||
impl Drop for Server { fn drop(&mut self) { self.stop.store(true, Ordering::Relaxed); if let Some(thread) = self.thread.take() { thread.join().unwrap(); } } }
|
||||
|
||||
#[test]
|
||||
fn continuing_download_may_exceed_the_read_timeout_in_total() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(3))).unwrap();
|
||||
let mut request = Vec::new(); let mut byte = [0u8];
|
||||
while stream.read(&mut byte).unwrap() > 0 { request.push(byte[0]); if request.ends_with(b"\r\n\r\n") { break; } }
|
||||
stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\n").unwrap();
|
||||
for byte in b"abcd" {
|
||||
stream.write_all(&[*byte]).unwrap(); stream.flush().unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(400));
|
||||
}
|
||||
});
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
let client = http_client(std::time::Duration::from_secs(1)).unwrap();
|
||||
let body = runtime.block_on(async { client.get(url).send().await.unwrap().bytes().await.unwrap() });
|
||||
assert_eq!(&body[..], b"abcd");
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
fn chunk(data: &[u8]) -> (Value, String, Vec<u8>) {
|
||||
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default()); encoder.write_all(data).unwrap();
|
||||
let packed = encoder.finish().unwrap(); let hash = md5_hex(&packed);
|
||||
(json!({"md5": md5_hex(data), "size": data.len(), "compressedMd5": hash, "compressedSize": packed.len()}),
|
||||
format!("/{}", super::super::plan::build_cdn_path(&hash)), packed)
|
||||
}
|
||||
fn execute(root: &Path, files: Value, old: Value, server: &Server) -> GogRunResult {
|
||||
let plan = json!({"files": files, "oldFiles": old, "patches": [], "links": {"1": [server.base]}, "downloadBytes": 4096});
|
||||
run(&GogRequest { install_dir: root.to_string_lossy().into_owned(), depot_manifests: vec![plan.to_string()], ..Default::default() }, &AtomicBool::new(false), &Events)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuses_moved_and_repeated_chunks_and_downloads_only_missing_bytes() {
|
||||
let temp = Temp::new();
|
||||
let (a, _, _) = chunk(b"aaaa"); let (b, path, packed) = chunk(b"bbbb");
|
||||
fs::write(temp.0.join("archive"), b"aaaaaaaa").unwrap();
|
||||
let server = Server::new(HashMap::from([(path, packed.clone())]), false);
|
||||
let old = json!([{"path":"archive", "size":8, "md5":md5_hex(b"aaaaaaaa"), "chunks":[a,a]}]);
|
||||
let files = json!([{"path":"archive", "size":12, "md5":md5_hex(b"bbbbaaaaaaaa"), "chunks":[b,a,a], "product":"1"}]);
|
||||
let result = execute(&temp.0, files, old, &server);
|
||||
assert!(result.success, "{}", result.error);
|
||||
assert_eq!(fs::read(temp.0.join("archive")).unwrap(), b"bbbbaaaaaaaa");
|
||||
assert_eq!(server.bytes.load(Ordering::Relaxed), packed.len() as u64);
|
||||
assert_eq!(result.bytes_written, packed.len() as u64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revalidates_partial_staging_and_preserves_original_until_verified() {
|
||||
let temp = Temp::new(); let (a, _, _) = chunk(b"aaaa"); let (b, path, packed) = chunk(b"bbbb");
|
||||
let stages = temp.0.join(".droiddeck-gog/stage"); fs::create_dir_all(&stages).unwrap();
|
||||
fs::write(temp.0.join("archive"), b"original").unwrap();
|
||||
fs::write(stages.join(md5_hex(b"archive")), b"aaaabadd").unwrap();
|
||||
let server = Server::new(HashMap::from([(path, packed.clone())]), false);
|
||||
let files = json!([{"path":"archive", "size":8, "md5":md5_hex(b"aaaabbbb"), "chunks":[a,b], "product":"1"}]);
|
||||
let result = execute(&temp.0, files, json!([]), &server);
|
||||
assert!(result.success, "{}", result.error);
|
||||
assert_eq!(server.bytes.load(Ordering::Relaxed), packed.len() as u64);
|
||||
assert_eq!(fs::read(temp.0.join("archive")).unwrap(), b"aaaabbbb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_files_need_no_network_and_obsolete_modified_files_survive() {
|
||||
let temp = Temp::new(); let (a, _, _) = chunk(b"aaaa");
|
||||
fs::write(temp.0.join("current"), b"aaaa").unwrap();
|
||||
fs::write(temp.0.join("obsolete"), b"old").unwrap(); fs::write(temp.0.join("modded"), b"mod").unwrap();
|
||||
let server = Server::new(HashMap::new(), false);
|
||||
let files = json!([{"path":"current", "size":4, "md5":md5_hex(b"aaaa"), "chunks":[a], "product":"1"}, {"path":"empty", "size":0, "chunks":[], "product":"1"}]);
|
||||
let old = json!([{"path":"obsolete", "size":3, "md5":md5_hex(b"old")}, {"path":"modded", "size":3, "md5":md5_hex(b"old")}]);
|
||||
let result = execute(&temp.0, files, old, &server);
|
||||
assert!(result.success, "{}", result.error);
|
||||
assert_eq!(server.bytes.load(Ordering::Relaxed), 0);
|
||||
assert!(!temp.0.join("obsolete").exists()); assert!(temp.0.join("modded").exists());
|
||||
assert_eq!(fs::metadata(temp.0.join("empty")).unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gen1_same_size_corruption_is_replaced_using_hash_and_range() {
|
||||
let temp = Temp::new(); fs::write(temp.0.join("game"), b"bad!").unwrap();
|
||||
let server = Server::new(HashMap::from([("/range".to_string(), b"good".to_vec())]), true);
|
||||
let files = json!([{"path":"game", "size":4, "md5":md5_hex(b"good"), "chunks":[], "product":"1", "remotePath":"range", "offset":10}]);
|
||||
let result = execute(&temp.0, files, json!([]), &server);
|
||||
assert!(result.success, "{}", result.error); assert_eq!(fs::read(temp.0.join("game")).unwrap(), b"good");
|
||||
assert_eq!(server.bytes.load(Ordering::Relaxed), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_chunks_never_replace_original_and_expired_links_are_reported() {
|
||||
let temp = Temp::new(); fs::write(temp.0.join("game"), b"old!").unwrap();
|
||||
let (a, path, mut packed) = chunk(b"new!"); packed[0] ^= 1;
|
||||
let server = Server::new(HashMap::from([(path, packed)]), false);
|
||||
let files = json!([{"path":"game", "size":4, "md5":md5_hex(b"new!"), "chunks":[a], "product":"1"}]);
|
||||
let result = execute(&temp.0, files.clone(), json!([]), &server);
|
||||
assert!(!result.success); assert_eq!(fs::read(temp.0.join("game")).unwrap(), b"old!");
|
||||
let missing = Server::new(HashMap::new(), false);
|
||||
let result = execute(&temp.0, files, json!([]), &missing);
|
||||
assert!(result.link_expiry, "{}", result.error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_traversal_symlinks_and_case_collisions_before_fetching() {
|
||||
let temp = Temp::new(); let outside = Temp::new();
|
||||
std::os::unix::fs::symlink(&outside.0, temp.0.join("linked")).unwrap();
|
||||
for path in ["../escape", "/absolute", "a/./b", "a//b", "linked/game"] { assert!(inside(&temp.0, path).is_err(), "{path}"); }
|
||||
let server = Server::new(HashMap::new(), false);
|
||||
let result = execute(&temp.0, json!([{"path":"Game"}, {"path":"game"}]), json!([]), &server);
|
||||
assert!(!result.success); assert_eq!(server.bytes.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_xdelta_downloads_only_delta_and_corrupt_source_falls_back() {
|
||||
let old = b"the old archive contents\n".repeat(4096);
|
||||
let mut new = b"the new archive contents\n".to_vec(); new.extend_from_slice(&old); new.extend_from_slice(b"END\n");
|
||||
let delta = include_bytes!("fixtures/update.vcdiff");
|
||||
let (patch_chunk, patch_url, packed_delta) = chunk(delta);
|
||||
let (target_chunk, target_url, packed_target) = chunk(&new);
|
||||
for mode in 0..3 {
|
||||
let corrupt = mode == 1;
|
||||
let temp = Temp::new();
|
||||
fs::write(temp.0.join("game"), if corrupt { vec![b'x'; old.len()] } else { old.clone() }).unwrap();
|
||||
let (delta_chunk, delta_url, delta_body) = if mode == 2 { chunk(b"unsupported VCDIFF") } else { (patch_chunk.clone(), patch_url.clone(), packed_delta.clone()) };
|
||||
let server = Server::new(HashMap::from([(delta_url, delta_body.clone()), (target_url.clone(), packed_target.clone())]), false);
|
||||
let plan = json!({"files":[{"path":"game", "product":"1", "size":new.len(), "md5":md5_hex(&new), "chunks":[target_chunk]}],
|
||||
"oldFiles":[{"path":"game", "size":old.len(), "md5":md5_hex(&old), "chunks":[]}],
|
||||
"patches":[{"path_source":"game", "path_target":"game", "product":"1", "md5_source":md5_hex(&old), "md5_target":md5_hex(&new), "md5":if mode == 2 { md5_hex(b"unsupported VCDIFF") } else { md5_hex(delta) }, "chunks":[delta_chunk]}],
|
||||
"links":{"1":[server.base]}, "patchLinks":{"1":[server.base]}, "downloadBytes":packed_target.len()});
|
||||
let result = run(&GogRequest {install_dir:temp.0.to_string_lossy().into_owned(), depot_manifests:vec![plan.to_string()], ..Default::default()}, &AtomicBool::new(false), &Events);
|
||||
assert!(result.success, "{}", result.error);
|
||||
assert_eq!(fs::read(temp.0.join("game")).unwrap(), new);
|
||||
assert_eq!(server.bytes.load(Ordering::Relaxed), match mode { 1 => packed_target.len(), 2 => delta_body.len() + packed_target.len(), _ => packed_delta.len() } as u64);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_chunks_starting_with_x_are_not_mistaken_for_zlib() {
|
||||
let temp = Temp::new(); let raw = b"xyz stored data";
|
||||
let hash = md5_hex(raw);
|
||||
let path = format!("/{}", super::super::plan::build_cdn_path(&hash));
|
||||
let server = Server::new(HashMap::from([(path, raw.to_vec())]), false);
|
||||
let result = execute(&temp.0, json!([{"path":"game", "product":"1", "size":raw.len(), "md5":hash,
|
||||
"chunks":[{"md5":hash,"compressedMd5":hash,"size":raw.len(),"compressedSize":raw.len()}]}]), json!([]), &server);
|
||||
assert!(result.success, "{}", result.error);
|
||||
assert_eq!(fs::read(temp.0.join("game")).unwrap(), raw);
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
@@ -0,0 +1,7 @@
|
||||
Xdelta3 decoder from jmacd/xdelta revision 0525275fe4b553a10f38e455d30c60dc6ed9b45d (release3_0_apl), the
|
||||
Apache-2.0 revision used by heroic-gogdl. Upstream sources are unmodified.
|
||||
https://github.com/jmacd/xdelta/tree/0525275/xdelta3
|
||||
|
||||
DroidDeck's streaming wrapper is src/gog/delta.c. Encoding and secondary
|
||||
compression are disabled, matching heroic-gogdl's decoder baseline. Unsupported
|
||||
streams fall back to verified Galaxy chunks. No Python runtime is required.
|
||||
@@ -0,0 +1,171 @@
|
||||
/* xdelta3 - delta compression tools and library
|
||||
Copyright 2016 Joshua MacDonald
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
/******************************************************************
|
||||
SOFT string matcher
|
||||
******************************************************************/
|
||||
|
||||
#if XD3_BUILD_SOFT
|
||||
|
||||
#define TEMPLATE soft
|
||||
#define LLOOK stream->smatcher.large_look
|
||||
#define LSTEP stream->smatcher.large_step
|
||||
#define SLOOK stream->smatcher.small_look
|
||||
#define SCHAIN stream->smatcher.small_chain
|
||||
#define SLCHAIN stream->smatcher.small_lchain
|
||||
#define MAXLAZY stream->smatcher.max_lazy
|
||||
#define LONGENOUGH stream->smatcher.long_enough
|
||||
|
||||
#define SOFTCFG 1
|
||||
#include "xdelta3.c"
|
||||
#undef SOFTCFG
|
||||
|
||||
#undef TEMPLATE
|
||||
#undef LLOOK
|
||||
#undef SLOOK
|
||||
#undef LSTEP
|
||||
#undef SCHAIN
|
||||
#undef SLCHAIN
|
||||
#undef MAXLAZY
|
||||
#undef LONGENOUGH
|
||||
#endif
|
||||
|
||||
#define SOFTCFG 0
|
||||
|
||||
/************************************************************
|
||||
FASTEST string matcher
|
||||
**********************************************************/
|
||||
#if XD3_BUILD_FASTEST
|
||||
#define TEMPLATE fastest
|
||||
#define LLOOK 9
|
||||
#define LSTEP 26
|
||||
#define SLOOK 4U
|
||||
#define SCHAIN 1
|
||||
#define SLCHAIN 1
|
||||
#define MAXLAZY 6
|
||||
#define LONGENOUGH 6
|
||||
|
||||
#include "xdelta3.c"
|
||||
|
||||
#undef TEMPLATE
|
||||
#undef LLOOK
|
||||
#undef SLOOK
|
||||
#undef LSTEP
|
||||
#undef SCHAIN
|
||||
#undef SLCHAIN
|
||||
#undef MAXLAZY
|
||||
#undef LONGENOUGH
|
||||
#endif
|
||||
|
||||
/************************************************************
|
||||
FASTER string matcher
|
||||
**********************************************************/
|
||||
#if XD3_BUILD_FASTER
|
||||
#define TEMPLATE faster
|
||||
#define LLOOK 9
|
||||
#define LSTEP 15
|
||||
#define SLOOK 4U
|
||||
#define SCHAIN 1
|
||||
#define SLCHAIN 1
|
||||
#define MAXLAZY 18
|
||||
#define LONGENOUGH 18
|
||||
|
||||
#include "xdelta3.c"
|
||||
|
||||
#undef TEMPLATE
|
||||
#undef LLOOK
|
||||
#undef SLOOK
|
||||
#undef LSTEP
|
||||
#undef SCHAIN
|
||||
#undef SLCHAIN
|
||||
#undef MAXLAZY
|
||||
#undef LONGENOUGH
|
||||
#endif
|
||||
|
||||
/******************************************************
|
||||
FAST string matcher
|
||||
********************************************************/
|
||||
#if XD3_BUILD_FAST
|
||||
#define TEMPLATE fast
|
||||
#define LLOOK 9
|
||||
#define LSTEP 8
|
||||
#define SLOOK 4U
|
||||
#define SCHAIN 4
|
||||
#define SLCHAIN 1
|
||||
#define MAXLAZY 18
|
||||
#define LONGENOUGH 35
|
||||
|
||||
#include "xdelta3.c"
|
||||
|
||||
#undef TEMPLATE
|
||||
#undef LLOOK
|
||||
#undef SLOOK
|
||||
#undef LSTEP
|
||||
#undef SCHAIN
|
||||
#undef SLCHAIN
|
||||
#undef MAXLAZY
|
||||
#undef LONGENOUGH
|
||||
#endif
|
||||
|
||||
/**************************************************
|
||||
SLOW string matcher
|
||||
**************************************************************/
|
||||
#if XD3_BUILD_SLOW
|
||||
#define TEMPLATE slow
|
||||
#define LLOOK 9
|
||||
#define LSTEP 2
|
||||
#define SLOOK 4U
|
||||
#define SCHAIN 44
|
||||
#define SLCHAIN 13
|
||||
#define MAXLAZY 90
|
||||
#define LONGENOUGH 70
|
||||
|
||||
#include "xdelta3.c"
|
||||
|
||||
#undef TEMPLATE
|
||||
#undef LLOOK
|
||||
#undef SLOOK
|
||||
#undef LSTEP
|
||||
#undef SCHAIN
|
||||
#undef SLCHAIN
|
||||
#undef MAXLAZY
|
||||
#undef LONGENOUGH
|
||||
#endif
|
||||
|
||||
/********************************************************
|
||||
DEFAULT string matcher
|
||||
************************************************************/
|
||||
#if XD3_BUILD_DEFAULT
|
||||
#define TEMPLATE default
|
||||
#define LLOOK 9
|
||||
#define LSTEP 3
|
||||
#define SLOOK 4U
|
||||
#define SCHAIN 8
|
||||
#define SLCHAIN 2
|
||||
#define MAXLAZY 36
|
||||
#define LONGENOUGH 70
|
||||
|
||||
#include "xdelta3.c"
|
||||
|
||||
#undef TEMPLATE
|
||||
#undef LLOOK
|
||||
#undef SLOOK
|
||||
#undef LSTEP
|
||||
#undef SCHAIN
|
||||
#undef SLCHAIN
|
||||
#undef MAXLAZY
|
||||
#undef LONGENOUGH
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,167 @@
|
||||
/* xdelta3 - delta compression tools and library
|
||||
Copyright 2016 Joshua MacDonald
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
#ifndef _XDELTA3_HASH_H_
|
||||
#define _XDELTA3_HASH_H_
|
||||
|
||||
#if XD3_DEBUG
|
||||
#define SMALL_HASH_DEBUG1(s,inp) \
|
||||
uint32_t debug_state; \
|
||||
uint32_t debug_hval = xd3_checksum_hash (& (s)->small_hash, \
|
||||
xd3_scksum (&debug_state, (inp), (s)->smatcher.small_look))
|
||||
#define SMALL_HASH_DEBUG2(s,inp) \
|
||||
XD3_ASSERT (debug_hval == xd3_checksum_hash (& (s)->small_hash, \
|
||||
xd3_scksum (&debug_state, (inp), (s)->smatcher.small_look)))
|
||||
#else
|
||||
#define SMALL_HASH_DEBUG1(s,inp)
|
||||
#define SMALL_HASH_DEBUG2(s,inp)
|
||||
#endif /* XD3_DEBUG */
|
||||
|
||||
/* This is a good hash multiplier for 32-bit LCGs: see "linear
|
||||
* congruential generators of different sizes and good lattice
|
||||
* structure" */
|
||||
static const uint32_t hash_multiplier = 1597334677U;
|
||||
|
||||
/***********************************************************************
|
||||
Permute stuff
|
||||
***********************************************************************/
|
||||
|
||||
#if HASH_PERMUTE == 0
|
||||
#define PERMUTE(x) (x)
|
||||
#else
|
||||
#define PERMUTE(x) (__single_hash[(uint32_t)x])
|
||||
|
||||
extern const uint16_t __single_hash[256];
|
||||
#endif
|
||||
|
||||
/* Update the checksum state. */
|
||||
#if ADLER_LARGE_CKSUM
|
||||
inline uint32_t
|
||||
xd3_large_cksum_update (uint32_t cksum,
|
||||
const uint8_t *base,
|
||||
usize_t look) {
|
||||
uint32_t old_c = PERMUTE(base[0]);
|
||||
uint32_t new_c = PERMUTE(base[look]);
|
||||
uint32_t low = ((cksum & 0xffff) - old_c + new_c) & 0xffff;
|
||||
uint32_t high = ((cksum >> 16) - (old_c * look) + low) & 0xffff;
|
||||
return (high << 16) | low;
|
||||
}
|
||||
#else
|
||||
/* TODO: revisit this topic */
|
||||
#endif
|
||||
|
||||
#if UNALIGNED_OK
|
||||
#define UNALIGNED_READ32(dest,src) (*(dest)) = (*(uint32_t*)(src))
|
||||
#else
|
||||
#define UNALIGNED_READ32(dest,src) memcpy((dest), (src), 4);
|
||||
#endif
|
||||
|
||||
/* TODO: small cksum is hard-coded for 4 bytes (i.e., "look" is unused) */
|
||||
static inline uint32_t
|
||||
xd3_scksum (uint32_t *state,
|
||||
const uint8_t *base,
|
||||
const usize_t look)
|
||||
{
|
||||
UNALIGNED_READ32(state, base);
|
||||
return (*state) * hash_multiplier;
|
||||
}
|
||||
static inline uint32_t
|
||||
xd3_small_cksum_update (uint32_t *state,
|
||||
const uint8_t *base,
|
||||
usize_t look)
|
||||
{
|
||||
UNALIGNED_READ32(state, base+1);
|
||||
return (*state) * hash_multiplier;
|
||||
}
|
||||
|
||||
/***********************************************************************
|
||||
Ctable stuff
|
||||
***********************************************************************/
|
||||
|
||||
static inline usize_t
|
||||
xd3_checksum_hash (const xd3_hash_cfg *cfg, const usize_t cksum)
|
||||
{
|
||||
return (cksum >> cfg->shift) ^ (cksum & cfg->mask);
|
||||
}
|
||||
|
||||
/***********************************************************************
|
||||
Cksum function
|
||||
***********************************************************************/
|
||||
|
||||
#if ADLER_LARGE_CKSUM
|
||||
static inline uint32_t
|
||||
xd3_lcksum (const uint8_t *seg, const usize_t ln)
|
||||
{
|
||||
usize_t i = 0;
|
||||
uint32_t low = 0;
|
||||
uint32_t high = 0;
|
||||
|
||||
for (; i < ln; i += 1)
|
||||
{
|
||||
low += PERMUTE(*seg++);
|
||||
high += low;
|
||||
}
|
||||
|
||||
return ((high & 0xffff) << 16) | (low & 0xffff);
|
||||
}
|
||||
#else
|
||||
static inline uint32_t
|
||||
xd3_lcksum (const uint8_t *seg, const usize_t ln)
|
||||
{
|
||||
usize_t i, j;
|
||||
uint32_t h = 0;
|
||||
for (i = 0, j = ln - 1; i < ln; ++i, --j) {
|
||||
h += PERMUTE(seg[i]) * hash_multiplier_powers[j];
|
||||
}
|
||||
return h;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if XD3_ENCODER
|
||||
static usize_t
|
||||
xd3_size_log2 (usize_t slots)
|
||||
{
|
||||
int bits = 28; /* This should not be an unreasonable limit. */
|
||||
int i;
|
||||
|
||||
for (i = 3; i <= bits; i += 1)
|
||||
{
|
||||
if (slots < (1U << i))
|
||||
{
|
||||
/* TODO: this is compaction=1 in checksum_test.cc and maybe should
|
||||
* not be fixed at -1. */
|
||||
bits = i - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return bits;
|
||||
}
|
||||
|
||||
static void
|
||||
xd3_size_hashtable (xd3_stream *stream,
|
||||
usize_t slots,
|
||||
xd3_hash_cfg *cfg)
|
||||
{
|
||||
int bits = xd3_size_log2 (slots);
|
||||
|
||||
/* TODO: there's a 32-bit assumption here */
|
||||
cfg->size = (1 << bits);
|
||||
cfg->mask = (cfg->size - 1);
|
||||
cfg->shift = 32 - bits;
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,370 @@
|
||||
/* xdelta3 - delta compression tools and library
|
||||
Copyright 2016 Joshua MacDonald
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
#ifndef XDELTA3_INTERNAL_H__
|
||||
#define XDELTA3_INTERNAL_H__
|
||||
|
||||
#include "xdelta3.h"
|
||||
|
||||
typedef struct _main_file main_file;
|
||||
typedef struct _main_extcomp main_extcomp;
|
||||
|
||||
void main_buffree (void *ptr);
|
||||
void* main_bufalloc (size_t size);
|
||||
void main_file_init (main_file *xfile);
|
||||
int main_file_close (main_file *xfile);
|
||||
void main_file_cleanup (main_file *xfile);
|
||||
int main_file_isopen (main_file *xfile);
|
||||
int main_file_open (main_file *xfile, const char* name, int mode);
|
||||
int main_file_exists (main_file *xfile);
|
||||
int xd3_whole_append_window (xd3_stream *stream);
|
||||
int xd3_main_cmdline (int argc, char **argv);
|
||||
int main_file_read (main_file *ifile,
|
||||
uint8_t *buf,
|
||||
size_t size,
|
||||
size_t *nread,
|
||||
const char *msg);
|
||||
int main_file_write (main_file *ofile, uint8_t *buf,
|
||||
usize_t size, const char *msg);
|
||||
int test_compare_files (const char* f0, const char* f1);
|
||||
usize_t xd3_bytes_on_srcblk (xd3_source *src, xoff_t blkno);
|
||||
xoff_t xd3_source_eof(const xd3_source *src);
|
||||
uint32_t xd3_large_cksum_update (uint32_t cksum,
|
||||
const uint8_t *base,
|
||||
usize_t look);
|
||||
int xd3_emit_byte (xd3_stream *stream,
|
||||
xd3_output **outputp,
|
||||
uint8_t code);
|
||||
|
||||
int xd3_emit_bytes (xd3_stream *stream,
|
||||
xd3_output **outputp,
|
||||
const uint8_t *base,
|
||||
usize_t size);
|
||||
xd3_output* xd3_alloc_output (xd3_stream *stream,
|
||||
xd3_output *old_output);
|
||||
|
||||
int xd3_encode_init_full (xd3_stream *stream);
|
||||
size_t xd3_pow2_roundup (size_t x);
|
||||
int xd3_process_stream (int is_encode,
|
||||
xd3_stream *stream,
|
||||
int (*func) (xd3_stream *),
|
||||
int close_stream,
|
||||
const uint8_t *input,
|
||||
usize_t input_size,
|
||||
uint8_t *output,
|
||||
usize_t *output_size,
|
||||
usize_t output_size_max);
|
||||
|
||||
#if PYTHON_MODULE || SWIG_MODULE || NOT_MAIN
|
||||
int xd3_main_cmdline (int argc, char **argv);
|
||||
#endif
|
||||
|
||||
/* main_file->mode values */
|
||||
typedef enum
|
||||
{
|
||||
XO_READ = 0,
|
||||
XO_WRITE = 1
|
||||
} main_file_modes;
|
||||
|
||||
#ifndef XD3_POSIX
|
||||
#define XD3_POSIX 0
|
||||
#endif
|
||||
#ifndef XD3_STDIO
|
||||
#define XD3_STDIO 0
|
||||
#endif
|
||||
#ifndef XD3_WIN32
|
||||
#define XD3_WIN32 0
|
||||
#endif
|
||||
#ifndef NOT_MAIN
|
||||
#define NOT_MAIN 0
|
||||
#endif
|
||||
|
||||
/* If none are set, default to posix. */
|
||||
#if (XD3_POSIX + XD3_STDIO + XD3_WIN32) == 0
|
||||
#undef XD3_POSIX
|
||||
#define XD3_POSIX 1
|
||||
#endif
|
||||
|
||||
struct _main_file
|
||||
{
|
||||
#if XD3_WIN32
|
||||
HANDLE file;
|
||||
#elif XD3_STDIO
|
||||
FILE *file;
|
||||
#elif XD3_POSIX
|
||||
int file;
|
||||
#endif
|
||||
|
||||
int mode; /* XO_READ and XO_WRITE */
|
||||
const char *filename; /* File name or /dev/stdin,
|
||||
* /dev/stdout, /dev/stderr. */
|
||||
char *filename_copy; /* File name or /dev/stdin,
|
||||
* /dev/stdout, /dev/stderr. */
|
||||
const char *realname; /* File name or /dev/stdin,
|
||||
* /dev/stdout, /dev/stderr. */
|
||||
const main_extcomp *compressor; /* External compression struct. */
|
||||
int flags; /* RD_FIRST, RD_NONEXTERNAL, ... */
|
||||
xoff_t nread; /* for input position */
|
||||
xoff_t nwrite; /* for output position */
|
||||
uint8_t *snprintf_buf; /* internal snprintf() use */
|
||||
int size_known; /* Set by main_set_souze */
|
||||
xoff_t source_position; /* for avoiding seek in getblk_func */
|
||||
int seek_failed; /* after seek fails once, try FIFO */
|
||||
};
|
||||
|
||||
#ifdef _WIN32
|
||||
#define vsnprintf_func _vsnprintf
|
||||
#define snprintf_func _snprintf
|
||||
#else
|
||||
#define vsnprintf_func vsnprintf
|
||||
#define snprintf_func snprintf
|
||||
#endif
|
||||
#define short_sprintf(sb,fmt,...) \
|
||||
snprintf_func((sb).buf,sizeof((sb).buf),fmt,__VA_ARGS__)
|
||||
|
||||
/* Type used for short snprintf calls. */
|
||||
typedef struct {
|
||||
char buf[48];
|
||||
} shortbuf;
|
||||
|
||||
/* Prior to SVN 303 this function was only defined in DJGPP and WIN32
|
||||
* environments and other platforms would use the builtin snprintf()
|
||||
* with an arrangement of macros below. In OS X 10.6, Apply made
|
||||
* snprintf() a macro, which defeated those macros (since snprintf
|
||||
* would be evaluated before its argument macros were expanded,
|
||||
* therefore always define xsnprintf_func. */
|
||||
#undef PRINTF_ATTRIBUTE
|
||||
#ifdef __GNUC__
|
||||
/* Let's just assume no one uses gcc 2.x! */
|
||||
#define PRINTF_ATTRIBUTE(x,y) __attribute__ ((__format__ (__printf__, x, y)))
|
||||
#else
|
||||
#define PRINTF_ATTRIBUTE(x,y)
|
||||
#endif
|
||||
|
||||
/* Underlying xprintf() */
|
||||
int xsnprintf_func (char *str, int n, const char *fmt, ...)
|
||||
PRINTF_ATTRIBUTE(3,4);
|
||||
|
||||
/* XPR(NT "", ...) (used by main) prefixes an "xdelta3: " to the output. */
|
||||
void xprintf(const char *fmt, ...) PRINTF_ATTRIBUTE(1,2);
|
||||
#define XPR xprintf
|
||||
#define NT "xdelta3: "
|
||||
#define NTR ""
|
||||
|
||||
#ifndef UINT32_MAX
|
||||
#define UINT32_MAX 4294967295U
|
||||
#endif
|
||||
|
||||
#ifndef UINT64_MAX
|
||||
#define UINT64_MAX 18446744073709551615ULL
|
||||
#endif
|
||||
|
||||
#define UINT32_OFLOW_MASK 0xfe000000U
|
||||
#define UINT64_OFLOW_MASK 0xfe00000000000000ULL
|
||||
|
||||
/*********************************************************************
|
||||
Integer encoder/decoder functions
|
||||
**********************************************************************/
|
||||
|
||||
/* Consume N bytes of input, only used by the decoder. */
|
||||
#define DECODE_INPUT(n) \
|
||||
do { \
|
||||
stream->total_in += (xoff_t) (n); \
|
||||
stream->avail_in -= (n); \
|
||||
stream->next_in += (n); \
|
||||
} while (0)
|
||||
|
||||
#define DECODE_INTEGER_TYPE(PART,OFLOW) \
|
||||
while (stream->avail_in != 0) \
|
||||
{ \
|
||||
usize_t next = stream->next_in[0]; \
|
||||
\
|
||||
DECODE_INPUT(1); \
|
||||
\
|
||||
if (PART & OFLOW) \
|
||||
{ \
|
||||
stream->msg = "overflow in decode_integer"; \
|
||||
return XD3_INVALID_INPUT; \
|
||||
} \
|
||||
\
|
||||
PART = (PART << 7) | (next & 127); \
|
||||
\
|
||||
if ((next & 128) == 0) \
|
||||
{ \
|
||||
(*val) = PART; \
|
||||
PART = 0; \
|
||||
return 0; \
|
||||
} \
|
||||
} \
|
||||
\
|
||||
stream->msg = "further input required"; \
|
||||
return XD3_INPUT
|
||||
|
||||
#define READ_INTEGER_TYPE(TYPE, OFLOW) \
|
||||
TYPE val = 0; \
|
||||
const uint8_t *inp = (*inpp); \
|
||||
usize_t next; \
|
||||
\
|
||||
do \
|
||||
{ \
|
||||
if (inp == maxp) \
|
||||
{ \
|
||||
stream->msg = "end-of-input in read_integer"; \
|
||||
return XD3_INVALID_INPUT; \
|
||||
} \
|
||||
\
|
||||
if (val & OFLOW) \
|
||||
{ \
|
||||
stream->msg = "overflow in read_intger"; \
|
||||
return XD3_INVALID_INPUT; \
|
||||
} \
|
||||
\
|
||||
next = (*inp++); \
|
||||
val = (val << 7) | (next & 127); \
|
||||
} \
|
||||
while (next & 128); \
|
||||
\
|
||||
(*valp) = val; \
|
||||
(*inpp) = inp; \
|
||||
\
|
||||
return 0
|
||||
|
||||
#define EMIT_INTEGER_TYPE() \
|
||||
/* max 64-bit value in base-7 encoding is 9.1 bytes */ \
|
||||
uint8_t buf[10]; \
|
||||
usize_t bufi = 10; \
|
||||
\
|
||||
/* This loop performs division and turns on all MSBs. */ \
|
||||
do \
|
||||
{ \
|
||||
buf[--bufi] = (num & 127) | 128; \
|
||||
num >>= 7U; \
|
||||
} \
|
||||
while (num != 0); \
|
||||
\
|
||||
/* Turn off MSB of the last byte. */ \
|
||||
buf[9] &= 127; \
|
||||
\
|
||||
return xd3_emit_bytes (stream, output, buf + bufi, 10 - bufi)
|
||||
|
||||
#define IF_SIZEOF32(x) if (num < (1U << (7 * (x)))) return (x);
|
||||
#define IF_SIZEOF64(x) if (num < (1ULL << (7 * (x)))) return (x);
|
||||
|
||||
#if USE_UINT32
|
||||
static inline uint32_t
|
||||
xd3_sizeof_uint32_t (uint32_t num)
|
||||
{
|
||||
IF_SIZEOF32(1);
|
||||
IF_SIZEOF32(2);
|
||||
IF_SIZEOF32(3);
|
||||
IF_SIZEOF32(4);
|
||||
return 5;
|
||||
}
|
||||
|
||||
static inline int
|
||||
xd3_decode_uint32_t (xd3_stream *stream, uint32_t *val)
|
||||
{ DECODE_INTEGER_TYPE (stream->dec_32part, UINT32_OFLOW_MASK); }
|
||||
|
||||
static inline int
|
||||
xd3_read_uint32_t (xd3_stream *stream, const uint8_t **inpp,
|
||||
const uint8_t *maxp, uint32_t *valp)
|
||||
{ READ_INTEGER_TYPE (uint32_t, UINT32_OFLOW_MASK); }
|
||||
|
||||
#if XD3_ENCODER
|
||||
static inline int
|
||||
xd3_emit_uint32_t (xd3_stream *stream, xd3_output **output, uint32_t num)
|
||||
{ EMIT_INTEGER_TYPE (); }
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if USE_UINT64
|
||||
static inline int
|
||||
xd3_decode_uint64_t (xd3_stream *stream, uint64_t *val)
|
||||
{ DECODE_INTEGER_TYPE (stream->dec_64part, UINT64_OFLOW_MASK); }
|
||||
|
||||
#if XD3_ENCODER
|
||||
static inline int
|
||||
xd3_emit_uint64_t (xd3_stream *stream, xd3_output **output, uint64_t num)
|
||||
{ EMIT_INTEGER_TYPE (); }
|
||||
#endif
|
||||
|
||||
/* These are tested but not used */
|
||||
#if REGRESSION_TEST
|
||||
static int
|
||||
xd3_read_uint64_t (xd3_stream *stream, const uint8_t **inpp,
|
||||
const uint8_t *maxp, uint64_t *valp)
|
||||
{ READ_INTEGER_TYPE (uint64_t, UINT64_OFLOW_MASK); }
|
||||
|
||||
static uint32_t
|
||||
xd3_sizeof_uint64_t (uint64_t num)
|
||||
{
|
||||
IF_SIZEOF64(1);
|
||||
IF_SIZEOF64(2);
|
||||
IF_SIZEOF64(3);
|
||||
IF_SIZEOF64(4);
|
||||
IF_SIZEOF64(5);
|
||||
IF_SIZEOF64(6);
|
||||
IF_SIZEOF64(7);
|
||||
IF_SIZEOF64(8);
|
||||
IF_SIZEOF64(9);
|
||||
|
||||
return 10;
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#if SIZEOF_USIZE_T == 4
|
||||
#define USIZE_T_MAX UINT32_MAX
|
||||
#define USIZE_T_MAXBLKSZ 0x80000000U
|
||||
#define xd3_decode_size xd3_decode_uint32_t
|
||||
#define xd3_emit_size xd3_emit_uint32_t
|
||||
#define xd3_sizeof_size xd3_sizeof_uint32_t
|
||||
#define xd3_read_size xd3_read_uint32_t
|
||||
#elif SIZEOF_USIZE_T == 8
|
||||
#define USIZE_T_MAX UINT64_MAX
|
||||
#define USIZE_T_MAXBLKSZ 0x8000000000000000ULL
|
||||
#define xd3_decode_size xd3_decode_uint64_t
|
||||
#define xd3_emit_size xd3_emit_uint64_t
|
||||
#define xd3_sizeof_size xd3_sizeof_uint64_t
|
||||
#define xd3_read_size xd3_read_uint64_t
|
||||
#endif
|
||||
|
||||
#if SIZEOF_XOFF_T == 4
|
||||
#define XOFF_T_MAX UINT32_MAX
|
||||
#define xd3_emit_offset xd3_emit_uint32_t
|
||||
static inline int
|
||||
xd3_decode_offset (xd3_stream *stream, xoff_t *val)
|
||||
{
|
||||
return xd3_decode_uint32_t (stream, (uint32_t*) val);
|
||||
}
|
||||
#elif SIZEOF_XOFF_T == 8
|
||||
#define XOFF_T_MAX UINT64_MAX
|
||||
#define xd3_emit_offset xd3_emit_uint64_t
|
||||
static inline int
|
||||
xd3_decode_offset (xd3_stream *stream, xoff_t *val)
|
||||
{
|
||||
return xd3_decode_uint64_t (stream, (uint64_t*) val);
|
||||
}
|
||||
#endif
|
||||
|
||||
#define USIZE_T_OVERFLOW(a,b) ((USIZE_T_MAX - (usize_t) (a)) < (usize_t) (b))
|
||||
#define XOFF_T_OVERFLOW(a,b) ((XOFF_T_MAX - (xoff_t) (a)) < (xoff_t) (b))
|
||||
|
||||
#define MAX_LRU_SIZE 32U
|
||||
#define XD3_MINSRCWINSZ (XD3_ALLOCSIZE * MAX_LRU_SIZE)
|
||||
#define XD3_MAXSRCWINSZ (1ULL << 31)
|
||||
|
||||
#endif // XDELTA3_INTERNAL_H__
|
||||
@@ -0,0 +1,127 @@
|
||||
/* xdelta3 - delta compression tools and library
|
||||
Copyright 2016 Joshua MacDonald
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
#ifndef __XDELTA3_LIST__
|
||||
#define __XDELTA3_LIST__
|
||||
|
||||
#define XD3_MAKELIST(LTYPE,ETYPE,LNAME) \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _entry (LTYPE* l) \
|
||||
{ \
|
||||
return (ETYPE*) ((char*) l - (ptrdiff_t) &((ETYPE*) 0)->LNAME); \
|
||||
} \
|
||||
\
|
||||
static inline void \
|
||||
LTYPE ## _init (LTYPE *l) \
|
||||
{ \
|
||||
l->next = l; \
|
||||
l->prev = l; \
|
||||
} \
|
||||
\
|
||||
static inline void \
|
||||
LTYPE ## _add (LTYPE *prev, LTYPE *next, LTYPE *ins) \
|
||||
{ \
|
||||
next->prev = ins; \
|
||||
prev->next = ins; \
|
||||
ins->next = next; \
|
||||
ins->prev = prev; \
|
||||
} \
|
||||
\
|
||||
static inline void \
|
||||
LTYPE ## _push_back (LTYPE *l, ETYPE *i) \
|
||||
{ \
|
||||
LTYPE ## _add (l->prev, l, & i->LNAME); \
|
||||
} \
|
||||
\
|
||||
static inline void \
|
||||
LTYPE ## _del (LTYPE *next, \
|
||||
LTYPE *prev) \
|
||||
{ \
|
||||
next->prev = prev; \
|
||||
prev->next = next; \
|
||||
} \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _remove (ETYPE *f) \
|
||||
{ \
|
||||
LTYPE *i = f->LNAME.next; \
|
||||
LTYPE ## _del (f->LNAME.next, f->LNAME.prev); \
|
||||
return LTYPE ## _entry (i); \
|
||||
} \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _pop_back (LTYPE *l) \
|
||||
{ \
|
||||
LTYPE *i = l->prev; \
|
||||
LTYPE ## _del (i->next, i->prev); \
|
||||
return LTYPE ## _entry (i); \
|
||||
} \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _pop_front (LTYPE *l) \
|
||||
{ \
|
||||
LTYPE *i = l->next; \
|
||||
LTYPE ## _del (i->next, i->prev); \
|
||||
return LTYPE ## _entry (i); \
|
||||
} \
|
||||
\
|
||||
static inline int \
|
||||
LTYPE ## _empty (LTYPE *l) \
|
||||
{ \
|
||||
return l == l->next; \
|
||||
} \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _front (LTYPE *f) \
|
||||
{ \
|
||||
return LTYPE ## _entry (f->next); \
|
||||
} \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _back (LTYPE *f) \
|
||||
{ \
|
||||
return LTYPE ## _entry (f->prev); \
|
||||
} \
|
||||
\
|
||||
static inline int \
|
||||
LTYPE ## _end (LTYPE *f, ETYPE *i) \
|
||||
{ \
|
||||
return f == & i->LNAME; \
|
||||
} \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _next (ETYPE *f) \
|
||||
{ \
|
||||
return LTYPE ## _entry (f->LNAME.next); \
|
||||
} \
|
||||
\
|
||||
static inline usize_t \
|
||||
LTYPE ## _length (LTYPE *l) \
|
||||
{ \
|
||||
LTYPE *p; \
|
||||
int c = 0; \
|
||||
\
|
||||
for (p = l->next; p != l; p = p->next) \
|
||||
{ \
|
||||
c += 1; \
|
||||
} \
|
||||
\
|
||||
return c; \
|
||||
} \
|
||||
\
|
||||
typedef int unused_ ## LTYPE
|
||||
|
||||
#endif
|
||||
+4835
File diff suppressed because it is too large.
Load diff
+1396
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user