Skip to main content

fritz_core/
callmonitor.rs

1//! The call monitor of the device: a TCP stream on port 1012 with a line
2//! per event of a call, like `23.11.26 18:02:11;RING;0;030987;030123;SIP0;`.
3//! It needs no login. Nothing is sent to it.
4//!
5//! The lines are untrusted and parsed strictly: a line that is not a known
6//! event with valid fields is skipped.
7
8use std::collections::{HashMap, VecDeque};
9use std::io;
10use std::time::Duration;
11
12use serde::Serialize;
13use tokio::io::{AsyncBufReadExt as _, AsyncReadExt as _, BufReader};
14use tokio::net::TcpStream;
15
16use crate::personal::{self, Phonebook};
17
18/// The port of the call monitor.
19pub const PORT: u16 = 1012;
20
21/// How to turn the call monitor on and off.
22pub const HINT: &str = "the call monitor may be off: dial #96*5* on a phone connected to the \
23                        device to turn it on, #96*4* turns it off";
24
25/// The longest line read; events are much shorter.
26const MAX_LINE: u64 = 512;
27
28/// The first wait before connecting again, doubled after every attempt up
29/// to [`MAX_BACKOFF`].
30const BACKOFF: Duration = Duration::from_secs(1);
31const MAX_BACKOFF: Duration = Duration::from_secs(60);
32
33/// The events remembered to drop repeated ones after connecting again.
34const SEEN: usize = 64;
35
36/// The call monitor cannot be reached.
37#[derive(Debug, thiserror::Error)]
38#[error("cannot connect to the call monitor at {address}: {error}; {HINT}")]
39pub struct Error {
40    pub address: String,
41    /// Part of the message, not a source, so that it is shown once.
42    pub error: io::Error,
43}
44
45/// An event of a call.
46#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
47pub struct Event {
48    /// Like `2026-11-23 18:02:11`, in the time zone of the device.
49    pub time: String,
50    /// `ring` (incoming), `call` (outgoing), `connect` or `disconnect`.
51    pub kind: &'static str,
52    /// The connection: the events of a call share it.
53    pub id: u32,
54    /// The number of the other party, none if it is withheld.
55    pub number: Option<String>,
56    /// The name of the other party, from the phonebooks.
57    pub name: Option<String>,
58    /// The own number the call came in on or went out from.
59    pub own_number: Option<String>,
60    /// The internal number of the phone, for `call` and `connect`.
61    pub extension: Option<String>,
62    /// The line, like `SIP0`, for `ring` and `call`.
63    pub line: Option<String>,
64    /// How long the call took, for `disconnect`.
65    pub seconds: Option<u64>,
66}
67
68/// Parses a line of the call monitor, or `None` if it is not a valid
69/// event.
70pub fn parse(line: &str) -> Option<Event> {
71    let line = line.trim_end_matches(['\r', '\n']);
72    let fields: Vec<&str> = line.strip_suffix(';')?.split(';').collect();
73    let (time, kind, id) = (fields.first()?, fields.get(1)?, fields.get(2)?);
74    let event = Event {
75        time: time_of(time)?,
76        id: count(id, 5)?,
77        ..Event::default()
78    };
79    let field = |index: usize| fields.get(index).copied();
80    let event = match (*kind, fields.len()) {
81        ("RING", 6) => Event {
82            kind: "ring",
83            number: number(field(3)?)?,
84            own_number: number(field(4)?)?,
85            line: Some(line_of(field(5)?)?),
86            ..event
87        },
88        ("CALL", 7) => Event {
89            kind: "call",
90            extension: Some(extension(field(3)?)?),
91            own_number: number(field(4)?)?,
92            number: number(field(5)?)?,
93            line: Some(line_of(field(6)?)?),
94            ..event
95        },
96        ("CONNECT", 5) => Event {
97            kind: "connect",
98            extension: Some(extension(field(3)?)?),
99            number: number(field(4)?)?,
100            ..event
101        },
102        ("DISCONNECT", 4) => Event {
103            kind: "disconnect",
104            seconds: Some(count(field(3)?, 9)?),
105            ..event
106        },
107        _ => return None,
108    };
109    Some(event)
110}
111
112/// A time like `23.11.26 18:02:11` as `2026-11-23 18:02:11`.
113fn time_of(text: &str) -> Option<String> {
114    let (day, time) = text.split_once(' ')?;
115    let parts: Vec<&str> = time.split(':').collect();
116    let valid = personal::is_date(day)
117        && parts.len() == 3
118        && parts.iter().all(|p| p.len() == 2 && is_digits(p, 2));
119    valid.then(|| personal::date(text))
120}
121
122/// A number, `None` inside if empty: digits, `*` and `#`, optionally after
123/// a `+`, at most 40.
124#[allow(clippy::option_option)]
125fn number(text: &str) -> Option<Option<String>> {
126    let digits = text.strip_prefix('+').unwrap_or(text);
127    let valid = text.len() <= 40
128        && digits
129            .bytes()
130            .all(|b| b.is_ascii_digit() || b == b'*' || b == b'#');
131    match text {
132        "" => Some(None),
133        _ if valid && !digits.is_empty() => Some(Some(text.to_owned())),
134        _ => None,
135    }
136}
137
138/// An internal number of up to 4 digits.
139fn extension(text: &str) -> Option<String> {
140    is_digits(text, 4).then(|| text.to_owned())
141}
142
143/// A line like `SIP0`: up to 16 letters and digits.
144fn line_of(text: &str) -> Option<String> {
145    let valid =
146        !text.is_empty() && text.len() <= 16 && text.bytes().all(|b| b.is_ascii_alphanumeric());
147    valid.then(|| text.to_owned())
148}
149
150/// A number of 1 to `max` digits.
151fn count<T: std::str::FromStr>(text: &str, max: usize) -> Option<T> {
152    is_digits(text, max).then(|| text.parse().ok()).flatten()
153}
154
155/// Whether `text` has 1 to `max` digits and nothing else.
156fn is_digits(text: &str, max: usize) -> bool {
157    (1..=max).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit())
158}
159
160/// The names of the numbers in the phonebooks, found by their digits.
161#[derive(Debug, Clone, Default)]
162pub struct Names(HashMap<String, String>);
163
164impl Names {
165    /// The names of all numbers of `phonebooks`; the first contact wins.
166    pub fn new(phonebooks: &[Phonebook]) -> Self {
167        let mut names = HashMap::new();
168        for contact in phonebooks.iter().flat_map(|p| &p.contacts) {
169            let Some(name) = &contact.name else { continue };
170            for number in &contact.numbers {
171                let digits = personal::digits(&number.number);
172                if !digits.is_empty() {
173                    names.entry(digits).or_insert_with(|| name.clone());
174                }
175            }
176        }
177        Self(names)
178    }
179
180    /// Sets the name of the event from its number, if it has one.
181    pub fn name(&self, event: &mut Event) {
182        let digits = event.number.as_deref().map(personal::digits);
183        event.name = digits.and_then(|d| self.0.get(&d)).cloned();
184    }
185}
186
187/// A connection to the call monitor that connects again when it is lost.
188#[derive(Debug)]
189pub struct Monitor {
190    address: (String, u16),
191    stream: Option<BufReader<TcpStream>>,
192    backoff: Duration,
193    seen: VecDeque<(String, &'static str, u32)>,
194}
195
196impl Monitor {
197    /// Connects to the call monitor on `host`, like `fritz.box` or
198    /// `[fd00::1]`.
199    ///
200    /// # Errors
201    ///
202    /// [`Error`] if the connection fails, with a hint on how to turn the
203    /// call monitor on.
204    pub async fn connect(host: &str, port: u16) -> Result<Self, Error> {
205        let host = host.trim_start_matches('[').trim_end_matches(']');
206        let address = (host.to_owned(), port);
207        let stream = open(&address).await.map_err(|error| Error {
208            address: format!("{}:{port}", address.0),
209            error,
210        })?;
211        Ok(Self {
212            address,
213            stream: Some(stream),
214            backoff: BACKOFF,
215            seen: VecDeque::new(),
216        })
217    }
218
219    /// The next event. Connects again with growing waits when the
220    /// connection is lost, and tells `note` about it. Skips invalid lines
221    /// and events seen before.
222    pub async fn next(&mut self, note: &mut impl FnMut(String)) -> Event {
223        loop {
224            if let Some(stream) = &mut self.stream {
225                match read_line(stream).await {
226                    Ok(Some(line)) => match self.accept(&line) {
227                        Some(event) => return event,
228                        None => continue,
229                    },
230                    Ok(None) => note("the call monitor closed the connection".to_owned()),
231                    Err(error) => note(format!("lost the call monitor: {error}")),
232                }
233                self.stream = None;
234            }
235            note(format!("connecting again in {}s", self.backoff.as_secs()));
236            tokio::time::sleep(self.backoff).await;
237            self.backoff = (self.backoff * 2).min(MAX_BACKOFF);
238            match open(&self.address).await {
239                Ok(stream) => self.stream = Some(stream),
240                Err(error) => note(format!("cannot connect to the call monitor: {error}")),
241            }
242        }
243    }
244
245    /// The event of a line, unless it is invalid or was seen before.
246    fn accept(&mut self, line: &str) -> Option<Event> {
247        let Some(event) = parse(line) else {
248            tracing::debug!(bytes = line.len(), "skipped a line that is not an event");
249            return None;
250        };
251        let key = (event.time.clone(), event.kind, event.id);
252        if self.seen.contains(&key) {
253            tracing::debug!("skipped an event seen before");
254            return None;
255        }
256        if self.seen.len() == SEEN {
257            self.seen.pop_front();
258        }
259        self.seen.push_back(key);
260        self.backoff = BACKOFF;
261        Some(event)
262    }
263}
264
265async fn open(address: &(String, u16)) -> io::Result<BufReader<TcpStream>> {
266    let stream = TcpStream::connect((address.0.as_str(), address.1)).await?;
267    Ok(BufReader::new(stream))
268}
269
270/// The next line, `None` at the end of the stream. A line that is too long
271/// comes in parts that do not parse.
272async fn read_line(stream: &mut BufReader<TcpStream>) -> io::Result<Option<String>> {
273    let mut line = Vec::new();
274    let read = (&mut *stream)
275        .take(MAX_LINE)
276        .read_until(b'\n', &mut line)
277        .await?;
278    Ok((read > 0).then(|| String::from_utf8_lossy(&line).into_owned()))
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284    use crate::personal::{Contact, ContactNumber};
285
286    #[test]
287    fn parses_events() {
288        let ring = parse("23.11.26 18:02:11;RING;0;030987;030123;SIP0;\r\n").unwrap();
289        assert_eq!(
290            ring,
291            Event {
292                time: "2026-11-23 18:02:11".to_owned(),
293                kind: "ring",
294                id: 0,
295                number: Some("030987".to_owned()),
296                own_number: Some("030123".to_owned()),
297                line: Some("SIP0".to_owned()),
298                ..Event::default()
299            }
300        );
301        let call = parse("23.11.26 18:10:03;CALL;1;10;030123;+49157*#;SIP1;").unwrap();
302        assert_eq!(
303            (call.kind, call.extension.as_deref(), call.number.as_deref()),
304            ("call", Some("10"), Some("+49157*#"))
305        );
306        let connect = parse("23.11.26 18:02:15;CONNECT;0;12;;").unwrap();
307        assert_eq!((connect.kind, connect.number), ("connect", None));
308        let disconnect = parse("23.11.26 18:04:40;DISCONNECT;0;145;").unwrap();
309        assert_eq!(
310            (disconnect.kind, disconnect.seconds),
311            ("disconnect", Some(145))
312        );
313    }
314
315    #[test]
316    fn skips_invalid_lines() {
317        for line in [
318            "",
319            "hello",
320            "23.11.26 18:02:11;RING;0;030987;030123;SIP0;extra;",
321            "23.11.26 18:02:11;HANGUP;0;",
322            "23.11.2026 18:02:11;DISCONNECT;0;1;",
323            "23.11.26 18:02;DISCONNECT;0;1;",
324            "23.11.26 18:02:1x;DISCONNECT;0;1;",
325            "23.11.26;DISCONNECT;0;1;",
326            "23.11.26 18:02:11;DISCONNECT;x;1;",
327            "23.11.26 18:02:11;DISCONNECT;0;-1;",
328            "23.11.26 18:02:11;RING;0;03\x1b[2J;030123;SIP0;",
329            "23.11.26 18:02:11;RING;0;+;030123;SIP0;",
330            "23.11.26 18:02:11;RING;0;030987;030123;;",
331            "23.11.26 18:02:11;RING;0;030987;030123;SIP 0;",
332            "23.11.26 18:02:11;CALL;0;abc;030123;030987;SIP0;",
333            "23.11.26 18:02:11;CALL;0;10;030123;030987;SIP0",
334        ] {
335            assert_eq!(parse(line), None, "{line:?}");
336        }
337        let long = format!("23.11.26 18:02:11;RING;0;{};1;SIP0;", "1".repeat(41));
338        assert_eq!(parse(&long), None);
339    }
340
341    #[test]
342    fn forgets_the_oldest_event_seen() {
343        let mut monitor = Monitor {
344            address: ("localhost".to_owned(), 1012),
345            stream: None,
346            backoff: BACKOFF,
347            seen: VecDeque::new(),
348        };
349        let line = |id: usize| format!("23.11.26 18:02:11;DISCONNECT;{id};1;");
350        for id in 0..=SEEN {
351            assert!(monitor.accept(&line(id)).is_some());
352        }
353        assert_eq!(monitor.seen.len(), SEEN);
354        assert!(monitor.accept(&line(SEEN)).is_none());
355        assert!(monitor.accept(&line(0)).is_some());
356    }
357
358    #[test]
359    fn finds_names() {
360        let contact = |name: Option<&str>, number: &str| Contact {
361            name: name.map(str::to_owned),
362            numbers: vec![ContactNumber {
363                number: number.to_owned(),
364                kind: None,
365            }],
366        };
367        let names = Names::new(&[Phonebook {
368            contacts: vec![
369                contact(Some("name-1"), "030 98-7"),
370                contact(Some("name-2"), "030987"),
371                contact(None, "0301"),
372                contact(Some("name-3"), "-"),
373            ],
374            ..Phonebook::default()
375        }]);
376        let mut event = Event {
377            number: Some("030987".to_owned()),
378            ..Event::default()
379        };
380        names.name(&mut event);
381        assert_eq!(event.name.as_deref(), Some("name-1"));
382        event.number = Some("0301".to_owned());
383        names.name(&mut event);
384        assert_eq!(event.name, None);
385    }
386}