Skip to main content

functora_core/
package.rs

1use crate::Error;
2use crate::crypto::{ChunkKind, CipherType, Kdf, STREAM_CHUNK, STREAM_TAG, StreamParts};
3use crate::progress::{Job, yield_to_paint};
4use crate::worker::Reporter;
5use crate::zip::zip_entries;
6use serde::{Deserialize, Serialize};
7use std::io::{Read, Seek, Write};
8use std::path::PathBuf;
9use zip::CompressionMethod;
10
11pub const METADATA_ENTRY: &str = "metadata.json";
12pub const PAYLOAD_ENTRY: &str = "payload.cpt";
13
14#[must_use]
15pub fn aad(prefix: &[u8], cipher: CipherType, kdf: Kdf) -> Vec<u8> {
16    prefix
17        .iter()
18        .chain(&[cipher as u8, kdf as u8])
19        .copied()
20        .collect()
21}
22
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24pub struct ArchiveMetadata {
25    pub cipher: Option<CipherType>,
26    pub kdf: Kdf,
27    pub nonce: Vec<u8>,
28    pub salt: Vec<u8>,
29}
30
31#[derive(Debug, Clone, PartialEq)]
32pub enum ArchiveSource {
33    Bytes(Vec<u8>),
34    Path(PathBuf),
35}
36
37trait SeekableRead: Read + Seek {}
38
39impl<T: Read + Seek> SeekableRead for T {}
40
41impl ArchiveSource {
42    fn open(&self) -> Result<Box<dyn SeekableRead + '_>, Error> {
43        match self {
44            Self::Bytes(bytes) => Ok(Box::new(std::io::Cursor::new(bytes.as_slice()))),
45            Self::Path(path) => Ok(Box::new(std::fs::File::open(path)?)),
46        }
47    }
48
49    pub fn into_bytes(self) -> Result<Vec<u8>, Error> {
50        match self {
51            Self::Bytes(bytes) => Ok(bytes),
52            Self::Path(path) => Ok(std::fs::read(path)?),
53        }
54    }
55}
56
57#[derive(Debug, Clone, Copy)]
58pub struct PackageStages<S> {
59    pub zip: S,
60    pub encrypt: S,
61    pub decrypt: S,
62}
63
64impl<S> PackageStages<S> {
65    pub const fn new(zip: S, encrypt: S, decrypt: S) -> Self {
66        Self {
67            zip,
68            encrypt,
69            decrypt,
70        }
71    }
72}
73
74fn stored_opts() -> zip::write::FileOptions<'static, ()> {
75    zip::write::FileOptions::default().compression_method(CompressionMethod::Stored)
76}
77
78fn write_package_entries(
79    zip: &mut zip::ZipWriter<std::io::Cursor<&mut Vec<u8>>>,
80    meta: &ArchiveMetadata,
81) -> Result<(), Error> {
82    zip.start_file(METADATA_ENTRY, stored_opts())?;
83    zip.write_all(&serde_json::to_vec(meta)?)?;
84    zip.start_file(PAYLOAD_ENTRY, stored_opts())?;
85    Ok(())
86}
87
88pub async fn package_report<S>(
89    entries: Vec<(String, Vec<u8>)>,
90    password: &str,
91    cipher: Option<CipherType>,
92    prefix: &'static [u8],
93    stages: PackageStages<S>,
94    report: &mut Reporter<S>,
95) -> Result<Vec<u8>, Error>
96where
97    S: Copy + Send + Sync + 'static,
98{
99    let total = entries.iter().map(|(_, d)| d.len() as u64).sum::<u64>();
100    let mut inner = Vec::new();
101    {
102        let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut inner));
103        let mut done = 0u64;
104        zip_entries(&mut zip, &entries, stages.zip, report, &mut done, total).await?;
105        let _ = zip.finish()?;
106    }
107    match cipher {
108        Some(cipher_sel) => {
109            package_with_encryption(&inner, password, cipher_sel, prefix, stages, report).await
110        }
111        None => package_plain(&inner, stages, report).await,
112    }
113}
114
115async fn package_with_encryption<S>(
116    inner: &[u8],
117    password: &str,
118    cipher: CipherType,
119    prefix: &'static [u8],
120    stages: PackageStages<S>,
121    report: &mut Reporter<S>,
122) -> Result<Vec<u8>, Error>
123where
124    S: Copy + Send + Sync + 'static,
125{
126    let parts = StreamParts::derive(password, cipher, &aad(prefix, cipher, Kdf::Argon2id))?;
127    let meta = ArchiveMetadata {
128        cipher: Some(cipher),
129        kdf: Kdf::Argon2id,
130        nonce: parts.nonce().to_vec(),
131        salt: parts.salt().to_vec(),
132    };
133    let mut pkg = Vec::new();
134    {
135        let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut pkg));
136        write_package_entries(&mut zip, &meta)?;
137        let mut offset = 0usize;
138        let mut position = 0u32;
139        while offset < inner.len() {
140            let end = (offset + STREAM_CHUNK).min(inner.len());
141            let kind = if end == inner.len() {
142                ChunkKind::Last
143            } else {
144                ChunkKind::NonLast
145            };
146            let ct = parts.encrypt_chunk(position, kind, &inner[offset..end])?;
147            zip.write_all(&ct)?;
148            offset = end;
149            position += 1;
150            report(Job {
151                stage: stages.encrypt,
152                done: offset as u64,
153                total: inner.len() as u64,
154                name: None,
155            });
156            yield_to_paint().await;
157        }
158        let _ = zip.finish()?;
159    }
160    Ok(pkg)
161}
162
163async fn package_plain<S>(
164    inner: &[u8],
165    stages: PackageStages<S>,
166    report: &mut Reporter<S>,
167) -> Result<Vec<u8>, Error>
168where
169    S: Copy + Send + Sync + 'static,
170{
171    let meta = ArchiveMetadata {
172        cipher: None,
173        kdf: Kdf::Argon2id,
174        nonce: Vec::new(),
175        salt: Vec::new(),
176    };
177    let mut pkg = Vec::new();
178    {
179        let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut pkg));
180        write_package_entries(&mut zip, &meta)?;
181        let mut done = 0u64;
182        for chunk in inner.chunks(2 * 1024 * 1024) {
183            zip.write_all(chunk)?;
184            done += chunk.len() as u64;
185            report(Job {
186                stage: stages.zip,
187                done,
188                total: inner.len() as u64,
189                name: None,
190            });
191            yield_to_paint().await;
192        }
193        let _ = zip.finish()?;
194    }
195    Ok(pkg)
196}
197
198fn read_entry<R: Read + Seek>(
199    archive: &mut zip::ZipArchive<R>,
200    name: &str,
201) -> Result<Vec<u8>, Error> {
202    let mut file = archive.by_name(name)?;
203    let capacity = usize::try_from(file.size()).map_err(|e| Error::Convert {
204        context: "entry size too large",
205        source: e,
206    })?;
207    let mut data = Vec::with_capacity(capacity);
208    let _ = file.read_to_end(&mut data)?;
209    Ok(data)
210}
211
212pub fn read_metadata(source: &ArchiveSource) -> Result<ArchiveMetadata, Error> {
213    let mut archive = zip::ZipArchive::new(source.open()?)?;
214    let meta_json = read_entry(&mut archive, METADATA_ENTRY)?;
215    Ok(serde_json::from_slice::<ArchiveMetadata>(&meta_json)?)
216}
217
218fn read_package(source: &ArchiveSource) -> Result<(ArchiveMetadata, Vec<u8>), Error> {
219    let mut archive = zip::ZipArchive::new(source.open()?)?;
220    let meta: ArchiveMetadata = serde_json::from_slice(&read_entry(&mut archive, METADATA_ENTRY)?)?;
221    let payload = read_entry(&mut archive, PAYLOAD_ENTRY)?;
222    Ok((meta, payload))
223}
224
225async fn unseal_report<S>(
226    meta: &ArchiveMetadata,
227    payload: Vec<u8>,
228    password: &str,
229    cipher: CipherType,
230    prefix: &'static [u8],
231    stages: PackageStages<S>,
232    report: &mut Reporter<S>,
233) -> Result<Vec<u8>, Error>
234where
235    S: Copy + Send + Sync + 'static,
236{
237    let parts = StreamParts::recover(
238        password,
239        cipher,
240        &meta.salt,
241        &meta.nonce,
242        &aad(prefix, cipher, meta.kdf),
243    )?;
244    let total = payload.len();
245    let mut out = Vec::with_capacity(payload.len());
246    let mut offset = 0usize;
247    let mut position = 0u32;
248    while offset < total {
249        let end = (offset + STREAM_CHUNK + STREAM_TAG).min(total);
250        let kind = if end == total {
251            ChunkKind::Last
252        } else {
253            ChunkKind::NonLast
254        };
255        let plain = parts.decrypt_chunk(position, kind, &payload[offset..end])?;
256        out.extend_from_slice(&plain);
257        offset = end;
258        position += 1;
259        report(Job {
260            stage: stages.decrypt,
261            done: offset as u64,
262            total: total as u64,
263            name: None,
264        });
265        yield_to_paint().await;
266    }
267    Ok(out)
268}
269
270pub async fn extract_package_report<S>(
271    source: ArchiveSource,
272    password: &str,
273    prefix: &'static [u8],
274    stages: PackageStages<S>,
275    report: &mut Reporter<S>,
276) -> Result<Vec<u8>, Error>
277where
278    S: Copy + Send + Sync + 'static,
279{
280    let (meta, payload) = read_package(&source)?;
281    match meta.cipher {
282        Some(cipher) => {
283            unseal_report(&meta, payload, password, cipher, prefix, stages, report).await
284        }
285        None => Ok(payload),
286    }
287}