Skip to main content

wechat_protocol/
push.rs

1//! Persistent authenticated incoming notifications. The outer longlink command
2//! is distinct from the encrypted business CGI: heartbeat 238/518, sync 121/138.
3use crate::{
4    business::AuthenticatedPacket,
5    mmtls::{Longlink, Session},
6    wire, AccountState,
7};
8use anyhow::{ensure, Result};
9use std::collections::VecDeque;
10use std::time::{Duration, Instant};
11
12const REPLY_OFFSET: u32 = 1_000_000_000;
13const NOOP: u32 = 6;
14const NOOP_SEQUENCE: u32 = u32::MAX;
15const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(30);
16const KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(15);
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub struct Notification {
20    pub command: u32,
21    pub selector: u32,
22}
23
24/// Unknown commands are retained as transport traffic, not interpreted as sync
25/// work. Command 24 has a four-byte big-endian selector, not protobuf data.
26fn notification(packet: &Longlink) -> Result<Option<Notification>> {
27    if packet.sequence != 0 {
28        return Ok(None);
29    }
30    if packet.command == 356 {
31        use crate::protobuf as p;
32        ensure!(
33            packet.payload.len() <= 128 * 1024,
34            "Contact hint exceeds limit"
35        );
36        let fields = p::decode(&packet.payload)?;
37        if p::scalar(&fields, 2)? != 11 {
38            return Ok(None);
39        }
40        let notice = p::decode(p::data(&fields, 3)?)?;
41        if p::scalar(&notice, 1)? != 2048 {
42            return Ok(None);
43        }
44        // Some namespace notices have no selector payload. They do not match
45        // the mapped contact hint and must not interrupt an in-flight reply.
46        let Some(raw_selectors) = p::optional_data(&notice, 2)? else {
47            return Ok(None);
48        };
49        let selectors = p::decode(raw_selectors)?;
50        if p::optional(&selectors, 1)?.is_none() {
51            return Ok(None);
52        }
53        let selector = u32::try_from(p::scalar(&selectors, 1)?)?;
54        // Contact notices vary their high selector bits with the kind of
55        // change: a phone mute toggle carried 0x20004 and a phone remark edit
56        // 0x4000004. Any notice sharing a contact-sync bit asks for the same
57        // contactsync drain; the drain itself still uses CONTACT_SELECTOR.
58        let contact_bits = crate::contact_sync::CONTACT_SELECTOR as u32;
59        return Ok((selector & contact_bits != 0).then_some(Notification {
60            command: 356,
61            selector,
62        }));
63    }
64    if packet.command != 24 {
65        return Ok(None);
66    }
67    ensure!(packet.payload.len() == 4, "Invalid native push selector");
68    let selector = u32::from_be_bytes(packet.payload.as_slice().try_into()?);
69    Ok((selector & 7 != 0).then_some(Notification {
70        command: 24,
71        selector,
72    }))
73}
74
75#[derive(Default)]
76struct Inbox {
77    pending: VecDeque<Notification>,
78    noop_sent: Option<Instant>,
79}
80impl Inbox {
81    fn observe(&mut self, packet: &Longlink) -> Result<()> {
82        if packet.command == NOOP + REPLY_OFFSET && packet.sequence == NOOP_SEQUENCE {
83            ensure!(packet.payload.is_empty(), "Invalid keepalive reply");
84            self.noop_sent = None;
85        } else if let Some(next) = notification(packet)? {
86            // Repeated notifications announce work; they are not message IDs.
87            // Coalesce them while a business response is in flight.
88            match self
89                .pending
90                .iter_mut()
91                .find(|prior| prior.command == next.command)
92            {
93                Some(prior) => prior.selector |= next.selector,
94                None => self.pending.push_back(next),
95            }
96        }
97        Ok(())
98    }
99}
100
101pub(crate) struct Connection {
102    session: Session,
103    timeout: Duration,
104    sequence: u32,
105    last_keepalive: Instant,
106    inbox: Inbox,
107}
108impl Connection {
109    pub(crate) fn open(
110        state: &AccountState,
111        timeout: Duration,
112        receive_budget: usize,
113    ) -> Result<Self> {
114        state.validate()?;
115        Ok(Self {
116            session: Session::connect(&state.long_host, timeout, receive_budget)?,
117            timeout,
118            sequence: 1,
119            last_keepalive: Instant::now(),
120            inbox: Inbox::default(),
121        })
122    }
123    fn keepalive(&mut self) -> Result<()> {
124        let now = Instant::now();
125        ensure!(
126            self.inbox
127                .noop_sent
128                .is_none_or(|sent| now.duration_since(sent) < KEEPALIVE_TIMEOUT),
129            "Native keepalive timed out"
130        );
131        if now.duration_since(self.last_keepalive) >= KEEPALIVE_INTERVAL
132            && self.inbox.noop_sent.is_none()
133        {
134            self.session.send_application(NOOP, NOOP_SEQUENCE, &[])?;
135            self.inbox.noop_sent = Some(now);
136            self.last_keepalive = now;
137        }
138        Ok(())
139    }
140    fn rpc(
141        &mut self,
142        state: &mut AccountState,
143        cgi: u16,
144        command: u32,
145        plain: &[u8],
146        before_submit: impl FnOnce() -> Result<()>,
147    ) -> Result<Vec<u8>> {
148        self.keepalive()?;
149        let sequence = self.sequence;
150        self.sequence = self
151            .sequence
152            .checked_add(1)
153            .filter(|next| *next != NOOP_SEQUENCE)
154            .ok_or_else(|| anyhow::anyhow!("Longlink sequence exhausted"))?;
155        let packet = AuthenticatedPacket::prepare(state, cgi, plain)?;
156        before_submit()?;
157        self.session
158            .send_application(command, sequence, &packet.packet)?;
159        let deadline = Instant::now() + self.timeout;
160        for _ in 0..64 {
161            let remaining = deadline.saturating_duration_since(Instant::now());
162            ensure!(!remaining.is_zero(), "Native longlink response timed out");
163            let reply = self
164                .session
165                .poll_application(remaining)?
166                .ok_or_else(|| anyhow::anyhow!("Native longlink response timed out"))?;
167            if reply.sequence != sequence {
168                self.inbox.observe(&reply)?;
169                continue;
170            }
171            ensure!(
172                reply.command == command + REPLY_OFFSET,
173                "Unexpected longlink response command"
174            );
175            let (plain, cookie) = packet.decode_verified_transport_reply(&reply.payload)?;
176            if !cookie.is_empty() {
177                state.cookie = cookie;
178            }
179            return Ok(plain);
180        }
181        anyhow::bail!("Native longlink response frame limit")
182    }
183    /// Also associates the authenticated account with this persistent socket.
184    pub(crate) fn heartbeat_guarded(
185        &mut self,
186        state: &mut AccountState,
187        cursor: &[u8],
188        before_submit: impl FnOnce() -> Result<()>,
189    ) -> Result<wire::Heartbeat> {
190        let request = wire::heartbeat_request(state, cursor)?;
191        wire::decode_heartbeat(&self.rpc(state, 518, 238, &request, before_submit)?)
192    }
193
194    /// One sticker piece (CGI 175) on the long link, which the official client
195    /// prefers over the short link while connected. Notifications that arrive
196    /// before the reply stay queued for [`Self::poll`].
197    pub(crate) fn sticker_chunk_guarded(
198        &mut self,
199        state: &mut AccountState,
200        chunk: &crate::sticker_send::StickerSendChunk<'_>,
201        before_submit: impl FnOnce() -> Result<()>,
202    ) -> Result<Vec<u8>> {
203        let request = crate::sticker_send::sticker_send_request(state, chunk)?;
204        self.rpc(state, 175, 68, &request, before_submit)
205    }
206
207    pub(crate) fn sync_guarded(
208        &mut self,
209        state: &mut AccountState,
210        cursor: &[u8],
211        scene: u32,
212        before_submit: impl FnOnce() -> Result<()>,
213    ) -> Result<wire::SyncBatch> {
214        ensure!([1, 6, 7].contains(&scene), "Unsupported sync scene");
215        let sent = if cursor.is_empty() { &[0][..] } else { cursor };
216        let request = wire::sync_request(sent, &state.device.device_type, scene)?;
217        wire::decode_sync(&self.rpc(state, 138, 121, &request, before_submit)?, cursor)
218    }
219    /// Waiting owns no account mutation lock. The caller rechecks its credential
220    /// and logout fences under that lock before acting on a notification.
221    pub fn poll(&mut self, timeout: Duration) -> Result<Option<Notification>> {
222        self.keepalive()?;
223        if !self.inbox.pending.is_empty() {
224            return Ok(self.inbox.pending.pop_front());
225        }
226        let deadline = Instant::now() + timeout;
227        for _ in 0..64 {
228            let remaining = deadline.saturating_duration_since(Instant::now());
229            if remaining.is_zero() {
230                return Ok(None);
231            }
232            let Some(packet) = self.session.poll_application(remaining)? else {
233                return Ok(None);
234            };
235            self.inbox.observe(&packet)?;
236            if !self.inbox.pending.is_empty() {
237                return Ok(self.inbox.pending.pop_front());
238            }
239        }
240        anyhow::bail!("Native notification frame limit")
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247    fn push(sequence: u32, selector: &[u8]) -> Longlink {
248        Longlink {
249            command: 24,
250            sequence,
251            payload: selector.to_vec(),
252        }
253    }
254    #[test]
255    fn selectors_are_strict_big_endian_work_hints() {
256        assert_eq!(
257            notification(&push(0, &6u32.to_be_bytes())).unwrap(),
258            Some(Notification {
259                command: 24,
260                selector: 6
261            })
262        );
263        assert!(notification(&push(0, &8u32.to_be_bytes()))
264            .unwrap()
265            .is_none());
266        assert!(notification(&push(12, &6u32.to_be_bytes()))
267            .unwrap()
268            .is_none());
269        for invalid in [&[][..], &[6][..], &[0, 0, 6][..], &[0; 5][..]] {
270            assert!(notification(&push(0, invalid)).is_err());
271        }
272    }
273    #[test]
274    fn unmapped_contact_notices_without_selectors_leave_the_inbox_intact() {
275        use crate::protobuf as p;
276        let mut inbox = Inbox::default();
277        inbox.observe(&push(0, &2u32.to_be_bytes())).unwrap();
278        for notice in [
279            p::uint(1, 2048),
280            p::message(&[p::uint(1, 2048), p::bytes(2, b"")]).unwrap(),
281        ] {
282            inbox
283                .observe(&Longlink {
284                    command: 356,
285                    sequence: 0,
286                    payload: p::message(&[p::uint(2, 11), p::bytes(3, &notice)]).unwrap(),
287                })
288                .unwrap();
289        }
290        assert_eq!(
291            inbox.pending.pop_front().unwrap(),
292            Notification {
293                command: 24,
294                selector: 2
295            }
296        );
297        assert!(inbox.pending.is_empty());
298    }
299    #[test]
300    fn contact_notices_with_other_contact_selector_bits_request_a_drain() {
301        use crate::protobuf as p;
302        let notice = |selector: u64| Longlink {
303            command: 356,
304            sequence: 0,
305            payload: p::message(&[
306                p::uint(2, 11),
307                p::bytes(
308                    3,
309                    &p::message(&[p::uint(1, 2048), p::bytes(2, &p::uint(1, selector))]).unwrap(),
310                ),
311            ])
312            .unwrap(),
313        };
314        for selector in [0x20004, 0x4000004, 0x20000] {
315            assert_eq!(
316                notification(&notice(selector)).unwrap(),
317                Some(Notification {
318                    command: 356,
319                    selector: selector as u32
320                })
321            );
322        }
323        for selector in [0, 0x8, 0x4000000] {
324            assert_eq!(notification(&notice(selector)).unwrap(), None);
325        }
326    }
327    #[test]
328    fn contact_hint_coalesces_separately_from_message_work() {
329        use crate::protobuf as p;
330        let hint = Longlink {
331            command: 356,
332            sequence: 0,
333            payload: p::message(&[
334                p::bytes(1, b"opaque"),
335                p::uint(2, 11),
336                p::bytes(
337                    3,
338                    &p::message(&[
339                        p::uint(1, 2048),
340                        p::bytes(2, &p::uint(1, crate::contact_sync::CONTACT_SELECTOR)),
341                    ])
342                    .unwrap(),
343                ),
344            ])
345            .unwrap(),
346        };
347        let mut inbox = Inbox::default();
348        inbox.observe(&push(0, &2u32.to_be_bytes())).unwrap();
349        inbox.observe(&hint).unwrap();
350        inbox.observe(&push(0, &4u32.to_be_bytes())).unwrap();
351        inbox.observe(&hint).unwrap();
352        assert_eq!(inbox.pending.len(), 2);
353        assert_eq!(
354            inbox.pending.pop_front().unwrap(),
355            Notification {
356                command: 24,
357                selector: 6
358            }
359        );
360        assert_eq!(
361            inbox.pending.pop_front().unwrap(),
362            Notification {
363                command: 356,
364                selector: 0x20004
365            }
366        );
367        let mut malformed = hint;
368        malformed.payload = p::message(&[p::uint(2, 11), p::bytes(3, b"invalid")]).unwrap();
369        assert!(notification(&malformed).is_err());
370    }
371    #[test]
372    fn interleaved_pushes_coalesce_without_confusing_keepalive_or_unknown_commands() {
373        let mut inbox = Inbox {
374            noop_sent: Some(Instant::now()),
375            ..Default::default()
376        };
377        inbox.observe(&push(0, &2u32.to_be_bytes())).unwrap();
378        inbox
379            .observe(&Longlink {
380                command: REPLY_OFFSET + NOOP,
381                sequence: NOOP_SEQUENCE,
382                payload: vec![],
383            })
384            .unwrap();
385        inbox
386            .observe(&Longlink {
387                command: 912,
388                sequence: 0,
389                payload: vec![1, 2, 3],
390            })
391            .unwrap();
392        inbox.observe(&push(0, &4u32.to_be_bytes())).unwrap();
393        assert!(inbox.noop_sent.is_none());
394        assert_eq!(inbox.pending.pop_front().unwrap().selector, 6);
395        assert!(inbox.pending.is_empty());
396        assert!(inbox
397            .observe(&Longlink {
398                command: REPLY_OFFSET + NOOP,
399                sequence: NOOP_SEQUENCE,
400                payload: vec![1]
401            })
402            .is_err());
403    }
404}