Skip to main content

wechat_protocol/
media_send.rs

1//! Final media-message metadata. CDN upload and message submission are separate
2//! steps; persist source bytes, generated keys and intent before either step.
3use crate::{
4    file_upload::{FileUploadReservation, MAX_RESERVED_FILE_BYTES},
5    media::{MediaQuality, UploadedImage, UploadedMedia, UploadedVideo},
6    protobuf as p, silk,
7    wire::base_request,
8    AccountState,
9};
10use anyhow::{ensure, Result};
11use serde::{Deserialize, Serialize};
12fn clean(s: &str, max: usize) -> Result<&[u8]> {
13    ensure!(
14        !s.is_empty() && s.len() <= max && !s.chars().any(|c| c.is_control()),
15        "Invalid media text"
16    );
17    Ok(s.as_bytes())
18}
19fn hex32(value: &str) -> Result<String> {
20    ensure!(
21        value.len() == 32 && value.bytes().all(|b| b.is_ascii_hexdigit()),
22        "Invalid media MD5"
23    );
24    Ok(value.to_ascii_lowercase())
25}
26fn descriptor(v: &UploadedMedia, kind: MediaQuality) -> Result<()> {
27    descriptor_bound(v, kind, 25 * 1024 * 1024)
28}
29fn descriptor_bound(v: &UploadedMedia, kind: MediaQuality, max_bytes: usize) -> Result<()> {
30    ensure!(
31        v.descriptor.quality == kind
32            && v.descriptor.aes_key.len() == 16
33            && v.plaintext_bytes > 0
34            && v.plaintext_bytes as usize <= max_bytes,
35        "Invalid uploaded media descriptor"
36    );
37    clean(&v.descriptor.file_id, 8192)?;
38    hex32(&v.md5)?;
39    ensure!(
40        v.descriptor.expected_bytes == Some(v.plaintext_bytes as u64)
41            && v.descriptor
42                .expected_md5
43                .as_deref()
44                .is_some_and(|m| m.eq_ignore_ascii_case(&v.md5)),
45        "Uploaded media metadata differs"
46    );
47    Ok(())
48}
49fn escape(s: &str) -> String {
50    s.replace('&', "&amp;")
51        .replace('<', "&lt;")
52        .replace('>', "&gt;")
53        .replace('"', "&quot;")
54        .replace('\'', "&apos;")
55}
56fn tag(name: &str, value: impl ToString) -> String {
57    format!("<{name}>{}</{name}>", escape(&value.to_string()))
58}
59/// Generic URL shares use app subtype 5. Metadata is supplied by the caller;
60/// composing or sending a card never fetches the target page or thumbnail.
61pub fn share_xml(
62    sender: &str,
63    title: &str,
64    url: &str,
65    description: Option<&str>,
66    thumbnail_url: Option<&str>,
67) -> Result<String> {
68    clean(sender, 256)?;
69    ensure!(
70        !title.trim().is_empty()
71            && title.len() <= 16384
72            && !title
73                .chars()
74                .any(|c| c.is_control() && !matches!(c, '\n' | '\t')),
75        "invalid_share_request"
76    );
77    crate::media::validate_shared_link_url(url)?;
78    let description = description.unwrap_or("");
79    ensure!(
80        description.len() <= 16384
81            && !description
82                .chars()
83                .any(|c| c.is_control() && !matches!(c, '\n' | '\t')),
84        "invalid_share_request"
85    );
86    if let Some(url) = thumbnail_url {
87        crate::media::validate_link_thumbnail_url(url)?;
88    }
89    let xml = format!(
90        "<appmsg appid=\"\" sdkver=\"0\">{}{}{}{}{}{}{}{}{}{}</appmsg>{}",
91        tag("title", title),
92        tag("des", description),
93        tag("action", "view"),
94        tag("type", 5),
95        tag("showtype", 0),
96        tag("url", url),
97        tag("lowurl", ""),
98        tag("thumburl", thumbnail_url.unwrap_or("")),
99        tag("sourceusername", ""),
100        tag("sourcedisplayname", ""),
101        tag("fromusername", sender)
102    );
103    ensure!(xml.len() <= 256 * 1024, "invalid_share_request");
104    Ok(xml)
105}
106pub fn share_send_request(
107    state: &AccountState,
108    destination: &str,
109    client_id: &str,
110    created_at: u32,
111    content: &str,
112) -> Result<Vec<u8>> {
113    clean(destination, 256)?;
114    clean(client_id, 1024)?;
115    ensure!(
116        created_at > 0 && !content.is_empty() && content.len() <= 256 * 1024,
117        "invalid_share_request"
118    );
119    let app = p::message(&[
120        p::bytes(1, state.own_username.as_bytes()),
121        p::bytes(2, &[]),
122        p::uint(3, 0),
123        p::bytes(4, destination.as_bytes()),
124        p::uint(5, 5),
125        p::bytes(6, content.as_bytes()),
126        p::uint(7, created_at as u64),
127        p::bytes(8, client_id.as_bytes()),
128        p::int32(10, 1),
129        p::bytes(13, &[]),
130        p::bytes(14, &[]),
131        p::bytes(15, &[]),
132    ])?;
133    p::message(&[
134        p::bytes(1, &base_request(&state.device, state.uin, 0)?),
135        p::bytes(2, &app),
136        p::uint(9, 0),
137        p::uint(10, 0),
138        p::uint(11, 2),
139    ])
140}
141pub fn file_xml(sender: &str, upload: &UploadedMedia) -> Result<String> {
142    file_xml_with_reservation(sender, upload, None)
143}
144pub fn file_xml_with_reservation(
145    sender: &str,
146    upload: &UploadedMedia,
147    reservation: Option<&FileUploadReservation>,
148) -> Result<String> {
149    clean(sender, 1024)?;
150    if let Some(reservation) = reservation {
151        reservation.validate()?;
152        ensure!(
153            matches!(
154                upload.descriptor.quality,
155                MediaQuality::File | MediaQuality::LargeFile
156            ),
157            "Expected an uploaded file descriptor"
158        );
159        descriptor_bound(upload, upload.descriptor.quality, MAX_RESERVED_FILE_BYTES)?;
160    } else {
161        descriptor(upload, MediaQuality::File)?;
162    }
163    let name = &upload.file_name;
164    clean(name, 255)?;
165    ensure!(
166        name != "." && name != ".." && !name.contains(['/', '\\']),
167        "Expected a single filename component"
168    );
169    let extension = name
170        .rsplit_once('.')
171        .filter(|(base, _)| !base.is_empty())
172        .map(|(_, extension)| extension)
173        .unwrap_or("");
174    let mut app = tag("title", name);
175    for name in ["des", "action"] {
176        app.push_str(&tag(name, ""));
177    }
178    app.push_str(&tag("type", 6));
179    app.push_str(&tag("showtype", 0));
180    app.push_str(&tag("soundtype", 0));
181    for name in ["mediatagname", "messageext", "messageaction", "content"] {
182        app.push_str(&tag(name, ""));
183    }
184    app.push_str(&tag("contentattr", 0));
185    for name in ["url", "lowurl", "dataurl", "lowdataurl"] {
186        app.push_str(&tag(name, ""));
187    }
188    app.push_str("<appattach>");
189    app.push_str(&tag("totallen", upload.plaintext_bytes));
190    let aes_key = hex::encode(&upload.descriptor.aes_key);
191    let attach_id = reservation
192        .map(|_| format!("@cdn_{}_{aes_key}_1", upload.descriptor.file_id))
193        .unwrap_or_default();
194    app.push_str(&tag("attachid", attach_id));
195    app.push_str(&tag("emoticonmd5", ""));
196    app.push_str(&tag("fileext", extension));
197    app.push_str(&tag("cdnattachurl", &upload.descriptor.file_id));
198    app.push_str(&tag("aeskey", aes_key));
199    app.push_str(&tag("encryver", if reservation.is_some() { 0 } else { 1 }));
200    if let Some(reservation) = reservation {
201        app.push_str(&tag("overwrite_newmsgid", reservation.overwrite_newmsgid));
202        app.push_str(&tag("fileuploadtoken", &reservation.file_upload_token));
203    }
204    app.push_str("</appattach>");
205    for name in ["extinfo", "sourceusername", "sourcedisplayname", "thumburl"] {
206        app.push_str(&tag(name, ""));
207    }
208    app.push_str(&tag("md5", hex32(&upload.md5)?));
209    app.push_str(&tag("statextstr", ""));
210    Ok(format!(
211        "<appmsg appid=\"\" sdkver=\"0\">{app}</appmsg>{}",
212        tag("fromusername", sender)
213    ))
214}
215/// Reconstruct local metadata from accepted uploaded tuples. These are local
216/// cache records, not a claim that a server returned this exact XML spelling.
217fn local_element(name: &str, attributes: Vec<(&str, String)>) -> String {
218    let attributes = attributes
219        .into_iter()
220        .map(|(key, value)| format!(" {key}=\"{}\"", escape(&value)))
221        .collect::<String>();
222    format!("<msg><{name}{attributes}/></msg>")
223}
224/// Reconstruct metadata for the uploaded image copies, including an original when present.
225pub fn local_image_xml(image: &UploadedImage) -> Result<String> {
226    if let Some(original) = &image.original {
227        descriptor(original, MediaQuality::Original)?;
228        ensure!(
229            original.descriptor.aes_key == image.standard.descriptor.aes_key,
230            "Image variants require one main key"
231        );
232    }
233    descriptor(&image.standard, MediaQuality::Standard)?;
234    descriptor(&image.thumbnail, MediaQuality::Thumbnail)?;
235    let main = image.original.as_ref().unwrap_or(&image.standard);
236    let original_id = image
237        .original
238        .as_ref()
239        .map(|v| v.descriptor.file_id.clone())
240        .unwrap_or_default();
241    let original_bytes = image
242        .original
243        .as_ref()
244        .map(|v| v.plaintext_bytes)
245        .unwrap_or(0);
246    Ok(local_element(
247        "img",
248        vec![
249            ("aeskey", hex::encode(&main.descriptor.aes_key)),
250            ("encryver", "1".into()),
251            ("cdnbigimgurl", original_id),
252            ("cdnmidimgurl", image.standard.descriptor.file_id.clone()),
253            ("cdnthumburl", image.thumbnail.descriptor.file_id.clone()),
254            (
255                "cdnthumbaeskey",
256                hex::encode(&image.thumbnail.descriptor.aes_key),
257            ),
258            ("md5", hex32(&main.md5)?),
259            ("hdlength", original_bytes.to_string()),
260            ("length", image.standard.plaintext_bytes.to_string()),
261            (
262                "cdnthumblength",
263                image.thumbnail.plaintext_bytes.to_string(),
264            ),
265            (
266                "cdnthumbwidth",
267                image.thumbnail.width.unwrap_or(0).to_string(),
268            ),
269            (
270                "cdnthumbheight",
271                image.thumbnail.height.unwrap_or(0).to_string(),
272            ),
273        ],
274    ))
275}
276pub fn local_video_xml(video: &UploadedVideo, seconds: u32) -> Result<String> {
277    descriptor(&video.video, MediaQuality::Video)?;
278    descriptor(&video.thumbnail, MediaQuality::Thumbnail)?;
279    ensure!(seconds > 0, "Invalid video duration");
280    let mut fields = vec![
281        ("aeskey", hex::encode(&video.video.descriptor.aes_key)),
282        ("cdnvideourl", video.video.descriptor.file_id.clone()),
283        ("length", video.video.plaintext_bytes.to_string()),
284        ("md5", hex32(&video.video.md5)?),
285        ("playlength", seconds.to_string()),
286        ("cdnthumburl", video.thumbnail.descriptor.file_id.clone()),
287        (
288            "cdnthumbaeskey",
289            hex::encode(&video.thumbnail.descriptor.aes_key),
290        ),
291        (
292            "cdnthumblength",
293            video.thumbnail.plaintext_bytes.to_string(),
294        ),
295        (
296            "cdnthumbwidth",
297            video.thumbnail.width.unwrap_or(0).to_string(),
298        ),
299        (
300            "cdnthumbheight",
301            video.thumbnail.height.unwrap_or(0).to_string(),
302        ),
303    ];
304    if let Some(original) = &video.original {
305        descriptor_bound(
306            original,
307            MediaQuality::Video,
308            wechat_media::MAX_VIDEO_SOURCE_BYTES,
309        )?;
310        fields.extend([
311            ("cdnrawvideourl", original.descriptor.file_id.clone()),
312            (
313                "cdnrawvideoaeskey",
314                hex::encode(&original.descriptor.aes_key),
315            ),
316            ("rawlength", original.plaintext_bytes.to_string()),
317            ("rawmd5", hex32(&original.md5)?),
318        ]);
319    }
320    Ok(local_element("videomsg", fields))
321}
322pub fn local_voice_xml(encoded_bytes: usize, duration_ms: u32) -> Result<String> {
323    ensure!(
324        encoded_bytes > 0
325            && encoded_bytes <= silk::MAX_NOTE_BYTES
326            && (1..=silk::MAX_NOTE_MS).contains(&duration_ms),
327        "Invalid voice note metadata"
328    );
329    Ok(local_element(
330        "voicemsg",
331        vec![
332            ("voiceformat", "4".into()),
333            ("length", encoded_bytes.to_string()),
334            ("voicelength", duration_ms.to_string()),
335            ("endflag", "1".into()),
336        ],
337    ))
338}
339pub fn local_file_xml(sender: &str, upload: &UploadedMedia) -> Result<String> {
340    local_file_xml_with_reservation(sender, upload, None)
341}
342pub fn local_file_xml_with_reservation(
343    sender: &str,
344    upload: &UploadedMedia,
345    reservation: Option<&FileUploadReservation>,
346) -> Result<String> {
347    Ok(format!(
348        "<msg>{}</msg>",
349        file_xml_with_reservation(sender, upload, reservation)?
350    ))
351}
352pub fn file_send_request(
353    state: &AccountState,
354    destination: &str,
355    client_id: &str,
356    created_at: u32,
357    upload: &UploadedMedia,
358) -> Result<Vec<u8>> {
359    file_send_request_with_reservation(state, destination, client_id, created_at, upload, None)
360}
361pub fn file_send_request_with_reservation(
362    state: &AccountState,
363    destination: &str,
364    client_id: &str,
365    created_at: u32,
366    upload: &UploadedMedia,
367    reservation: Option<&FileUploadReservation>,
368) -> Result<Vec<u8>> {
369    clean(destination, 512)?;
370    clean(client_id, 1024)?;
371    ensure!(created_at > 0, "Invalid media timestamp");
372    let content = file_xml_with_reservation(&state.own_username, upload, reservation)?;
373    let app = p::message(&[
374        p::bytes(1, state.own_username.as_bytes()),
375        p::bytes(2, &[]),
376        p::uint(3, 0),
377        p::bytes(4, destination.as_bytes()),
378        p::uint(5, 6),
379        p::bytes(6, content.as_bytes()),
380        p::uint(7, created_at as u64),
381        p::bytes(8, client_id.as_bytes()),
382        p::int32(10, 1),
383        p::bytes(13, &[]),
384        p::bytes(14, &[]),
385        p::bytes(15, &[]),
386    ])?;
387    let mut fields = vec![
388        p::bytes(1, &base_request(&state.device, state.uin, 0)?),
389        p::bytes(2, &app),
390        p::bytes(5, hex32(&upload.md5)?.as_bytes()),
391    ];
392    if upload.plaintext_bytes > 25 * 1024 * 1024 {
393        fields.push(p::uint(6, 7));
394    }
395    fields.extend([p::uint(9, 0), p::uint(10, 0), p::uint(11, 2)]);
396    p::message(&fields)
397}
398/// Build a submission for the uploaded image copies, including an original when present.
399pub fn image_send_request(
400    state: &AccountState,
401    destination: &str,
402    client_id: &str,
403    image: &UploadedImage,
404) -> Result<Vec<u8>> {
405    clean(destination, 512)?;
406    clean(client_id, 4096)?;
407    if let Some(original) = &image.original {
408        descriptor(original, MediaQuality::Original)?;
409        ensure!(
410            original.descriptor.aes_key == image.standard.descriptor.aes_key,
411            "Image main variants require one shared key"
412        );
413    }
414    descriptor(&image.standard, MediaQuality::Standard)?;
415    descriptor(&image.thumbnail, MediaQuality::Thumbnail)?;
416    let main = image.original.as_ref().unwrap_or(&image.standard);
417    let original_id = image
418        .original
419        .as_ref()
420        .map(|v| v.descriptor.file_id.as_bytes())
421        .unwrap_or(&[]);
422    let original_bytes = image
423        .original
424        .as_ref()
425        .map(|v| v.plaintext_bytes)
426        .unwrap_or(0);
427    let thumbnail = &image.thumbnail;
428    let width = thumbnail
429        .width
430        .ok_or_else(|| anyhow::anyhow!("Missing thumbnail width"))?;
431    let height = thumbnail
432        .height
433        .ok_or_else(|| anyhow::anyhow!("Missing thumbnail height"))?;
434    ensure!(
435        width > 0 && width <= 8192 && height > 0 && height <= 8192,
436        "Invalid thumbnail dimensions"
437    );
438    let sk = |s: &[u8]| p::bytes(1, s);
439    p::message(&[
440        p::bytes(1, &base_request(&state.device, state.uin, 0)?),
441        p::bytes(2, &sk(client_id.as_bytes())),
442        p::bytes(3, &sk(state.own_username.as_bytes())),
443        p::bytes(4, &sk(destination.as_bytes())),
444        p::uint(5, thumbnail.plaintext_bytes as u64),
445        p::uint(6, 0),
446        p::uint(7, thumbnail.plaintext_bytes as u64),
447        p::bytes(8, &p::buffer(&[])),
448        p::uint(9, 3),
449        p::uint(11, u64::from(image.original.is_some())),
450        p::int32(12, 2),
451        p::int32(13, 0),
452        p::bytes(15, original_id),
453        p::bytes(16, image.standard.descriptor.file_id.as_bytes()),
454        p::bytes(17, hex::encode(&main.descriptor.aes_key).as_bytes()),
455        p::int32(18, 1),
456        p::int32(19, original_bytes as i32),
457        p::int32(20, image.standard.plaintext_bytes as i32),
458        p::bytes(21, thumbnail.descriptor.file_id.as_bytes()),
459        p::int32(22, thumbnail.plaintext_bytes as i32),
460        p::int32(23, height as i32),
461        p::int32(24, width as i32),
462        p::bytes(25, hex::encode(&thumbnail.descriptor.aes_key).as_bytes()),
463        p::bytes(27, hex32(&main.md5)?.as_bytes()),
464        p::uint(28, 0),
465        p::uint(30, 0),
466        p::uint(36, 0),
467        p::uint(41, 0),
468    ])
469}
470pub fn video_send_request(
471    state: &AccountState,
472    destination: &str,
473    client_id: &str,
474    video: &UploadedVideo,
475    play_seconds: u32,
476) -> Result<Vec<u8>> {
477    clean(destination, 512)?;
478    clean(client_id, 1024)?;
479    ensure!(play_seconds > 0, "Invalid video play duration");
480    descriptor(&video.video, MediaQuality::Video)?;
481    descriptor(&video.thumbnail, MediaQuality::Thumbnail)?;
482    let v = &video.video;
483    let t = &video.thumbnail;
484    let width = t
485        .width
486        .ok_or_else(|| anyhow::anyhow!("Missing video thumbnail width"))?;
487    let height = t
488        .height
489        .ok_or_else(|| anyhow::anyhow!("Missing video thumbnail height"))?;
490    ensure!(
491        width > 0 && height > 0 && width <= 8192 && height <= 8192,
492        "Invalid video thumbnail dimensions"
493    );
494    let mut fields = vec![
495        p::bytes(1, &base_request(&state.device, state.uin, 0)?),
496        p::bytes(2, client_id.as_bytes()),
497        p::bytes(3, state.own_username.as_bytes()),
498        p::bytes(4, destination.as_bytes()),
499        p::uint(5, t.plaintext_bytes as u64),
500        p::uint(6, 0),
501        p::bytes(7, &p::buffer(&[])),
502        p::uint(8, v.plaintext_bytes as u64),
503        p::uint(9, 0),
504        p::bytes(10, &p::buffer(&[])),
505        p::uint(11, play_seconds as u64),
506        p::uint(12, 1),
507        p::uint(13, 0),
508        p::uint(14, 0),
509        p::bytes(15, &[]),
510        p::bytes(16, v.descriptor.file_id.as_bytes()),
511        p::bytes(17, hex::encode(&v.descriptor.aes_key).as_bytes()),
512        p::int32(18, 1),
513        p::bytes(19, t.descriptor.file_id.as_bytes()),
514        p::int32(20, t.plaintext_bytes as i32),
515        p::int32(21, height as i32),
516        p::int32(22, width as i32),
517        p::bytes(23, hex::encode(&t.descriptor.aes_key).as_bytes()),
518        p::bytes(26, hex32(&v.md5)?.as_bytes()),
519        p::bytes(37, &[]),
520        p::uint(38, 0),
521    ];
522    if let Some(original) = &video.original {
523        descriptor_bound(
524            original,
525            MediaQuality::Video,
526            wechat_media::MAX_VIDEO_SOURCE_BYTES,
527        )?;
528        // Linux 4.1.13.26 CGI149's generated M7 serializer emits these
529        // separately from the normal rendition (0x7d094d8..0x7d0954a).
530        fields.extend([
531            p::bytes(48, hex32(&original.md5)?.as_bytes()),
532            p::bytes(49, original.descriptor.file_id.as_bytes()),
533            p::bytes(50, hex::encode(&original.descriptor.aes_key).as_bytes()),
534            p::uint(51, u64::from(original.plaintext_bytes)),
535        ]);
536    }
537    p::message(&fields)
538}
539/// Encoded SILK bytes carried by one `uploadvoice` request. A short-link
540/// request travels in one MMTLS record of at most 65,519 plaintext bytes,
541/// including the route, packet header and envelope, so a 60-second note (about
542/// 126-131 KB from the bundled 16 kbit/s profile) cannot use one request. 32 KiB
543/// matches the `downloadvoice` range size and leaves room for that overhead.
544pub const VOICE_UPLOAD_CHUNK_BYTES: usize = 32 * 1024;
545
546/// One voice note submitted through `uploadvoice`. A note of at most
547/// [`VOICE_UPLOAD_CHUNK_BYTES`] uses a single request with the end flag set.
548/// A larger note is sent as consecutive byte ranges (offset/length) under the
549/// same client message ID; only the last range sets the end flag, and later
550/// ranges carry a server message ID returned for an earlier range. Each range
551/// is submitted once: an error after any submission is an uncertain outcome.
552pub struct VoiceUpload<'a> {
553    destination: &'a str,
554    client_id: &'a str,
555    created_at: u32,
556    duration_ms: u32,
557    encoded: &'a [u8],
558    offset: usize,
559    server_msg_id: Option<u32>,
560    new_msg_id: Option<u64>,
561}
562impl<'a> VoiceUpload<'a> {
563    pub fn new(
564        destination: &'a str,
565        client_id: &'a str,
566        created_at: u32,
567        duration_ms: u32,
568        encoded: &'a [u8],
569    ) -> Result<Self> {
570        clean(destination, 512)?;
571        let client = clean(client_id, 128)?;
572        ensure!(
573            client.len() >= 16
574                && client
575                    .iter()
576                    .all(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'-'),
577            "Invalid voice client ID"
578        );
579        ensure!(
580            created_at > 0
581                && (1..=silk::MAX_NOTE_MS).contains(&duration_ms)
582                && encoded.len() >= 12
583                && encoded.len() <= silk::MAX_NOTE_BYTES
584                && encoded[0] == 2
585                && encoded[1..10] == *b"#!SILK_V3",
586            "Unsupported bounded SILK voice profile"
587        );
588        Ok(Self {
589            destination,
590            client_id,
591            created_at,
592            duration_ms,
593            encoded,
594            offset: 0,
595            server_msg_id: None,
596            new_msg_id: None,
597        })
598    }
599    fn range(&self) -> std::ops::Range<usize> {
600        self.offset..(self.offset + VOICE_UPLOAD_CHUNK_BYTES).min(self.encoded.len())
601    }
602    /// Number of requests needed for the whole note.
603    pub fn request_count(&self) -> usize {
604        self.encoded.len().div_ceil(VOICE_UPLOAD_CHUNK_BYTES)
605    }
606    /// Whether the next request carries the last range and the end flag.
607    pub fn is_final(&self) -> bool {
608        self.range().end == self.encoded.len()
609    }
610    /// Build the request for the next unsent range.
611    pub fn request(&self, state: &AccountState) -> Result<Vec<u8>> {
612        let range = self.range();
613        let chunk = &self.encoded[range.clone()];
614        let client = self.client_id.as_bytes();
615        let mut parts = vec![
616            p::bytes(1, state.own_username.as_bytes()),
617            p::bytes(2, self.destination.as_bytes()),
618            p::uint(3, range.start as u64),
619            p::uint(4, chunk.len() as u64),
620            p::bytes(5, client),
621        ];
622        if let Some(id) = self.server_msg_id {
623            parts.push(p::uint(6, id.into()));
624        }
625        parts.extend([
626            p::uint(7, self.duration_ms.into()),
627            p::bytes(8, &p::buffer(chunk)),
628            p::uint(9, self.is_final().into()),
629            p::bytes(10, &base_request(&state.device, state.uin, 0)?),
630            p::uint(11, 0),
631            p::uint(13, 4),
632            p::uint(15, 0),
633            p::uint(16, 0),
634            p::uint(17, self.created_at.into()),
635        ]);
636        // Only the first range carries this buffer; field 5 identifies every range.
637        if range.start == 0 {
638            parts.push(p::bytes(18, &p::buffer(client)));
639        }
640        parts.push(p::bytes(21, &[]));
641        p::message(&parts)
642    }
643    /// Apply the reply for the request built last. Returns the note's result
644    /// after the final range, or `None` when the next range must be sent. A
645    /// rejection after an earlier range was accepted needs review, because the
646    /// server already holds part of the note under this client message ID.
647    pub fn accept_reply(&mut self, input: &[u8]) -> Result<Option<MediaSendResult>> {
648        let continued = self.offset > 0;
649        if self.is_final() {
650            let mut result = decode_voice_send(input, self.client_id)?;
651            let changed = self.new_msg_id.is_some_and(|known| {
652                result.server_message_id.as_deref() != Some(known.to_string().as_str())
653            });
654            if (continued && result.status == SendStatus::Rejected) || changed {
655                result.status = SendStatus::NeedsReview;
656            }
657            return Ok(Some(result));
658        }
659        let (f, code) = voice_reply(input)?;
660        if code != 0 {
661            let mut result = rejected(code);
662            if continued {
663                result.status = SendStatus::NeedsReview;
664            }
665            return Ok(Some(result));
666        }
667        let scalar = |n| -> Result<Option<u64>> {
668            Ok(match p::optional(&f, n)? {
669                Some(p::Value::Varint(v)) => Some(*v),
670                _ => None,
671            })
672        };
673        for n in [3, 4, 5, 7, 8, 9] {
674            if let Some(v) = scalar(n)? {
675                u32::try_from(v)?;
676            }
677        }
678        ensure!(
679            scalar(9)?.unwrap_or(0) == 0,
680            "Voice upload ended before its last range"
681        );
682        if let Some(id) = scalar(7)?.filter(|id| *id != 0) {
683            let id = u32::try_from(id)?;
684            ensure!(
685                self.server_msg_id.is_none_or(|known| known == id),
686                "Voice upload message ID changed"
687            );
688            self.server_msg_id = Some(id);
689        }
690        if let Some(id) = scalar(12)?.filter(|id| *id != 0) {
691            ensure!(
692                self.new_msg_id.is_none_or(|known| known == id),
693                "Voice upload message ID changed"
694            );
695            self.new_msg_id = Some(id);
696        }
697        self.offset = self.range().end;
698        Ok(None)
699    }
700}
701#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
702#[serde(rename_all = "snake_case")]
703pub enum SendStatus {
704    ServerAccepted,
705    Rejected,
706    NeedsReview,
707}
708#[derive(Clone, Serialize, Deserialize, Debug)]
709#[serde(rename_all = "camelCase")]
710pub struct MediaSendResult {
711    pub status: SendStatus,
712    pub service_code: i32,
713    pub server_message_id: Option<String>,
714    pub client_id_matches: Option<bool>,
715}
716fn rejected(code: i32) -> MediaSendResult {
717    MediaSendResult {
718        status: SendStatus::Rejected,
719        service_code: code,
720        server_message_id: None,
721        client_id_matches: None,
722    }
723}
724pub fn decode_file_send(input: &[u8], client_id: &str) -> Result<MediaSendResult> {
725    let f = p::decode(input)?;
726    let code = p::base_code(&f)?;
727    if code != 0 {
728        return Ok(rejected(code));
729    }
730    for n in [5, 7] {
731        u32::try_from(p::scalar(&f, n)?)?;
732    }
733    let id = p::scalar(&f, 9)?;
734    ensure!(id != 0, "Accepted file response has no server ID");
735    let mut matches = false;
736    for n in [2, 3, 4, 6, 10, 11, 13] {
737        if let Some(v) = p::optional_data(&f, n)? {
738            std::str::from_utf8(v)?;
739            matches |= v == client_id.as_bytes();
740        }
741    }
742    Ok(MediaSendResult {
743        status: SendStatus::ServerAccepted,
744        service_code: code,
745        server_message_id: Some(id.to_string()),
746        client_id_matches: matches.then_some(true),
747    })
748}
749/// Correlate the final reply for a reserved file with its submitted intent.
750pub fn decode_file_send_correlated(
751    input: &[u8],
752    client_id: &str,
753    sender: &str,
754    destination: &str,
755    aes_key: &[u8],
756) -> Result<MediaSendResult> {
757    ensure!(aes_key.len() == 16, "Invalid file AES key");
758    let mut result = decode_file_send(input, client_id)?;
759    if result.status == SendStatus::Rejected {
760        return Ok(result);
761    }
762    let fields = p::decode(input)?;
763    let base = p::decode(p::data(&fields, 1)?)?;
764    ensure!(p::scalar(&base, 1)? == 0, "Invalid file response status");
765    let key = hex::encode(aes_key);
766    let mut correlated = true;
767    for (number, expected) in [
768        (3, sender.as_bytes()),
769        (4, destination.as_bytes()),
770        (6, client_id.as_bytes()),
771        (10, key.as_bytes()),
772    ] {
773        correlated &= p::optional_data(&fields, number)? == Some(expected);
774    }
775    result.status = if correlated {
776        SendStatus::ServerAccepted
777    } else {
778        SendStatus::NeedsReview
779    };
780    result.client_id_matches = Some(correlated);
781    Ok(result)
782}
783pub fn decode_image_send(
784    input: &[u8],
785    client_id: &str,
786    sender: &str,
787    destination: &str,
788) -> Result<MediaSendResult> {
789    let f = p::decode(input)?;
790    for n in 1..=13 {
791        p::optional(&f, n)?;
792    }
793    let code = p::base_code(&f)?;
794    if code != 0 {
795        return Ok(rejected(code));
796    }
797    for n in [2, 6, 7, 8, 9] {
798        u32::try_from(p::scalar(&f, n)?)?;
799    }
800    let nested = |n| -> Result<Vec<u8>> {
801        let item = p::decode(p::data(&f, n)?)?;
802        Ok(p::data(&item, 1)?.to_vec())
803    };
804    let correlated = nested(3)? == client_id.as_bytes()
805        && nested(4)? == sender.as_bytes()
806        && nested(5)? == destination.as_bytes();
807    let id = p::scalar(&f, 10)?;
808    ensure!(id != 0, "Accepted image response has no server ID");
809    for n in [11, 12, 13] {
810        p::optional_data(&f, n)?;
811    }
812    Ok(MediaSendResult {
813        status: if correlated {
814            SendStatus::ServerAccepted
815        } else {
816            SendStatus::NeedsReview
817        },
818        service_code: code,
819        server_message_id: Some(id.to_string()),
820        client_id_matches: Some(correlated),
821    })
822}
823pub fn decode_video_send(input: &[u8], client_id: &str) -> Result<MediaSendResult> {
824    let f = p::decode(input)?;
825    let code = p::base_code(&f)?;
826    if code != 0 {
827        return Ok(rejected(code));
828    }
829    for n in [3, 4, 5] {
830        u32::try_from(p::scalar(&f, n)?)?;
831    }
832    let id = p::scalar(&f, 6)?;
833    ensure!(id != 0, "Accepted video response has no server ID");
834    let mut matches = false;
835    for n in [2, 7, 8] {
836        if let Some(v) = p::optional_data(&f, n)? {
837            std::str::from_utf8(v)?;
838            matches |= v == client_id.as_bytes();
839        }
840    }
841    Ok(MediaSendResult {
842        status: SendStatus::ServerAccepted,
843        service_code: code,
844        server_message_id: Some(id.to_string()),
845        client_id_matches: matches.then_some(true),
846    })
847}
848fn voice_reply(input: &[u8]) -> Result<(Vec<p::Field>, i32)> {
849    let f = p::decode(input)?;
850    for n in 1..=13 {
851        let v = p::optional(&f, n)?;
852        if let Some(v) = v {
853            ensure!(
854                matches!(
855                    (n, v),
856                    (1 | 2 | 6 | 10, p::Value::Bytes(_))
857                        | (3 | 4 | 5 | 7 | 8 | 9 | 11 | 12 | 13, p::Value::Varint(_))
858                ),
859                "Invalid voice response field"
860            );
861        }
862    }
863    let base = p::decode(p::data(&f, 10)?)?;
864    let code = p::scalar(&base, 1)? as u32 as i32;
865    Ok((f, code))
866}
867/// Decode the reply to the request carrying a note's end flag.
868pub fn decode_voice_send(input: &[u8], client_id: &str) -> Result<MediaSendResult> {
869    let (f, code) = voice_reply(input)?;
870    if code != 0 {
871        return Ok(rejected(code));
872    }
873    for n in [3, 4, 5, 7, 8, 9] {
874        u32::try_from(p::scalar(&f, n)?)?;
875    }
876    let id = p::scalar(&f, 12)?;
877    ensure!(id != 0, "Accepted voice response has no server ID");
878    let mut matches = 0;
879    for n in [1, 2, 6] {
880        if let Some(v) = p::optional_data(&f, n)? {
881            std::str::from_utf8(v)?;
882            if v == client_id.as_bytes() {
883                matches += 1;
884            }
885        }
886    }
887    Ok(MediaSendResult {
888        status: if matches == 1 {
889            SendStatus::ServerAccepted
890        } else {
891            SendStatus::NeedsReview
892        },
893        service_code: code,
894        server_message_id: Some(id.to_string()),
895        client_id_matches: Some(matches == 1),
896    })
897}
898
899#[cfg(test)]
900mod tests {
901    use super::*;
902    fn synthetic_state() -> AccountState {
903        AccountState {
904            schema: 1,
905            device: crate::DeviceProfile {
906                device_id: vec![1; 16],
907                device_type: "UnifiedPCLinux synthetic x86_64".into(),
908                client_version: -227271398,
909            },
910            uin: 123,
911            own_username: "synthetic-user".into(),
912            cookie: vec![],
913            session_key: vec![1; 16],
914            request_key: vec![],
915            response_key: vec![],
916            auto_auth_key: vec![],
917            key_info: vec![],
918            database_password: vec![],
919            auth_snapshot: Default::default(),
920            long_host: "long.weixin.qq.com".into(),
921            short_host: "short.weixin.qq.com".into(),
922        }
923    }
924    fn synthetic_file(size: usize, quality: MediaQuality) -> UploadedMedia {
925        UploadedMedia {
926            descriptor: crate::media::MediaDescriptor {
927                file_id: "synthetic-file-id".into(),
928                aes_key: vec![1; 16],
929                quality,
930                expected_bytes: Some(size as u64),
931                expected_md5: Some("a".repeat(32)),
932                strict_size: true,
933                expires_at: None,
934            },
935            plaintext_bytes: size.try_into().unwrap(),
936            md5: "a".repeat(32),
937            sha256: "b".repeat(64),
938            file_name: "synthetic&file.txt".into(),
939            width: None,
940            height: None,
941        }
942    }
943    fn synthetic_reservation() -> FileUploadReservation {
944        FileUploadReservation {
945            file_upload_token: "v1_c3ludGhldGlj".into(),
946            overwrite_newmsgid: u64::MAX,
947        }
948    }
949    #[test]
950    fn file_upload_reservation_ordinary_request_schema() {
951        let state = synthetic_state();
952        let raw = crate::file_upload::file_upload_request(
953            &state,
954            "filehelper",
955            "filehelper_1234567_42",
956            "synthetic&file.TXT",
957            32 * 1024 * 1024,
958            &"A".repeat(32),
959        )
960        .unwrap();
961        let fields = p::decode(&raw).unwrap();
962        assert_eq!(
963            fields.iter().map(|f| f.number).collect::<Vec<_>>(),
964            [1, 2, 3, 4, 5, 7, 12]
965        );
966        assert_eq!(p::data(&fields, 2).unwrap(), b"filehelper");
967        assert_eq!(p::data(&fields, 3).unwrap(), b"filehelper_1234567_42");
968        assert_ne!(p::data(&fields, 2).unwrap(), state.own_username.as_bytes());
969        assert_eq!(p::scalar(&fields, 4).unwrap(), 1);
970        assert_eq!(p::scalar(&fields, 7).unwrap(), 0);
971        assert_eq!(p::scalar(&fields, 12).unwrap(), 0);
972        let base = p::decode(p::data(&fields, 1).unwrap()).unwrap();
973        assert_eq!(p::scalar(&base, 2).unwrap(), 123);
974        assert_eq!(p::scalar(&base, 6).unwrap(), 0);
975        let info = p::decode(p::data(&fields, 5).unwrap()).unwrap();
976        assert_eq!(
977            info.iter().map(|f| f.number).collect::<Vec<_>>(),
978            [1, 2, 3, 4]
979        );
980        assert_eq!(p::data(&info, 1).unwrap(), b"synthetic&file.TXT");
981        assert_eq!(p::data(&info, 2).unwrap(), b"TXT");
982        assert_eq!(
983            p::data(&info, 3).unwrap(),
984            b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
985        );
986        assert_eq!(p::scalar(&info, 4).unwrap(), 33_554_432);
987        let final_client_id = "filehelper_1234567_42_xwechat_1";
988        let final_request = file_send_request_with_reservation(
989            &state,
990            "filehelper",
991            final_client_id,
992            1_234_567,
993            &synthetic_file(MAX_RESERVED_FILE_BYTES, MediaQuality::LargeFile),
994            Some(&synthetic_reservation()),
995        )
996        .unwrap();
997        let final_fields = p::decode(&final_request).unwrap();
998        let final_app = p::decode(p::data(&final_fields, 2).unwrap()).unwrap();
999        assert_eq!(p::data(&final_app, 8).unwrap(), final_client_id.as_bytes());
1000        assert_ne!(
1001            p::data(&fields, 3).unwrap(),
1002            p::data(&final_app, 8).unwrap()
1003        );
1004        assert!(
1005            final_client_id.starts_with(std::str::from_utf8(p::data(&fields, 3).unwrap()).unwrap())
1006        );
1007        assert!(crate::file_upload::file_upload_request(
1008            &state,
1009            "bad\npeer",
1010            "filehelper_1234567_42",
1011            "file.txt",
1012            1,
1013            &"a".repeat(32)
1014        )
1015        .is_err());
1016        for progress_id in ["", "bad\nidentity", &"a".repeat(1025)] {
1017            assert!(crate::file_upload::file_upload_request(
1018                &state,
1019                "filehelper",
1020                progress_id,
1021                "file.txt",
1022                1,
1023                &"a".repeat(32)
1024            )
1025            .is_err());
1026        }
1027    }
1028    #[test]
1029    fn reserved_file_metadata_and_plaintext_boundary_flag() {
1030        let state = synthetic_state();
1031        let reservation = synthetic_reservation();
1032        let threshold = 25 * 1024 * 1024;
1033        for size in [
1034            threshold - 17,
1035            threshold - 16,
1036            threshold - 15,
1037            threshold - 1,
1038            threshold,
1039            threshold + 1,
1040            MAX_RESERVED_FILE_BYTES,
1041        ] {
1042            let upload = synthetic_file(size, MediaQuality::LargeFile);
1043            let raw = file_send_request_with_reservation(
1044                &state,
1045                "filehelper",
1046                "synthetic-client",
1047                1,
1048                &upload,
1049                Some(&reservation),
1050            )
1051            .unwrap();
1052            let fields = p::decode(&raw).unwrap();
1053            assert_eq!(p::optional(&fields, 6).unwrap().is_some(), size > threshold);
1054            if size > threshold {
1055                assert_eq!(p::scalar(&fields, 6).unwrap(), 7);
1056            }
1057            let app = p::decode(p::data(&fields, 2).unwrap()).unwrap();
1058            let xml = std::str::from_utf8(p::data(&app, 6).unwrap()).unwrap();
1059            assert!(xml.contains("<encryver>0</encryver>"));
1060            assert!(xml.contains(
1061                "<attachid>@cdn_synthetic-file-id_01010101010101010101010101010101_1</attachid>"
1062            ));
1063            assert!(xml.contains("<fileuploadtoken>v1_c3ludGhldGlj</fileuploadtoken>"));
1064            assert!(xml.contains("<overwrite_newmsgid>18446744073709551615</overwrite_newmsgid>"));
1065            assert!(xml.contains("<title>synthetic&amp;file.txt</title>"));
1066            assert_eq!(
1067                local_file_xml_with_reservation(&state.own_username, &upload, Some(&reservation))
1068                    .unwrap(),
1069                format!("<msg>{xml}</msg>")
1070            );
1071            assert!(
1072                file_send_request(&state, "filehelper", "synthetic-client", 1, &upload).is_err()
1073            );
1074        }
1075        // Upload routing changes at an AES-padding boundary; the app-message
1076        // field6 still follows plaintext size, including at exactly 25 MiB.
1077        assert_eq!(((threshold - 17) / 16 + 1) * 16, threshold - 16);
1078        assert_eq!(((threshold - 16) / 16 + 1) * 16, threshold);
1079        let small = synthetic_file(1, MediaQuality::File);
1080        assert!(file_xml("synthetic-user", &small)
1081            .unwrap()
1082            .contains("<encryver>1</encryver>"));
1083        assert!(!file_xml("synthetic-user", &small)
1084            .unwrap()
1085            .contains("fileuploadtoken"));
1086        let too_large = synthetic_file(MAX_RESERVED_FILE_BYTES + 1, MediaQuality::LargeFile);
1087        assert!(
1088            file_xml_with_reservation("synthetic-user", &too_large, Some(&reservation)).is_err()
1089        );
1090        let mut mismatch = synthetic_file(MAX_RESERVED_FILE_BYTES, MediaQuality::LargeFile);
1091        mismatch.descriptor.expected_md5 = Some("0".repeat(32));
1092        assert!(
1093            file_xml_with_reservation("synthetic-user", &mismatch, Some(&reservation)).is_err()
1094        );
1095    }
1096    #[test]
1097    fn reserved_file_acceptance_requires_all_correlations() {
1098        let response = |sender: &[u8], destination: &[u8], client: &[u8], key: &[u8]| {
1099            p::message(&[
1100                p::bytes(1, &p::int32(1, 0)),
1101                p::bytes(3, sender),
1102                p::bytes(4, destination),
1103                p::uint(5, 1),
1104                p::bytes(6, client),
1105                p::uint(7, 1),
1106                p::uint(9, u64::MAX),
1107                p::bytes(10, key),
1108                p::bytes(13, b"synthetic-client"),
1109            ])
1110            .unwrap()
1111        };
1112        let key = b"01010101010101010101010101010101";
1113        for (sender, destination, client, aes, status) in [
1114            (
1115                &b"synthetic-user"[..],
1116                &b"filehelper"[..],
1117                &b"synthetic-client"[..],
1118                &key[..],
1119                SendStatus::ServerAccepted,
1120            ),
1121            (
1122                &b"wrong"[..],
1123                &b"filehelper"[..],
1124                &b"synthetic-client"[..],
1125                &key[..],
1126                SendStatus::NeedsReview,
1127            ),
1128            (
1129                &b"synthetic-user"[..],
1130                &b"wrong"[..],
1131                &b"synthetic-client"[..],
1132                &key[..],
1133                SendStatus::NeedsReview,
1134            ),
1135            (
1136                &b"synthetic-user"[..],
1137                &b"filehelper"[..],
1138                &b"wrong"[..],
1139                &key[..],
1140                SendStatus::NeedsReview,
1141            ),
1142            (
1143                &b"synthetic-user"[..],
1144                &b"filehelper"[..],
1145                &b"synthetic-client"[..],
1146                &b"00000000000000000000000000000000"[..],
1147                SendStatus::NeedsReview,
1148            ),
1149        ] {
1150            let raw = response(sender, destination, client, aes);
1151            let result = decode_file_send_correlated(
1152                &raw,
1153                "synthetic-client",
1154                "synthetic-user",
1155                "filehelper",
1156                &[1; 16],
1157            )
1158            .unwrap();
1159            assert_eq!(result.status, status);
1160            assert_eq!(result.server_message_id, Some(u64::MAX.to_string()));
1161        }
1162        let rejected = p::bytes(1, &p::int32(1, -13));
1163        assert_eq!(
1164            decode_file_send_correlated(
1165                &rejected,
1166                "synthetic-client",
1167                "synthetic-user",
1168                "filehelper",
1169                &[1; 16]
1170            )
1171            .unwrap()
1172            .status,
1173            SendStatus::Rejected
1174        );
1175    }
1176    #[test]
1177    fn video_original_metadata_is_independent_and_old_plans_still_decode() {
1178        use crate::media::MediaDescriptor;
1179        let uploaded = |quality, id: &str, key: u8, size: u32, digest: &str| UploadedMedia {
1180            descriptor: MediaDescriptor {
1181                file_id: id.into(),
1182                aes_key: vec![key; 16],
1183                quality,
1184                expected_bytes: Some(u64::from(size)),
1185                expected_md5: Some(digest.into()),
1186                strict_size: true,
1187                expires_at: None,
1188            },
1189            plaintext_bytes: size,
1190            md5: digest.into(),
1191            sha256: "c".repeat(64),
1192            file_name: "synthetic.mp4".into(),
1193            width: Some(16),
1194            height: Some(12),
1195        };
1196        let mut video = UploadedVideo {
1197            video: uploaded(MediaQuality::Video, "normal-object", 1, 30, &"1".repeat(32)),
1198            thumbnail: uploaded(
1199                MediaQuality::Thumbnail,
1200                "thumbnail-object",
1201                2,
1202                20,
1203                &"2".repeat(32),
1204            ),
1205            original: None,
1206        };
1207        let mut old_plan = serde_json::to_value(&video).unwrap();
1208        old_plan.as_object_mut().unwrap().remove("original");
1209        let cold: UploadedVideo = serde_json::from_value(old_plan).unwrap();
1210        assert!(cold.original.is_none());
1211        let normal =
1212            video_send_request(&synthetic_state(), "filehelper", "client", &cold, 4).unwrap();
1213        let normal = p::decode(&normal).unwrap();
1214        for number in 48..=51 {
1215            assert!(!normal.iter().any(|field| field.number == number));
1216        }
1217        video.original = Some(uploaded(
1218            MediaQuality::Video,
1219            "raw-object",
1220            3,
1221            wechat_media::MAX_VIDEO_SOURCE_BYTES as u32,
1222            &"A".repeat(32),
1223        ));
1224        let request =
1225            video_send_request(&synthetic_state(), "filehelper", "client", &video, 4).unwrap();
1226        let fields = p::decode(&request).unwrap();
1227        assert_eq!(p::data(&fields, 16).unwrap(), b"normal-object");
1228        assert_eq!(p::data(&fields, 17).unwrap(), "01".repeat(16).as_bytes());
1229        assert_eq!(p::scalar(&fields, 8).unwrap(), 30);
1230        assert_eq!(p::data(&fields, 26).unwrap(), "1".repeat(32).as_bytes());
1231        assert_eq!(p::data(&fields, 48).unwrap(), "a".repeat(32).as_bytes());
1232        assert_eq!(p::data(&fields, 49).unwrap(), b"raw-object");
1233        assert_eq!(p::data(&fields, 50).unwrap(), "03".repeat(16).as_bytes());
1234        assert_eq!(p::scalar(&fields, 51).unwrap(), 536_870_912);
1235        let xml = local_video_xml(&video, 4).unwrap();
1236        for expected in [
1237            "cdnvideourl=\"normal-object\"",
1238            "length=\"30\"",
1239            "cdnrawvideourl=\"raw-object\"",
1240            "rawlength=\"536870912\"",
1241            "rawmd5=\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"",
1242        ] {
1243            assert!(xml.contains(expected));
1244        }
1245        assert!(xml.contains(&format!("cdnrawvideoaeskey=\"{}\"", "03".repeat(16))));
1246        for corruption in 0..4 {
1247            let mut altered = video.clone();
1248            let original = altered.original.as_mut().unwrap();
1249            match corruption {
1250                0 => original.descriptor.quality = MediaQuality::LargeFile,
1251                1 => original.descriptor.expected_md5 = Some("0".repeat(32)),
1252                2 => {
1253                    original.plaintext_bytes += 1;
1254                    original.descriptor.expected_bytes = Some(u64::from(original.plaintext_bytes));
1255                }
1256                _ => original.descriptor.expected_bytes = None,
1257            }
1258            assert!(
1259                video_send_request(&synthetic_state(), "filehelper", "client", &altered, 4)
1260                    .is_err()
1261            );
1262            assert!(local_video_xml(&altered, 4).is_err());
1263        }
1264    }
1265
1266    #[test]
1267    fn standard_only_image_leaves_original_unadvertised() {
1268        use crate::media::MediaDescriptor;
1269        let uploaded = |quality, id: &str, size: u32, md5: &str| UploadedMedia {
1270            descriptor: MediaDescriptor {
1271                file_id: id.into(),
1272                aes_key: vec![1; 16],
1273                quality,
1274                expected_bytes: Some(u64::from(size)),
1275                expected_md5: Some(md5.into()),
1276                strict_size: true,
1277                expires_at: None,
1278            },
1279            plaintext_bytes: size,
1280            md5: md5.into(),
1281            sha256: "0".repeat(64),
1282            file_name: "synthetic.jpg".into(),
1283            width: Some(16),
1284            height: Some(12),
1285        };
1286        let image = UploadedImage {
1287            original: None,
1288            standard: uploaded(MediaQuality::Standard, "standard-copy", 60, &"1".repeat(32)),
1289            thumbnail: uploaded(
1290                MediaQuality::Thumbnail,
1291                "thumbnail-copy",
1292                30,
1293                &"2".repeat(32),
1294            ),
1295        };
1296        let raw = image_send_request(&synthetic_state(), "filehelper", "client", &image).unwrap();
1297        let fields = p::decode(&raw).unwrap();
1298        assert_eq!(p::scalar(&fields, 11).unwrap(), 0);
1299        assert_eq!(p::data(&fields, 15).unwrap(), b"");
1300        assert_eq!(p::scalar(&fields, 19).unwrap(), 0);
1301        assert_eq!(p::data(&fields, 16).unwrap(), b"standard-copy");
1302        assert_eq!(p::scalar(&fields, 20).unwrap(), 60);
1303        assert_eq!(p::data(&fields, 21).unwrap(), b"thumbnail-copy");
1304        assert_eq!(p::data(&fields, 27).unwrap(), "1".repeat(32).as_bytes());
1305        let xml = local_image_xml(&image).unwrap();
1306        assert!(xml.contains("hdlength=\"0\""));
1307        assert!(xml.contains("cdnbigimgurl=\"\""));
1308        assert!(xml.contains("cdnmidimgurl=\"standard-copy\""));
1309
1310        let mut saved = serde_json::to_value(&image).unwrap();
1311        saved.as_object_mut().unwrap().remove("original");
1312        let restored: UploadedImage = serde_json::from_value(saved).unwrap();
1313        assert!(restored.original.is_none());
1314        assert_eq!(
1315            image_send_request(&synthetic_state(), "filehelper", "client", &restored).unwrap(),
1316            raw
1317        );
1318
1319        let mut original_image = image;
1320        original_image.original = Some(uploaded(
1321            MediaQuality::Original,
1322            "original-copy",
1323            90,
1324            &"0".repeat(32),
1325        ));
1326        let raw = image_send_request(&synthetic_state(), "filehelper", "client", &original_image)
1327            .unwrap();
1328        let fields = p::decode(&raw).unwrap();
1329        assert_eq!(p::scalar(&fields, 11).unwrap(), 1);
1330        assert_eq!(p::data(&fields, 15).unwrap(), b"original-copy");
1331        assert_eq!(p::scalar(&fields, 19).unwrap(), 90);
1332        assert_eq!(p::data(&fields, 27).unwrap(), "0".repeat(32).as_bytes());
1333        assert!(local_image_xml(&original_image)
1334            .unwrap()
1335            .contains("cdnbigimgurl=\"original-copy\""));
1336        for wrong_quality in [false, true] {
1337            let mut invalid = original_image.clone();
1338            let original = invalid.original.as_mut().unwrap();
1339            if wrong_quality {
1340                original.descriptor.quality = MediaQuality::Standard;
1341            } else {
1342                original.descriptor.aes_key = vec![2; 16];
1343            }
1344            assert!(
1345                image_send_request(&synthetic_state(), "filehelper", "client", &invalid).is_err()
1346            );
1347            assert!(local_image_xml(&invalid).is_err());
1348        }
1349    }
1350
1351    #[test]
1352    fn metadata_matches_independent_synthetic_wire_vectors() {
1353        use crate::media::MediaDescriptor;
1354        let state = synthetic_state();
1355        let descriptor = |quality, file_name: &str| UploadedMedia {
1356            descriptor: MediaDescriptor {
1357                file_id: "synthetic-file-id".into(),
1358                aes_key: vec![1; 16],
1359                quality,
1360                expected_bytes: Some(30),
1361                expected_md5: Some("0".repeat(32)),
1362                strict_size: true,
1363                expires_at: None,
1364            },
1365            plaintext_bytes: 30,
1366            md5: "0".repeat(32),
1367            sha256: "0".repeat(64),
1368            file_name: file_name.into(),
1369            width: Some(16),
1370            height: Some(12),
1371        };
1372        let expected: serde_json::Value =
1373            serde_json::from_str(include_str!("../fixtures/synthetic-media-wire.json")).unwrap();
1374        let file = file_send_request(
1375            &state,
1376            "filehelper",
1377            "synthetic_client_id_0001",
1378            1234567,
1379            &descriptor(MediaQuality::File, "example&.txt"),
1380        )
1381        .unwrap();
1382        assert_eq!(hex::encode(file), expected["fileHex"]);
1383        let share_xml = share_xml(
1384            "synthetic-user",
1385            "A <title> & preview",
1386            "https://example.invalid/a?x=1&y=2",
1387            Some("Description <as text>"),
1388            Some("https://example.invalid/preview.jpg"),
1389        )
1390        .unwrap();
1391        assert!(share_xml.starts_with("<appmsg "));
1392        assert!(share_xml.contains("<title>A &lt;title&gt; &amp; preview</title>"));
1393        assert!(share_xml.contains("<type>5</type>"));
1394        assert!(share_xml.contains("<url>https://example.invalid/a?x=1&amp;y=2</url>"));
1395        assert!(share_xml.ends_with("<fromusername>synthetic-user</fromusername>"));
1396        assert!(!share_xml.contains("<msg>"));
1397        let share =
1398            share_send_request(&state, "room@chatroom", "share-client", 1234567, &share_xml)
1399                .unwrap();
1400        let outer = p::decode(&share).unwrap();
1401        let app = p::decode(p::data(&outer, 2).unwrap()).unwrap();
1402        assert_eq!(p::scalar(&app, 5).unwrap(), 5);
1403        assert_eq!(p::data(&app, 4).unwrap(), b"room@chatroom");
1404        assert_eq!(p::data(&app, 6).unwrap(), share_xml.as_bytes());
1405        assert_eq!(p::scalar(&app, 7).unwrap(), 1234567);
1406        assert_eq!(p::data(&app, 8).unwrap(), b"share-client");
1407        assert!(p::optional_data(&outer, 5).unwrap().is_none()); // No file MD5 for a URL share.
1408        let image = UploadedImage {
1409            original: Some(descriptor(MediaQuality::Original, "image.jpg")),
1410            standard: descriptor(MediaQuality::Standard, "image.jpg"),
1411            thumbnail: descriptor(MediaQuality::Thumbnail, "image.jpg"),
1412        };
1413        assert_eq!(
1414            hex::encode(
1415                image_send_request(&state, "filehelper", "synthetic_client_id_0001", &image)
1416                    .unwrap()
1417            ),
1418            expected["imageHex"]
1419        );
1420        let video = UploadedVideo {
1421            video: descriptor(MediaQuality::Video, "video.mp4"),
1422            thumbnail: descriptor(MediaQuality::Thumbnail, "thumb.jpg"),
1423            original: None,
1424        };
1425        assert_eq!(
1426            hex::encode(
1427                video_send_request(&state, "filehelper", "synthetic_client_id_0001", &video, 4)
1428                    .unwrap()
1429            ),
1430            expected["videoHex"]
1431        );
1432        // A note that fits one request keeps the single end-flagged request shape.
1433        let encoded = [vec![2], b"#!SILK_V3".to_vec(), vec![0; 6]].concat();
1434        let upload = VoiceUpload::new(
1435            "filehelper",
1436            "synthetic_client_id_0001",
1437            1234567,
1438            4000,
1439            &encoded,
1440        )
1441        .unwrap();
1442        assert_eq!((upload.request_count(), upload.is_final()), (1, true));
1443        assert_eq!(
1444            hex::encode(upload.request(&state).unwrap()),
1445            expected["voiceHex"]
1446        );
1447    }
1448    fn synthetic_note(len: usize) -> Vec<u8> {
1449        let mut note = [vec![2], b"#!SILK_V3".to_vec()].concat();
1450        let mut seed = 0x2545_f491_4f6c_dd1du64;
1451        note.extend((note.len()..len).map(|_| {
1452            seed ^= seed << 13;
1453            seed ^= seed >> 7;
1454            seed ^= seed << 17;
1455            seed as u8
1456        }));
1457        note
1458    }
1459    fn voice_reply_bytes(code: i32, extra: &[Vec<u8>]) -> Vec<u8> {
1460        let mut parts = vec![p::bytes(10, &p::int32(1, code))];
1461        parts.extend_from_slice(extra);
1462        p::message(&parts).unwrap()
1463    }
1464    #[test]
1465    fn long_voice_note_uses_consecutive_ranges_of_one_client_id() {
1466        let state = synthetic_state();
1467        let client = "synthetic_voice_id";
1468        let note = synthetic_note(2 * VOICE_UPLOAD_CHUNK_BYTES + 100);
1469        let mut upload = VoiceUpload::new("filehelper", client, 1234567, 60_000, &note).unwrap();
1470        assert_eq!(upload.request_count(), 3);
1471        let mut sent = vec![];
1472        for (index, (offset, length)) in [
1473            (0, VOICE_UPLOAD_CHUNK_BYTES),
1474            (VOICE_UPLOAD_CHUNK_BYTES, VOICE_UPLOAD_CHUNK_BYTES),
1475            (2 * VOICE_UPLOAD_CHUNK_BYTES, 100),
1476        ]
1477        .into_iter()
1478        .enumerate()
1479        {
1480            let f = p::decode(&upload.request(&state).unwrap()).unwrap();
1481            assert_eq!(p::data(&f, 5).unwrap(), client.as_bytes());
1482            assert_eq!(p::scalar(&f, 3).unwrap(), offset as u64);
1483            assert_eq!(p::scalar(&f, 4).unwrap(), length as u64);
1484            assert_eq!(p::scalar(&f, 7).unwrap(), 60_000);
1485            assert_eq!(p::scalar(&f, 9).unwrap(), u64::from(index == 2));
1486            assert_eq!(p::scalar(&f, 11).unwrap(), 0);
1487            assert_eq!(p::scalar(&f, 13).unwrap(), 4);
1488            if index == 0 {
1489                assert_eq!(
1490                    p::unbuffer(p::data(&f, 18).unwrap()).unwrap(),
1491                    client.as_bytes()
1492                );
1493            } else {
1494                assert!(
1495                    p::optional_data(&f, 18).unwrap().is_none(),
1496                    "continuation range {index} repeats first-range metadata"
1497                );
1498            }
1499            // Later ranges continue the server message ID returned by the first.
1500            assert_eq!(
1501                p::optional(&f, 6).unwrap().is_some(),
1502                index > 0,
1503                "range {index}"
1504            );
1505            if index > 0 {
1506                assert_eq!(p::scalar(&f, 6).unwrap(), 77);
1507            }
1508            let data = p::unbuffer(p::data(&f, 8).unwrap()).unwrap();
1509            assert_eq!(data.len(), length);
1510            sent.extend(data);
1511            let reply = if index < 2 {
1512                voice_reply_bytes(
1513                    0,
1514                    &[
1515                        p::uint(3, offset as u64),
1516                        p::uint(4, length as u64),
1517                        p::bytes(6, client.as_bytes()),
1518                        p::uint(7, 77),
1519                        p::uint(9, 0),
1520                    ],
1521                )
1522            } else {
1523                let mut extra = vec![p::bytes(6, client.as_bytes()), p::uint(12, 9_000)];
1524                extra.extend([3, 4, 5, 7, 8, 9].map(|n| p::uint(n, 0)));
1525                voice_reply_bytes(0, &extra)
1526            };
1527            let result = upload.accept_reply(&reply).unwrap();
1528            assert_eq!(result.is_some(), index == 2);
1529            if let Some(result) = result {
1530                assert_eq!(result.status, SendStatus::ServerAccepted);
1531                assert_eq!(result.server_message_id.as_deref(), Some("9000"));
1532            }
1533        }
1534        assert_eq!(sent, note);
1535    }
1536    #[test]
1537    fn long_voice_note_partial_or_odd_replies_stop_without_acceptance() {
1538        let note = synthetic_note(2 * VOICE_UPLOAD_CHUNK_BYTES + 100);
1539        let start =
1540            || VoiceUpload::new("filehelper", "synthetic_voice_id", 1, 60_000, &note).unwrap();
1541        let progress = voice_reply_bytes(0, &[p::uint(7, 5), p::uint(9, 0)]);
1542        // Rejecting the first range leaves nothing on the server.
1543        let mut upload = start();
1544        let result = upload
1545            .accept_reply(&voice_reply_bytes(-2, &[]))
1546            .unwrap()
1547            .unwrap();
1548        assert_eq!(
1549            (result.status, result.service_code),
1550            (SendStatus::Rejected, -2)
1551        );
1552        // A later rejection follows accepted ranges and needs review.
1553        let mut upload = start();
1554        assert!(upload.accept_reply(&progress).unwrap().is_none());
1555        let result = upload
1556            .accept_reply(&voice_reply_bytes(-2, &[]))
1557            .unwrap()
1558            .unwrap();
1559        assert_eq!(result.status, SendStatus::NeedsReview);
1560        let mut upload = start();
1561        assert!(upload.accept_reply(&progress).unwrap().is_none());
1562        assert!(upload.accept_reply(&progress).unwrap().is_none());
1563        assert!(upload.is_final());
1564        let result = upload
1565            .accept_reply(&voice_reply_bytes(-2, &[]))
1566            .unwrap()
1567            .unwrap();
1568        assert_eq!(result.status, SendStatus::NeedsReview);
1569        // An early end flag or a changed server message ID is an uncertain error.
1570        let mut upload = start();
1571        assert!(upload
1572            .accept_reply(&voice_reply_bytes(0, &[p::uint(9, 1)]))
1573            .is_err());
1574        let mut upload = start();
1575        assert!(upload.accept_reply(&progress).unwrap().is_none());
1576        assert!(upload
1577            .accept_reply(&voice_reply_bytes(0, &[p::uint(7, 6)]))
1578            .is_err());
1579        // A final ID that differs from one announced earlier needs review.
1580        let mut upload = start();
1581        let early_id = voice_reply_bytes(0, &[p::uint(12, 41)]);
1582        assert!(upload.accept_reply(&early_id).unwrap().is_none());
1583        assert!(upload.accept_reply(&early_id).unwrap().is_none());
1584        let mut extra = vec![p::bytes(6, b"synthetic_voice_id"), p::uint(12, 42)];
1585        extra.extend([3, 4, 5, 7, 8, 9].map(|n| p::uint(n, 0)));
1586        let result = upload
1587            .accept_reply(&voice_reply_bytes(0, &extra))
1588            .unwrap()
1589            .unwrap();
1590        assert_eq!(result.status, SendStatus::NeedsReview);
1591    }
1592    #[test]
1593    fn voice_note_bounds_follow_the_sixty_second_profile() {
1594        let note = synthetic_note(silk::MAX_NOTE_BYTES);
1595        assert!(VoiceUpload::new("filehelper", "synthetic_voice_id", 1, 60_000, &note).is_ok());
1596        assert!(VoiceUpload::new("filehelper", "synthetic_voice_id", 1, 60_001, &note).is_err());
1597        let oversized = synthetic_note(silk::MAX_NOTE_BYTES + 1);
1598        assert!(
1599            VoiceUpload::new("filehelper", "synthetic_voice_id", 1, 60_000, &oversized).is_err()
1600        );
1601        assert!(local_voice_xml(silk::MAX_NOTE_BYTES, 60_000).is_ok());
1602        assert!(local_voice_xml(silk::MAX_NOTE_BYTES + 1, 60_000).is_err());
1603        assert!(local_voice_xml(1000, 60_001).is_err());
1604        assert!(local_voice_xml(1000, 0).is_err());
1605    }
1606    #[test]
1607    fn largest_voice_request_fits_one_short_link_record() {
1608        // Worst case: longest accepted identities, a full incompressible range,
1609        // either packet mode and the longest host name the route can carry.
1610        let mut state = synthetic_state();
1611        state.own_username = "u".repeat(256);
1612        let destination = "d".repeat(512);
1613        let client = "c".repeat(128);
1614        let note = synthetic_note(silk::MAX_NOTE_BYTES);
1615        let upload = VoiceUpload::new(&destination, &client, u32::MAX, 60_000, &note).unwrap();
1616        let request = upload.request(&state).unwrap();
1617        let path = b"/cgi-bin/micromsg-bin/uploadvoice";
1618        for keys in [vec![], vec![2; 24]] {
1619            state.request_key = keys.clone();
1620            state.response_key = keys;
1621            let packet = crate::business::AuthenticatedPacket::prepare(&state, 127, &request)
1622                .unwrap()
1623                .packet
1624                .clone();
1625            let route = crate::mmtls::section(
1626                &[
1627                    (path.len() as u16).to_be_bytes().as_slice(),
1628                    path,
1629                    &253u16.to_be_bytes(),
1630                    &[b'h'; 253],
1631                    &crate::mmtls::section(&packet),
1632                ]
1633                .concat(),
1634            );
1635            assert!(route.len() <= 65519, "{}", route.len());
1636            assert!(crate::mmtls::seal(0x17, &route, &[0; 16], &[0; 12], 2).is_ok());
1637        }
1638    }
1639    #[test]
1640    fn voice_response_needs_unique_correlation() {
1641        let mut parts = vec![p::bytes(10, &p::uint(1, 0)), p::uint(12, u64::MAX)];
1642        for n in [3, 4, 5, 7, 8, 9] {
1643            parts.push(p::uint(n, 0));
1644        }
1645        let no_echo = p::message(&parts).unwrap();
1646        assert_eq!(
1647            decode_voice_send(&no_echo, "synthetic_voice_id")
1648                .unwrap()
1649                .status,
1650            SendStatus::NeedsReview
1651        );
1652        parts.push(p::bytes(6, b"synthetic_voice_id"));
1653        let result = decode_voice_send(&p::message(&parts).unwrap(), "synthetic_voice_id").unwrap();
1654        assert_eq!(result.status, SendStatus::ServerAccepted);
1655        assert_eq!(result.server_message_id, Some(u64::MAX.to_string()));
1656        parts.push(p::bytes(2, b"synthetic_voice_id"));
1657        assert_eq!(
1658            decode_voice_send(&p::message(&parts).unwrap(), "synthetic_voice_id")
1659                .unwrap()
1660                .status,
1661            SendStatus::NeedsReview
1662        );
1663    }
1664    #[test]
1665    fn xml_escapes_filename_and_rejects_paths() {
1666        use crate::media::MediaDescriptor;
1667        let mut upload = UploadedMedia {
1668            descriptor: MediaDescriptor {
1669                file_id: "synthetic-file-id".into(),
1670                aes_key: vec![1; 16],
1671                quality: MediaQuality::File,
1672                expected_bytes: Some(3),
1673                expected_md5: Some("0".repeat(32)),
1674                strict_size: true,
1675                expires_at: None,
1676            },
1677            plaintext_bytes: 3,
1678            md5: "0".repeat(32),
1679            sha256: "0".repeat(64),
1680            file_name: "test&<.txt".into(),
1681            width: None,
1682            height: None,
1683        };
1684        let xml = file_xml("synthetic-user", &upload).unwrap();
1685        assert!(xml.contains("test&amp;&lt;.txt"));
1686        upload.file_name = "../secret".into();
1687        assert!(file_xml("synthetic-user", &upload).is_err());
1688    }
1689    #[test]
1690    fn rejected_response_does_not_require_success_fields() {
1691        let reply = p::bytes(1, &p::int32(1, -2));
1692        assert_eq!(
1693            decode_file_send(&reply, "client").unwrap().status,
1694            SendStatus::Rejected
1695        );
1696    }
1697}