garage44.eu/jeroen/pinnacle

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

.. /modem/src/pdu.rs

raw

//! Text messages as the network carries them (3GPP TS 23.040, 23.038):
//! the PDUs a modem in PDU mode (`AT+CMGF=0`) takes and gives as hex.
//! SMS-SUBMIT goes out, SMS-DELIVER comes in. A text is put in GSM's
//! 7-bit alphabet when every character is in it (160 to a message), in
//! UCS-2 otherwise (70); a longer one goes as parts with a concatenation
//! header (153 or 67 each), which [`Parts`] puts back together.
//!
//! The simulated network ([`crate::sim`]) reads SUBMITs and writes
//! DELIVERs with the same code.

use alloc::string::String;
use alloc::vec::Vec;

/// The GSM 7-bit default alphabet, by septet (TS 23.038 6.2.1). 0x1B is
/// the escape to [`EXTENSION`].
const ALPHABET: [char; 128] = [
    '@', '£', '$', '¥', 'è', 'é', 'ù', 'ì', 'ò', 'Ç', '\n', 'Ø', 'ø', '\r', 'Å', 'å', //
    'Δ', '_', 'Φ', 'Γ', 'Λ', 'Ω', 'Π', 'Ψ', 'Σ', 'Θ', 'Ξ', '\u{1b}', 'Æ', 'æ', 'ß', 'É', //
    ' ', '!', '"', '#', '¤', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', //
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', //
    '¡', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', //
    'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'Ä', 'Ö', 'Ñ', 'Ü', '§', //
    '¿', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', //
    'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'ä', 'ö', 'ñ', 'ü', 'à', //
];

/// The extension table's characters, each after an escape (6.2.1.1).
const EXTENSION: [(u8, char); 10] = [
    (0x0a, '\u{c}'),
    (0x14, '^'),
    (0x28, '{'),
    (0x29, '}'),
    (0x2f, '\\'),
    (0x3c, '['),
    (0x3d, '~'),
    (0x3e, ']'),
    (0x40, '|'),
    (0x65, '€'),
];
const ESCAPE: u8 = 0x1b;

/// User data holds 140 octets: 160 septets, or 70 UCS-2 units.
const OCTETS: usize = 140;
const SEPTETS: usize = 160;
/// The concatenation header (8-bit reference): its length, then
/// element 0, three long: reference, how many parts, which this is.
const CONCAT_HEADER: usize = 6;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Coding {
    Gsm7,
    Ucs2,
    /// Binary data: kept as bytes, shown as text where it is.
    Octets,
}

/// One message as the network carries it: who it is from (a DELIVER) or
/// to (a SUBMIT), its text, and where it belongs when it is a part.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Part {
    pub number: String,
    pub text: String,
    pub concat: Option<Concat>,
}

/// A part's place in a long text: its reference, how many parts, which
/// this is (from 1).
pub type Concat = (u16, u8, u8);

/// A character's septets: one, two (an escape first), or none.
fn septets(c: char) -> Option<Vec<u8>> {
    if c == '\u{1b}' {
        return None;
    }
    if let Some(i) = ALPHABET.iter().position(|&a| a == c) {
        return Some(alloc::vec![i as u8]);
    }
    let &(e, _) = EXTENSION.iter().find(|&&(_, e)| e == c)?;
    Some(alloc::vec![ESCAPE, e])
}

/// How a text is coded, and its pieces: each a run of whole characters
/// that fits one message (or one part of several).
fn pieces(text: &str) -> (Coding, Vec<Vec<u8>>) {
    let gsm = text.chars().all(|c| septets(c).is_some());
    let (coding, units): (Coding, Vec<Vec<u8>>) = if gsm {
        let u = text.chars().filter_map(septets).collect();
        (Coding::Gsm7, u)
    } else {
        let u = text
            .chars()
            .map(|c| {
                let mut b = [0u16; 2];
                c.encode_utf16(&mut b)
                    .iter()
                    .flat_map(|u| u.to_be_bytes())
                    .collect()
            })
            .collect();
        (Coding::Ucs2, u)
    };
    let (whole, part) = match coding {
        Coding::Gsm7 => (SEPTETS, SEPTETS - (CONCAT_HEADER * 8).div_ceil(7)),
        _ => (OCTETS, OCTETS - CONCAT_HEADER),
    };
    let total: usize = units.iter().map(Vec::len).sum();
    if total <= whole {
        return (coding, alloc::vec![units.concat()]);
    }
    let mut out: Vec<Vec<u8>> = alloc::vec![Vec::new()];
    for u in units {
        if out.last().unwrap().len() + u.len() > part {
            out.push(Vec::new());
        }
        out.last_mut().unwrap().extend_from_slice(&u);
    }
    (coding, out)
}

/// Bits written least significant first, as 7-bit user data packs them.
#[derive(Default)]
struct Bits {
    out: Vec<u8>,
    at: usize,
}

impl Bits {
    fn put(&mut self, value: u8, width: usize) {
        for i in 0..width {
            if self.at.is_multiple_of(8) {
                self.out.push(0);
            }
            if value >> i & 1 == 1 {
                *self.out.last_mut().unwrap() |= 1 << (self.at % 8);
            }
            self.at += 1;
        }
    }
}

fn bit(data: &[u8], at: usize) -> u8 {
    data.get(at / 8).map_or(0, |b| b >> (at % 8) & 1)
}

/// The user data and its length field: septets for 7-bit, octets else.
fn user_data(coding: Coding, header: &[u8], body: &[u8]) -> (u8, Vec<u8>) {
    let udh: Vec<u8> = match header.is_empty() {
        true => Vec::new(),
        false => [&[header.len() as u8][..], header].concat(),
    };
    match coding {
        Coding::Gsm7 => {
            let mut bits = Bits::default();
            for &b in &udh {
                bits.put(b, 8);
            }
            // The septets start on a septet boundary.
            let fill = (7 - bits.at % 7) % 7;
            bits.put(0, fill);
            let head = bits.at / 7;
            for &s in body {
                bits.put(s, 7);
            }
            ((head + body.len()) as u8, bits.out)
        }
        _ => {
            let ud = [&udh[..], body].concat();
            (ud.len() as u8, ud)
        }
    }
}

/// An address field: digits, type, semi-octets (TS 23.040 9.1.2.5).
fn address(number: &str) -> Vec<u8> {
    let international = number.starts_with('+');
    let digits: Vec<u8> = number
        .bytes()
        .filter(u8::is_ascii_digit)
        .map(|d| d - b'0')
        .collect();
    let mut out = alloc::vec![digits.len() as u8, if international { 0x91 } else { 0x81 }];
    for pair in digits.chunks(2) {
        out.push(pair[0] | pair.get(1).map_or(0xf0, |d| d << 4));
    }
    out
}

/// An address field read at `at`: the number, and where the next field is.
fn read_address(pdu: &[u8], at: usize) -> Option<(String, usize)> {
    let len = usize::from(*pdu.get(at)?);
    let toa = *pdu.get(at + 1)?;
    let octets = len.div_ceil(2);
    let bytes = pdu.get(at + 2..at + 2 + octets)?;
    let mut number = String::new();
    if toa >> 4 & 7 == 5 {
        // Alphanumeric: a sender's name, in 7-bit (`len` is semi-octets).
        number = decode_gsm(bytes, 0, len * 4 / 7);
    } else {
        if toa >> 4 & 7 == 1 {
            number.push('+');
        }
        let digits = bytes.iter().flat_map(|b| [b & 0xf, b >> 4]).take(len);
        for d in digits {
            match d {
                0..=9 => number.push(char::from(b'0' + d)),
                0xa => number.push('*'),
                0xb => number.push('#'),
                _ => {}
            }
        }
    }
    Some((number, at + 2 + octets))
}

/// `count` septets from `data`, starting `skip` bits in.
fn decode_gsm(data: &[u8], skip: usize, count: usize) -> String {
    let mut out = String::new();
    let mut escaped = false;
    for i in 0..count {
        let at = skip + i * 7;
        let s = (0..7).fold(0u8, |v, k| v | bit(data, at + k) << k);
        if escaped {
            escaped = false;
            // An unknown escape shows as a space (TS 23.038 6.2.1.1).
            out.push(EXTENSION.iter().find(|&&(e, _)| e == s).map_or(' ', |&(_, c)| c));
        } else if s == ESCAPE {
            escaped = true;
        } else {
            out.push(ALPHABET[usize::from(s)]);
        }
    }
    out
}

fn coding_of(dcs: u8) -> Coding {
    match dcs >> 4 {
        0..=3 => match dcs >> 2 & 3 {
            1 => Coding::Octets,
            2 => Coding::Ucs2,
            _ => Coding::Gsm7,
        },
        0xe => Coding::Ucs2,
        0xf if dcs & 4 != 0 => Coding::Octets,
        _ => Coding::Gsm7,
    }
}

/// The user data at `at` (its length field first): the text, and the
/// concatenation it belongs to.
fn read_user_data(pdu: &[u8], at: usize, coding: Coding, header: bool) -> Option<(String, Option<Concat>)> {
    let udl = usize::from(*pdu.get(at)?);
    let ud = pdu.get(at + 1..)?;
    let mut concat = None;
    let mut head = 0;
    if header {
        let udhl = usize::from(*ud.first()?);
        let h = ud.get(1..1 + udhl)?;
        head = 1 + udhl;
        let mut i = 0;
        while i + 2 <= h.len() {
            let (iei, len) = (h[i], usize::from(h[i + 1]));
            let v = h.get(i + 2..i + 2 + len)?;
            match (iei, len) {
                (0, 3) => concat = Some((u16::from(v[0]), v[1], v[2])),
                (8, 4) => concat = Some((u16::from_be_bytes([v[0], v[1]]), v[2], v[3])),
                _ => {}
            }
            i += 2 + len;
        }
        concat = concat.filter(|&(_, total, seq)| total >= 1 && (1..=total).contains(&seq));
    }
    let text = match coding {
        Coding::Gsm7 => {
            let skip = (head * 8).div_ceil(7);
            decode_gsm(ud, skip * 7, udl.checked_sub(skip)?)
        }
        Coding::Ucs2 => {
            let body = ud.get(head..udl.min(ud.len()))?;
            let units = body.as_chunks::<2>().0.iter().map(|&p| u16::from_be_bytes(p));
            char::decode_utf16(units)
                .map(|c| c.unwrap_or('\u{fffd}'))
                .collect()
        }
        Coding::Octets => String::from_utf8_lossy(ud.get(head..udl.min(ud.len()))?).into_owned(),
    };
    Some((text, concat))
}

/// The SUBMITs that send `text` to `number`, one PDU each (with no
/// service centre address: the SIM's is used). `reference` ties the
/// parts of a long text together.
pub fn submit(number: &str, text: &str, reference: u8) -> Vec<Vec<u8>> {
    messages(number, text, reference, |udhi| [0x01 | udhi, 0x00].to_vec(), &[])
}

/// The DELIVERs that bring `text` from `number`: what the network sends.
pub fn deliver(number: &str, text: &str, reference: u8) -> Vec<Vec<u8>> {
    // The service centre's time stamp: 2026-11-27 12:00:00 UTC, in
    // swapped semi-octets.
    const STAMP: [u8; 7] = [0x62, 0x11, 0x72, 0x21, 0x00, 0x00, 0x00];
    let pdus = messages(number, text, reference, |udhi| alloc::vec![0x04 | udhi], &STAMP);
    // A DELIVER names its service centre: none here.
    pdus.into_iter().map(|p| [&[0x00][..], &p].concat()).collect()
}

/// The PDUs of either kind: `first` gives the octets before the address
/// (the first octet, and a SUBMIT's message reference); `stamp` is what
/// follows the coding (a DELIVER's time stamp).
fn messages(
    number: &str,
    text: &str,
    reference: u8,
    first: impl Fn(u8) -> Vec<u8>,
    stamp: &[u8],
) -> Vec<Vec<u8>> {
    let (coding, pieces) = pieces(text);
    let total = pieces.len();
    pieces
        .iter()
        .enumerate()
        .map(|(i, body)| {
            let header: Vec<u8> = match total {
                1 => Vec::new(),
                _ => alloc::vec![0x00, 0x03, reference, total as u8, i as u8 + 1],
            };
            let udhi = if header.is_empty() { 0 } else { 0x40 };
            let mut pdu = first(udhi);
            pdu.extend(address(number));
            pdu.push(0x00);
            pdu.push(if coding == Coding::Ucs2 { 0x08 } else { 0x00 });
            pdu.extend_from_slice(stamp);
            let (udl, ud) = user_data(coding, &header, body);
            pdu.push(udl);
            pdu.extend(ud);
            pdu
        })
        .collect()
}

/// A DELIVER, as `+CMT` gives it after its service centre's address.
pub fn parse_deliver(pdu: &[u8]) -> Option<Part> {
    let sca = usize::from(*pdu.first()?);
    let first = *pdu.get(1 + sca)?;
    if first & 3 != 0 {
        return None;
    }
    let (number, at) = read_address(pdu, 2 + sca)?;
    let coding = coding_of(*pdu.get(at + 1)?);
    let (text, concat) = read_user_data(pdu, at + 2 + 7, coding, first & 0x40 != 0)?;
    Some(Part { number, text, concat })
}

/// A SUBMIT, as `+CMGS` takes it (no service centre address), and the
/// validity period it may carry skipped: what the network reads.
pub fn parse_submit(pdu: &[u8]) -> Option<Part> {
    let first = *pdu.first()?;
    if first & 3 != 1 {
        return None;
    }
    let (number, at) = read_address(pdu, 2)?;
    let coding = coding_of(*pdu.get(at + 1)?);
    let vp = match first >> 3 & 3 {
        0 => 0,
        2 => 1,
        _ => 7,
    };
    let (text, concat) = read_user_data(pdu, at + 2 + vp, coding, first & 0x40 != 0)?;
    Some(Part { number, text, concat })
}

pub fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| alloc::format!("{b:02X}")).collect()
}

pub fn from_hex(text: &str) -> Option<Vec<u8>> {
    let t = text.trim().as_bytes();
    if !t.len().is_multiple_of(2) {
        return None;
    }
    t.chunks(2)
        .map(|p| u8::from_str_radix(core::str::from_utf8(p).ok()?, 16).ok())
        .collect()
}

/// How many sets of parts are held at once, waiting for the rest; the
/// oldest goes when another starts.
const HELD: usize = 16;

/// Parts of long texts waiting for the rest.
#[derive(Default)]
pub struct Parts {
    /// Number, reference, the parts by place.
    held: Vec<(String, u16, Vec<Option<String>>)>,
}

impl Parts {
    /// Takes a part: the whole text and who sent it once every part is
    /// there (at once for a text that came in one).
    pub fn add(&mut self, part: Part) -> Option<(String, String)> {
        let Some((reference, total, seq)) = part.concat.filter(|c| c.1 > 1) else {
            return Some((part.number, part.text));
        };
        let i = match self
            .held
            .iter()
            .position(|(n, r, p)| *n == part.number && *r == reference && p.len() == usize::from(total))
        {
            Some(i) => i,
            None => {
                if self.held.len() == HELD {
                    self.held.remove(0);
                }
                self.held.push((
                    part.number.clone(),
                    reference,
                    alloc::vec![None; usize::from(total)],
                ));
                self.held.len() - 1
            }
        };
        self.held[i].2[usize::from(seq) - 1] = Some(part.text);
        if self.held[i].2.iter().any(Option::is_none) {
            return None;
        }
        let (number, _, parts) = self.held.remove(i);
        Some((number, parts.into_iter().flatten().collect()))
    }
}