1use 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
24fn 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(¬ice, 1)? != 2048 {
42 return Ok(None);
43 }
44 let Some(raw_selectors) = p::optional_data(¬ice, 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 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 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 pub(crate) fn sync_guarded(
192 &mut self,
193 state: &mut AccountState,
194 cursor: &[u8],
195 scene: u32,
196 before_submit: impl FnOnce() -> Result<()>,
197 ) -> Result<wire::SyncBatch> {
198 ensure!([1, 6, 7].contains(&scene), "Unsupported sync scene");
199 let sent = if cursor.is_empty() { &[0][..] } else { cursor };
200 let request = wire::sync_request(sent, &state.device.device_type, scene)?;
201 wire::decode_sync(&self.rpc(state, 138, 121, &request, before_submit)?, cursor)
202 }
203 pub fn poll(&mut self, timeout: Duration) -> Result<Option<Notification>> {
206 self.keepalive()?;
207 if !self.inbox.pending.is_empty() {
208 return Ok(self.inbox.pending.pop_front());
209 }
210 let deadline = Instant::now() + timeout;
211 for _ in 0..64 {
212 let remaining = deadline.saturating_duration_since(Instant::now());
213 if remaining.is_zero() {
214 return Ok(None);
215 }
216 let Some(packet) = self.session.poll_application(remaining)? else {
217 return Ok(None);
218 };
219 self.inbox.observe(&packet)?;
220 if !self.inbox.pending.is_empty() {
221 return Ok(self.inbox.pending.pop_front());
222 }
223 }
224 anyhow::bail!("Native notification frame limit")
225 }
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231 fn push(sequence: u32, selector: &[u8]) -> Longlink {
232 Longlink {
233 command: 24,
234 sequence,
235 payload: selector.to_vec(),
236 }
237 }
238 #[test]
239 fn selectors_are_strict_big_endian_work_hints() {
240 assert_eq!(
241 notification(&push(0, &6u32.to_be_bytes())).unwrap(),
242 Some(Notification {
243 command: 24,
244 selector: 6
245 })
246 );
247 assert!(notification(&push(0, &8u32.to_be_bytes()))
248 .unwrap()
249 .is_none());
250 assert!(notification(&push(12, &6u32.to_be_bytes()))
251 .unwrap()
252 .is_none());
253 for invalid in [&[][..], &[6][..], &[0, 0, 6][..], &[0; 5][..]] {
254 assert!(notification(&push(0, invalid)).is_err());
255 }
256 }
257 #[test]
258 fn unmapped_contact_notices_without_selectors_leave_the_inbox_intact() {
259 use crate::protobuf as p;
260 let mut inbox = Inbox::default();
261 inbox.observe(&push(0, &2u32.to_be_bytes())).unwrap();
262 for notice in [
263 p::uint(1, 2048),
264 p::message(&[p::uint(1, 2048), p::bytes(2, b"")]).unwrap(),
265 ] {
266 inbox
267 .observe(&Longlink {
268 command: 356,
269 sequence: 0,
270 payload: p::message(&[p::uint(2, 11), p::bytes(3, ¬ice)]).unwrap(),
271 })
272 .unwrap();
273 }
274 assert_eq!(
275 inbox.pending.pop_front().unwrap(),
276 Notification {
277 command: 24,
278 selector: 2
279 }
280 );
281 assert!(inbox.pending.is_empty());
282 }
283 #[test]
284 fn contact_hint_coalesces_separately_from_message_work() {
285 use crate::protobuf as p;
286 let hint = Longlink {
287 command: 356,
288 sequence: 0,
289 payload: p::message(&[
290 p::bytes(1, b"opaque"),
291 p::uint(2, 11),
292 p::bytes(
293 3,
294 &p::message(&[
295 p::uint(1, 2048),
296 p::bytes(2, &p::uint(1, crate::contact_sync::CONTACT_SELECTOR)),
297 ])
298 .unwrap(),
299 ),
300 ])
301 .unwrap(),
302 };
303 let mut inbox = Inbox::default();
304 inbox.observe(&push(0, &2u32.to_be_bytes())).unwrap();
305 inbox.observe(&hint).unwrap();
306 inbox.observe(&push(0, &4u32.to_be_bytes())).unwrap();
307 inbox.observe(&hint).unwrap();
308 assert_eq!(inbox.pending.len(), 2);
309 assert_eq!(
310 inbox.pending.pop_front().unwrap(),
311 Notification {
312 command: 24,
313 selector: 6
314 }
315 );
316 assert_eq!(
317 inbox.pending.pop_front().unwrap(),
318 Notification {
319 command: 356,
320 selector: 0x20004
321 }
322 );
323 let mut malformed = hint;
324 malformed.payload = p::message(&[p::uint(2, 11), p::bytes(3, b"invalid")]).unwrap();
325 assert!(notification(&malformed).is_err());
326 }
327 #[test]
328 fn interleaved_pushes_coalesce_without_confusing_keepalive_or_unknown_commands() {
329 let mut inbox = Inbox {
330 noop_sent: Some(Instant::now()),
331 ..Default::default()
332 };
333 inbox.observe(&push(0, &2u32.to_be_bytes())).unwrap();
334 inbox
335 .observe(&Longlink {
336 command: REPLY_OFFSET + NOOP,
337 sequence: NOOP_SEQUENCE,
338 payload: vec![],
339 })
340 .unwrap();
341 inbox
342 .observe(&Longlink {
343 command: 912,
344 sequence: 0,
345 payload: vec![1, 2, 3],
346 })
347 .unwrap();
348 inbox.observe(&push(0, &4u32.to_be_bytes())).unwrap();
349 assert!(inbox.noop_sent.is_none());
350 assert_eq!(inbox.pending.pop_front().unwrap().selector, 6);
351 assert!(inbox.pending.is_empty());
352 assert!(inbox
353 .observe(&Longlink {
354 command: REPLY_OFFSET + NOOP,
355 sequence: NOOP_SEQUENCE,
356 payload: vec![1]
357 })
358 .is_err());
359 }
360}