Skip to main content

wechat_protocol/
sticker_send.rs

1//! Single-intent sticker sends with a probe and bounded byte continuations.
2use crate::{protobuf as p, AccountState};
3use anyhow::{ensure, Context, Result};
4
5/// Maximum native byte continuation; the initial probe has a present empty buffer.
6pub const STICKER_SEND_CHUNK: usize = 8192;
7/// Journaled request identity and bytes, shared by the probe and all continuations.
8pub struct StickerSendChunk<'a> {
9    /// Lowercase original GIF MD5.
10    pub id: &'a str,
11    /// Intended chat identity.
12    pub recipient: &'a str,
13    /// Unique durable per-send identity, never a product ID.
14    pub client_id: &'a str,
15    /// Complete owned source; its length is the request total.
16    pub source: &'a [u8],
17    /// Acknowledged source offset.
18    pub offset: u32,
19    /// Initial empty probe; only valid at offset zero.
20    pub probe: bool,
21}
22/// Encode a type-2 send after the caller validates the complete GIF and MD5.
23/// Field4 is a nested buffer, not raw bytes; no source rehash occurs per chunk.
24pub fn sticker_send_request(state: &AccountState, chunk: &StickerSendChunk<'_>) -> Result<Vec<u8>> {
25    sticker_send_body(
26        &crate::wire::base_request(&state.device, state.uin, 0)?,
27        chunk,
28    )
29}
30fn sticker_send_body(base: &[u8], chunk: &StickerSendChunk<'_>) -> Result<Vec<u8>> {
31    ensure!(
32        chunk.id.len() == 32
33            && chunk.id.bytes().all(|b| b.is_ascii_hexdigit())
34            && !chunk.source.is_empty()
35            && chunk.source.len() <= 16 * 1024 * 1024
36            && (chunk.offset as usize) < chunk.source.len()
37            && (!chunk.probe || chunk.offset == 0),
38        "invalid_sticker_send_source"
39    );
40    for value in [chunk.recipient, chunk.client_id] {
41        ensure!(
42            !value.is_empty() && value.len() <= 512 && !value.chars().any(char::is_control),
43            "invalid_sticker_send_identity"
44        );
45    }
46    let offset = chunk.offset as usize;
47    let bytes = if chunk.probe {
48        &[][..]
49    } else {
50        &chunk.source[offset..(offset + STICKER_SEND_CHUNK).min(chunk.source.len())]
51    };
52    let item = p::message(&[
53        p::bytes(1, chunk.id.as_bytes()),
54        p::int32(2, chunk.offset as i32),
55        p::int32(3, chunk.source.len() as i32),
56        p::bytes(4, &p::buffer(bytes)),
57        p::int32(5, 2),
58        p::bytes(6, chunk.recipient.as_bytes()),
59        p::bytes(7, b"<gameext type=\"0\" content=\"0\" ></gameext>"),
60        p::bytes(9, chunk.client_id.as_bytes()),
61    ])?;
62    p::message(&[p::bytes(1, base), p::int32(2, 1), p::bytes(3, &item)])
63}
64/// Validated progress. A server ID alone does not establish final acceptance.
65pub struct StickerSendAcknowledgement {
66    /// Exact acknowledged next offset within this owned source.
67    pub next_offset: u32,
68    /// Nonzero 64-bit server identity, required on the complete acknowledgement.
69    pub server_id: Option<String>,
70}
71/// Validate cardinality, returns, identity, total and source range correlation.
72/// Retain raw bytes before calling. A decoding failure leaves submission uncertain.
73pub fn decode_sticker_send_acknowledgement(
74    raw: &[u8],
75    chunk: &StickerSendChunk<'_>,
76) -> Result<StickerSendAcknowledgement> {
77    let fields = p::decode(raw)?;
78    ensure!(p::base_code(&fields)? == 0, "sticker_send_rejected");
79    ensure!(
80        p::scalar(&fields, 2)? == 1 && fields.iter().filter(|f| f.number == 3).count() == 1,
81        "sticker_send_reply_mismatch"
82    );
83    let item = p::decode(p::data(&fields, 3)?)?;
84    ensure!(p::scalar(&item, 1)? == 0, "sticker_send_rejected");
85    let next = u32::try_from(p::scalar(&item, 2)?)?;
86    let total = u32::try_from(p::scalar(&item, 3)?)?;
87    let identity = std::str::from_utf8(p::data(&item, 4)?)?;
88    let _legacy = u32::try_from(p::scalar(&item, 5)?)?;
89    ensure!(
90        identity.eq_ignore_ascii_case(chunk.id)
91            && total as usize == chunk.source.len()
92            && next <= total
93            && next >= chunk.offset,
94        "sticker_send_reply_mismatch"
95    );
96    if !chunk.probe {
97        ensure!(
98            next > chunk.offset
99                && next as usize
100                    <= (chunk.offset as usize + STICKER_SEND_CHUNK).min(chunk.source.len()),
101            "sticker_send_reply_mismatch"
102        );
103    }
104    let server_id = match p::optional(&item, 6)? {
105        Some(p::Value::Varint(id)) if *id > 0 => Some(id.to_string()),
106        None | Some(p::Value::Varint(0)) => None,
107        _ => anyhow::bail!("sticker_send_reply_mismatch"),
108    };
109    if next == total {
110        server_id
111            .as_ref()
112            .context("sticker_send_final_id_missing")?;
113    }
114    Ok(StickerSendAcknowledgement {
115        next_offset: next,
116        server_id,
117    })
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    #[test]
124    fn independently_encoded_probe_and_final_match_field_boundaries() {
125        let base = hex::decode("0a0010011a0664657669636520012a056c696e75783000").unwrap();
126        let mut chunk = StickerSendChunk {
127            id: "900150983cd24fb0d6963f7d28e17f72",
128            recipient: "peer",
129            client_id: "intent-1",
130            source: b"abc",
131            offset: 0,
132            probe: true,
133        };
134        assert_eq!(hex::encode(sticker_send_body(&base,&chunk).unwrap()),"0a170a0010011a0664657669636520012a056c696e7578300010011a690a2039303031353039383363643234666230643639363366376432386531376637321000180322040800120028023204706565723a293c67616d6565787420747970653d22302220636f6e74656e743d223022203e3c2f67616d656578743e4a08696e74656e742d31");
135        chunk.probe = false;
136        assert_eq!(hex::encode(sticker_send_body(&base,&chunk).unwrap()),"0a170a0010011a0664657669636520012a056c696e7578300010011a6c0a2039303031353039383363643234666230643639363366376432386531376637321000180322070803120361626328023204706565723a293c67616d6565787420747970653d22302220636f6e74656e743d223022203e3c2f67616d656578743e4a08696e74656e742d31");
137    }
138    #[test]
139    fn incomplete_progress_is_not_acceptance_and_ranges_cannot_fast_forward() {
140        let source = vec![b'a'; 8193];
141        let mut chunk = StickerSendChunk {
142            id: "b7652d9bca37038c342cc0c492dd70f9",
143            recipient: "peer",
144            client_id: "intent-1",
145            source: &source,
146            offset: 0,
147            probe: true,
148        };
149        let reply = |next, server| {
150            p::message(&[
151                p::bytes(1, &p::int32(1, 0)),
152                p::int32(2, 1),
153                p::bytes(
154                    3,
155                    &p::message(&[
156                        p::int32(1, 0),
157                        p::uint(2, next),
158                        p::uint(3, 8193),
159                        p::bytes(4, chunk.id.as_bytes()),
160                        p::uint(5, 1),
161                        p::uint(6, server),
162                    ])
163                    .unwrap(),
164                ),
165            ])
166            .unwrap()
167        };
168        assert_eq!(
169            decode_sticker_send_acknowledgement(&reply(0, 42), &chunk)
170                .unwrap()
171                .next_offset,
172            0
173        );
174        chunk.probe = false;
175        assert!(decode_sticker_send_acknowledgement(&reply(8193, 42), &chunk).is_err());
176        assert_eq!(
177            decode_sticker_send_acknowledgement(&reply(8192, 42), &chunk)
178                .unwrap()
179                .next_offset,
180            8192
181        );
182        chunk.offset = 8192;
183        assert!(decode_sticker_send_acknowledgement(&reply(8193, 0), &chunk).is_err());
184        assert_eq!(
185            decode_sticker_send_acknowledgement(&reply(8193, u64::MAX), &chunk)
186                .unwrap()
187                .server_id
188                .as_deref(),
189            Some("18446744073709551615")
190        );
191    }
192}