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        return Ok(
55            (selector == crate::contact_sync::CONTACT_SELECTOR as u32).then_some(Notification {
56                command: 356,
57                selector,
58            }),
59        );
60    }
61    if packet.command != 24 {
62        return Ok(None);
63    }
64    ensure!(packet.payload.len() == 4, "Invalid native push selector");
65    let selector = u32::from_be_bytes(packet.payload.as_slice().try_into()?);
66    Ok((selector & 7 != 0).then_some(Notification {
67        command: 24,
68        selector,
69    }))
70}
71
72#[derive(Default)]
73struct Inbox {
74    pending: VecDeque<Notification>,
75    noop_sent: Option<Instant>,
76}
77impl Inbox {
78    fn observe(&mut self, packet: &Longlink) -> Result<()> {
79        if packet.command == NOOP + REPLY_OFFSET && packet.sequence == NOOP_SEQUENCE {
80            ensure!(packet.payload.is_empty(), "Invalid keepalive reply");
81            self.noop_sent = None;
82        } else if let Some(next) = notification(packet)? {
83            // Repeated notifications announce work; they are not message IDs.
84            // Coalesce them while a business response is in flight.
85            match self
86                .pending
87                .iter_mut()
88                .find(|prior| prior.command == next.command)
89            {
90                Some(prior) => prior.selector |= next.selector,
91                None => self.pending.push_back(next),
92            }
93        }
94        Ok(())
95    }
96}
97
98pub(crate) struct Connection {
99    session: Session,
100    timeout: Duration,
101    sequence: u32,
102    last_keepalive: Instant,
103    inbox: Inbox,
104}
105impl Connection {
106    pub(crate) fn open(
107        state: &AccountState,
108        timeout: Duration,
109        receive_budget: usize,
110    ) -> Result<Self> {
111        state.validate()?;
112        Ok(Self {
113            session: Session::connect(&state.long_host, timeout, receive_budget)?,
114            timeout,
115            sequence: 1,
116            last_keepalive: Instant::now(),
117            inbox: Inbox::default(),
118        })
119    }
120    fn keepalive(&mut self) -> Result<()> {
121        let now = Instant::now();
122        ensure!(
123            self.inbox
124                .noop_sent
125                .is_none_or(|sent| now.duration_since(sent) < KEEPALIVE_TIMEOUT),
126            "Native keepalive timed out"
127        );
128        if now.duration_since(self.last_keepalive) >= KEEPALIVE_INTERVAL
129            && self.inbox.noop_sent.is_none()
130        {
131            self.session.send_application(NOOP, NOOP_SEQUENCE, &[])?;
132            self.inbox.noop_sent = Some(now);
133            self.last_keepalive = now;
134        }
135        Ok(())
136    }
137    fn rpc(
138        &mut self,
139        state: &mut AccountState,
140        cgi: u16,
141        command: u32,
142        plain: &[u8],
143        before_submit: impl FnOnce() -> Result<()>,
144    ) -> Result<Vec<u8>> {
145        self.keepalive()?;
146        let sequence = self.sequence;
147        self.sequence = self
148            .sequence
149            .checked_add(1)
150            .filter(|next| *next != NOOP_SEQUENCE)
151            .ok_or_else(|| anyhow::anyhow!("Longlink sequence exhausted"))?;
152        let packet = AuthenticatedPacket::prepare(state, cgi, plain)?;
153        before_submit()?;
154        self.session
155            .send_application(command, sequence, &packet.packet)?;
156        let deadline = Instant::now() + self.timeout;
157        for _ in 0..64 {
158            let remaining = deadline.saturating_duration_since(Instant::now());
159            ensure!(!remaining.is_zero(), "Native longlink response timed out");
160            let reply = self
161                .session
162                .poll_application(remaining)?
163                .ok_or_else(|| anyhow::anyhow!("Native longlink response timed out"))?;
164            if reply.sequence != sequence {
165                self.inbox.observe(&reply)?;
166                continue;
167            }
168            ensure!(
169                reply.command == command + REPLY_OFFSET,
170                "Unexpected longlink response command"
171            );
172            let (plain, cookie) = packet.decode_verified_transport_reply(&reply.payload)?;
173            if !cookie.is_empty() {
174                state.cookie = cookie;
175            }
176            return Ok(plain);
177        }
178        anyhow::bail!("Native longlink response frame limit")
179    }
180    /// Also associates the authenticated account with this persistent socket.
181    pub(crate) fn heartbeat_guarded(
182        &mut self,
183        state: &mut AccountState,
184        cursor: &[u8],
185        before_submit: impl FnOnce() -> Result<()>,
186    ) -> Result<wire::Heartbeat> {
187        let request = wire::heartbeat_request(state, cursor)?;
188        wire::decode_heartbeat(&self.rpc(state, 518, 238, &request, before_submit)?)
189    }
190
191    /// One sticker piece (CGI 175) on the long link, which the official client
192    /// prefers over the short link while connected. Notifications that arrive
193    /// before the reply stay queued for [`Self::poll`].
194    pub(crate) fn sticker_chunk_guarded(
195        &mut self,
196        state: &mut AccountState,
197        chunk: &crate::sticker_send::StickerSendChunk<'_>,
198        before_submit: impl FnOnce() -> Result<()>,
199    ) -> Result<Vec<u8>> {
200        let request = crate::sticker_send::sticker_send_request(state, chunk)?;
201        self.rpc(state, 175, 68, &request, before_submit)
202    }
203
204    pub(crate) fn sync_guarded(
205        &mut self,
206        state: &mut AccountState,
207        cursor: &[u8],
208        scene: u32,
209        before_submit: impl FnOnce() -> Result<()>,
210    ) -> Result<wire::SyncBatch> {
211        ensure!([1, 6, 7].contains(&scene), "Unsupported sync scene");
212        let sent = if cursor.is_empty() { &[0][..] } else { cursor };
213        let request = wire::sync_request(sent, &state.device.device_type, scene)?;
214        wire::decode_sync(&self.rpc(state, 138, 121, &request, before_submit)?, cursor)
215    }
216    /// Waiting owns no account mutation lock. The caller rechecks its credential
217    /// and logout fences under that lock before acting on a notification.
218    pub fn poll(&mut self, timeout: Duration) -> Result<Option<Notification>> {
219        self.keepalive()?;
220        if !self.inbox.pending.is_empty() {
221            return Ok(self.inbox.pending.pop_front());
222        }
223        let deadline = Instant::now() + timeout;
224        for _ in 0..64 {
225            let remaining = deadline.saturating_duration_since(Instant::now());
226            if remaining.is_zero() {
227                return Ok(None);
228            }
229            let Some(packet) = self.session.poll_application(remaining)? else {
230                return Ok(None);
231            };
232            self.inbox.observe(&packet)?;
233            if !self.inbox.pending.is_empty() {
234                return Ok(self.inbox.pending.pop_front());
235            }
236        }
237        anyhow::bail!("Native notification frame limit")
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244    fn push(sequence: u32, selector: &[u8]) -> Longlink {
245        Longlink {
246            command: 24,
247            sequence,
248            payload: selector.to_vec(),
249        }
250    }
251    #[test]
252    fn selectors_are_strict_big_endian_work_hints() {
253        assert_eq!(
254            notification(&push(0, &6u32.to_be_bytes())).unwrap(),
255            Some(Notification {
256                command: 24,
257                selector: 6
258            })
259        );
260        assert!(notification(&push(0, &8u32.to_be_bytes()))
261            .unwrap()
262            .is_none());
263        assert!(notification(&push(12, &6u32.to_be_bytes()))
264            .unwrap()
265            .is_none());
266        for invalid in [&[][..], &[6][..], &[0, 0, 6][..], &[0; 5][..]] {
267            assert!(notification(&push(0, invalid)).is_err());
268        }
269    }
270    #[test]
271    fn unmapped_contact_notices_without_selectors_leave_the_inbox_intact() {
272        use crate::protobuf as p;
273        let mut inbox = Inbox::default();
274        inbox.observe(&push(0, &2u32.to_be_bytes())).unwrap();
275        for notice in [
276            p::uint(1, 2048),
277            p::message(&[p::uint(1, 2048), p::bytes(2, b"")]).unwrap(),
278        ] {
279            inbox
280                .observe(&Longlink {
281                    command: 356,
282                    sequence: 0,
283                    payload: p::message(&[p::uint(2, 11), p::bytes(3, &notice)]).unwrap(),
284                })
285                .unwrap();
286        }
287        assert_eq!(
288            inbox.pending.pop_front().unwrap(),
289            Notification {
290                command: 24,
291                selector: 2
292            }
293        );
294        assert!(inbox.pending.is_empty());
295    }
296    #[test]
297    fn contact_hint_coalesces_separately_from_message_work() {
298        use crate::protobuf as p;
299        let hint = Longlink {
300            command: 356,
301            sequence: 0,
302            payload: p::message(&[
303                p::bytes(1, b"opaque"),
304                p::uint(2, 11),
305                p::bytes(
306                    3,
307                    &p::message(&[
308                        p::uint(1, 2048),
309                        p::bytes(2, &p::uint(1, crate::contact_sync::CONTACT_SELECTOR)),
310                    ])
311                    .unwrap(),
312                ),
313            ])
314            .unwrap(),
315        };
316        let mut inbox = Inbox::default();
317        inbox.observe(&push(0, &2u32.to_be_bytes())).unwrap();
318        inbox.observe(&hint).unwrap();
319        inbox.observe(&push(0, &4u32.to_be_bytes())).unwrap();
320        inbox.observe(&hint).unwrap();
321        assert_eq!(inbox.pending.len(), 2);
322        assert_eq!(
323            inbox.pending.pop_front().unwrap(),
324            Notification {
325                command: 24,
326                selector: 6
327            }
328        );
329        assert_eq!(
330            inbox.pending.pop_front().unwrap(),
331            Notification {
332                command: 356,
333                selector: 0x20004
334            }
335        );
336        let mut malformed = hint;
337        malformed.payload = p::message(&[p::uint(2, 11), p::bytes(3, b"invalid")]).unwrap();
338        assert!(notification(&malformed).is_err());
339    }
340    #[test]
341    fn interleaved_pushes_coalesce_without_confusing_keepalive_or_unknown_commands() {
342        let mut inbox = Inbox {
343            noop_sent: Some(Instant::now()),
344            ..Default::default()
345        };
346        inbox.observe(&push(0, &2u32.to_be_bytes())).unwrap();
347        inbox
348            .observe(&Longlink {
349                command: REPLY_OFFSET + NOOP,
350                sequence: NOOP_SEQUENCE,
351                payload: vec![],
352            })
353            .unwrap();
354        inbox
355            .observe(&Longlink {
356                command: 912,
357                sequence: 0,
358                payload: vec![1, 2, 3],
359            })
360            .unwrap();
361        inbox.observe(&push(0, &4u32.to_be_bytes())).unwrap();
362        assert!(inbox.noop_sent.is_none());
363        assert_eq!(inbox.pending.pop_front().unwrap().selector, 6);
364        assert!(inbox.pending.is_empty());
365        assert!(inbox
366            .observe(&Longlink {
367                command: REPLY_OFFSET + NOOP,
368                sequence: NOOP_SEQUENCE,
369                payload: vec![1]
370            })
371            .is_err());
372    }
373}