Skip to main content

umbera_core/devlink/
package.rs

1// Phone → desktop transfer package: a stream of records split into parts.
2//
3// HEADER : version ‖ package_id (16) ‖ flags (bit 0: with history) ‖ part size
4// PART   : part number u32 ‖ stream bytes (each part is a separate link AEAD blob,
5//          AAD = domain ‖ link_id ‖ seq ‖ kind)
6// END    : parts u32 ‖ records u64 ‖ stream bytes u64 ‖ SHA-256(domain ‖ package_id ‖ stream)
7// ACK    : (desktop → phone) the same checksum: "received in full".
8//
9// Stream record: section u8 ‖ id (u16 length) ‖ body (u32 length). Sections and limits
10// are strict on BOTH sides: the package does not carry video or large files.
11//
12
13use sha2::{Digest, Sha256};
14
15use super::codec::{Rd, W};
16use super::{ct_eq, LinkError, DOMAIN, LR};
17
18const PKG_VERSION: u8 = 1;
19const FLAG_HISTORY: u8 = 1;
20/// Plaintext size of one part. With the part number and AEAD tag the blob stays below
21/// the relay limit (1 MiB).
22pub const PACKAGE_CHUNK: usize = 960 * 1024;
23/// Package stream limit: the relay accepts at most 64 MiB phone→desktop per link, 1 MiB
24/// is reserved for ACCEPT, the certificate, MLS requests and control blobs. Whatever does not fit: photos via
25/// /api/blob (SECTION_PHOTO_BLOB_REF).
26pub const PACKAGE_MAX_BYTES: u64 = 63 * 1024 * 1024;
27
28pub const SECTION_PROFILE: u8 = 1;
29pub const SECTION_CONTACT: u8 = 2;
30pub const SECTION_CHAT: u8 = 3;
31pub const SECTION_MESSAGE_TEXT: u8 = 4;
32pub const SECTION_MESSAGE_PHOTO: u8 = 5;
33pub const SECTION_MLS_WELCOME: u8 = 6;
34pub const SECTION_COMM_VAULT: u8 = 7;
35pub const SECTION_COMM_MEMBERSHIP: u8 = 8;
36/// Shared key of the account's devices (account_sync_key, 32 B): device names etc.
37pub const SECTION_ACCOUNT_SYNC: u8 = 9;
38/// History photo uploaded to /api/blob (body is the file reference and key, ≤ 4 KiB): used when the package
39/// does not fit the relay limit (64 MiB). The "is a still image" check happens
40/// on the desktop after download and decryption (link_is_still_image).
41pub const SECTION_PHOTO_BLOB_REF: u8 = 10;
42
43const ID_MAX: usize = 256;
44const KIB: usize = 1024;
45const MIB: usize = 1024 * 1024;
46/// Photos larger than this are not transferred (treated as a large file).
47pub const PHOTO_MAX: usize = 16 * MIB;
48
49/// Package record.
50#[derive(uniffi::Record, Clone, Debug, PartialEq, Eq)]
51pub struct PackageRecord {
52    pub section: u8,
53    pub id: Vec<u8>,
54    pub body: Vec<u8>,
55}
56
57/// What arrived with the latest package blob.
58#[derive(uniffi::Record, Clone, Debug, PartialEq, Eq)]
59pub struct PackageProgress {
60    /// Records fully assembled by this blob (in stream order).
61    pub records: Vec<PackageRecord>,
62    /// END accepted and the checksum matched: records may be committed to the database.
63    pub done: bool,
64    pub include_history: bool,
65    pub parts: u32,
66    pub bytes: u64,
67}
68
69struct Limits {
70    id_min: usize,
71    body_max: usize,
72    history: bool,
73    once: bool,
74}
75
76fn limits(section: u8) -> LR<Limits> {
77    let l = |id_min, body_max, history, once| Limits { id_min, body_max, history, once };
78    Ok(match section {
79        SECTION_PROFILE => l(0, MIB, false, true),
80        SECTION_CONTACT => l(1, 256 * KIB, false, false),
81        SECTION_CHAT => l(1, 256 * KIB, false, false),
82        SECTION_MESSAGE_TEXT => l(1, 256 * KIB, true, false),
83        SECTION_MESSAGE_PHOTO => l(1, PHOTO_MAX, true, false),
84        SECTION_MLS_WELCOME => l(1, MIB, false, false),
85        SECTION_COMM_VAULT => l(0, 64, false, true),
86        SECTION_COMM_MEMBERSHIP => l(1, 256 * KIB, false, false),
87        SECTION_ACCOUNT_SYNC => l(0, 32, false, true),
88        SECTION_PHOTO_BLOB_REF => l(1, 4 * KIB, true, false),
89        s => return Err(LinkError::Malformed(format!("unknown package section {s}"))),
90    })
91}
92
93/// Still images only, by signature: JPEG, PNG, GIF, WebP, HEIC/HEIF, AVIF.
94/// Video in an ISO BMFF container (mp4/mov/3gp/HEIF sequences) is rejected.
95#[uniffi::export]
96pub fn link_is_still_image(bytes: Vec<u8>) -> bool {
97    is_still_image(&bytes)
98}
99
100pub(crate) fn is_still_image(b: &[u8]) -> bool {
101    if b.len() < 12 {
102        return false;
103    }
104    if b.starts_with(&[0xFF, 0xD8, 0xFF]) || b.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]) {
105        return true;
106    }
107    if b.starts_with(b"GIF87a") || b.starts_with(b"GIF89a") {
108        return true;
109    }
110    if &b[0..4] == b"RIFF" && &b[8..12] == b"WEBP" {
111        return true;
112    }
113    if &b[4..8] == b"ftyp" {
114        return matches!(&b[8..12], b"heic" | b"heix" | b"mif1" | b"avif");
115    }
116    false
117}
118
119fn check_record(section: u8, id: &[u8], body: &[u8], include_history: bool, seen: &mut [bool; 256]) -> LR<()> {
120    let l = limits(section)?;
121    if l.history && !include_history {
122        return Err(LinkError::Malformed(format!("section {section} needs \"with history\"")));
123    }
124    if id.len() < l.id_min || id.len() > ID_MAX {
125        return Err(LinkError::Malformed(format!("section {section}: id length {}", id.len())));
126    }
127    if body.len() > l.body_max {
128        return Err(LinkError::Malformed(format!("section {section}: body {} > {}", body.len(), l.body_max)));
129    }
130    if section == SECTION_COMM_VAULT && body.len() != 64 {
131        return Err(LinkError::Malformed("communities vault roots must be 64 bytes".into()));
132    }
133    if section == SECTION_ACCOUNT_SYNC && body.len() != 32 {
134        return Err(LinkError::Malformed("account sync key must be 32 bytes".into()));
135    }
136    if section == SECTION_MESSAGE_PHOTO && !is_still_image(body) {
137        return Err(LinkError::Malformed("only still images are transferred".into()));
138    }
139    if l.once {
140        if seen[section as usize] {
141            return Err(LinkError::Malformed(format!("section {section} may appear once")));
142        }
143        seen[section as usize] = true;
144    }
145    Ok(())
146}
147
148fn digest_init(package_id: &[u8; 16]) -> Sha256 {
149    let mut h = Sha256::new();
150    h.update(DOMAIN);
151    h.update(b"/package");
152    h.update(package_id);
153    h
154}
155
156pub(crate) struct PackageWriter {
157    buf: Vec<u8>,
158    hash: Option<Sha256>,
159    include_history: bool,
160    next_part: u32,
161    records: u64,
162    bytes: u64,
163    seen: [bool; 256],
164    digest: Option<[u8; 32]>,
165}
166
167impl PackageWriter {
168    pub fn begin(package_id: [u8; 16], include_history: bool) -> (Self, Vec<u8>) {
169        let mut w = W::new();
170        w.u8(PKG_VERSION).raw(&package_id).u8(if include_history { FLAG_HISTORY } else { 0 }).u32(PACKAGE_CHUNK as u32);
171        (
172            PackageWriter {
173                buf: Vec::new(),
174                hash: Some(digest_init(&package_id)),
175                include_history,
176                next_part: 0,
177                records: 0,
178                bytes: 0,
179                seen: [false; 256],
180                digest: None,
181            },
182            w.done(),
183        )
184    }
185
186    fn cut(&mut self, all: bool) -> Vec<Vec<u8>> {
187        let mut out = Vec::new();
188        while self.buf.len() >= PACKAGE_CHUNK || (all && !self.buf.is_empty()) {
189            let n = self.buf.len().min(PACKAGE_CHUNK);
190            let mut w = W::new();
191            w.u32(self.next_part).raw(&self.buf[..n]);
192            self.buf.drain(..n);
193            self.next_part += 1;
194            out.push(w.done());
195        }
196        out
197    }
198
199    pub fn add(&mut self, section: u8, id: &[u8], body: &[u8]) -> LR<Vec<Vec<u8>>> {
200        let h = self.hash.as_mut().ok_or_else(|| LinkError::State("package already finished".into()))?;
201        check_record(section, id, body, self.include_history, &mut self.seen)?;
202        let mut w = W::new();
203        w.u8(section).b16(id).b32(body);
204        let rec = w.done();
205        if self.bytes + rec.len() as u64 > PACKAGE_MAX_BYTES {
206            return Err(LinkError::Malformed("package budget exceeded: send the rest of the photos via /api/blob".into()));
207        }
208        h.update(&rec);
209        self.bytes += rec.len() as u64;
210        self.records += 1;
211        self.buf.extend_from_slice(&rec);
212        Ok(self.cut(false))
213    }
214
215    pub fn finish(&mut self) -> LR<(Vec<Vec<u8>>, Vec<u8>)> {
216        let h = self.hash.take().ok_or_else(|| LinkError::State("package already finished".into()))?;
217        let parts = self.cut(true);
218        let digest: [u8; 32] = h.finalize().into();
219        let mut w = W::new();
220        w.u32(self.next_part).u64(self.records).u64(self.bytes).raw(&digest);
221        self.digest = Some(digest);
222        Ok((parts, w.done()))
223    }
224
225    pub fn digest(&self) -> Option<Vec<u8>> {
226        self.digest.map(|d| d.to_vec())
227    }
228}
229
230pub(crate) struct PackageReader {
231    buf: Vec<u8>,
232    hash: Option<Sha256>,
233    include_history: bool,
234    next_part: u32,
235    records: u64,
236    bytes: u64,
237    seen: [bool; 256],
238    digest: Option<[u8; 32]>,
239}
240
241impl PackageReader {
242    pub fn begin(header: &[u8]) -> LR<(Self, PackageProgress)> {
243        let mut r = Rd::new(header, "package header");
244        let v = r.u8()?;
245        if v != PKG_VERSION {
246            return Err(LinkError::Malformed(format!("package version {v}")));
247        }
248        let package_id = r.arr::<16>()?;
249        let flags = r.u8()?;
250        if flags & !FLAG_HISTORY != 0 {
251            return Err(LinkError::Malformed(format!("package flags {flags:#x}")));
252        }
253        let chunk = r.u32()?;
254        if chunk as usize != PACKAGE_CHUNK {
255            return Err(LinkError::Malformed(format!("package chunk size {chunk}")));
256        }
257        r.end()?;
258        let rd = PackageReader {
259            buf: Vec::new(),
260            hash: Some(digest_init(&package_id)),
261            include_history: flags & FLAG_HISTORY != 0,
262            next_part: 0,
263            records: 0,
264            bytes: 0,
265            seen: [false; 256],
266            digest: None,
267        };
268        let p = rd.progress(Vec::new());
269        Ok((rd, p))
270    }
271
272    fn progress(&self, records: Vec<PackageRecord>) -> PackageProgress {
273        PackageProgress {
274            records,
275            done: self.digest.is_some(),
276            include_history: self.include_history,
277            parts: self.next_part,
278            bytes: self.bytes,
279        }
280    }
281
282    /// Extract all complete records from the buffer. The body length is checked against the section limit BEFORE
283    /// the body is accumulated, so a declared "giant" size is rejected immediately.
284    fn drain(&mut self) -> LR<Vec<PackageRecord>> {
285        let mut out = Vec::new();
286        loop {
287            let b = &self.buf;
288            if b.len() < 3 {
289                break;
290            }
291            let section = b[0];
292            let l = limits(section)?;
293            let id_len = u16::from_be_bytes([b[1], b[2]]) as usize;
294            if id_len > ID_MAX {
295                return Err(LinkError::Malformed(format!("section {section}: id length {id_len}")));
296            }
297            if b.len() < 3 + id_len + 4 {
298                break;
299            }
300            let o = 3 + id_len;
301            let body_len = u32::from_be_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]) as usize;
302            if body_len > l.body_max {
303                return Err(LinkError::Malformed(format!("section {section}: body {body_len} > {}", l.body_max)));
304            }
305            let total = o + 4 + body_len;
306            if b.len() < total {
307                break;
308            }
309            let id = b[3..o].to_vec();
310            let body = b[o + 4..total].to_vec();
311            check_record(section, &id, &body, self.include_history, &mut self.seen)?;
312            self.buf.drain(..total);
313            self.records += 1;
314            out.push(PackageRecord { section, id, body });
315        }
316        Ok(out)
317    }
318
319    pub fn part(&mut self, pt: &[u8]) -> LR<PackageProgress> {
320        let h = self.hash.as_mut().ok_or_else(|| LinkError::Mismatch("package part after END".into()))?;
321        let mut r = Rd::new(pt, "package part");
322        let idx = r.u32()?;
323        if idx != self.next_part {
324            return Err(LinkError::Mismatch(format!("package part {idx}, expected {}", self.next_part)));
325        }
326        let data = r.raw(pt.len() - 4)?;
327        if data.is_empty() || data.len() > PACKAGE_CHUNK {
328            return Err(LinkError::Malformed(format!("package part size {}", data.len())));
329        }
330        if self.bytes + data.len() as u64 > PACKAGE_MAX_BYTES {
331            return Err(LinkError::Mismatch("package larger than the budget".into()));
332        }
333        h.update(data);
334        self.bytes += data.len() as u64;
335        self.next_part += 1;
336        self.buf.extend_from_slice(data);
337        let recs = self.drain()?;
338        Ok(self.progress(recs))
339    }
340
341    pub fn end(&mut self, pt: &[u8]) -> LR<PackageProgress> {
342        let h = self.hash.take().ok_or_else(|| LinkError::Mismatch("second package END".into()))?;
343        let mut r = Rd::new(pt, "package end");
344        let parts = r.u32()?;
345        let records = r.u64()?;
346        let bytes = r.u64()?;
347        let want = r.arr::<32>()?;
348        r.end()?;
349        if !self.buf.is_empty() {
350            return Err(LinkError::Mismatch("package ends inside a record".into()));
351        }
352        let got: [u8; 32] = h.finalize().into();
353        if parts != self.next_part || records != self.records || bytes != self.bytes || !ct_eq(&got, &want) {
354            return Err(LinkError::Mismatch("package digest or counts differ".into()));
355        }
356        self.digest = Some(got);
357        Ok(self.progress(Vec::new()))
358    }
359
360    pub fn digest(&self) -> Option<Vec<u8>> {
361        self.digest.map(|d| d.to_vec())
362    }
363}