garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /modem/src/sim.rs

raw

//! A simulated modem, and the network between several: what the driver is
//! tested against, and what `cargo xtask` puts behind a QEMU's serial port
//! so the system makes and takes phone calls and texts with no radio. A
//! modem takes AT commands ([`Modem::receive`]) and answers as a voice
//! modem does ([`Modem::transmit`]); the [`Network`] puts calls through
//! between its modems by number, and to and from numbers outside it that
//! answer, are busy or never pick up ([`Behaviour`]); and carries texts
//! between them, a number outside keeping those it is sent.

use crate::{number, pdu};
use alloc::collections::VecDeque;
use alloc::string::String;
use alloc::vec::Vec;

/// How often a call ringing in rings again.
const RING_MS: u64 = 3000;
/// How long the network lets a call ring before giving up on it.
pub const NO_ANSWER_MS: u64 = 30_000;

/// Error 11 of TS 27.007: the SIM wants its PIN; 16: a wrong password.
const SIM_PIN_REQUIRED: &str = "+CME ERROR: 11";
const INCORRECT_PASSWORD: &str = "+CME ERROR: 16";

/// What the modem's host asked of the network since the last step.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Request {
    Dial(String),
    Answer,
    HangUp,
    /// A line arrived while dialling: the dial is aborted (V.250 6.3.1).
    Abort,
    /// A text sent: its SUBMIT PDU.
    Text(Vec<u8>),
}

pub struct Modem {
    pub number: String,
    pin: Option<String>,
    unlocked: bool,
    echo: bool,
    clip: bool,
    colp: bool,
    creg: bool,
    registered: bool,
    partial: Vec<u8>,
    out: VecDeque<Vec<u8>>,
    requests: Vec<Request>,
    /// `ATD` waits for its result.
    dialling: bool,
    /// `AT+CMGF=0`: texts as PDUs (the only mode this modem has).
    pdu_mode: bool,
    /// `AT+CNMI=2,2,…`: texts handed to the host as they come.
    cnmi: bool,
    /// After `AT+CMGS`, its `> `: the PDU being written, until ctrl-Z.
    composing: Option<Vec<u8>>,
    /// Texts that came while the host did not ask for them as they come
    /// (`+CNMI`): on the SIM, which the driver does not read.
    pub stored: Vec<(String, String)>,
    /// Parts of long texts this modem sends, held until the last.
    sent_parts: pdu::Parts,
    next_reference: u8,
    /// Every command line the host sent, for tests to read.
    pub commands: Vec<String>,
}

impl Modem {
    /// A modem whose SIM has `number`, locked by `pin` when there is one.
    pub fn new(number: &str, pin: Option<&str>) -> Modem {
        Modem {
            number: number.into(),
            pin: pin.map(Into::into),
            unlocked: pin.is_none(),
            echo: true,
            clip: false,
            colp: false,
            creg: false,
            registered: true,
            partial: Vec::new(),
            out: VecDeque::new(),
            requests: Vec::new(),
            dialling: false,
            pdu_mode: false,
            cnmi: false,
            composing: None,
            stored: Vec::new(),
            sent_parts: pdu::Parts::default(),
            next_reference: 0,
            commands: Vec::new(),
        }
    }

    /// The next bytes for the host.
    pub fn transmit(&mut self) -> Option<Vec<u8>> {
        self.out.pop_front()
    }

    fn say(&mut self, line: &str) {
        self.out.push_back(alloc::format!("\r\n{line}\r\n").into_bytes());
    }

    /// The result `ATD` waited for.
    fn dial_result(&mut self, line: &str) {
        if core::mem::take(&mut self.dialling) {
            self.say(line);
        }
    }

    /// Bytes from the host.
    pub fn receive(&mut self, bytes: &[u8]) {
        for &b in bytes {
            if let Some(pdu) = &mut self.composing {
                match b {
                    // Ctrl-Z sends it; escape cancels it.
                    0x1a => {
                        let hex = core::mem::take(pdu);
                        self.composing = None;
                        match pdu::from_hex(&String::from_utf8_lossy(&hex)) {
                            Some(p) => self.requests.push(Request::Text(p)),
                            None => self.say("+CMS ERROR: 304"),
                        }
                    }
                    0x1b => {
                        self.composing = None;
                        self.say("OK");
                    }
                    b'\r' | b'\n' => {}
                    _ => pdu.push(b),
                }
                continue;
            }
            if b == b'\r' || b == b'\n' {
                let line = String::from_utf8_lossy(&core::mem::take(&mut self.partial)).into_owned();
                if !line.trim().is_empty() {
                    self.command(line.trim());
                }
            } else {
                self.partial.push(b);
            }
        }
    }

    fn command(&mut self, line: &str) {
        self.commands.push(line.into());
        if self.echo {
            self.out.push_back(alloc::format!("{line}\r").into_bytes());
        }
        if self.dialling {
            self.requests.push(Request::Abort);
            return;
        }
        let Some(cmd) = line.strip_prefix("AT").or_else(|| line.strip_prefix("at")) else {
            return;
        };
        let call = cmd.starts_with('D')
            || cmd == "A"
            || cmd == "+CHUP"
            || cmd.starts_with('H')
            || cmd.starts_with("+CMGS");
        if call && !self.unlocked {
            self.say(SIM_PIN_REQUIRED);
            return;
        }
        match cmd {
            "" | "+CMEE=1" => self.say("OK"),
            "E0" | "E1" => {
                self.echo = cmd == "E1";
                self.say("OK");
            }
            "+CPIN?" => {
                let state = if self.unlocked { "READY" } else { "SIM PIN" };
                self.say(&alloc::format!("+CPIN: {state}"));
                self.say("OK");
            }
            "+CLIP=0" | "+CLIP=1" => {
                self.clip = cmd.ends_with('1');
                self.say("OK");
            }
            "+COLP=0" | "+COLP=1" => {
                self.colp = cmd.ends_with('1');
                self.say("OK");
            }
            "+CMGF=0" => {
                self.pdu_mode = true;
                self.say("OK");
            }
            _ if cmd.starts_with("+CNMI=") => {
                self.cnmi = cmd["+CNMI=".len()..].split(',').nth(1) == Some("2");
                self.say("OK");
            }
            _ if cmd.starts_with("+CMGS=") && self.pdu_mode => {
                self.composing = Some(Vec::new());
                self.out.push_back(b"\r\n> ".to_vec());
            }
            "+CREG=0" | "+CREG=1" => {
                self.creg = cmd.ends_with('1');
                self.say("OK");
            }
            "+CREG?" => {
                let line = alloc::format!("+CREG: {},{}", u8::from(self.creg), u8::from(self.registered));
                self.say(&line);
                self.say("OK");
            }
            "A" => self.requests.push(Request::Answer),
            "+CHUP" | "H" | "H0" => self.requests.push(Request::HangUp),
            _ if cmd.starts_with("+CPIN=") => {
                let given = cmd["+CPIN=".len()..].trim_matches('"');
                if self.unlocked || self.pin.as_deref() == Some(given) {
                    self.unlocked = true;
                    self.say("OK");
                } else {
                    self.say(INCORRECT_PASSWORD);
                }
            }
            _ if cmd.starts_with('D') && cmd.ends_with(';') => {
                self.dialling = true;
                self.requests.push(Request::Dial(cmd[1..cmd.len() - 1].into()));
            }
            _ => self.say("ERROR"),
        }
    }
}

/// How a number outside the network answers a call.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Behaviour {
    /// Picks up after this long.
    Answers {
        after_ms: u64,
    },
    Busy,
    /// Never picks up.
    Silent,
}

pub struct Outside {
    pub number: String,
    pub behaviour: Behaviour,
    /// The texts it was sent, whole, and who from.
    pub texts: Vec<(String, String)>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Party {
    Modem(usize),
    Outside(usize),
}

#[derive(Clone, Debug)]
pub struct Call {
    pub caller: Party,
    pub callee: Party,
    /// When it started ringing, while it does.
    ringing: Option<u64>,
    next_ring: u64,
}

impl Call {
    pub fn active(&self) -> bool {
        self.ringing.is_none()
    }
}

#[derive(Default)]
pub struct Network {
    pub modems: Vec<Modem>,
    pub outside: Vec<Outside>,
    pub calls: Vec<Call>,
}

impl Network {
    /// Adds a modem with `number` on its SIM; returns its index.
    pub fn add(&mut self, number: &str, pin: Option<&str>) -> usize {
        self.modems.push(Modem::new(number, pin));
        self.modems.len() - 1
    }

    /// Adds a number outside the network; returns its index.
    pub fn add_outside(&mut self, number: &str, behaviour: Behaviour) -> usize {
        self.outside.push(Outside {
            number: number.into(),
            behaviour,
            texts: Vec::new(),
        });
        self.outside.len() - 1
    }

    /// Modem `i` sent a SUBMIT: the network takes it (`+CMGS` and `OK`)
    /// when the modem is on it, and carries it once its last part is in.
    /// A number it does not know takes it too, as a real one does.
    fn text_sent(&mut self, i: usize, submit: &[u8]) {
        let modem = &mut self.modems[i];
        let Some(part) = pdu::parse_submit(submit) else {
            // 304: invalid PDU mode parameter.
            modem.say("+CMS ERROR: 304");
            return;
        };
        if !modem.registered {
            // 331: no network service.
            modem.say("+CMS ERROR: 331");
            return;
        }
        modem.next_reference = modem.next_reference.wrapping_add(1);
        let line = alloc::format!("+CMGS: {}", modem.next_reference);
        modem.say(&line);
        modem.say("OK");
        let Some((to, text)) = modem.sent_parts.add(part) else {
            return;
        };
        let from = modem.number.clone();
        if let Some(j) = self.modems.iter().position(|m| number::same(&m.number, &to)) {
            self.text_to(j, &from, &text);
        } else if let Some(o) = self.outside.iter_mut().find(|o| number::same(&o.number, &to)) {
            o.texts.push((from, text));
        }
    }

    /// A text to modem `i` from `from`: `+CMT` and its PDUs, one a part,
    /// when the host asked for texts as they come; on the SIM else.
    pub fn text_to(&mut self, i: usize, from: &str, text: &str) {
        let modem = &mut self.modems[i];
        if !modem.cnmi {
            modem.stored.push((from.into(), text.into()));
            return;
        }
        modem.next_reference = modem.next_reference.wrapping_add(1);
        for p in pdu::deliver(from, text, modem.next_reference) {
            // The length leaves the service centre address out.
            modem.say(&alloc::format!("+CMT: ,{}\r\n{}", p.len() - 1, pdu::hex(&p)));
        }
    }

    /// Number outside `from` texts modem `to`.
    pub fn text_from_outside(&mut self, from: usize, to: usize, text: &str) {
        let number = self.outside[from].number.clone();
        self.text_to(to, &number, text);
    }

    /// Puts modem `i` on the network, or takes it off (its calls drop).
    pub fn set_registered(&mut self, i: usize, registered: bool) {
        let m = &mut self.modems[i];
        if m.registered == registered {
            return;
        }
        m.registered = registered;
        if m.creg {
            m.say(&alloc::format!("+CREG: {}", u8::from(registered)));
        }
        if !registered {
            self.drop_calls_of(Party::Modem(i), "NO CARRIER");
        }
    }

    fn number_of(&self, p: Party) -> &str {
        match p {
            Party::Modem(i) => &self.modems[i].number,
            Party::Outside(i) => &self.outside[i].number,
        }
    }

    fn in_call(&self, p: Party) -> bool {
        self.calls.iter().any(|c| c.caller == p || c.callee == p)
    }

    /// A number outside rings modem `to`. False when that cannot be.
    pub fn ring_from_outside(&mut self, from: usize, to: usize, now: u64) -> bool {
        let (caller, callee) = (Party::Outside(from), Party::Modem(to));
        if !self.modems[to].registered || self.in_call(caller) || self.in_call(callee) {
            return false;
        }
        self.calls.push(Call {
            caller,
            callee,
            ringing: Some(now),
            next_ring: now,
        });
        true
    }

    /// The number outside ends its call.
    pub fn hang_up_outside(&mut self, i: usize) {
        self.drop_calls_of(Party::Outside(i), "NO CARRIER");
    }

    /// Ends `p`'s calls; the other side hears `other`, or `NO CARRIER`.
    fn drop_calls_of(&mut self, p: Party, why: &str) {
        let (ended, kept): (Vec<Call>, Vec<Call>) =
            self.calls.drain(..).partition(|c| c.caller == p || c.callee == p);
        self.calls = kept;
        for c in ended {
            let other = if c.caller == p { c.callee } else { c.caller };
            if let Party::Modem(m) = other {
                self.tell_end(m, why);
            }
        }
    }

    /// Modem `m`'s call ended with `why`: the result its `ATD` waited
    /// for, or said of its own accord.
    fn tell_end(&mut self, m: usize, why: &str) {
        let modem = &mut self.modems[m];
        if modem.dialling {
            modem.dial_result(why);
        } else {
            modem.say("NO CARRIER");
        }
    }

    fn connected(&mut self, caller: Party, callee: Party) {
        if let Party::Modem(m) = caller {
            let line = alloc::format!("+COLP: \"{}\",129", self.number_of(callee));
            let modem = &mut self.modems[m];
            if modem.colp && modem.dialling {
                modem.say(&line);
            }
            modem.dial_result("OK");
        }
    }

    /// Carries what happened since the last step: dials, answers, hang-ups,
    /// rings and calls nobody picks up.
    pub fn step(&mut self, now: u64) {
        for i in 0..self.modems.len() {
            for request in core::mem::take(&mut self.modems[i].requests) {
                self.request(i, request, now);
            }
        }
        let mut give_up = Vec::new();
        let mut answer = Vec::new();
        for (k, call) in self.calls.iter_mut().enumerate() {
            let Some(since) = call.ringing else { continue };
            if now.saturating_sub(since) >= NO_ANSWER_MS {
                give_up.push(k);
                continue;
            }
            match call.callee {
                Party::Modem(m) if now >= call.next_ring => {
                    call.next_ring = now + RING_MS;
                    let from = match call.caller {
                        Party::Modem(c) => self.modems[c].number.clone(),
                        Party::Outside(c) => self.outside[c].number.clone(),
                    };
                    let modem = &mut self.modems[m];
                    modem.say("RING");
                    if modem.clip {
                        modem.say(&alloc::format!("+CLIP: \"{from}\",145,,,,0"));
                    }
                }
                Party::Outside(o) => {
                    if let Behaviour::Answers { after_ms } = self.outside[o].behaviour
                        && now.saturating_sub(since) >= after_ms
                    {
                        call.ringing = None;
                        answer.push((call.caller, call.callee));
                    }
                }
                _ => {}
            }
        }
        for (caller, callee) in answer {
            self.connected(caller, callee);
        }
        for k in give_up.into_iter().rev() {
            let c = self.calls.remove(k);
            if let Party::Modem(m) = c.caller {
                self.modems[m].dial_result("NO ANSWER");
            }
            if let Party::Modem(m) = c.callee {
                self.modems[m].say("NO CARRIER");
            }
        }
    }

    fn request(&mut self, i: usize, request: Request, now: u64) {
        let me = Party::Modem(i);
        match request {
            Request::Dial(n) => {
                let callee = self
                    .modems
                    .iter()
                    .position(|m| number::same(&m.number, &n))
                    .map(Party::Modem)
                    .or_else(|| {
                        self.outside
                            .iter()
                            .position(|o| number::same(&o.number, &n))
                            .map(Party::Outside)
                    });
                let Some(callee) = callee.filter(|_| self.modems[i].registered) else {
                    self.modems[i].dial_result("NO CARRIER");
                    return;
                };
                let reachable = match callee {
                    Party::Modem(j) => j != i && self.modems[j].registered,
                    Party::Outside(_) => true,
                };
                let busy = self.in_call(callee)
                    || matches!(callee, Party::Outside(o) if self.outside[o].behaviour == Behaviour::Busy);
                if !reachable {
                    self.modems[i].dial_result("NO CARRIER");
                } else if busy {
                    self.modems[i].dial_result("BUSY");
                } else {
                    self.calls.push(Call {
                        caller: me,
                        callee,
                        ringing: Some(now),
                        next_ring: now,
                    });
                }
            }
            Request::Answer => {
                let Some(call) = self
                    .calls
                    .iter_mut()
                    .find(|c| c.callee == me && c.ringing.is_some())
                else {
                    self.modems[i].say("NO CARRIER");
                    return;
                };
                call.ringing = None;
                let caller = call.caller;
                self.modems[i].say("OK");
                self.connected(caller, me);
            }
            Request::Text(p) => self.text_sent(i, &p),
            Request::HangUp | Request::Abort => {
                let declined = self.calls.iter().any(|c| c.callee == me && c.ringing.is_some());
                // A call declined is busy to its caller.
                self.drop_calls_of(me, if declined { "BUSY" } else { "NO CARRIER" });
                if request == Request::Abort {
                    self.modems[i].dial_result("NO CARRIER");
                } else {
                    self.modems[i].say("OK");
                }
            }
        }
    }
}