garage44.eu/jeroen/pinnacle

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

.. /contacts/src/lib.rs

raw

//! The address book's entries, and vCards: what the p2p service keeps a
//! contact as on disk, what it hands the apps, and what is imported and
//! exported. A contact is a person, with or without a Pinnacle device: the
//! ones with one carry their key and their signed card (`p2p::identity`),
//! which is what messages and calls reach them by.
//!
//! vCards are read as phones, mail programs and address books write them:
//! 2.1 (Android's export, quoted-printable for what is not ASCII), 3.0 and
//! 4.0, lines folded or not, grouped properties (`item1.TEL`). What is not
//! kept here (photos, types, a structured name) is skipped on import.
//! They are written as 3.0, which every address book reads, the key and
//! the card as `X-PINNACLE-KEY` and `X-PINNACLE-CARD`, so an export carries
//! a contact's device across to another Pinnacle.

#![no_std]

extern crate alloc;

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

pub mod book;
pub use book::Book;

/// A contact's key: its Ed25519 public key.
pub type Key = [u8; 32];

/// The size of a signed card (`p2p::identity::Card::SIZE`).
pub const CARD_SIZE: usize = 160;

/// A contact.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Entry {
    /// What the p2p service knows it by: 32 hex digits, written as
    /// `X-PINNACLE-ID` when set; empty for one not kept yet. An export
    /// leaves it out ([`to_vcards`]).
    pub id: String,
    /// The vCard's UID, which an import of the same contact matches.
    pub uid: String,
    pub name: String,
    pub phones: Vec<String>,
    pub emails: Vec<String>,
    /// The address, on one line.
    pub address: String,
    /// As written: `1985-04-12`, or `--04-12` without the year.
    pub birthday: String,
    pub organisation: String,
    pub note: String,
    /// The contact's Pinnacle device, when it has one.
    pub key: Option<Key>,
    /// Its signed card, which the p2p service checks before it trusts it.
    pub card: Option<Vec<u8>>,
}

impl Entry {
    /// What the contact is shown as: the name, or failing one whatever
    /// else tells it apart.
    pub fn title(&self) -> &str {
        [&self.name, &self.organisation]
            .into_iter()
            .chain(self.phones.iter())
            .chain(self.emails.iter())
            .map(|s| s.trim())
            .find(|s| !s.is_empty())
            .unwrap_or("No name")
    }

    /// Whether there is nothing in it worth keeping.
    pub fn is_empty(&self) -> bool {
        self.key.is_none()
            && [
                &self.name,
                &self.address,
                &self.birthday,
                &self.organisation,
                &self.note,
            ]
            .iter()
            .all(|s| s.trim().is_empty())
            && self
                .phones
                .iter()
                .chain(&self.emails)
                .all(|s| s.trim().is_empty())
    }

    /// The entry as a vCard 3.0, lines ending CRLF and folded at 75 bytes.
    pub fn to_vcard(&self) -> String {
        let mut out = String::new();
        let mut put = |name: &str, value: &str| fold(&mut out, name, value);
        put("BEGIN", "VCARD");
        put("VERSION", "3.0");
        if !self.uid.is_empty() {
            put("UID", &escape(&self.uid));
        }
        put("FN", &escape(&self.name));
        // 3.0 asks for N: the whole name as the given one, since where a
        // family name starts is not known ("Jan van der Berg").
        put("N", &alloc::format!(";{};;;", escape(&self.name)));
        for phone in self.phones.iter().filter(|p| !p.trim().is_empty()) {
            put("TEL", &escape(phone.trim()));
        }
        for email in self.emails.iter().filter(|e| !e.trim().is_empty()) {
            put("EMAIL", &escape(email.trim()));
        }
        if !self.address.trim().is_empty() {
            put("ADR", &alloc::format!(";;{};;;;", escape(self.address.trim())));
        }
        if !self.birthday.trim().is_empty() {
            put("BDAY", &escape(self.birthday.trim()));
        }
        if !self.organisation.trim().is_empty() {
            put("ORG", &escape(self.organisation.trim()));
        }
        if !self.note.trim().is_empty() {
            put("NOTE", &escape(self.note.trim_end()));
        }
        if let Some(key) = &self.key {
            put("X-PINNACLE-KEY", &hex(key));
        }
        if let Some(card) = &self.card {
            put("X-PINNACLE-CARD", &hex(card));
        }
        if !self.id.is_empty() {
            put("X-PINNACLE-ID", &self.id);
        }
        put("END", "VCARD");
        out
    }
}

/// Every contact in `entries`, one vCard after another, without the ids
/// this device knows them by: an export.
pub fn to_vcards(entries: &[Entry]) -> String {
    entries
        .iter()
        .map(|e| {
            Entry {
                id: String::new(),
                ..e.clone()
            }
            .to_vcard()
        })
        .collect()
}

/// The contacts in vCard text: one entry per `BEGIN:VCARD` … `END:VCARD`,
/// those with nothing in them left out.
pub fn parse(text: &str) -> Vec<Entry> {
    let mut entries = Vec::new();
    let mut current: Option<Building> = None;
    for line in logical_lines(text) {
        let Some(prop) = Property::parse(&line) else {
            continue;
        };
        match (prop.name.as_str(), &mut current) {
            ("BEGIN", _) if prop.value.eq_ignore_ascii_case("VCARD") => {
                current = Some(Building::default());
            }
            ("END", Some(_)) if prop.value.eq_ignore_ascii_case("VCARD") => {
                let entry = current.take().unwrap().finish();
                if !entry.is_empty() {
                    entries.push(entry);
                }
            }
            (_, Some(b)) => b.take(&prop),
            _ => {}
        }
    }
    entries
}

/// An entry as it is read, with what only helps to finish it.
#[derive(Default)]
struct Building {
    entry: Entry,
    /// N's parts: family, given, additional, prefixes, suffixes.
    n: Vec<String>,
}

impl Building {
    fn take(&mut self, prop: &Property) {
        let e = &mut self.entry;
        let text = || unescape(&prop.value).trim().into();
        match prop.name.as_str() {
            "FN" => e.name = text(),
            "N" => self.n = split(&prop.value, ';'),
            "UID" => e.uid = text(),
            "TEL" => {
                let v: String = text();
                let v = v.strip_prefix("tel:").unwrap_or(&v).trim();
                if !v.is_empty() {
                    e.phones.push(v.into());
                }
            }
            "EMAIL" => {
                let v: String = text();
                let v = v.strip_prefix("mailto:").unwrap_or(&v).trim();
                if !v.is_empty() {
                    e.emails.push(v.into());
                }
            }
            "ADR" if e.address.is_empty() => e.address = joined(&split(&prop.value, ';'), ", "),
            "BDAY" => e.birthday = birthday(&text()),
            "ORG" if e.organisation.is_empty() => e.organisation = joined(&split(&prop.value, ';'), ", "),
            "NOTE" => {
                if !e.note.is_empty() {
                    e.note.push('\n');
                }
                e.note.push_str(unescape(&prop.value).trim());
            }
            "X-PINNACLE-KEY" => e.key = unhex(prop.value.trim()).and_then(|k| k.try_into().ok()),
            "X-PINNACLE-CARD" => e.card = unhex(prop.value.trim()).filter(|c| c.len() == CARD_SIZE),
            "X-PINNACLE-ID" => {
                let id = prop.value.trim();
                if id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit()) {
                    e.id = id.to_ascii_lowercase();
                }
            }
            _ => {}
        }
    }

    fn finish(mut self) -> Entry {
        let e = &mut self.entry;
        if e.name.is_empty() && !self.n.is_empty() {
            // Prefixes, given, additional, family, suffixes.
            let order = [3, 1, 2, 0, 4];
            let parts: Vec<String> = order.iter().filter_map(|&i| self.n.get(i).cloned()).collect();
            e.name = joined(&parts, " ");
        }
        // A card is only for its own key.
        if let Some(card) = &e.card {
            let of: Key = card[..32].try_into().unwrap();
            match e.key {
                Some(k) if k != of => e.card = None,
                _ => e.key = Some(of),
            }
        }
        self.entry
    }
}

/// `19850412` as `1985-04-12`, `--0412` as `--04-12`; a time after the
/// date dropped; anything else as it is.
fn birthday(v: &str) -> String {
    let date = v.split('T').next().unwrap_or(v);
    let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit());
    if date.len() == 8 && digits(date) {
        alloc::format!("{}-{}-{}", &date[..4], &date[4..6], &date[6..])
    } else if date.len() == 6 && date.starts_with("--") && digits(&date[2..]) {
        alloc::format!("--{}-{}", &date[2..4], &date[4..])
    } else {
        date.into()
    }
}

/// One content line: `group.NAME;param;param:value`, the name upper case
/// and the group dropped, the value decoded from quoted-printable when it
/// says so (still escaped as vCard text).
struct Property {
    name: String,
    value: String,
}

impl Property {
    fn parse(line: &str) -> Option<Property> {
        let colon = value_start(line)?;
        let (head, value) = (&line[..colon], &line[colon + 1..]);
        let mut parts = head.split(';');
        let name = parts.next()?;
        let name = name
            .rsplit('.')
            .next()
            .unwrap_or(name)
            .trim()
            .to_ascii_uppercase();
        let mut value: String = value.into();
        if parts.any(is_quoted_printable) {
            value = String::from_utf8_lossy(&quoted_printable(&value)).into_owned();
        }
        Some(Property { name, value })
    }
}

/// Where the value starts: after the first colon outside a quoted
/// parameter value.
fn value_start(line: &str) -> Option<usize> {
    let mut quoted = false;
    for (i, c) in line.char_indices() {
        match c {
            '"' => quoted = !quoted,
            ':' if !quoted => return Some(i),
            _ => {}
        }
    }
    None
}

fn is_quoted_printable(param: &str) -> bool {
    let p = param.trim();
    p.eq_ignore_ascii_case("QUOTED-PRINTABLE")
        || p.split_once('=').is_some_and(|(k, v)| {
            k.trim().eq_ignore_ascii_case("ENCODING") && v.trim().eq_ignore_ascii_case("QUOTED-PRINTABLE")
        })
}

/// The text's lines unfolded: a line starting with a space or a tab goes
/// on the one before (RFC 6350 §3.2), and so does the line after one of a
/// quoted-printable value ending `=` (vCard 2.1's soft line break).
fn logical_lines(text: &str) -> Vec<String> {
    let mut lines: Vec<String> = Vec::new();
    let mut soft = false;
    for raw in text.split('\n') {
        let raw = raw.strip_suffix('\r').unwrap_or(raw);
        match lines.last_mut() {
            Some(last) if soft => {
                last.pop();
                last.push_str(raw);
            }
            Some(last) if raw.starts_with([' ', '\t']) => last.push_str(&raw[1..]),
            _ => lines.push(raw.into()),
        }
        let last = lines.last().expect("pushed or extended");
        soft = last.ends_with('=')
            && value_start(last).is_some_and(|c| last[..c].split(';').skip(1).any(is_quoted_printable));
    }
    lines
}

fn quoted_printable(v: &str) -> Vec<u8> {
    let b = v.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'=' {
            let pair = b
                .get(i + 1..i + 3)
                .and_then(|h| Some(nibble(h[0])? << 4 | nibble(h[1])?));
            if let Some(byte) = pair {
                out.push(byte);
                i += 3;
                continue;
            }
        }
        out.push(b[i]);
        i += 1;
    }
    out
}

/// vCard text with its escapes resolved: `\n` a new line, `\,` `\;` `\\`
/// themselves.
fn unescape(v: &str) -> String {
    let mut out = String::with_capacity(v.len());
    let mut chars = v.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some('n' | 'N') => out.push('\n'),
            Some(c) => out.push(c),
            None => {}
        }
    }
    out
}

fn escape(v: &str) -> String {
    let mut out = String::with_capacity(v.len());
    for c in v.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => {}
            ',' => out.push_str("\\,"),
            ';' => out.push_str("\\;"),
            c => out.push(c),
        }
    }
    out
}

/// A structured value's parts, split where `sep` is not escaped, each
/// unescaped and trimmed.
fn split(v: &str, sep: char) -> Vec<String> {
    let mut parts = Vec::new();
    let mut start = 0;
    let mut escaped = false;
    for (i, c) in v.char_indices() {
        match c {
            _ if escaped => escaped = false,
            '\\' => escaped = true,
            c if c == sep => {
                parts.push(unescape(&v[start..i]).trim().into());
                start = i + c.len_utf8();
            }
            _ => {}
        }
    }
    parts.push(unescape(&v[start..]).trim().into());
    parts
}

fn joined(parts: &[String], sep: &str) -> String {
    let parts: Vec<&str> = parts.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).collect();
    parts.join(sep)
}

/// `NAME:value` written folded: no line longer than 75 bytes, a
/// continuation starting with a space, never inside a character.
fn fold(out: &mut String, name: &str, value: &str) {
    let line = alloc::format!("{name}:{value}");
    let mut width = 0;
    for c in line.chars() {
        if width + c.len_utf8() > 75 {
            out.push_str("\r\n ");
            width = 1;
        }
        out.push(c);
        width += c.len_utf8();
    }
    out.push_str("\r\n");
}

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

pub fn unhex(text: &str) -> Option<Vec<u8>> {
    if !text.len().is_multiple_of(2) {
        return None;
    }
    text.as_bytes()
        .chunks(2)
        .map(|p| Some(nibble(p[0])? << 4 | nibble(p[1])?))
        .collect()
}

fn nibble(c: u8) -> Option<u8> {
    match c {
        b'0'..=b'9' => Some(c - b'0'),
        b'a'..=b'f' => Some(c - b'a' + 10),
        b'A'..=b'F' => Some(c - b'A' + 10),
        _ => None,
    }
}

#[cfg(test)]
mod tests;