garage44.eu/jeroen/pinnacle

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

.. /programs/src/bin/kees.rs

raw

//! Kees: mail, calendar and contacts, from the account a person already
//! has. The engine and screens of `jeroen/kees` (IMAP and SMTP, CalDAV and
//! CardDAV, invites by mail) in a window, its interface drawn with Mithril
//! through `pinnacle_view`. A system program, as Fien is: it uses the
//! network, and puts the cards it syncs into the address book.
//!
//! - The engine runs on a thread of its own: it waits on servers, the
//!   window never does. It syncs when asked, when the app comes to the
//!   front, and every five minutes while it runs.
//! - Its connections are `pinnacle_rt::net` under Pinnacle's own TLS
//!   ([`Stream`]), checked against the roots on the system disk; HTTPS for
//!   CalDAV and CardDAV is `pinnacle_rt::net::request`.
//! - What it keeps (the account with its password, the mail's summaries,
//!   the calendars) is in its folder in the vault; with no vault open it
//!   keeps nothing, and the account is asked for each start.
//! - Cards that come or go on the server go into or out of Contacts (by
//!   their UID), through the p2p service that keeps the address book.
//! - Started with [`pinnacle_rt::abi::KEES_CHECK`] (the kernel's
//!   self-check) it syncs a whole account against the provider held in
//!   memory (`kees_core::demo`) and prints what it found.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::collections::VecDeque;
use alloc::format;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::cell::UnsafeCell;
use core::sync::atomic::{AtomicBool, Ordering};

use kees_core::account::{Account, Security, Server};
use kees_core::dav::{Answer as DavAnswer, Request as DavRequest};
use kees_core::engine::{Engine, Net, Sent};
use kees_core::ical::Zone;
use kees_core::link::{Error, Link};
use kees_core::message::Message;
use kees_core::store::Store;
use kees_view::{Kees, Request};
use pinnacle_rt::{Channel, Received, fs, net};
use pinnacle_ui::{App, Event};
use pinnacle_view::{Clipboard, Screen};

const ANNOUNCE: &str = "kees: control ";
/// A sync this often while the app runs.
const SYNC_EVERY_MS: u64 = 5 * 60 * 1000;
/// The longest wait for a server's next bytes.
const TIMEOUT_MS: u64 = 20_000;

/// Kees's folder: in the vault, or nowhere (None) while none is open.
fn own() -> Option<&'static str> {
    fs::disk("data").is_some().then_some("data:/apps/kees")
}

/// The device's zone: `system:/locale/zone` (Settings' time zone) when it
/// names one Kees knows, else Europe/Amsterdam.
fn device_zone() -> Zone {
    fs::read_string("system:/locale/zone")
        .and_then(|z| Zone::known(z.trim()))
        .unwrap_or_else(|| Zone::known("Europe/Amsterdam").expect("a known zone"))
}

fn random() -> u64 {
    let mut b = [0u8; 8];
    pinnacle_rt::random(&mut b);
    u64::from_le_bytes(b)
}

// ── The network, for the engine ─────────────────────────────────────────

/// A TCP connection, plain or under TLS (from the start, or after a
/// STARTTLS), with the roots on the system disk.
struct Stream {
    channel: Channel,
    host: String,
    tls: Option<pinnacle_tls::client::Client>,
    buffer: Vec<u8>,
}

fn net_error(what: &str) -> Error {
    Error::Net(String::from(what))
}

impl Stream {
    fn open(server: &Server) -> Result<Stream, Error> {
        let ip = net::resolve(&server.host).ok_or_else(|| net_error("its name was not found"))?;
        let channel = net::connect(ip, server.port).ok_or_else(|| net_error("no connection"))?;
        let mut s = Stream {
            channel,
            host: server.host.clone(),
            tls: None,
            buffer: alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE],
        };
        if server.security == Security::Tls {
            s.handshake()?;
        }
        Ok(s)
    }

    /// TLS 1.3 on the connection, done before it returns.
    fn handshake(&mut self) -> Result<(), Error> {
        use pinnacle_tls::client::{Client, Config, Verify};
        let roots =
            fs::read_string(net::ROOTS).ok_or_else(|| net_error("no certificate roots on this device"))?;
        let config = Config {
            host: self.host.clone(),
            verify: Verify::Roots {
                roots: pinnacle_tls::pem::certificates(&roots),
                now: pinnacle_rt::clock() as i64,
            },
            min_rsa_bits: 2048,
            // IMAP and SMTP, no application protocol to choose.
            alpn: Vec::new(),
        };
        let mut r = [0u8; 96];
        pinnacle_rt::random(&mut r);
        self.tls = Some(Client::new(
            config,
            r[..32].try_into().unwrap(),
            r[32..64].try_into().unwrap(),
            r[64..].try_into().unwrap(),
        ));
        loop {
            self.flush();
            if self.tls.as_ref().is_some_and(|c| c.connected()) {
                return Ok(());
            }
            match pinnacle_rt::receive(
                &[&self.channel],
                &mut self.buffer,
                Some(pinnacle_rt::time() + TIMEOUT_MS),
            ) {
                Received::Message { len, .. } => self
                    .tls
                    .as_mut()
                    .unwrap()
                    .receive(&self.buffer[..len])
                    .map_err(|e| Error::Net(format!("TLS: {e:?}")))?,
                Received::Closed { .. } => return Err(Error::Closed),
                Received::Timeout => return Err(net_error("the server did not answer")),
            }
        }
    }

    fn flush(&mut self) {
        if let Some(c) = &mut self.tls {
            for chunk in c.take_output().chunks(pinnacle_rt::abi::MAX_MESSAGE) {
                self.channel.send(chunk, Vec::new());
            }
        }
    }
}

impl Link for Stream {
    fn send(&mut self, bytes: &[u8]) -> Result<(), Error> {
        match &mut self.tls {
            Some(c) => {
                c.write(bytes);
                self.flush();
            }
            None => {
                for chunk in bytes.chunks(pinnacle_rt::abi::MAX_MESSAGE) {
                    if !self.channel.send(chunk, Vec::new()) {
                        return Err(Error::Closed);
                    }
                }
            }
        }
        Ok(())
    }

    fn receive(&mut self) -> Result<Vec<u8>, Error> {
        loop {
            if self.tls.as_ref().is_some_and(|c| c.closed()) {
                return Err(Error::Closed);
            }
            match pinnacle_rt::receive(
                &[&self.channel],
                &mut self.buffer,
                Some(pinnacle_rt::time() + TIMEOUT_MS),
            ) {
                Received::Message { len, .. } => {
                    let Some(c) = &mut self.tls else {
                        return Ok(self.buffer[..len].to_vec());
                    };
                    c.receive(&self.buffer[..len])
                        .map_err(|e| Error::Net(format!("TLS: {e:?}")))?;
                    self.flush();
                    let plain = self.tls.as_mut().unwrap().read();
                    if !plain.is_empty() {
                        return Ok(plain);
                    }
                }
                Received::Closed { .. } => return Err(Error::Closed),
                Received::Timeout => return Err(net_error("the server stopped answering")),
            }
        }
    }

    fn start_tls(&mut self) -> Result<(), Error> {
        self.handshake()
    }
}

struct Pinnacle;

impl Net for Pinnacle {
    type Link = Stream;

    fn connect(&mut self, server: &Server) -> Result<Stream, Error> {
        Stream::open(server)
    }

    fn http(&mut self, r: &DavRequest, authorization: &str) -> Result<DavAnswer, Error> {
        let mut headers: Vec<(&str, &str)> = r.headers.iter().map(|(k, v)| (*k, v.as_str())).collect();
        headers.push(("Authorization", authorization));
        let mut body = Vec::new();
        let head = net::request(
            r.method,
            &r.url,
            &headers,
            r.body.as_bytes(),
            TIMEOUT_MS,
            |piece| {
                body.extend_from_slice(piece);
                true
            },
        )
        .map_err(|e| Error::Net(format!("{e:?}")))?;
        Ok(DavAnswer {
            status: head.status,
            headers: head.headers.clone(),
            body,
        })
    }

    fn now(&mut self) -> i64 {
        pinnacle_rt::clock() as i64
    }

    fn random(&mut self) -> u64 {
        random()
    }
}

// ── Between the window and the engine's thread ──────────────────────────

/// A lock for what the two threads share: taken by one atomic swap.
struct Lock<T> {
    taken: AtomicBool,
    value: UnsafeCell<T>,
}

// SAFETY: the value is reached only while `taken` is held.
unsafe impl<T: Send> Sync for Lock<T> {}

impl<T> Lock<T> {
    fn new(value: T) -> Lock<T> {
        Lock {
            taken: AtomicBool::new(false),
            value: UnsafeCell::new(value),
        }
    }

    fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
        while self.taken.swap(true, Ordering::Acquire) {
            core::hint::spin_loop();
        }
        // SAFETY: held, so nobody else has it.
        let r = f(unsafe { &mut *self.value.get() });
        self.taken.store(false, Ordering::Release);
        r
    }
}

/// What the window asks of the engine.
enum Work {
    Asked(alloc::boxed::Box<Request>),
    /// The app came to the front: sync.
    Front,
    /// It left the front: let the mail connection go.
    Back,
}

/// What the engine tells the window.
enum Told {
    Account(Option<Account>),
    Store(Store),
    Status(String, bool),
    Opened(String, u32, Result<Message, String>),
}

#[derive(Default)]
struct Mailbox {
    work: VecDeque<Work>,
    told: Vec<Told>,
}

struct Worker {
    shared: Arc<Lock<Mailbox>>,
    tell: Channel,
    engine: Option<Engine<Pinnacle>>,
    zone: Zone,
}

impl Worker {
    fn say(&self, t: Told) {
        self.shared.with(|m| m.told.push(t));
        self.tell.send(&[1], Vec::new());
    }

    fn status(&self, text: &str, busy: bool) {
        pinnacle_rt::println!("kees: {text}");
        self.say(Told::Status(String::from(text), busy));
    }

    /// What is kept, written; and shown.
    fn kept(&self) {
        let Some(e) = &self.engine else { return };
        if let Some(dir) = own() {
            fs::write(&format!("{dir}/store"), e.store.to_kept().as_bytes());
        }
        self.say(Told::Store(e.store.clone()));
    }

    fn sync(&mut self) {
        if self.engine.is_none() {
            return;
        }
        if net::state() != pinnacle_rt::abi::net::ONLINE {
            self.status("Offline: what you do now goes with the next sync", false);
            return;
        }
        self.say(Told::Status(String::from("Syncing…"), true));
        let e = self.engine.as_mut().unwrap();
        let report = e.sync();
        let said = report.said();
        pinnacle_rt::println!("kees: synced: {said}");
        into_contacts(&report.cards_changed, &report.cards_removed);
        self.kept();
        self.status(&said, false);
    }

    fn sign_in(&mut self, account: Account) {
        let store = match (own(), &self.engine) {
            (_, Some(e)) if e.account.email == account.email => e.store.clone(),
            _ => Store::default(),
        };
        let mut e = Engine::new(account.clone(), store, Pinnacle, self.zone.clone());
        // Mail first: it is what says whether the login works.
        if let Err(err) = e.sync_mail() {
            self.status(&format!("Not signed in. {}", err.explain()), false);
            return;
        }
        match own() {
            Some(dir) => {
                fs::create_dir("data:/apps");
                fs::create_dir(dir);
                fs::write(&format!("{dir}/account"), account.to_kept().as_bytes());
            }
            None => pinnacle_rt::println!("kees: no vault open: the account is not kept"),
        }
        pinnacle_rt::println!("kees: signed in as {}", account.email);
        self.engine = Some(e);
        self.say(Told::Account(Some(account)));
        self.sync();
    }

    fn sign_out(&mut self) {
        if let Some(e) = &mut self.engine {
            e.hang_up();
        }
        self.engine = None;
        if let Some(dir) = own() {
            fs::remove(&format!("{dir}/account"));
            fs::remove(&format!("{dir}/store"));
        }
        self.say(Told::Account(None));
        self.status("Signed out", false);
    }

    fn work(&mut self, w: Work) {
        let r = match w {
            Work::Front => return self.sync(),
            Work::Back => {
                if let Some(e) = &mut self.engine {
                    e.hang_up();
                }
                return;
            }
            Work::Asked(r) => *r,
        };
        match r {
            Request::SignIn(a) => return self.sign_in(a),
            Request::SignOut => return self.sign_out(),
            Request::Sync => return self.sync(),
            _ => {}
        }
        let Some(e) = &mut self.engine else { return };
        let said = match r {
            Request::Open { folder, uid } => {
                let got = e
                    .body(&folder, uid)
                    .map(|b| Message::parse(&b))
                    .map_err(|x| x.explain());
                self.say(Told::Opened(folder, uid, got));
                return;
            }
            Request::Flag {
                folder,
                uid,
                flag,
                on,
            } => {
                e.set_flag(&folder, uid, &flag, on);
                return self.kept();
            }
            Request::Delete { folder, uid } => {
                e.delete(&folder, uid);
                return self.kept();
            }
            Request::Send(draft) => match e.send(&draft) {
                Ok(Sent::Now) => String::from("Sent"),
                Ok(Sent::Later) => String::from("Offline: it goes with the next sync"),
                Err(x) => format!("Not sent. {}", x.explain()),
            },
            Request::Answer { invite, answer } => match e.answer_invite(&invite, answer) {
                Ok(_) => format!("You {} {}", answer.said(), invite.event().summary),
                Err(x) => format!("Not answered. {}", x.explain()),
            },
            Request::Apply(invite) => match e.apply_invite(&invite) {
                Ok(()) => String::from("The calendar is up to date"),
                Err(x) => x.explain(),
            },
            Request::PutEvent { calendar, uid, text } => match e.put_event(calendar, &uid, text) {
                Ok(()) => String::from("Saved"),
                Err(x) => format!("Not saved. {}", x.explain()),
            },
            Request::DeleteEvent(uid) => match e.delete_event(&uid) {
                Ok(()) => String::from("Deleted"),
                Err(x) => format!("Not deleted. {}", x.explain()),
            },
            Request::Save(file) => match own() {
                Some(dir) => {
                    let files = format!("{dir}/files");
                    fs::create_dir(&files);
                    let name: String = file
                        .name
                        .chars()
                        .map(|c| if c == '/' || c == ':' { '_' } else { c })
                        .collect();
                    if fs::write(&format!("{files}/{name}"), &file.data) {
                        format!("Saved in Files: Kees ▸ files ▸ {name}")
                    } else {
                        String::from("It could not be saved")
                    }
                }
                None => String::from("Open the vault to save files"),
            },
            Request::SignIn(_) | Request::SignOut | Request::Sync => unreachable!(),
        };
        self.kept();
        self.status(&said, false);
    }

    fn run(mut self, wake: Channel) {
        let mut buffer = [0u8; 16];
        let mut next_sync = pinnacle_rt::time() + SYNC_EVERY_MS;
        loop {
            while let Some(w) = self.shared.with(|m| m.work.pop_front()) {
                self.work(w);
            }
            match pinnacle_rt::receive(&[&wake], &mut buffer, Some(next_sync)) {
                Received::Message { .. } => {}
                Received::Timeout => {
                    self.sync();
                    next_sync = pinnacle_rt::time() + SYNC_EVERY_MS;
                }
                Received::Closed { .. } => return,
            }
        }
    }
}

/// Cards from the server into the address book, by their UID; the ones
/// gone from it out.
fn into_contacts(changed: &[String], removed: &[String]) {
    if changed.is_empty() && removed.is_empty() {
        return;
    }
    let Some(client) = pinnacle_ui::p2p::Client::connect(2000) else {
        pinnacle_rt::println!("kees: the address book did not answer");
        return;
    };
    let mut pending = Vec::new();
    let entries: Vec<pinnacle_contacts::Entry> =
        changed.iter().flat_map(|v| pinnacle_contacts::parse(v)).collect();
    let kept = client.import(&entries, &mut pending);
    if !removed.is_empty() {
        for e in client.book(&mut pending) {
            if !e.uid.is_empty() && removed.contains(&e.uid) {
                client.remove_entry(&e.id);
            }
        }
    }
    pinnacle_rt::println!("kees: contacts: {kept} kept, {} gone", removed.len());
}

// ── The self-check ──────────────────────────────────────────────────────

/// A whole account against the provider in memory: what the kernel's
/// self-check runs, so Kees is known to work here and not only on a
/// development machine.
fn check() -> u64 {
    use kees_core::demo::{FakeNet, World};
    use kees_core::imap::Role;
    let world = alloc::rc::Rc::new(core::cell::RefCell::new(World::default()));
    let net = FakeNet::new(&world);
    *world.borrow_mut() = World::sample(net.now);
    let mut account = Account::guess("Kees Jansen", "kees@example.nl", kees_core::demo::PASSWORD);
    account.user = String::from(kees_core::demo::USER);
    account.imap = Server::tls("imap.example.nl", 993);
    account.smtp = Server::tls("smtp.example.nl", 465);
    account.calendars = String::from("https://dav.example.nl/.well-known/caldav");
    account.contacts = String::from("https://dav.example.nl/.well-known/carddav");
    let mut e = Engine::new(account, Store::default(), net, device_zone());
    let report = e.sync();
    let mails = e.store.role(Role::Inbox).map_or(0, |f| f.mails.len());
    let now = e.net.now;
    let events = e.agenda(now - 7 * 86_400, now + 7 * 86_400).len();
    let cards = e.cards().len();
    let invite = e
        .store
        .role(Role::Inbox)
        .and_then(|f| f.mails.first())
        .map(|m| m.uid);
    let answered = invite
        .and_then(|uid| e.body("INBOX", uid).ok())
        .and_then(|b| Engine::<FakeNet>::invite_in(&Message::parse(&b)))
        .map(|inv| e.answer_invite(&inv, kees_core::ical::Answer::Accepted).is_ok());
    pinnacle_rt::println!(
        "kees: {mails} messages, {events} events, {cards} contacts, invite answered: {}",
        answered == Some(true)
    );
    let ok = report.ok() && mails == 4 && events > 0 && cards == 2 && answered == Some(true);
    if ok {
        0
    } else {
        pinnacle_rt::println!("kees: failed: {}", report.said());
        1
    }
}

// ── The window ──────────────────────────────────────────────────────────

#[unsafe(no_mangle)]
fn main(argument: u64) -> u64 {
    if argument == pinnacle_rt::abi::KEES_CHECK {
        return check();
    }
    let zone = device_zone();
    let account = own()
        .and_then(|d| fs::read_string(&format!("{d}/account")))
        .and_then(|t| Account::from_kept(&t));
    let store = match (&account, own()) {
        (Some(_), Some(d)) => fs::read_string(&format!("{d}/store"))
            .map(|t| Store::from_kept(&t))
            .unwrap_or_default(),
        _ => Store::default(),
    };
    let now = pinnacle_rt::clock() as i64;
    let kees = Kees::new(account.clone(), store.clone(), zone.clone(), now, random());

    // The engine's thread, with what is kept.
    let shared = Arc::new(Lock::new(Mailbox::default()));
    let (wake_here, wake_there) = Channel::pair();
    let (told_here, told_there) = Channel::pair();
    let worker = Worker {
        shared: shared.clone(),
        tell: told_there,
        engine: account.map(|a| Engine::new(a, store, Pinnacle, zone.clone())),
        zone,
    };
    if pinnacle_rt::thread::spawn(move || worker.run(wake_there)).is_none() {
        pinnacle_rt::println!("kees: no thread for the engine");
        return 1;
    }
    let ask = |w: Work| {
        shared.with(|m| m.work.push_back(w));
        wake_here.send(&[1], Vec::new());
    };

    let mut app = App::new("Kees");
    let mut screen = Screen::new(app.width, app.height);
    screen.mount(kees.view());
    screen.draw(&mut app.canvas(), true);
    app.present_all();
    screen.announce(ANNOUNCE);
    pinnacle_rt::println!("kees: started");
    ask(Work::Front);
    let mut buffer = alloc::vec![0u8; 64];
    loop {
        let mut all = false;
        match app.wait(&[&told_here], &mut buffer, Some(pinnacle_rt::time() + 30_000)) {
            Event::Shown(true) => {
                ask(Work::Front);
                all = true;
            }
            Event::Shown(false) => ask(Work::Back),
            Event::Resized => {
                screen.resize(app.width, app.height);
                all = true;
            }
            Event::Input(input) => {
                screen.input(&input);
                match screen.clipboard() {
                    Some(Clipboard::Paste) => app.paste(),
                    Some(Clipboard::Copy) => {
                        if let Some(text) = screen.selected_text() {
                            app.copy(&text);
                        }
                    }
                    None => {}
                }
            }
            Event::Clipboard(text) => {
                screen.paste(&text);
            }
            Event::Channel { .. } => {
                for t in shared.with(|m| core::mem::take(&mut m.told)) {
                    match t {
                        Told::Account(a) => kees.set_account(a),
                        Told::Store(s) => kees.set_store(s),
                        Told::Status(text, busy) => kees.set_status(&text, busy),
                        Told::Opened(folder, uid, m) => {
                            pinnacle_rt::println!("kees: opened {uid}");
                            kees.opened(&folder, uid, m);
                        }
                    }
                }
            }
            Event::ChannelClosed { .. } => {
                pinnacle_rt::println!("kees: the engine's thread ended");
                return 1;
            }
            Event::Closed => return 0,
            _ => {}
        }
        kees.set_now(pinnacle_rt::clock() as i64);
        for r in kees.requests() {
            if let Request::Send(d) = &r {
                pinnacle_rt::println!("kees: sending {}", d.subject);
            }
            ask(Work::Asked(alloc::boxed::Box::new(r)));
        }
        if all {
            screen.draw(&mut app.canvas(), true);
            app.present_all();
            screen.announce(ANNOUNCE);
        } else if let Some(area) = screen.draw(&mut app.canvas(), false) {
            app.present(area);
            screen.announce(ANNOUNCE);
        }
    }
}