Skip to main content

euv_cli/builder/archive/
fn.rs

1use super::*;
2
3/// Computes the standard IEEE 802.3 CRC-32 checksum used by PNG, PKZIP, and GZIP.
4///
5/// # Arguments
6///
7/// - `&[u8]` - Input byte slice.
8///
9/// # Returns
10///
11/// - `u32` - Computed CRC-32 checksum.
12#[must_use]
13pub fn crc32_bytes(data: &[u8]) -> u32 {
14    let mut crc: u32 = 0xFFFF_FFFF;
15    for &byte_val in data.iter() {
16        crc ^= u32::from(byte_val);
17        let mut bit_idx: u8 = 0;
18        while bit_idx < 8 {
19            if (crc & 1) != 0 {
20                crc = (crc >> 1) ^ CRC32_POLY;
21            } else {
22                crc >>= 1;
23            }
24            bit_idx += 1;
25        }
26    }
27    !crc
28}
29
30/// Computes the RFC 1950 Adler-32 checksum used inside zlib streams and PNG `IDAT` chunks.
31///
32/// # Arguments
33///
34/// - `&[u8]` - Input byte slice.
35///
36/// # Returns
37///
38/// - `u32` - Computed Adler-32 checksum.
39#[must_use]
40pub fn adler32_bytes(data: &[u8]) -> u32 {
41    let mut sum_low: u32 = 1;
42    let mut sum_high: u32 = 0;
43    for &byte_val in data.iter() {
44        sum_low = (sum_low + u32::from(byte_val)) % ADLER32_MOD;
45        sum_high = (sum_high + sum_low) % ADLER32_MOD;
46    }
47    (sum_high << 16) | sum_low
48}
49
50/// Compresses raw bytes into an RFC 1951 raw DEFLATE bitstream.
51///
52/// # Arguments
53///
54/// - `&[u8]` - Uncompressed input bytes.
55///
56/// # Returns
57///
58/// - `Vec<u8>` - Compressed RFC 1951 DEFLATE stream.
59#[must_use]
60pub fn deflate_compress(input: &[u8]) -> Vec<u8> {
61    if input.is_empty() {
62        return deflate_store_blocks(input);
63    }
64    let fixed: Vec<u8> = deflate_fixed_lz77(input);
65    let stored_estimate: usize = input.len() + ((input.len() / DEFLATE_MAX_STORED_BLOCK) + 1) * 5;
66    if fixed.len() <= stored_estimate {
67        fixed
68    } else {
69        deflate_store_blocks(input)
70    }
71}
72
73/// Decompresses an RFC 1951 raw DEFLATE bitstream (stored, fixed Huffman, and dynamic Huffman).
74///
75/// # Arguments
76///
77/// - `&[u8]` - Compressed RFC 1951 DEFLATE payload.
78///
79/// # Returns
80///
81/// - `io::Result<Vec<u8>>` - Decompressed bytes or error if malformed.
82pub fn deflate_decompress(input: &[u8]) -> io::Result<Vec<u8>> {
83    let mut reader: DeflateBitReader<'_> = DeflateBitReader::new(input);
84    let mut out: Vec<u8> = Vec::new();
85    loop {
86        let is_final: u32 = reader.read_bits(1)?;
87        let block_type: u32 = reader.read_bits(2)?;
88        match block_type {
89            0 => {
90                reader.align_byte();
91                let block_len: u16 = reader.read_aligned_u16()?;
92                let inverted_len: u16 = reader.read_aligned_u16()?;
93                if block_len != !inverted_len {
94                    return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
95                }
96                reader.read_aligned_bytes(usize::from(block_len), &mut out)?;
97            }
98            1 => {
99                let (lit_dec, dist_dec): (HuffmanDecoder, HuffmanDecoder) = build_fixed_decoders()?;
100                decode_huffman_block(&mut reader, &lit_dec, &dist_dec, &mut out)?;
101            }
102            2 => {
103                let (lit_dec, dist_dec): (HuffmanDecoder, HuffmanDecoder) =
104                    read_dynamic_decoders(&mut reader)?;
105                decode_huffman_block(&mut reader, &lit_dec, &dist_dec, &mut out)?;
106            }
107            _ => return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID)),
108        }
109        if is_final != 0 {
110            break;
111        }
112    }
113    Ok(out)
114}
115
116/// Compresses bytes into a standard RFC 1950 zlib stream with Adler-32 trailer.
117///
118/// # Arguments
119///
120/// - `&[u8]` - Uncompressed input bytes.
121///
122/// # Returns
123///
124/// - `Vec<u8>` - Complete RFC 1950 zlib byte stream.
125#[must_use]
126pub fn zlib_compress(input: &[u8]) -> Vec<u8> {
127    let body: Vec<u8> = deflate_compress(input);
128    let checksum: u32 = adler32_bytes(input);
129    let mut out: Vec<u8> = Vec::with_capacity(body.len() + 6);
130    out.push(ZLIB_HEADER_CMF);
131    out.push(ZLIB_HEADER_FLG);
132    out.extend_from_slice(&body);
133    out.extend_from_slice(&checksum.to_be_bytes());
134    out
135}
136
137/// Decompresses an RFC 1950 zlib stream and validates its header and Adler-32 checksum.
138///
139/// # Arguments
140///
141/// - `&[u8]` - Compressed zlib byte stream.
142///
143/// # Returns
144///
145/// - `io::Result<Vec<u8>>` - Verified decompressed bytes.
146pub fn zlib_decompress(input: &[u8]) -> io::Result<Vec<u8>> {
147    if input.len() < 6 {
148        return Err(Error::new(ErrorKind::InvalidData, ERR_ZLIB_INVALID));
149    }
150    let cmf: u8 = input[0];
151    let flg: u8 = input[1];
152    let check_word: u16 = (u16::from(cmf) << 8) | u16::from(flg);
153    if (cmf & 0x0F) != 8 || (flg & 0x20) != 0 || !check_word.is_multiple_of(31) {
154        return Err(Error::new(ErrorKind::InvalidData, ERR_ZLIB_INVALID));
155    }
156    let body_end: usize = input.len() - 4;
157    let decoded: Vec<u8> = deflate_decompress(&input[2..body_end])?;
158    let expected: u32 = u32::from_be_bytes([
159        input[body_end],
160        input[body_end + 1],
161        input[body_end + 2],
162        input[body_end + 3],
163    ]);
164    let actual: u32 = adler32_bytes(&decoded);
165    if actual != expected {
166        return Err(Error::new(ErrorKind::InvalidData, ERR_ZLIB_INVALID));
167    }
168    Ok(decoded)
169}
170
171/// Compresses bytes into a standard RFC 1952 GZIP stream with CRC-32 and ISIZE trailers.
172///
173/// # Arguments
174///
175/// - `&[u8]` - Uncompressed input bytes.
176///
177/// # Returns
178///
179/// - `Vec<u8>` - Complete RFC 1952 GZIP byte stream.
180#[must_use]
181pub fn gzip_compress(input: &[u8]) -> Vec<u8> {
182    let body: Vec<u8> = deflate_compress(input);
183    let checksum: u32 = crc32_bytes(input);
184    let isize_val: u32 = input.len() as u32;
185    let mut out: Vec<u8> = Vec::with_capacity(GZIP_HEADER_BYTES.len() + body.len() + 8);
186    out.extend_from_slice(&GZIP_HEADER_BYTES);
187    out.extend_from_slice(&body);
188    out.extend_from_slice(&checksum.to_le_bytes());
189    out.extend_from_slice(&isize_val.to_le_bytes());
190    out
191}
192
193/// Decompresses an RFC 1952 GZIP stream and verifies its CRC-32 and ISIZE trailers.
194///
195/// # Arguments
196///
197/// - `&[u8]` - Compressed GZIP byte stream.
198///
199/// # Returns
200///
201/// - `io::Result<Vec<u8>>` - Verified decompressed bytes.
202pub fn gzip_decompress(input: &[u8]) -> io::Result<Vec<u8>> {
203    if input.len() < 18 || input[0] != 0x1F || input[1] != 0x8B || input[2] != 0x08 {
204        return Err(Error::new(ErrorKind::InvalidData, ERR_GZIP_INVALID));
205    }
206    let flags: u8 = input[3];
207    let mut offset: usize = 10;
208    if (flags & 0x04) != 0 {
209        if offset + 2 > input.len() {
210            return Err(Error::new(ErrorKind::InvalidData, ERR_GZIP_INVALID));
211        }
212        let extra_len: usize = usize::from(u16::from_le_bytes([input[offset], input[offset + 1]]));
213        offset += 2 + extra_len;
214    }
215    if (flags & 0x08) != 0 {
216        while offset < input.len() && input[offset] != 0 {
217            offset += 1;
218        }
219        offset += 1;
220    }
221    if (flags & 0x10) != 0 {
222        while offset < input.len() && input[offset] != 0 {
223            offset += 1;
224        }
225        offset += 1;
226    }
227    if (flags & 0x02) != 0 {
228        offset += 2;
229    }
230    if offset + 8 > input.len() {
231        return Err(Error::new(ErrorKind::InvalidData, ERR_GZIP_INVALID));
232    }
233    let trailer_pos: usize = input.len() - 8;
234    let decoded: Vec<u8> = deflate_decompress(&input[offset..trailer_pos])?;
235    let expected_crc: u32 = u32::from_le_bytes([
236        input[trailer_pos],
237        input[trailer_pos + 1],
238        input[trailer_pos + 2],
239        input[trailer_pos + 3],
240    ]);
241    let expected_len: u32 = u32::from_le_bytes([
242        input[trailer_pos + 4],
243        input[trailer_pos + 5],
244        input[trailer_pos + 6],
245        input[trailer_pos + 7],
246    ]);
247    if crc32_bytes(&decoded) != expected_crc || (decoded.len() as u32) != expected_len {
248        return Err(Error::new(ErrorKind::InvalidData, ERR_GZIP_INVALID));
249    }
250    Ok(decoded)
251}
252
253/// Validates whether `version` matches strict numeric semantic versioning `MAJOR.MINOR.PATCH`.
254///
255/// # Arguments
256///
257/// - `&str` - Candidate version string.
258///
259/// # Returns
260///
261/// - `bool` - `true` when strictly numeric `MAJOR.MINOR.PATCH` without leading zeroes.
262#[must_use]
263pub fn is_valid_numeric_semver(version: &str) -> bool {
264    let parts: Vec<&str> = version.split('.').collect();
265    if parts.len() != 3 {
266        return false;
267    }
268    parts.iter().all(|part: &&str| {
269        if part.is_empty() || !part.bytes().all(|byte_val: u8| byte_val.is_ascii_digit()) {
270            return false;
271        }
272        part.len() == 1 || !part.starts_with('0')
273    })
274}
275
276/// Validates that a forward-slash relative release path contains no traversal, control, or reserved segments.
277///
278/// # Arguments
279///
280/// - `&str` - POSIX-style relative file path inside a release directory.
281///
282/// # Returns
283///
284/// - `bool` - `true` when safe to emit into `euv-release.json`.
285#[must_use]
286pub fn is_safe_release_relative_path(relative: &str) -> bool {
287    if relative.is_empty() {
288        return false;
289    }
290    for byte_val in relative.bytes() {
291        let forbidden: bool = RELEASE_FORBIDDEN_PATH_BYTES.contains(&byte_val);
292        if byte_val < 32 || byte_val == 127 || forbidden {
293            return false;
294        }
295    }
296    for segment in relative.split('/') {
297        if segment.is_empty()
298            || segment == "."
299            || segment == ".."
300            || RELEASE_MANIFEST_RESERVED_NAMES.contains(&segment)
301        {
302            return false;
303        }
304    }
305    true
306}
307
308/// Generates and writes the deterministic SHA-256 `euv-release.json` manifest for `dist_dir`.
309///
310/// # Arguments
311///
312/// - `&Path` - Distribution root directory containing `index.html` and release assets.
313/// - `&str` - Numeric semantic version string (`MAJOR.MINOR.PATCH`).
314///
315/// # Returns
316///
317/// - `io::Result<ReleaseAssetManifest>` - Written manifest inventory or validation error.
318pub fn write_release_manifest(dist_dir: &Path, version: &str) -> io::Result<ReleaseAssetManifest> {
319    if !is_valid_numeric_semver(version) {
320        return Err(Error::new(ErrorKind::InvalidInput, ERR_INVALID_SEMVER));
321    }
322    let root_meta: Metadata = fs::symlink_metadata(dist_dir)?;
323    if root_meta.file_type().is_symlink() || !root_meta.is_dir() {
324        return Err(Error::new(ErrorKind::InvalidInput, ERR_INVALID_DIST_DIR));
325    }
326    let mut collected_paths: Vec<(String, PathBuf)> = Vec::new();
327    collect_release_files_recursive(dist_dir, dist_dir, &mut collected_paths)?;
328    collected_paths
329        .sort_by(|left: &(String, PathBuf), right: &(String, PathBuf)| left.0.cmp(&right.0));
330    let mut entries: Vec<ReleaseManifestFileEntry> = Vec::with_capacity(collected_paths.len());
331    let mut has_nonempty_index: bool = false;
332    for (relative, full_path) in collected_paths.into_iter() {
333        let data: Vec<u8> = fs::read(&full_path)?;
334        let digest: String = sha256_hex(&data);
335        let size: u64 = data.len() as u64;
336        if relative == RELEASE_MANIFEST_INDEX_HTML && size > 0 {
337            has_nonempty_index = true;
338        }
339        entries.push(ReleaseManifestFileEntry::new(relative, digest, size));
340    }
341    if !has_nonempty_index {
342        return Err(Error::new(ErrorKind::InvalidInput, ERR_MISSING_INDEX_HTML));
343    }
344    let manifest: ReleaseAssetManifest =
345        ReleaseAssetManifest::new(RELEASE_MANIFEST_FORMAT, version.to_string(), entries);
346    let mut json_text: String = to_string_pretty(&manifest)
347        .map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
348    json_text.push('\n');
349    fs::write(dist_dir.join(RELEASE_MANIFEST_NAME), json_text.as_bytes())?;
350    Ok(manifest)
351}
352
353/// Verifies `euv-release.json` schema, version, required assets, sizes, and SHA-256 digests on disk.
354///
355/// # Arguments
356///
357/// - `&Path` - Distribution root directory containing `euv-release.json`.
358/// - `Option<&str>` - Optional expected release semantic version to enforce.
359/// - `&[&str]` - Required relative asset paths that must exist and be non-empty.
360///
361/// # Returns
362///
363/// - `io::Result<ReleaseAssetManifest>` - Verified release manifest or integrity error.
364pub fn verify_release_manifest(
365    dist_dir: &Path,
366    expected_version: Option<&str>,
367    required_files: &[&str],
368) -> io::Result<ReleaseAssetManifest> {
369    let manifest_path: PathBuf = dist_dir.join(RELEASE_MANIFEST_NAME);
370    let raw_json: String = fs::read_to_string(&manifest_path)?;
371    let manifest: ReleaseAssetManifest = from_str(&raw_json)
372        .map_err(|err: serde_json::Error| Error::new(ErrorKind::InvalidData, err.to_string()))?;
373    if manifest.get_format() != RELEASE_MANIFEST_FORMAT {
374        return Err(Error::new(ErrorKind::InvalidData, ERR_MANIFEST_FORMAT));
375    }
376    if !is_valid_numeric_semver(manifest.get_version()) {
377        return Err(Error::new(ErrorKind::InvalidData, ERR_INVALID_SEMVER));
378    }
379    if let Some(expected) = expected_version
380        && manifest.get_version() != expected
381    {
382        return Err(Error::new(
383            ErrorKind::InvalidData,
384            format!(
385                "{ERR_MANIFEST_VERSION}: {} != {expected}",
386                manifest.get_version()
387            ),
388        ));
389    }
390    let mut indexed: BTreeMap<&str, &ReleaseManifestFileEntry> = BTreeMap::new();
391    for entry in manifest.get_files().iter() {
392        let rel_path: &str = entry.get_path().as_str();
393        if !is_safe_release_relative_path(rel_path) {
394            return Err(Error::new(
395                ErrorKind::InvalidData,
396                format!("{ERR_UNSAFE_RELEASE_PATH}: {rel_path}"),
397            ));
398        }
399        let disk_path: PathBuf = dist_dir.join(rel_path);
400        let meta: Metadata = fs::symlink_metadata(&disk_path)?;
401        if meta.file_type().is_symlink() {
402            return Err(Error::new(
403                ErrorKind::InvalidData,
404                format!("{ERR_SYMLINK_FORBIDDEN}: {rel_path}"),
405            ));
406        }
407        if !meta.is_file() {
408            return Err(Error::new(
409                ErrorKind::InvalidData,
410                format!("{ERR_NOT_REGULAR_FILE}: {rel_path}"),
411            ));
412        }
413        let raw_bytes: Vec<u8> = fs::read(&disk_path)?;
414        if (raw_bytes.len() as u64) != entry.get_size() {
415            return Err(Error::new(
416                ErrorKind::InvalidData,
417                format!("{ERR_MANIFEST_SIZE_MISMATCH}: {rel_path}"),
418            ));
419        }
420        let actual_sha: String = sha256_hex(&raw_bytes);
421        if actual_sha != *entry.get_sha256() {
422            return Err(Error::new(
423                ErrorKind::InvalidData,
424                format!("{ERR_MANIFEST_SHA_MISMATCH}: {rel_path}"),
425            ));
426        }
427        let _: Option<&ReleaseManifestFileEntry> = indexed.insert(rel_path, entry);
428    }
429    for &req_path in required_files.iter() {
430        let found: Option<&&ReleaseManifestFileEntry> = indexed.get(req_path);
431        if found.is_none_or(|entry: &&ReleaseManifestFileEntry| entry.get_size() == 0) {
432            return Err(Error::new(
433                ErrorKind::InvalidData,
434                format!("{ERR_MANIFEST_REQUIRED_MISSING}: {req_path}"),
435            ));
436        }
437    }
438    Ok(manifest)
439}
440
441/// Counts occurrences of `euv.ai.schema.v1` and `euv.ai.schema.v2` marker bytes in a slice.
442///
443/// # Arguments
444///
445/// - `&[u8]` - Raw binary bytes to scan.
446///
447/// # Returns
448///
449/// - `(usize, usize)` - Tuple of `(v1_matches, v2_matches)`.
450#[must_use]
451pub fn scan_bytes_for_ai_schema(bytes: &[u8]) -> (usize, usize) {
452    let v1_hits: usize = count_subslice_occurrences(bytes, AI_SCHEMA_V1_MARKER);
453    let v2_hits: usize = count_subslice_occurrences(bytes, AI_SCHEMA_V2_MARKER);
454    (v1_hits, v2_hits)
455}
456
457/// Scans an artifact file on disk for dev-only AI schema markers.
458///
459/// # Arguments
460///
461/// - `&Path` - Path to `.wasm`, `.so`, or native executable binary.
462///
463/// # Returns
464///
465/// - `io::Result<AiSchemaScanReport>` - Match counts across v1 and v2 schema markers.
466pub fn scan_file_for_ai_schema(path: &Path) -> io::Result<AiSchemaScanReport> {
467    let raw: Vec<u8> = fs::read(path)?;
468    let (v1_hits, v2_hits): (usize, usize) = scan_bytes_for_ai_schema(&raw);
469    Ok(AiSchemaScanReport::new(
470        path.to_path_buf(),
471        v1_hits,
472        v2_hits,
473        v1_hits + v2_hits,
474    ))
475}
476
477/// Verifies that a release artifact contains zero dev-only AI schema marker bytes.
478///
479/// # Arguments
480///
481/// - `&Path` - Path to the compiled release binary.
482///
483/// # Returns
484///
485/// - `io::Result<AiSchemaScanReport>` - Clean report on zero matches, or an error on any leak.
486pub fn verify_no_ai_schema_leak(path: &Path) -> io::Result<AiSchemaScanReport> {
487    let report: AiSchemaScanReport = scan_file_for_ai_schema(path)?;
488    if report.get_total_matches() > 0 {
489        return Err(Error::new(
490            ErrorKind::InvalidData,
491            format!(
492                "{ERR_AI_SCHEMA_LEAK}: {} (v1={}, v2={})",
493                path.display(),
494                report.get_v1_matches(),
495                report.get_v2_matches()
496            ),
497        ));
498    }
499    Ok(report)
500}
501
502/// Writes a pure-Rust PKZIP archive with per-entry stored (`-0`) or DEFLATE compression.
503///
504/// # Arguments
505///
506/// - `&Path` - Destination `.zip` file path.
507/// - `&[ZipEntryInput]` - Ordered slice of entries to archive.
508///
509/// # Returns
510///
511/// - `io::Result<u64>` - Total byte length of the written `.zip` file.
512pub fn write_zip_entries(output_path: &Path, entries: &[ZipEntryInput]) -> io::Result<u64> {
513    if let Some(parent) = output_path.parent()
514        && !parent.as_os_str().is_empty()
515    {
516        fs::create_dir_all(parent)?;
517    }
518    let mut out: Vec<u8> = Vec::new();
519    let mut records: Vec<ZipCentralRecord> = Vec::with_capacity(entries.len());
520    for entry in entries.iter() {
521        let normalized_name: String = normalize_archive_entry_name(entry.get_archive_path());
522        let name_bytes: Vec<u8> = normalized_name.into_bytes();
523        let raw_data: &[u8] = entry.get_data();
524        let crc: u32 = crc32_bytes(raw_data);
525        let (method, payload): (u16, Vec<u8>) = if entry.get_stored() {
526            (ZIP_METHOD_STORED, raw_data.to_vec())
527        } else {
528            let deflated: Vec<u8> = deflate_compress(raw_data);
529            if deflated.len() < raw_data.len() {
530                (ZIP_METHOD_DEFLATE, deflated)
531            } else {
532                (ZIP_METHOD_STORED, raw_data.to_vec())
533            }
534        };
535        let local_offset: u32 = out.len() as u32;
536        let comp_size: u32 = payload.len() as u32;
537        let uncomp_size: u32 = raw_data.len() as u32;
538        let external_attrs: u32 = (ZIP_UNIX_REGULAR_FILE | (entry.get_unix_mode() & 0o7777)) << 16;
539        push_zip_local_header(
540            &mut out,
541            &name_bytes,
542            method,
543            ZIP_FLAG_UTF8,
544            crc,
545            comp_size,
546            uncomp_size,
547        );
548        out.extend_from_slice(&payload);
549        records.push(ZipCentralRecord {
550            name_bytes,
551            method,
552            flags: ZIP_FLAG_UTF8,
553            crc32: crc,
554            compressed_size: comp_size,
555            uncompressed_size: uncomp_size,
556            local_offset,
557            external_attrs,
558        });
559    }
560    finalize_zip_central_directory(&mut out, &records);
561    fs::write(output_path, &out)?;
562    Ok(out.len() as u64)
563}
564
565/// Appends or replaces entries inside an existing ZIP archive (e.g. packing stored `.dex`/`.so` into an APK).
566///
567/// # Arguments
568///
569/// - `&Path` - Path to the existing `.zip` or `.apk` file to update in place.
570/// - `&[ZipEntryInput]` - Entries to append or replace by archive path.
571///
572/// # Returns
573///
574/// - `io::Result<u64>` - Final archive byte size after rewrite.
575pub fn append_entries_to_zip(
576    existing_zip: &Path,
577    extra_entries: &[ZipEntryInput],
578) -> io::Result<u64> {
579    let raw_zip: Vec<u8> = fs::read(existing_zip)?;
580    let existing: Vec<ExistingZipRawEntry> = parse_existing_zip_entries(&raw_zip)?;
581    let mut replace_names: BTreeSet<String> = BTreeSet::new();
582    for item in extra_entries.iter() {
583        let _: bool = replace_names.insert(normalize_archive_entry_name(item.get_archive_path()));
584    }
585    let mut out: Vec<u8> = Vec::with_capacity(raw_zip.len() + 65_536);
586    let mut records: Vec<ZipCentralRecord> =
587        Vec::with_capacity(existing.len() + extra_entries.len());
588    for entry in existing.into_iter() {
589        if replace_names.contains(&entry.name) {
590            continue;
591        }
592        let name_bytes: Vec<u8> = entry.name.into_bytes();
593        let local_offset: u32 = out.len() as u32;
594        let comp_size: u32 = entry.compressed_data.len() as u32;
595        push_zip_local_header(
596            &mut out,
597            &name_bytes,
598            entry.method,
599            entry.flags,
600            entry.crc32,
601            comp_size,
602            entry.uncompressed_size,
603        );
604        out.extend_from_slice(&entry.compressed_data);
605        records.push(ZipCentralRecord {
606            name_bytes,
607            method: entry.method,
608            flags: entry.flags,
609            crc32: entry.crc32,
610            compressed_size: comp_size,
611            uncompressed_size: entry.uncompressed_size,
612            local_offset,
613            external_attrs: entry.external_attrs,
614        });
615    }
616    for entry in extra_entries.iter() {
617        let name_bytes: Vec<u8> =
618            normalize_archive_entry_name(entry.get_archive_path()).into_bytes();
619        let raw_data: &[u8] = entry.get_data();
620        let crc: u32 = crc32_bytes(raw_data);
621        let (method, payload): (u16, Vec<u8>) = if entry.get_stored() {
622            (ZIP_METHOD_STORED, raw_data.to_vec())
623        } else {
624            let deflated: Vec<u8> = deflate_compress(raw_data);
625            if deflated.len() < raw_data.len() {
626                (ZIP_METHOD_DEFLATE, deflated)
627            } else {
628                (ZIP_METHOD_STORED, raw_data.to_vec())
629            }
630        };
631        let local_offset: u32 = out.len() as u32;
632        let comp_size: u32 = payload.len() as u32;
633        let uncomp_size: u32 = raw_data.len() as u32;
634        let external_attrs: u32 = (ZIP_UNIX_REGULAR_FILE | (entry.get_unix_mode() & 0o7777)) << 16;
635        push_zip_local_header(
636            &mut out,
637            &name_bytes,
638            method,
639            ZIP_FLAG_UTF8,
640            crc,
641            comp_size,
642            uncomp_size,
643        );
644        out.extend_from_slice(&payload);
645        records.push(ZipCentralRecord {
646            name_bytes,
647            method,
648            flags: ZIP_FLAG_UTF8,
649            crc32: crc,
650            compressed_size: comp_size,
651            uncompressed_size: uncomp_size,
652            local_offset,
653            external_attrs,
654        });
655    }
656    finalize_zip_central_directory(&mut out, &records);
657    fs::write(existing_zip, &out)?;
658    Ok(out.len() as u64)
659}
660
661/// Recursively archives all files in `source_dir` into a deterministic pure-Rust PKZIP file.
662///
663/// # Arguments
664///
665/// - `&Path` - Source directory to archive.
666/// - `&Path` - Destination `.zip` file path.
667/// - `bool` - When `true`, stores all entries uncompressed (`-0`); otherwise applies DEFLATE.
668///
669/// # Returns
670///
671/// - `io::Result<u64>` - Written `.zip` file byte size.
672pub fn archive_directory_to_zip(
673    source_dir: &Path,
674    output_zip: &Path,
675    store_only: bool,
676) -> io::Result<u64> {
677    let mut files: Vec<(String, PathBuf, u32)> = Vec::new();
678    collect_archive_files_recursive(source_dir, source_dir, None, &mut files)?;
679    files.sort_by(
680        |left: &(String, PathBuf, u32), right: &(String, PathBuf, u32)| left.0.cmp(&right.0),
681    );
682    let mut entries: Vec<ZipEntryInput> = Vec::with_capacity(files.len());
683    for (rel_path, disk_path, mode) in files.into_iter() {
684        let data: Vec<u8> = fs::read(&disk_path)?;
685        entries.push(ZipEntryInput::new(rel_path, data, store_only, mode));
686    }
687    write_zip_entries(output_zip, &entries)
688}
689
690/// Writes a deterministic pure-Rust gzipped POSIX ustar `.tar.gz` archive from explicit entries.
691///
692/// # Arguments
693///
694/// - `&Path` - Destination `.tar.gz` file path.
695/// - `&[TarEntryInput]` - Ordered slice of file and directory entries.
696///
697/// # Returns
698///
699/// - `io::Result<u64>` - Written `.tar.gz` file byte size.
700pub fn write_tar_gz_entries(output_path: &Path, entries: &[TarEntryInput]) -> io::Result<u64> {
701    if let Some(parent) = output_path.parent()
702        && !parent.as_os_str().is_empty()
703    {
704        fs::create_dir_all(parent)?;
705    }
706    let mut tar_bytes: Vec<u8> = Vec::new();
707    for entry in entries.iter() {
708        let mut norm_path: String = normalize_archive_entry_name(entry.get_archive_path());
709        if entry.get_is_dir() && !norm_path.ends_with('/') {
710            norm_path.push('/');
711        }
712        let data_len: usize = if entry.get_is_dir() {
713            0
714        } else {
715            entry.get_data().len()
716        };
717        let header: [u8; TAR_BLOCK_SIZE] = build_ustar_header(
718            &norm_path,
719            entry.get_unix_mode(),
720            data_len as u64,
721            entry.get_is_dir(),
722        )?;
723        tar_bytes.extend_from_slice(&header);
724        if !entry.get_is_dir() && data_len > 0 {
725            tar_bytes.extend_from_slice(entry.get_data());
726            let rem: usize = data_len % TAR_BLOCK_SIZE;
727            if rem > 0 {
728                tar_bytes.resize(tar_bytes.len() + (TAR_BLOCK_SIZE - rem), 0u8);
729            }
730        }
731    }
732    tar_bytes.resize(tar_bytes.len() + TAR_BLOCK_SIZE * 2, 0u8);
733    let gz_bytes: Vec<u8> = gzip_compress(&tar_bytes);
734    fs::write(output_path, &gz_bytes)?;
735    Ok(gz_bytes.len() as u64)
736}
737
738/// Recursively archives `source_dir` into a deterministic pure-Rust `.tar.gz` archive.
739///
740/// # Arguments
741///
742/// - `&Path` - Source directory to archive.
743/// - `&Path` - Destination `.tar.gz` file path.
744/// - `Option<&str>` - Optional top-level path prefix (e.g. `Some("EuvShowcase.app")`).
745///
746/// # Returns
747///
748/// - `io::Result<u64>` - Written `.tar.gz` file byte size.
749pub fn archive_directory_to_tar_gz(
750    source_dir: &Path,
751    output_tar_gz: &Path,
752    root_prefix: Option<&str>,
753) -> io::Result<u64> {
754    let mut files: Vec<(String, PathBuf, u32)> = Vec::new();
755    collect_archive_files_recursive(source_dir, source_dir, root_prefix, &mut files)?;
756    files.sort_by(
757        |left: &(String, PathBuf, u32), right: &(String, PathBuf, u32)| left.0.cmp(&right.0),
758    );
759    let mut entries: Vec<TarEntryInput> = Vec::with_capacity(files.len());
760    for (rel_path, disk_path, mode) in files.into_iter() {
761        let data: Vec<u8> = fs::read(&disk_path)?;
762        entries.push(TarEntryInput::new(rel_path, data, mode, false));
763    }
764    write_tar_gz_entries(output_tar_gz, &entries)
765}
766
767/// Archives `source_dir` into either `.zip` or `.tar.gz` automatically based on `output_archive` extension.
768///
769/// # Arguments
770///
771/// - `&Path` - Source directory to archive.
772/// - `&Path` - Destination archive path ending in `.zip`, `.tar.gz`, or `.tgz`.
773/// - `Option<&str>` - Optional top-level archive prefix for `.tar.gz` bundles.
774///
775/// # Returns
776///
777/// - `io::Result<u64>` - Written archive byte size.
778pub fn archive_directory_auto(
779    source_dir: &Path,
780    output_archive: &Path,
781    root_prefix: Option<&str>,
782) -> io::Result<u64> {
783    let name_lower: String = output_archive
784        .file_name()
785        .map(|name: &OsStr| name.to_string_lossy().to_ascii_lowercase())
786        .unwrap_or_default();
787    if name_lower.ends_with(ARCHIVE_EXT_ZIP) {
788        archive_directory_to_zip(source_dir, output_archive, false)
789    } else if name_lower.ends_with(ARCHIVE_EXT_TAR_GZ) || name_lower.ends_with(ARCHIVE_EXT_TGZ) {
790        archive_directory_to_tar_gz(source_dir, output_archive, root_prefix)
791    } else {
792        Err(Error::new(
793            ErrorKind::InvalidInput,
794            format!(
795                "{ERR_UNSUPPORTED_ARCHIVE_EXT}: {}",
796                output_archive.display()
797            ),
798        ))
799    }
800}
801
802/// Emits uncompressed RFC 1951 stored DEFLATE blocks covering `input`.
803///
804/// # Arguments
805///
806/// - `&[u8]` - Raw bytes to wrap in stored DEFLATE blocks.
807///
808/// # Returns
809///
810/// - `Vec<u8>` - Stored DEFLATE stream.
811fn deflate_store_blocks(input: &[u8]) -> Vec<u8> {
812    let mut out: Vec<u8> = Vec::with_capacity(input.len() + 16);
813    if input.is_empty() {
814        out.push(0x01);
815        out.extend_from_slice(&0u16.to_le_bytes());
816        out.extend_from_slice(&0xFFFFu16.to_le_bytes());
817        return out;
818    }
819    let mut offset: usize = 0;
820    while offset < input.len() {
821        let remaining: usize = input.len() - offset;
822        let chunk_len: usize = cmp::min(remaining, DEFLATE_MAX_STORED_BLOCK);
823        let is_final: u8 = if offset + chunk_len >= input.len() {
824            1
825        } else {
826            0
827        };
828        out.push(is_final);
829        let len_u16: u16 = chunk_len as u16;
830        out.extend_from_slice(&len_u16.to_le_bytes());
831        out.extend_from_slice(&(!len_u16).to_le_bytes());
832        out.extend_from_slice(&input[offset..offset + chunk_len]);
833        offset += chunk_len;
834    }
835    out
836}
837
838/// Compresses `input` using a single RFC 1951 Fixed-Huffman LZ77 block.
839///
840/// # Arguments
841///
842/// - `&[u8]` - Raw input bytes.
843///
844/// # Returns
845///
846/// - `Vec<u8>` - Compressed RFC 1951 bitstream.
847fn deflate_fixed_lz77(input: &[u8]) -> Vec<u8> {
848    let mut writer: DeflateBitWriter = DeflateBitWriter::with_capacity(input.len());
849    writer.write_bits(1, 1);
850    writer.write_bits(1, 2);
851    let mut head: Vec<usize> = vec![DEFLATE_HASH_EMPTY; DEFLATE_HASH_BUCKETS];
852    let mut pos: usize = 0;
853    let total_len: usize = input.len();
854    while pos < total_len {
855        let mut best_len: usize = 0;
856        let mut best_dist: usize = 0;
857        if pos + DEFLATE_MIN_MATCH <= total_len {
858            let bucket: usize = lz77_hash3(input[pos], input[pos + 1], input[pos + 2]);
859            let prev: usize = head[bucket];
860            head[bucket] = pos;
861            if prev != DEFLATE_HASH_EMPTY && pos > prev {
862                let dist: usize = pos - prev;
863                if dist <= DEFLATE_WINDOW_SIZE {
864                    let max_len: usize = cmp::min(DEFLATE_MAX_MATCH, total_len - pos);
865                    let mut matched: usize = 0;
866                    while matched < max_len && input[prev + matched] == input[pos + matched] {
867                        matched += 1;
868                    }
869                    if matched >= DEFLATE_MIN_MATCH {
870                        best_len = matched;
871                        best_dist = dist;
872                    }
873                }
874            }
875        }
876        if best_len >= DEFLATE_MIN_MATCH {
877            emit_fixed_match(&mut writer, best_len, best_dist);
878            let limit: usize = cmp::min(pos + best_len, total_len.saturating_sub(2));
879            let mut step: usize = pos + 1;
880            while step < limit {
881                let bucket: usize = lz77_hash3(input[step], input[step + 1], input[step + 2]);
882                head[bucket] = step;
883                step += 1;
884            }
885            pos += best_len;
886        } else {
887            emit_fixed_literal(&mut writer, u16::from(input[pos]));
888            pos += 1;
889        }
890    }
891    emit_fixed_literal(&mut writer, DEFLATE_EOB_SYMBOL as u16);
892    writer.finish()
893}
894
895/// Computes a 12-bit hash bucket index for 3 consecutive input bytes.
896///
897/// # Arguments
898///
899/// - `u8` - First byte.
900/// - `u8` - Second byte.
901/// - `u8` - Third byte.
902///
903/// # Returns
904///
905/// - `usize` - Bucket index in `0..DEFLATE_HASH_BUCKETS`.
906fn lz77_hash3(first: u8, second: u8, third: u8) -> usize {
907    let packed: u32 = (u32::from(first) << 16) + (u32::from(second) << 8) + u32::from(third);
908    let mixed: u32 = packed.wrapping_mul(2_654_435_761);
909    ((mixed >> 20) as usize) & (DEFLATE_HASH_BUCKETS - 1)
910}
911
912/// Emits one literal or length symbol using RFC 1951 fixed Huffman codewords.
913///
914/// # Arguments
915///
916/// - `&mut DeflateBitWriter` - Active bit writer.
917/// - `u16` - Symbol value in `0..=285`.
918fn emit_fixed_literal(writer: &mut DeflateBitWriter, symbol: u16) {
919    let sym: u32 = u32::from(symbol);
920    if sym <= 143 {
921        writer.write_huffman_bits(0b0011_0000 + sym, 8);
922    } else if sym <= 255 {
923        writer.write_huffman_bits(0b1_1001_0000 + (sym - 144), 9);
924    } else if sym <= 279 {
925        writer.write_huffman_bits(sym - 256, 7);
926    } else {
927        writer.write_huffman_bits(0b1100_0000 + (sym - 280), 8);
928    }
929}
930
931/// Emits a fixed-Huffman LZ77 `(length, distance)` back-reference pair.
932///
933/// # Arguments
934///
935/// - `&mut DeflateBitWriter` - Active bit writer.
936/// - `usize` - Match length in `3..=258`.
937/// - `usize` - Backward match distance in `1..=32768`.
938fn emit_fixed_match(writer: &mut DeflateBitWriter, match_len: usize, match_dist: usize) {
939    let len_u16: u16 = match_len as u16;
940    let mut len_code_idx: usize = DEFLATE_LEN_BASE.len() - 1;
941    let mut idx: usize = 0;
942    while idx < DEFLATE_LEN_BASE.len() {
943        let max_for_code: u16 = DEFLATE_LEN_BASE[idx] + ((1u16 << DEFLATE_LEN_EXTRA[idx]) - 1);
944        if len_u16 >= DEFLATE_LEN_BASE[idx] && len_u16 <= max_for_code {
945            len_code_idx = idx;
946            break;
947        }
948        idx += 1;
949    }
950    emit_fixed_literal(writer, (257 + len_code_idx) as u16);
951    let len_extra: u32 = u32::from(DEFLATE_LEN_EXTRA[len_code_idx]);
952    if len_extra > 0 {
953        let extra_val: u32 = u32::from(len_u16 - DEFLATE_LEN_BASE[len_code_idx]);
954        writer.write_bits(extra_val, len_extra);
955    }
956    let dist_u16: u16 = match_dist as u16;
957    let mut dist_code_idx: usize = DEFLATE_DIST_BASE.len() - 1;
958    let mut d_idx: usize = 0;
959    while d_idx < DEFLATE_DIST_BASE.len() {
960        let max_for_code: u16 =
961            DEFLATE_DIST_BASE[d_idx] + ((1u16 << DEFLATE_DIST_EXTRA[d_idx]) - 1);
962        if dist_u16 >= DEFLATE_DIST_BASE[d_idx] && dist_u16 <= max_for_code {
963            dist_code_idx = d_idx;
964            break;
965        }
966        d_idx += 1;
967    }
968    writer.write_huffman_bits(dist_code_idx as u32, 5);
969    let dist_extra: u32 = u32::from(DEFLATE_DIST_EXTRA[dist_code_idx]);
970    if dist_extra > 0 {
971        let extra_val: u32 = u32::from(dist_u16 - DEFLATE_DIST_BASE[dist_code_idx]);
972        writer.write_bits(extra_val, dist_extra);
973    }
974}
975
976/// Builds the RFC 1951 fixed literal/length and distance Huffman decoders.
977///
978/// # Returns
979///
980/// - `io::Result<(HuffmanDecoder, HuffmanDecoder)>` - Fixed literal/length and distance decoders.
981fn build_fixed_decoders() -> io::Result<(HuffmanDecoder, HuffmanDecoder)> {
982    let mut lit_lengths: [u8; 288] = [0u8; 288];
983    let mut idx: usize = 0;
984    while idx <= 143 {
985        lit_lengths[idx] = 8;
986        idx += 1;
987    }
988    while idx <= 255 {
989        lit_lengths[idx] = 9;
990        idx += 1;
991    }
992    while idx <= 279 {
993        lit_lengths[idx] = 7;
994        idx += 1;
995    }
996    while idx <= 287 {
997        lit_lengths[idx] = 8;
998        idx += 1;
999    }
1000    let dist_lengths: [u8; 32] = [5u8; 32];
1001    let lit_dec: HuffmanDecoder = HuffmanDecoder::from_lengths(&lit_lengths)?;
1002    let dist_dec: HuffmanDecoder = HuffmanDecoder::from_lengths(&dist_lengths)?;
1003    Ok((lit_dec, dist_dec))
1004}
1005
1006/// Parses dynamic Huffman tree headers from an RFC 1951 type-2 DEFLATE block.
1007///
1008/// # Arguments
1009///
1010/// - `&mut DeflateBitReader<'_>` - Active input bit reader.
1011///
1012/// # Returns
1013///
1014/// - `io::Result<(HuffmanDecoder, HuffmanDecoder)>` - Dynamic literal/length and distance decoders.
1015fn read_dynamic_decoders(
1016    reader: &mut DeflateBitReader<'_>,
1017) -> io::Result<(HuffmanDecoder, HuffmanDecoder)> {
1018    let hlit: usize = (reader.read_bits(5)? as usize) + 257;
1019    let hdist: usize = (reader.read_bits(5)? as usize) + 1;
1020    let hclen: usize = (reader.read_bits(4)? as usize) + 4;
1021    let invalid_counts: bool = hlit > 286 || hdist > 30;
1022    if invalid_counts || hclen > 19 {
1023        return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
1024    }
1025    let mut clen_lengths: [u8; 19] = [0u8; 19];
1026    let mut idx: usize = 0;
1027    while idx < hclen {
1028        clen_lengths[DEFLATE_CLEN_ORDER[idx]] = reader.read_bits(3)? as u8;
1029        idx += 1;
1030    }
1031    let clen_decoder: HuffmanDecoder = HuffmanDecoder::from_lengths(&clen_lengths)?;
1032    let total_codes: usize = hlit + hdist;
1033    let mut combined: Vec<u8> = Vec::with_capacity(total_codes);
1034    while combined.len() < total_codes {
1035        let sym: u16 = clen_decoder.decode(reader)?;
1036        match sym {
1037            0..=15 => combined.push(sym as u8),
1038            16 => {
1039                let repeat_count: usize = (reader.read_bits(2)? as usize) + 3;
1040                let prev_len: u8 = *combined
1041                    .last()
1042                    .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID))?;
1043                if combined.len() + repeat_count > total_codes {
1044                    return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
1045                }
1046                combined.resize(combined.len() + repeat_count, prev_len);
1047            }
1048            17 => {
1049                let repeat_count: usize = (reader.read_bits(3)? as usize) + 3;
1050                if combined.len() + repeat_count > total_codes {
1051                    return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
1052                }
1053                combined.resize(combined.len() + repeat_count, 0u8);
1054            }
1055            18 => {
1056                let repeat_count: usize = (reader.read_bits(7)? as usize) + 11;
1057                if combined.len() + repeat_count > total_codes {
1058                    return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
1059                }
1060                combined.resize(combined.len() + repeat_count, 0u8);
1061            }
1062            _ => return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID)),
1063        }
1064    }
1065    let lit_dec: HuffmanDecoder = HuffmanDecoder::from_lengths(&combined[..hlit])?;
1066    let dist_dec: HuffmanDecoder = HuffmanDecoder::from_lengths(&combined[hlit..])?;
1067    Ok((lit_dec, dist_dec))
1068}
1069
1070/// Decodes symbols from an RFC 1951 Huffman block until the End-of-Block symbol (`256`).
1071///
1072/// # Arguments
1073///
1074/// - `&mut DeflateBitReader<'_>` - Active input bit reader.
1075/// - `&HuffmanDecoder` - Literal/length Huffman decoder.
1076/// - `&HuffmanDecoder` - Distance Huffman decoder.
1077/// - `&mut Vec<u8>` - Destination decompressed output buffer.
1078///
1079/// # Returns
1080///
1081/// - `io::Result<()>` - Decoding completion status.
1082fn decode_huffman_block(
1083    reader: &mut DeflateBitReader<'_>,
1084    lit_dec: &HuffmanDecoder,
1085    dist_dec: &HuffmanDecoder,
1086    out: &mut Vec<u8>,
1087) -> io::Result<()> {
1088    loop {
1089        let sym: usize = usize::from(lit_dec.decode(reader)?);
1090        if sym < DEFLATE_EOB_SYMBOL {
1091            out.push(sym as u8);
1092        } else if sym == DEFLATE_EOB_SYMBOL {
1093            break;
1094        } else if sym <= 285 {
1095            let len_idx: usize = sym - 257;
1096            let len_extra: u32 = u32::from(DEFLATE_LEN_EXTRA[len_idx]);
1097            let copy_len: usize =
1098                usize::from(DEFLATE_LEN_BASE[len_idx]) + (reader.read_bits(len_extra)? as usize);
1099            let dist_sym: usize = usize::from(dist_dec.decode(reader)?);
1100            if dist_sym >= DEFLATE_DIST_BASE.len() {
1101                return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
1102            }
1103            let dist_extra: u32 = u32::from(DEFLATE_DIST_EXTRA[dist_sym]);
1104            let copy_dist: usize =
1105                usize::from(DEFLATE_DIST_BASE[dist_sym]) + (reader.read_bits(dist_extra)? as usize);
1106            if copy_dist == 0 || copy_dist > out.len() {
1107                return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
1108            }
1109            let mut copied: usize = 0;
1110            while copied < copy_len {
1111                let src_idx: usize = out.len() - copy_dist;
1112                let byte_val: u8 = out[src_idx];
1113                out.push(byte_val);
1114                copied += 1;
1115            }
1116        } else {
1117            return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
1118        }
1119    }
1120    Ok(())
1121}
1122
1123/// Counts non-overlapping occurrences of `needle` inside `haystack`.
1124///
1125/// # Arguments
1126///
1127/// - `&[u8]` - Byte slice to search.
1128/// - `&[u8]` - Non-empty byte pattern to count.
1129///
1130/// # Returns
1131///
1132/// - `usize` - Number of matches found.
1133fn count_subslice_occurrences(haystack: &[u8], needle: &[u8]) -> usize {
1134    if needle.is_empty() || haystack.len() < needle.len() {
1135        return 0;
1136    }
1137    let mut hits: usize = 0;
1138    let mut offset: usize = 0;
1139    let limit: usize = haystack.len() - needle.len();
1140    while offset <= limit {
1141        if &haystack[offset..offset + needle.len()] == needle {
1142            hits += 1;
1143            offset += needle.len();
1144        } else {
1145            offset += 1;
1146        }
1147    }
1148    hits
1149}
1150
1151/// Recursively collects regular non-reserved files under `dir` while rejecting symlinks and unsafe paths.
1152///
1153/// # Arguments
1154///
1155/// - `&Path` - Root distribution directory.
1156/// - `&Path` - Current directory being traversed.
1157/// - `&mut Vec<(String, PathBuf)>` - Accumulator of `(relative_posix_path, disk_path)`.
1158///
1159/// # Returns
1160///
1161/// - `io::Result<()>` - Traversal result.
1162fn collect_release_files_recursive(
1163    root: &Path,
1164    dir: &Path,
1165    out: &mut Vec<(String, PathBuf)>,
1166) -> io::Result<()> {
1167    let mut children: Vec<PathBuf> = Vec::new();
1168    for entry_res in fs::read_dir(dir)? {
1169        let entry: DirEntry = entry_res?;
1170        children.push(entry.path());
1171    }
1172    children.sort();
1173    for path in children.into_iter() {
1174        let rel_os: &Path = path
1175            .strip_prefix(root)
1176            .map_err(|err: StripPrefixError| Error::other(err.to_string()))?;
1177        let relative: String = path_to_posix_string(rel_os);
1178        let meta: Metadata = fs::symlink_metadata(&path)?;
1179        if meta.file_type().is_symlink() {
1180            return Err(Error::new(
1181                ErrorKind::InvalidInput,
1182                format!("{ERR_SYMLINK_FORBIDDEN}: {relative}"),
1183            ));
1184        }
1185        let file_name: String = path
1186            .file_name()
1187            .map(|name: &OsStr| name.to_string_lossy().into_owned())
1188            .unwrap_or_default();
1189        if RELEASE_MANIFEST_RESERVED_NAMES.contains(&file_name.as_str()) {
1190            continue;
1191        }
1192        if !is_safe_release_relative_path(&relative) {
1193            return Err(Error::new(
1194                ErrorKind::InvalidInput,
1195                format!("{ERR_UNSAFE_RELEASE_PATH}: {relative}"),
1196            ));
1197        }
1198        if meta.is_dir() {
1199            collect_release_files_recursive(root, &path, out)?;
1200        } else if meta.is_file() {
1201            out.push((relative, path));
1202        } else {
1203            return Err(Error::new(
1204                ErrorKind::InvalidInput,
1205                format!("{ERR_NOT_REGULAR_FILE}: {relative}"),
1206            ));
1207        }
1208    }
1209    Ok(())
1210}
1211
1212/// Recursively collects files and UNIX modes for `.zip` or `.tar.gz` archiving.
1213///
1214/// # Arguments
1215///
1216/// - `&Path` - Root directory being archived.
1217/// - `&Path` - Current directory being scanned.
1218/// - `Option<&str>` - Optional leading archive directory prefix.
1219/// - `&mut Vec<(String, PathBuf, u32)>` - Accumulator of `(archive_path, disk_path, unix_mode)`.
1220///
1221/// # Returns
1222///
1223/// - `io::Result<()>` - Traversal result.
1224fn collect_archive_files_recursive(
1225    root: &Path,
1226    dir: &Path,
1227    root_prefix: Option<&str>,
1228    out: &mut Vec<(String, PathBuf, u32)>,
1229) -> io::Result<()> {
1230    let mut children: Vec<PathBuf> = Vec::new();
1231    for entry_res in fs::read_dir(dir)? {
1232        let entry: DirEntry = entry_res?;
1233        children.push(entry.path());
1234    }
1235    children.sort();
1236    for path in children.into_iter() {
1237        let meta: Metadata = fs::symlink_metadata(&path)?;
1238        if meta.is_dir() {
1239            collect_archive_files_recursive(root, &path, root_prefix, out)?;
1240        } else if meta.is_file() {
1241            let rel_os: &Path = path
1242                .strip_prefix(root)
1243                .map_err(|err: StripPrefixError| Error::other(err.to_string()))?;
1244            let rel_posix: String = path_to_posix_string(rel_os);
1245            let archive_path: String = match root_prefix {
1246                Some(prefix) if !prefix.trim_matches('/').is_empty() => {
1247                    format!("{}/{}", prefix.trim_matches('/'), rel_posix)
1248                }
1249                _ => rel_posix,
1250            };
1251            let mode: u32 = file_unix_mode(&meta);
1252            out.push((archive_path, path, mode));
1253        }
1254    }
1255    Ok(())
1256}
1257
1258/// Extracts UNIX file permission bits from filesystem metadata with cross-platform fallback.
1259///
1260/// # Arguments
1261///
1262/// - `&Metadata` - File metadata.
1263///
1264/// # Returns
1265///
1266/// - `u32` - Permission bits (e.g. `0o755` or `0o644`).
1267fn file_unix_mode(meta: &Metadata) -> u32 {
1268    #[cfg(unix)]
1269    {
1270        let raw_mode: u32 = meta.permissions().mode() & 0o7777;
1271        if raw_mode == 0 {
1272            ARCHIVE_DEFAULT_FILE_MODE
1273        } else {
1274            raw_mode
1275        }
1276    }
1277    #[cfg(not(unix))]
1278    {
1279        let _: &Metadata = meta;
1280        ARCHIVE_DEFAULT_FILE_MODE
1281    }
1282}
1283
1284/// Converts a relative filesystem path to forward-slash POSIX format.
1285///
1286/// # Arguments
1287///
1288/// - `&Path` - Relative path.
1289///
1290/// # Returns
1291///
1292/// - `String` - Slash-separated relative path string.
1293fn path_to_posix_string(path: &Path) -> String {
1294    let segments: Vec<String> = path
1295        .components()
1296        .map(|comp: Component<'_>| comp.as_os_str().to_string_lossy().into_owned())
1297        .collect();
1298    segments.join("/")
1299}
1300
1301/// Normalizes an archive entry path to forward slashes without leading slashes.
1302///
1303/// # Arguments
1304///
1305/// - `&str` - Raw archive path string.
1306///
1307/// # Returns
1308///
1309/// - `String` - Normalized archive path.
1310fn normalize_archive_entry_name(raw: &str) -> String {
1311    raw.replace('\\', "/").trim_start_matches('/').to_string()
1312}
1313
1314/// Appends a PKZIP Local File Header to `out`.
1315///
1316/// # Arguments
1317///
1318/// - `&mut Vec<u8>` - Destination archive buffer.
1319/// - `&[u8]` - UTF-8 filename bytes.
1320/// - `u16` - Compression method (`0` or `8`).
1321/// - `u16` - General-purpose bit flags.
1322/// - `u32` - Entry CRC-32 checksum.
1323/// - `u32` - Compressed payload length.
1324/// - `u32` - Uncompressed payload length.
1325fn push_zip_local_header(
1326    out: &mut Vec<u8>,
1327    name_bytes: &[u8],
1328    method: u16,
1329    flags: u16,
1330    crc: u32,
1331    comp_size: u32,
1332    uncomp_size: u32,
1333) {
1334    out.extend_from_slice(&ZIP_LOCAL_HEADER_SIG.to_le_bytes());
1335    out.extend_from_slice(&ZIP_VERSION_NEEDED.to_le_bytes());
1336    out.extend_from_slice(&flags.to_le_bytes());
1337    out.extend_from_slice(&method.to_le_bytes());
1338    out.extend_from_slice(&0u16.to_le_bytes());
1339    out.extend_from_slice(&0u16.to_le_bytes());
1340    out.extend_from_slice(&crc.to_le_bytes());
1341    out.extend_from_slice(&comp_size.to_le_bytes());
1342    out.extend_from_slice(&uncomp_size.to_le_bytes());
1343    out.extend_from_slice(&(name_bytes.len() as u16).to_le_bytes());
1344    out.extend_from_slice(&0u16.to_le_bytes());
1345    out.extend_from_slice(name_bytes);
1346}
1347
1348/// Appends the PKZIP Central Directory and End of Central Directory record to `out`.
1349///
1350/// # Arguments
1351///
1352/// - `&mut Vec<u8>` - Destination archive buffer.
1353/// - `&[ZipCentralRecord]` - Accumulated central directory metadata records.
1354fn finalize_zip_central_directory(out: &mut Vec<u8>, records: &[ZipCentralRecord]) {
1355    let cd_offset: u32 = out.len() as u32;
1356    for rec in records.iter() {
1357        out.extend_from_slice(&ZIP_CENTRAL_HEADER_SIG.to_le_bytes());
1358        out.extend_from_slice(&ZIP_VERSION_MADE_BY.to_le_bytes());
1359        out.extend_from_slice(&ZIP_VERSION_NEEDED.to_le_bytes());
1360        out.extend_from_slice(&rec.flags.to_le_bytes());
1361        out.extend_from_slice(&rec.method.to_le_bytes());
1362        out.extend_from_slice(&0u16.to_le_bytes());
1363        out.extend_from_slice(&0u16.to_le_bytes());
1364        out.extend_from_slice(&rec.crc32.to_le_bytes());
1365        out.extend_from_slice(&rec.compressed_size.to_le_bytes());
1366        out.extend_from_slice(&rec.uncompressed_size.to_le_bytes());
1367        out.extend_from_slice(&(rec.name_bytes.len() as u16).to_le_bytes());
1368        out.extend_from_slice(&0u16.to_le_bytes());
1369        out.extend_from_slice(&0u16.to_le_bytes());
1370        out.extend_from_slice(&0u16.to_le_bytes());
1371        out.extend_from_slice(&0u16.to_le_bytes());
1372        out.extend_from_slice(&rec.external_attrs.to_le_bytes());
1373        out.extend_from_slice(&rec.local_offset.to_le_bytes());
1374        out.extend_from_slice(&rec.name_bytes);
1375    }
1376    let cd_size: u32 = (out.len() as u32) - cd_offset;
1377    let entry_count: u16 = records.len() as u16;
1378    out.extend_from_slice(&ZIP_EOCD_SIG.to_le_bytes());
1379    out.extend_from_slice(&0u16.to_le_bytes());
1380    out.extend_from_slice(&0u16.to_le_bytes());
1381    out.extend_from_slice(&entry_count.to_le_bytes());
1382    out.extend_from_slice(&entry_count.to_le_bytes());
1383    out.extend_from_slice(&cd_size.to_le_bytes());
1384    out.extend_from_slice(&cd_offset.to_le_bytes());
1385    out.extend_from_slice(&0u16.to_le_bytes());
1386}
1387
1388/// Parses Central Directory records and raw compressed payloads from an existing ZIP byte slice.
1389///
1390/// # Arguments
1391///
1392/// - `&[u8]` - Complete bytes of an existing `.zip` or `.apk` file.
1393///
1394/// # Returns
1395///
1396/// - `io::Result<Vec<ExistingZipRawEntry>>` - Extracted raw entries preserving compression payloads.
1397fn parse_existing_zip_entries(raw: &[u8]) -> io::Result<Vec<ExistingZipRawEntry>> {
1398    if raw.len() < 22 {
1399        return Err(Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID));
1400    }
1401    let min_eocd: usize = raw.len().saturating_sub(65_557);
1402    let mut eocd_pos: Option<usize> = None;
1403    let mut cursor: usize = raw.len() - 22;
1404    loop {
1405        if read_le_u32(raw, cursor)? == ZIP_EOCD_SIG {
1406            eocd_pos = Some(cursor);
1407            break;
1408        }
1409        if cursor == min_eocd {
1410            break;
1411        }
1412        cursor -= 1;
1413    }
1414    let eocd: usize =
1415        eocd_pos.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID))?;
1416    let entry_count: usize = usize::from(read_le_u16(raw, eocd + 10)?);
1417    let cd_offset: usize = read_le_u32(raw, eocd + 16)? as usize;
1418    let mut cd_pos: usize = cd_offset;
1419    let mut entries: Vec<ExistingZipRawEntry> = Vec::with_capacity(entry_count);
1420    let mut idx: usize = 0;
1421    while idx < entry_count {
1422        if read_le_u32(raw, cd_pos)? != ZIP_CENTRAL_HEADER_SIG {
1423            return Err(Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID));
1424        }
1425        let flags: u16 = read_le_u16(raw, cd_pos + 8)?;
1426        let method: u16 = read_le_u16(raw, cd_pos + 10)?;
1427        let crc: u32 = read_le_u32(raw, cd_pos + 16)?;
1428        let comp_size: usize = read_le_u32(raw, cd_pos + 20)? as usize;
1429        let uncomp_size: u32 = read_le_u32(raw, cd_pos + 24)?;
1430        let name_len: usize = usize::from(read_le_u16(raw, cd_pos + 28)?);
1431        let extra_len: usize = usize::from(read_le_u16(raw, cd_pos + 30)?);
1432        let comment_len: usize = usize::from(read_le_u16(raw, cd_pos + 32)?);
1433        let external_attrs: u32 = read_le_u32(raw, cd_pos + 38)?;
1434        let local_offset: usize = read_le_u32(raw, cd_pos + 42)? as usize;
1435        let name_slice: &[u8] = raw
1436            .get(cd_pos + 46..cd_pos + 46 + name_len)
1437            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID))?;
1438        let name: String = String::from_utf8_lossy(name_slice).into_owned();
1439        if read_le_u32(raw, local_offset)? != ZIP_LOCAL_HEADER_SIG {
1440            return Err(Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID));
1441        }
1442        let local_name_len: usize = usize::from(read_le_u16(raw, local_offset + 26)?);
1443        let local_extra_len: usize = usize::from(read_le_u16(raw, local_offset + 28)?);
1444        let data_start: usize = local_offset + 30 + local_name_len + local_extra_len;
1445        let data_end: usize = data_start
1446            .checked_add(comp_size)
1447            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID))?;
1448        let payload: &[u8] = raw
1449            .get(data_start..data_end)
1450            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID))?;
1451        entries.push(ExistingZipRawEntry {
1452            name,
1453            method,
1454            flags,
1455            crc32: crc,
1456            compressed_data: payload.to_vec(),
1457            uncompressed_size: uncomp_size,
1458            external_attrs,
1459        });
1460        cd_pos += 46 + name_len + extra_len + comment_len;
1461        idx += 1;
1462    }
1463    Ok(entries)
1464}
1465
1466/// Reads a little-endian `u16` at `offset` with bounds validation.
1467///
1468/// # Arguments
1469///
1470/// - `&[u8]` - Source byte slice.
1471/// - `usize` - Starting byte offset.
1472///
1473/// # Returns
1474///
1475/// - `io::Result<u16>` - Decoded 16-bit integer.
1476fn read_le_u16(bytes: &[u8], offset: usize) -> io::Result<u16> {
1477    let slice: &[u8] = bytes
1478        .get(offset..offset + 2)
1479        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID))?;
1480    Ok(u16::from_le_bytes([slice[0], slice[1]]))
1481}
1482
1483/// Reads a little-endian `u32` at `offset` with bounds validation.
1484///
1485/// # Arguments
1486///
1487/// - `&[u8]` - Source byte slice.
1488/// - `usize` - Starting byte offset.
1489///
1490/// # Returns
1491///
1492/// - `io::Result<u32>` - Decoded 32-bit integer.
1493fn read_le_u32(bytes: &[u8], offset: usize) -> io::Result<u32> {
1494    let slice: &[u8] = bytes
1495        .get(offset..offset + 4)
1496        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID))?;
1497    Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
1498}
1499
1500/// Constructs a 512-byte POSIX ustar tar header block.
1501///
1502/// # Arguments
1503///
1504/// - `&str` - Archive-relative POSIX entry path.
1505/// - `u32` - UNIX permission bits.
1506/// - `u64` - Entry payload byte length (`0` for directories).
1507/// - `bool` - `true` for directory entries, `false` for regular files.
1508///
1509/// # Returns
1510///
1511/// - `io::Result<[u8; TAR_BLOCK_SIZE]>` - Complete checksummed ustar header block.
1512fn build_ustar_header(
1513    archive_path: &str,
1514    unix_mode: u32,
1515    size: u64,
1516    is_dir: bool,
1517) -> io::Result<[u8; TAR_BLOCK_SIZE]> {
1518    let (prefix_bytes, name_bytes): (&[u8], &[u8]) = split_ustar_path(archive_path)?;
1519    let mut block: [u8; TAR_BLOCK_SIZE] = [0u8; TAR_BLOCK_SIZE];
1520    block[..name_bytes.len()].copy_from_slice(name_bytes);
1521    write_octal_field(&mut block[100..108], u64::from(unix_mode & 0o7777));
1522    write_octal_field(&mut block[108..116], 0);
1523    write_octal_field(&mut block[116..124], 0);
1524    write_octal_field(&mut block[124..136], size);
1525    write_octal_field(&mut block[136..148], 0);
1526    for slot in block[148..156].iter_mut() {
1527        *slot = b' ';
1528    }
1529    block[156] = if is_dir { b'5' } else { b'0' };
1530    block[257..263].copy_from_slice(TAR_USTAR_MAGIC);
1531    block[263..265].copy_from_slice(TAR_USTAR_VERSION);
1532    if !prefix_bytes.is_empty() {
1533        block[345..345 + prefix_bytes.len()].copy_from_slice(prefix_bytes);
1534    }
1535    let checksum: u32 = block.iter().map(|byte_val: &u8| u32::from(*byte_val)).sum();
1536    let cksum_str: String = format!("{checksum:06o}\0 ");
1537    block[148..156].copy_from_slice(cksum_str.as_bytes());
1538    Ok(block)
1539}
1540
1541/// Splits a tar entry path into POSIX ustar `(prefix, name)` slices (`<=155` and `<=100` bytes).
1542///
1543/// # Arguments
1544///
1545/// - `&str` - Archive-relative path.
1546///
1547/// # Returns
1548///
1549/// - `io::Result<(&[u8], &[u8])>` - Pair of `(prefix, name)` byte slices.
1550fn split_ustar_path(path: &str) -> io::Result<(&[u8], &[u8])> {
1551    let raw: &[u8] = path.as_bytes();
1552    if raw.len() <= 100 {
1553        return Ok((&[], raw));
1554    }
1555    let mut split_at: Option<usize> = None;
1556    let max_prefix: usize = cmp::min(155, raw.len());
1557    let mut idx: usize = 0;
1558    while idx < max_prefix {
1559        if raw[idx] == b'/' && raw.len() - idx - 1 <= 100 {
1560            split_at = Some(idx);
1561        }
1562        idx += 1;
1563    }
1564    let cut: usize = split_at.ok_or_else(|| {
1565        Error::new(
1566            ErrorKind::InvalidInput,
1567            format!("{ERR_TAR_PATH_TOO_LONG}: {path}"),
1568        )
1569    })?;
1570    Ok((&raw[..cut], &raw[cut + 1..]))
1571}
1572
1573/// Formats an unsigned integer as NUL-terminated zero-padded ASCII octal in a ustar field.
1574///
1575/// # Arguments
1576///
1577/// - `&mut [u8]` - Target header slice.
1578/// - `u64` - Numeric value to format.
1579fn write_octal_field(field: &mut [u8], value: u64) {
1580    let digits_len: usize = field.len() - 1;
1581    let formatted: String = format!("{value:0width$o}", width = digits_len);
1582    let raw: &[u8] = formatted.as_bytes();
1583    let copy_len: usize = cmp::min(digits_len, raw.len());
1584    field[..copy_len].copy_from_slice(&raw[raw.len() - copy_len..]);
1585    field[digits_len] = 0;
1586}